Jackson JSON将JSON对象转换为HashMap

时间:2016-07-27 13:29:20

标签: java json jackson deserialization

我在Jaunt之后开始使用jackson json,但我无法理解反序列化中的一些细节。

我有来自服务器的JSON响应,这里是: enter image description here



{
  success: true,
  stickers: [
     {
      id: "88899",
      name: "",
      img: ""
      },
    {
      id: "13161",
      name: "3DMAX",
      img: ""
    }
  ]
}




我的项目中有一个Sticker类



public class Sticker {

    @JsonProperty("id")
    private String id;

    @JsonProperty("name")
    private String name;

    @JsonProperty("img")
    private String imgUrl;

  //getters and setters and constructors
}
  




我想阅读此回复并创建贴纸列表: 列表(贴纸)stickerList;

**另一项任务(如果有可能使用jackson工具),我想在消毒过程中创建HashMap(String,Sticker)而不是List(Sticker)**

如何轻松妥善地做到这一点?

我找到了List的解决方案:我创建了类



public class StickerPage {

    @JsonProperty("stickers")
    private List<Sticker> stickerList;

    public List<Sticker> getStickerList() {
        return stickerList;
    }

    public void setStickerList(List<Sticker> stickerList) {
        this.stickerList = stickerList;
    }
}
&#13;
&#13;
&#13;

并将其用于此:

&#13;
&#13;
        ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        StickerPage stickerPage = objectMapper.readValue(inputStream, StickerPage.class);
        HashMap<String, Sticker> stickerHashMap = new HashMap<>();
        for (Sticker sticker : stickerPage.getStickerList()) {
            stickerHashMap.put(sticker.getName(), sticker);
        }
&#13;
&#13;
&#13;

但我认为这看起来很奇怪,你能帮助我完成这项任务吗?

0 个答案:

没有答案