我有以下两个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
}
]
}
我想做的是使用Jackson
和Gson
库使所有内容看起来都很漂亮。
类似这样的事情。 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文件进行迭代,或者尝试以某种方式检查数组是否存在。向其中添加其他对象/数组。
如果我发现Veg
或Fruit
,我想以某种方式添加VegList
和FruitList
,如图所示。由于它位于"Person": {}
符号中,因此应忽略{}
。
是否可以使用Gson
来做到这一点?
答案 0 :(得分:2)
如果我对您的理解正确,那么您想使用JSON Array
节点包装每个JSON Object
节点。为此,您无需使用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));
}
}
}
输出相同。
答案 1 :(得分:0)
还要检查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)