[英]Iterate over JSON and add the list array into the object/array
我有這兩個JSON
arrays:
{
"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
。 所以我想要的 output 是:
{
"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
做到這一點?
如果我理解正確,您想使用JSON Object
節點包裝每個JSON Array
節點。 為此,您不需要使用POJO
model,您可以讀取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));
}
}
}
Output 相同。
檢查獲得漂亮的打印機
還要檢查漂亮打印的特定 API
示例代碼:
//This example is using Input as JSONNode //One can serialize POJOs to JSONNode using ObjectMapper. ObjectMapper mapper = new ObjectMapper(); mapper.writerWithDefaultPrettyPrinter().writeValueAsString( inputNode)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.