繁体   English   中英

如何使用相同的键解析动态嵌套 JSON 并存储在 JAVA Class

[英]How to parse Dynamic nested JSON with same keys and store in JAVA Class

我正在尝试读取复杂的有效负载(树结构)来执行 PATCHMAPPING(部分更新)。 首先,我从有效负载中读取 JSON 并尝试解析和存储它的值。

JSON 数据:

{
  "data": [{
      "name": "name_new",
      "description": "new_decsription",
      "group_id": 1,
      "values": [{
          "inner_group_id": 1,
          "addclass_id": [1],
          "removeclass_id": [2, 3]
        },
        {
          "inner_group_id": 2,
          "addclass_id": [1],
          "removeclass_id": [2, 3]
        },
        {
          "addclass_id": [1],
          "removeclass_id": [2, 3]
        }
      ]
    },
    {
      "group_id": 2,
      "values": [{
        "inner_group_id": 2,
        "addclass_id": [1, 2, 3],
        "removeclass_id": []
      }]
    }
  ]
}

注意: group_id 可能有 inner_group_id 并且有要删除的类和要添加的类。 但它也可以直接有要删除的类和要添加的类。

我正在使用以下代码来解析它并尝试保存在 HASHMAP 中。 但它解析不正确。此外,我不确定是否保存在 hashmap 中,如何将每个 inner_group 标记到它的组或 class_id 到它的组。

    public static List<Map<String, String>> getKeyValue(JSONObject json) throws JSONException {
        
        Iterator<?> keys;
        JSONArray data = json.getJSONArray("data");
        List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
        HashMap role = new HashMap();
        HashMap group = new HashMap();
         for (int i = 0, size = data.length(); i < size; i++)
            {
              JSONObject objectInArray = data.getJSONObject(i);
              keys = objectInArray.keys();
                    while(keys.hasNext())
                    {
                        String nextKeys = (String) keys.next();
                        if (objectInArray.get(nextKeys) instanceof JSONArray)
                        {
                            JSONArray jsonarray = objectInArray.getJSONArray(nextKeys);
                            for(int ii=0; ii<jsonarray.length();ii++)
                            { 
                                String jsonarrayString =  jsonarray.getString(ii).toString();
                                JSONObject innerJSON = new JSONObject(jsonarrayString);
                                String[] elementNames = JSONObject.getNames(innerJSON);

                                  for (String elementName : elementNames)
                                  { 
                                     String value = innerJSON.getString(elementName);
                                     group.put(elementName, value);
                                  }
                            }

                    }

             String[] elementNames = JSONObject.getNames(objectInArray);
            // System.out.println(elementNames);
            //  System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
              for (String elementName : elementNames){ 
                  String value = objectInArray.getString(elementName);
                  role.put(elementName, value);
              }
              listOfMaps.add(role);
              listOfMaps.add(group);

            }
}
        return listOfMaps;

}

我已经制作了 2 个 JAVA 类来设置那些我可以解析后的类:

组.java

public class Group {
    int groupId;
    List<InnerGroup> innerGroups;
    List<Integer> addClassId;
    List<Integer> removeClassId;
    
    // Getters and Setters
    }

**InnerGroup.java**

public class InnerGroup {
    int innerGroupId;
    List<Integer> addClassId;
    List<Integer> removeClassId;

    // Getters and Setters
}

从过去的两天开始,我一直坚持这一点。 非常感谢任何帮助。 提前致谢。

下面的类,使用 Jackson 反序列化 JSON。 下面提供了如何解析提供的 JSON 的想法,可能不一定是完整的解决方案。

实体类

package org.test;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class GroupContainer {
    
    @JsonProperty(value = "data")
    private List<Group> data;

    public List<Group> getData() {return data;}
    public void setData(List<Group> data) {this.data = data;}

}//class closing

    package org.test;
    
    import java.util.List;
    
    import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
    import com.fasterxml.jackson.annotation.JsonProperty;
    
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Group {
    
        @JsonProperty(value = "group_id")
        private int id=-1;
        
        @JsonProperty(value = "name")
        private String name;
        
        @JsonProperty(value = "description")
        private String description;
        
        @JsonProperty(value = "values")
        private List<InnerGroup> values;
    
        public int getId() {return id;}
        public void setId(int id) {this.id = id;}
    
        public String getName() {return name;}
        public void setName(String name) {this.name = name;}
    
        public String getDescription() {return description;}
        public void setDescription(String description) {this.description = description;}
    
        public List<InnerGroup> getValues() {return values;}
        public void setValues(List<InnerGroup> values) {this.values = values;}
    
      }//class closing

package org.test;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class InnerGroup {
    
    @JsonProperty(value = "inner_group_id")
    private int id=-1;
    
    @JsonProperty(value = "removeclass_id")
    private List<Integer> removeClassIds;
    
    @JsonProperty(value = "addclass_id")
    private List<Integer> addClassIds;

    public int getId() {return id;}
    public void setId(int id) {this.id = id;}

    public List<Integer> getRemoveClassIds() {return removeClassIds;}
    public void setRemoveClassIds(List<Integer> removeClassIds) {this.removeClassIds = removeClassIds;}

    public List<Integer> getAddClassIds() {return addClassIds;}
    public void setAddClassIds(List<Integer> addClassIds) {this.addClassIds = addClassIds;}

}//class closing

解析器 Class

package org.test;

import java.io.File;
import java.io.FileInputStream;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonParseTest {

    public static void main(String[] args) throws Exception{
        
        ObjectMapper mapper=new ObjectMapper();
        
        File jsonFile=new File("D:\\etc\\testworkspace\\ExpJavaProject\\etc\\str.json");
        try(FileInputStream fis=new FileInputStream(jsonFile)){
            
            GroupContainer container=mapper.readValue(fis, GroupContainer.class);
            
            //Test =================================
            System.out.println(container.getData());
            
            for(Group g:container.getData()) {

                System.out.println("Group Name --> "+g.getName());
                for(InnerGroup ig:g.getValues()) {
                    
                    System.out.println("\t\tInner Grp. ID --> "+ig.getId());
                    
                }//for closing
                
            }//for closing
            //END-Test =================================
            
        }catch(Exception e) {e.printStackTrace();}

    }//main closing

}//class closing

注意:在选择的文件中添加上面原始帖子中提供的 JSON 并在解析器 class 中相应地更改路径以进行测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM