简体   繁体   中英

How to convert Json Array to Java Array of Objects

I have a json object which has following contents :

{
   "similarUserScores":[
      {
         "user":"u26",
         "score":0.6199970840986468
      },
      {
         "user":"u37",
         "score":0.5405403752816058
      },
      {
         "user":"u12",
         "score":0.523836143999991
      },
      {
         "user":"u24",
         "score":0.4990480549411648
      }
   ]
}

I need to convert it into java objects. So I created a java class to map this :

public class SimilarUserScores {

    private String user;

    private double score;

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

}

So how can I convert the above JSON to a list of java objects?

//Get Recommendations for this user
JsonObject recommendedUserJson  = PredictionIoClientHelper
                                       .getInstance().getRecommendedUser("u"+userId, limit);
if(recommendedUserJson != null) {
    Gson gson = new Gson();
    String jsonString = recommendedUserJson.toString();
    SimilarUserScores[] recommendedUsers= gson.fromJson(jsonString, SimilarUserScores[].class);
}

I tried to use the above snippet however it did not worked.

You have to initialize a JSONObject and an ArrayList<SimilarUserScores> .

Then you have to get the JSONArray and iterate over it.

For each iteration you set the data into the object and then append it to the output list. Here's an example of working code:

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;

String s = "{\"similarUserScores\":[{\"user\":\"u26\",\"score\":0.6199970840986468}, ...

ArrayList<SimilarUserScores> objects = new ArrayList();
JSONObject obj = new JSONObject(s);
JSONArray scores = obj.getJSONArray("similarUserScores");
for (int i = 0; i < scores.length(); i++) {
    JSONObject element = scores.getJSONObject(i);
    SimilarUserScores object = new SimilarUserScores();
    object.setUser(element.getString("user"));
    object.setScore(element.getDouble("score"));
    objects.add(object);
}

The previous code assumes that the JSON is in a String variable and that you have already defined SimilarUserScores class. This code uses "JSON" library. If you are using maven, you can import it adding the following snippet in your pom.xml under the tag <dependencies>

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180130</version>
</dependency>

You need an wrapper around your SimilarUserScores .

Honestly, your inner class should be better named UserScore

public class SimilarUserScores {
    private List<UserScore> similarUserScores;
    // Getter setter
}

public class UserScore {

    private String user;

    private double score;
}

Now parse your json against SimilarUserScores class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM