Jackson JSON映射键作为包含对象的属性

时间:2013-10-08 12:33:44

标签: java json jackson

给出这样的结构:

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

是否可以将其映射到:

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

class ScoreKeeper {
  String name;
  int score;
}

这样,您最终将name个实例的ScoreKeeper属性分别设置为"nameOfObject""anotherObject"

3 个答案:

答案 0 :(得分:3)

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

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);
}

答案 1 :(得分:2)

替代解决方案,其中使用自定义反序列化器在值对象上设置键name

@Test
public void test() throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();

    Data data = mapper.readValue("{\"users\": {\"John\": {\"id\": 20}, \"Pete\": {\"id\": 30}}}", Data.class);

    assertEquals(20, data.users.get("John").id);
    assertEquals(30, data.users.get("Pete").id);
    assertEquals("John", data.users.get("John").name);
    assertEquals("Pete", data.users.get("Pete").name);
}

public static class Data {
    @JsonDeserialize(contentUsing = Deser.class)
    public Map<String, User> users;
}

public static class User {
    public String name;
    public int id;
}

public static class Deser extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String name = ctxt.getParser().getCurrentName();

        User user = p.readValueAs(User.class);

        user.name = name;  // This copies the key name to the value object

        return user;
    }
}

答案 2 :(得分:0)

这是@Buzz Moschetti的改进版本,它使用Jackson的ObjectMapper.convertValue()来处理解析属性

ObjectMapper mapper = new ObjectMapper();

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

Container c = new Container();

for(Map.Entry<String, Object> entry : data.entrySet()) {
    String name = entry.getKey();
    ScoreKeeper sk = mapper.convertValue(entry.getValue(), ScoreKeeper.class);
    sk.name = name;
    c.scoreKeepers.put(name, sk);
}