【问题标题】:Iterate over JSON and add the list array into the object/array遍历 JSON 并将列表数组添加到对象/数组中
【发布时间】:2019-11-04 20:17:09
【问题描述】:

我有这两个JSON 数组:

{ 
  "Person": {
    "Info": [
      "name": "Becky",
      "age": 14
    ]
   },
  "Fruits": [
    {
      "name": "avocado",
      "organic": true
    },
    {
      "name": "mango",
      "organic": true
    }
  ],
  "Vegetables": [
    {
      "name": "brocoli",
      "organic": true
    },
    {
      "name": "lettuce",
      "organic": true
    }
  ]
}

我想要做的是使用JacksonGson 库让一切看起来都很漂亮。

类似的东西。这适用于Gson。所以我想要的输出是:

{ 
  "Person": {
    "Info": [
      "name":"Becky",
      "age": 14
    ]
  },
  "FruitsList": {
    "Fruits": [
      {
        "name": "avocado",
        "organic": true
      },
      {
        "name": "mango",
        "organic": true
      }
    ]
  },
  "VegetablesList": {
    "Vegetables": [
      {
        "name": "brocoli",
        "organic": true
      },
      {
        "name": "lettuce",
        "organic": true
      }
    ]
  }
}

我已将我的课程设置为:

class Person{
   private List<Info> InfoList;
   //Set and get were set
}

class Info{
   private String name;
   private int age;
   //Set and get were set
}

class Fruits{
   private String name;
   private boolean organic;
   //Set and get were set
   public String toString(){
            return "Fruits:{" +
            "name:'" + name+ '\'' +
            ", organic:" + organic+'\''+
            '}';
   }
 }

 class Vegetables{
   private String name;
   private boolean;
   //Set and get were set
   public String toString(){
            return "Fruits:[" +
            "name:'" + name+ '\'' +
            ", organic:" + organic+'\''+
            ']';
   }
 }

class rootFinal{
    private List<Fruits> fruitList;
    private List<Vegetables> vegetablesList;
    private List<Person> personList;
    //Set and get were set
}

class mainJson{
   final InputStream fileData = ..("testPVF.json");

   ObjectMapper map = new Ob..();
   rootFinal root = map.readValue(fileData,rootFinal.class);
   // I can access each class with 
   System.out.printl(root.getHeaderList.get(0));
}

这输出...

[Fruit{name:'avocado', organic:true}, Fruit{name:'mango', organic:true}]

但这不是我想要的。

我正在尝试对 JSON 文件进行迭代,或者是否有更好的方法来检查数组是否存在。向其中添加其他对象/数组。

如果我找到VegFruit,我想以某种方式添加VegListFruitList,如图所示。它应该忽略"Person": {},因为它位于{} 符号中。

有没有办法用Gson 做到这一点?

【问题讨论】:

    标签: java json gson deserialization json-deserialization


    【解决方案1】:

    如果我理解正确,您想使用 JSON Object 节点包装每个 JSON Array 节点。为此,您不需要使用POJO 模型,您可以将JSON 有效负载读取为ObjectNode 并使用它的API 来更新它。

    杰克逊

    Jackson 库的简单示例:

    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import com.fasterxml.jackson.databind.node.ObjectNode;
    
    import java.io.File;
    import java.util.Iterator;
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    public class JsonObjectApp {
    
        public static void main(String[] args) throws Exception {
            File jsonFile = new File("./resource/test.json").getAbsoluteFile();
    
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
    
            ObjectNode root = (ObjectNode) mapper.readTree(jsonFile);
    
            Map<String, JsonNode> valuesToAdd = new LinkedHashMap<>();
    
            // create fields iterator
            Iterator<Map.Entry<String, JsonNode>> fieldsIterator = root.fields();
            while (fieldsIterator.hasNext()) {
                Map.Entry<String, JsonNode> entry = fieldsIterator.next();
    
                // if entry represents array
                if (entry.getValue().isArray()) {
                    // create wrapper object
                    ObjectNode arrayWrapper = mapper.getNodeFactory().objectNode();
                    arrayWrapper.set(entry.getKey(), root.get(entry.getKey()));
    
                    valuesToAdd.put(entry.getKey(), arrayWrapper);
    
                    // remove it from object.
                    fieldsIterator.remove();
                }
            }
    
            valuesToAdd.forEach((k, v) -> root.set(k + "List", v));
    
            System.out.println(mapper.writeValueAsString(root));
        }
    }
    

    上面的代码打印为您的JSON

    {
      "Person" : {
        "Info" : [ {
          "name" : "Becky",
          "age" : 14
        } ]
      },
      "FruitsList" : {
        "Fruits" : [ {
          "name" : "avocado",
          "organic" : true
        }, {
          "name" : "mango",
          "organic" : true
        } ]
      },
      "VegetablesList" : {
        "Vegetables" : [ {
          "name" : "brocoli",
          "organic" : true
        }, {
          "name" : "lettuce",
          "organic" : true
        } ]
      }
    }
    

    格森

    我们可以使用Gson 库实现非常相似的解决方案:

    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.google.gson.JsonElement;
    import com.google.gson.JsonObject;
    
    import java.io.File;
    import java.io.FileReader;
    import java.util.Iterator;
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    public class GsonApp {
    
        public static void main(String[] args) throws Exception {
            File jsonFile = new File("./resource/test.json").getAbsoluteFile();
    
            Gson gson = new GsonBuilder()
                    .setPrettyPrinting()
                    .create();
    
            try (FileReader reader = new FileReader(jsonFile)) {
                JsonObject root = gson.fromJson(reader, JsonObject.class);
    
                Map<String, JsonElement> valuesToAdd = new LinkedHashMap<>();
    
                // create fields iterator
                Iterator<Map.Entry<String, JsonElement>> fieldsIterator = root.entrySet().iterator();
                while (fieldsIterator.hasNext()) {
                    Map.Entry<String, JsonElement> entry = fieldsIterator.next();
                    // if entry represents array
                    if (entry.getValue().isJsonArray()) {
                        // create wrapper object
                        JsonObject arrayWrapper = new JsonObject();
                        arrayWrapper.add(entry.getKey(), root.get(entry.getKey()));
    
                        valuesToAdd.put(entry.getKey(), arrayWrapper);
    
                        // remove it from object.
                        fieldsIterator.remove();
                    }
                }
    
                valuesToAdd.forEach((k, v) -> root.add(k + "List", v));
    
                System.out.println(gson.toJson(root));
            }
        }
    }
    

    输出是一样的。

    【讨论】:

    • 这太棒了!谢谢!这比我做的要简单得多。我在硬编码这个。
    • 信誉不高。对不起。刚开始用这个。对不起。
    • 您将如何使用 GSON 执行此操作?有没有办法用 GSON 做到这一点?
    【解决方案2】:

    查看Get Pretty Printer

    同时检查specific APIs for Pretty Printing

    示例代码:

    //This example is using Input as JSONNode
    //One can serialize POJOs to JSONNode using ObjectMapper.
    ObjectMapper mapper = new ObjectMapper();
    mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
    					inputNode)

    【讨论】:

      猜你喜欢
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      相关资源
      最近更新 更多