将JSON字符串转换为内部包含对象列表的对象-Java

时间:2019-02-04 17:30:53

标签: java json gson deserialization

我需要帮助,以Java中的以下格式反序列化JSON:

data.json

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

我已经创建了两个类,一个类称为Token,另一个类名为uggestination,其属性与JSON格式匹配。

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;
    }

}

如何将JSON“解包”到Token列表中,每个Token都有两个必需的字符串和一个Recommendation对象列表作为其属性? (理想情况下,它将使用Gson库)

我已经尝试过了,但是不起作用:

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

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

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

谢谢

3 个答案:

答案 0 :(得分:1)

您可以使用Jackson的TypeReference来实现此目的,例如:

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

您可以详细了解TypeReference here

答案 1 :(得分:1)

您必须创建另一个名为Output的类

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;
}

然后使用

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

然后,您可以使用输出获取tokens的列表,并进一步查找suggestion

答案 2 :(得分:-1)

如果您使用Jackson,则应在上述字段中使用@JsonProperty。尝试按以下方式编写文件:

公共类令牌{

@JsonProperty
private int position;

@JsonProperty
private String text;

@JsonProperty
private List<Suggestion> suggestions;

//getters/setters

}

公共课程建议{

@JsonProperty
private String suggestion;

@JsonProperty
private double points;

// getters/setters

}