如何使用Java更新JSON文件中的嵌套JSON对象?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用Java更新JSON文件中的嵌套JSON对象?相关的知识,希望对你有一定的参考价值。
我有一个包含User对象数组的JSON文件。每个User对象都包含一个包含对象的Goals数组,每个Goal对象中都有一个包含1到多个里程碑对象的Milestone数组。
我能够利用JSON-Simple轻松地解析它们并以Java对象的形式存储信息,但我发现重写JSON文件中的某些块或附加到其中一个数组很有挑战性。我在网上找到的例子过于简单,并没有考虑到这么多的嵌套。
如果我想在我的JSON文件或里程碑数组中的特定里程碑中重写Goal对象,我将如何根据相应Java对象模型中指定的属性更新文件?是否可以在其中一个数组中的JSON文本文件中修改/附加特定块?
[
{
"username": "example",
"password": "pwd",
"Goals":[
{
"goalId": "G0001",
"goalName": "COEN 275 Midterm",
"startDate": "02/14/2017",
"endDate": "02/28/2017",
"numMilestones": 5,
"color": "#4286f4",
"hoursPerDay": 4,
"milestones":[
{
"milestoneName": "Chapter 1",
"Difficulty": "E",
"dueDate": "02/18/2018",
"completed": true
},
{ "milestoneName": "Chapter 2",
"Difficulty": "E",
"dueDate": "02/22/2018",
"completed": true
},
{ "milestoneName": "Chapter 3",
"Difficulty": "M",
"dueDate": "02/23/2018",
"completed": true
},
{ "milestoneName": "Chapter 4",
"Difficulty": "M",
"dueDate": "02/25/2018",
"completed": false
},
{ "milestoneName": "Chapter 5",
"Difficulty": "H",
"dueDate": "02/28/2018",
"completed": false
}
]
}
]
},
{
"username": "username",
"password": "pwd",
"Goals":[
{
"goalId": "G0001",
"goalName": "COEN 279 Midterm",
"startDate": "02/14/2017",
"endDate": "02/28/2017",
"numMilestones": 5,
"color": "#4286f4",
"hoursPerDay": 4,
"milestones":[
{
"milestoneName": "Chapter 5",
"Difficulty": "E",
"dueDate": "02/18/2018",
"completed": true
},
{ "milestoneName": "Chapter 6",
"Difficulty": "E",
"dueDate": "02/22/2018",
"completed": true
},
{ "milestoneName": "Chapter 7",
"Difficulty": "M",
"dueDate": "02/23/2018",
"completed": true
},
{ "milestoneName": "Chapter 11",
"Difficulty": "M",
"dueDate": "02/25/2018",
"completed": false
},
{ "milestoneName": "Chapter 12",
"Difficulty": "H",
"dueDate": "02/28/2018",
"completed": false
}
]
}
]
}
]
答案
JSON中的数组简单是JSONArray类型的类(这只是一个java util ArrayList),所以一旦得到数组和对象(这是一个java util HashMap),你就可以修改它。
JSONArray users = (JSONArray) JSONValue.parse(json);
JSONObject firstUser = (JSONObject) users.get(0);
JSONArray firstUserGoals = (JSONArray) firstUser.get("Goals");
JSONObject firstUserFirstGoal = (JSONObject) firstUserGoals.get(0);
JSONArray firstUserFirstGoalMilestones = (JSONArray) firstUserFirstGoal.get("milestones");
JSONObject firstUserFirstGoalFirstMilestone = (JSONObject) firstUserFirstGoalMilestones.get(0);
因此,您可以编辑里程碑
firstUserFirstGoalFirstMilestone.put("milestoneName", "Chapter 0");
您可以创建新的里程碑
JSONObject milestone1 = new JSONObject();
milestone1.put("milestoneName", "Chapter 1");
milestone1.put("Difficulty", "H");
milestone1.put("dueDate", "02/18/2018");
milestone1.put("completed", true);
然后将其添加到位置1的里程碑列表中。如果未指定索引,则最后添加。
firstUserFirstGoalMilestones.add(1, milestone1);
最后,您可以将JSON作为字符串。
String finalJson = users.toJSONString();
或写入文件(应处理异常)
Writer writer = new FileWriter(path);
users.writeJSONString(writer);
writer.close();
以上是关于如何使用Java更新JSON文件中的嵌套JSON对象?的主要内容,如果未能解决你的问题,请参考以下文章