我有以下形式的Json:
"items": [
{
"id": 1,
"text": "As a user without a subscription, I get a choice of available ones.",
"status": "finished",
"tags": [
{
"id": 1234,
"name": "feature=subs"
},
{
"id": 1235,
"name": "epic=premium"
}
]
},
{
"id": 2,
...
还有更多字段,但为了清楚起见,我已将其省略。 我试图将每个故事映射到具有字段ID,文本,状态和标签列表的故事类。我使用以下方法可以正常工作:
public Project JsonToProject(byte[] json) throws JsonParseException, JsonMappingException, IOException
{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode rootNode = mapper.readValue(json, JsonNode.class);
int storyCount = rootNode.get("totalItems").asInt();
ArrayNode itemsNode = (ArrayNode) rootNode.get("items");
Project project = new Project();
for (int i = 0; i < storyCount; i++)
{
Story story = JsonToStory(rootNode.get(i));
project.addStory(story);
}
return project;
}
如果项目很简单,则Stories的ArrayList和JsonToStory是以下方法:
public Story JsonToStory(JsonNode rootNode) throws JsonParseException, JsonMappingException, IOException
{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Story story = mapper.readValue(rootNode, Story.class);
return story;
}
故事类如下:
public class Story {
private int id;
private String text = new String();
private String status = new String();
private final List<Tag> tags = new ArrayList<Tag>();
public void setId(int i)
{
id = i;
}
public void setText(String s)
{
text = s;
}
public void setStatus(String s)
{
status = s;
}
public void setTags(Tag[])
{
???
}
}
使用get方法和print方法。 Tag类只包含两个字符串字段。
我不知道如何构造setTags方法,以便导致Tag对象的arraylist,并且无法找到任何帮助。
谢谢!
答案 0 :(得分:0)
您已将标记标记为final,这可能会阻止setter设置标记。你可以试试这个:
public class Story {
private int id;
private String text = new String();
private String status = new String();
private List<Tag> tags;
public void setTags(List<Tag> tags){
this.tags = tags;
}
OR
public class Story {
private int id;
private String text = new String();
private String status = new String();
private Tag[] tags;
public void setTags(Tag[] tags){
this.tags = tags;
}