how whould I parse JSON with numerical object keys in Jackson JSON

≯℡__Kan透↙ 提交于 2021-02-19 23:26:48

问题


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.

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

how would I parse something like this in Jackson:

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

any help with this would be greatly apreceated


回答1:


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

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



回答2:


If you need a quick way, you can set it to a Map;

ObjectMapper mapper = new ObjectMapper();

Map<String, Map<String, String>> map = mapper.readValue(br, Map.class);
System.out.println(map);

Your map would now be:

{1={key1=val, key2=val}, 2={key1=val, key2=val}}

You can iterate over the Map(s) and set your ResetPassword accordingly.

PS: br is my BufferedReader instance which reads the json placed in numeric.txt,

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("numeric.txt"),    "UTF-8"));


来源:https://stackoverflow.com/questions/21759625/how-whould-i-parse-json-with-numerical-object-keys-in-jackson-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!