简体   繁体   中英

Converting a JSON string into an object with a list of objects inside it - Java

I need help deserialising JSON in the following format in Java:

data.json

{
   "tokens":[
      {
         "position":1,
         "text":"hello",
         "suggestions":[
            {
               "suggestion":"hi",
               "points":0.534
            },
            {
               "suggestion":"howdy",
               "points":0.734
            }
         ]
      },
   ]
}

I've created two classes, one called Token and another called Suggestion, with attributes matching the JSON format.

Token.java

public class Token {
    private int position;
    private String text;
    private List<Suggestion> suggestions;

    public Token(int position, String text, List<Suggestion> suggestions) {
        this.position = position;
        this.text = text;
        this.suggestions = suggestions;
    }
}

Suggestion.java

public class Suggestion {
    private String suggestion;
    private double points;

    public Suggestion(String suggestion, double points) {
        this.suggestion = suggestion;
        this.points = points;
    }

}

How do I "unpack" the JSON into a list of Tokens, each of which has the two required strings and a list of Suggestion objects as its attributes? (Ideally, it would be using the Gson library)

I've tried this, but it doesn't work:

Gson gson = new Gson();
Type listType = new TypeToken<List<Token>>(){}.getType();

List<Token> tokenList = gson.fromJson(jsonString, listType);

System.out.println(tokenList.get(0));

Thanks

You can use Jackson's TypeReference to achieve this, eg:

ObjectMapper objectMapper = new ObjectMapper();
TypeReference<List<Token>> typeReference = new TypeReference<List<Token>>() {};
List<Token> tokens = objectMapper.readValue("<json_stribg>", typeReference);

You can read more about TypeReference here .

You have to create another class say Output as

import java.util.List;

public class Output {
    public List<Token> getTokens() {
        return tokens;
    }

    public void setTokens(List<Token> tokens) {
        this.tokens = tokens;
    }

    private List<Token> tokens;
}

and then use

Output output = new Gson().fromJson(json, Output.class);

then you can use output to get list of tokens and go further for suggestion etc

If you use Jackson, you should use @JsonProperty above fields. Try write your files as below:

public class Token {

@JsonProperty
private int position;

@JsonProperty
private String text;

@JsonProperty
private List<Suggestion> suggestions;

//getters/setters

}

public class Suggestion {

@JsonProperty
private String suggestion;

@JsonProperty
private double points;

// getters/setters

}

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