使用任何杰克逊库解析JSON的最佳方法

时间:2018-06-27 15:45:40

标签: java jackson

对于一项正在进行的开发,外部休息服务正在返回如下响应:

{
    "type": "State",
    "id": "12344",
    "prodId": "wert",
    "players": 14,
    "feeds": {
        "abc123": {
            -----
        },
        "def1234": {
            -----
        },

        ---
        ---

        "someRandomAlphanumericValue": {

        }
    }
}

在这里,要求是,我想解析此JSON并以java对象的格式生成输出,以便于访问。

1 个答案:

答案 0 :(得分:1)

将随机字母数字属性设置为Map<String, WhateverIsTheTypeTheyContain>

Jackson将通过构建HashMap绑定它们,并向其中添加这些属性,将属性名称作为键,并将属性值作为值。

这是一个完整的示例:

给出在当前包中另存为“ feeds.json”的有效JSON文件:

{
  "id": "12344",
  "players": 14,
  "feeds": {
    "abc123": {
      "id": "1",
      "number": 1
    },
    "def1234": {
      "id": "2",
      "number": 2
    },
    "someRandomAlphanumericValue": {
      "id": "3",
      "number": 3
    }
  }
}

我们定义这些类将其绑定到:

public class FeedContainer {
  private String id;
  private int players;
  private Map<String, Feed> feeds;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public int getPlayers() {
    return players;
  }

  public void setPlayers(int players) {
    this.players = players;
  }

  public Map<String, Feed> getFeeds() {
    return feeds;
  }

  public void setFeeds(Map<String, Feed> feeds) {
    this.feeds = feeds;
  }
}

public class Feed {
  private String id;
  private int number;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public int getNumber() {
    return number;
  }

  public void setNumber(int number) {
    this.number = number;
  }
}

现在我们可以使用此类进行测试:

public class FeedContainerTry {

  public static void main(String[]args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    try(InputStream is = FeedContainerTry.class.getResourceAsStream("feeds.json")) {
      FeedContainer container = mapper.readValue(is, FeedContainer.class);
      container.getFeeds().forEach((key, feed) -> {
        System.out.println(key + ": " + feed.getId() + ", " + feed.getNumber());
      });
    }
  }
}

这表明我们可以访问所有属性