0

我有以下形式的一些 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;
}

一个项目是简单的故事的 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 方法。标记类只包含两个字符串字段。

我不知道如何构造 setTags 方法,以便生成 Tag 对象的数组列表,并且找不到任何帮助。

谢谢!

4

1 回答 1

0

您已将标签标记为最终标签,这可能会阻止 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;
    }

或者

  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;
    } 
于 2012-07-18T16:23:10.790 回答