我该如何解析Jackson JSON中带有数字对象键的JSON [英] how whould I parse JSON with numerical object keys in Jackson JSON

查看:203
本文介绍了我该如何解析Jackson JSON中带有数字对象键的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用Jackson JSON解析器,我很喜欢它,但是我尝试解析的JSON对象遇到了问题.

I just started using Jackson JSON parser, and I love it, but I've run into a problem with a JSON object I'm trying to parse.

这是我当前的Java代码:

here's my current java code:

public class resetPassword {
    private String id;
    private String key1;
    private String key2;


    public String getId() {
        return id;
    }

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

    public String getKey1() {
        return key1;
    }

    public void setKey1(String key1) {
        this.key1= key1;
    }

    public String getKey2() {
        return key2;
    }

    public void setKey2(String key2) {
        this.key2= key2;
    }
}

我将如何在Jackson中解析这样的内容:

how would I parse something like this in Jackson:

{
   "1":{
      "key1":"val",
      "key2":"val"
   },
   "2":{
     "key":"val",
     "key":"val"
     }, .. etc
}

对此有任何帮助

推荐答案

基于注释中的信息,我想您需要将遍历与数据绑定结合起来.

Based on the information in comments, I guess you need to combine traversing with data binding.

首先,使用遍历,获取具有{"key1": ..., "key2": ...}JsonNode个对象. 伪代码(未经测试):

First, using traversal, get JsonNode objects with {"key1": ..., "key2": ...}. Pseudocode (not tested):

    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(genreJson);
    Iterator<String> fieldNames = root.fieldNames();
    while (fieldNames.hasNext()) {
        String fieldName = fieldNames.next();
        JsonNode node = root.get(fieldName);
        // now you should have {"key1": ...} in node
    }

然后为每个节点使用数据绑定找到:

Then use data binding for each node you found:

ResetPassword item = mapper.readValue(node, ResetPassword.class);

这篇关于我该如何解析Jackson JSON中带有数字对象键的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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