Jackson JSON映射键作为包含对象的属性 [英] Jackson JSON map key as property of contained object

查看:239
本文介绍了Jackson JSON映射键作为包含对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这样的结构:

{
  "nameOfObject": { "score": 100 },
  "anotherObject": { "score": 30 }
}

是可以将其映射到:

class Container {
  Map<String, ScoreKeeper> scoreKeepers;
}

class ScoreKeeper {
  String name;
  int score;
}

这样你最终得到的是名称属性 ScoreKeeper 实例设置为nameOfObjectanotherObject ,分别?

So that you end up with the name property of the ScoreKeeper instances set to "nameOfObject" and "anotherObject", respectively?

推荐答案

我坚信将POJO与外部化分开。将您的JSON读入Map,然后构建像这样的Container / ScoreKeeper对象(适用于任何拼写错误):

I am a firm believer in separating your POJOs from externalization. Read your JSON into a Map and then build you Container/ScoreKeeper objects like this (apols for any typos):

mapper = new ObjectMapper();

Map<String,Object> data = mapper.readValue(inputstream, Map.class);

Container c = new Container();

for(Map.Entry<String, Object> me : data.entrySet()) {
    String key = me.getKey();
    Map info = (Map) me.getValue();

    ScoreKeeper sk = new ScoreKeeper();
    sk.setName(key);
    Integer q = info.get("score");
    sk.setScore(q);

    c.put(key, sk);
}

这篇关于Jackson JSON映射键作为包含对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆