我在文件中有以下json内容。
[
{
"prjId": 1,
"name" : "ABC",
"issueCounter": 7,
"issue": [
{
"id": 1,
"status" : "Closed",
"comment" : "blah blah blah",
"loggedBy": "shdkjdlsj"
},
{
"id": 2,
"status" : "Open",
"comment": "nothing",
"loggedBy": "xyz"
}
]
},
{
"prjId": 2,
"name" : "XYZ",
"issueCounter": 7,
"issue": [
{
"id": 3,
"status" : "Closed",
"comment": "jjjjjjjj",
"loggedBy": "klwm"
},
{
"id": 4,
"status" : "Closed",
"comment": "test test test",
"loggedBy": "NACK"
}
]
}]
我能够解析这个文件然后遍历这个json来到我希望更新的节点。到达那一点,我对如何更新它感到困惑,以便它反映在文件系统上的文件。
JSONParser parser = new JSONParser();
JSONArray rootArray = (JSONArray) parser.parse(new FileReader(pathToFile+fileName));
JSONObject project=null;
for (Object rootEntry : rootArray)
{
project = (JSONObject) rootEntry;
if( 1 == (Long) project.get("prjId"))
{
JSONArray issueArray = (JSONArray) project.get("issue");
for (Object issueEntry : issueArray)
{
JSONObject issue = (JSONObject) issueEntry;
System.out.println((Long) issue.get("id"));
if(2==(Long) issue.get("id"))
{
//now update the "comment" attribute here.
System.out.println("updated the comment: "+trckParam.getComment());
}
}
}
我只有json阅读器,所以我构建一个String as-当我遍历节点时,当我到达我需要更新的点时,我更新它(并构造其余的节点)这个json对象,(不要从循环中断))然后将整个重构的字符串写入同一个文件?或者有更好的方法我可以遍历JSONObject,一旦我更新它,将整个对象推送到一个文件而不构建整个文件的字符串。
我仍然需要找到一种方法来采取任何一种方法。所以任何指针或方向都会非常有用。