![](/img/trans.png)
[英]How to modify the value of a particular field in a JSON file using json-simple, after parcing the JSON file
[英]How to add subnode to json file using json-simple
我使用以下代码创建 json 文件:
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
public class CreatingJSONDocument {
public static void main(String args[]) {
//Creating a JSONObject object
JSONObject jsonObject = new JSONObject();
//Inserting key-value pairs into the json object
jsonObject.put("ID", "1");
jsonObject.put("First_Name", "Shikhar");
try {
FileWriter file = new FileWriter("E:/output.json");
file.write(jsonObject.toJSONString());
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("JSON file created: "+jsonObject);
}
}
输出:
JSON file created: {
"First_Name":"Shikhar",
"ID":"1"}
如何将 java 映射的内容作为新节点添加到此 json 输出中,以便最后得到以下输出:
JSON file created: {
"First_Name":"Shikhar",
"ID":"1",
"data": {
"a": "Test1",
"b": "Test2"
}
}
您只需要添加另一个 JsonObject 类型的对象,它就会这样做
//...
jsonObject.put("ID", "1");
jsonObject.put("First_Name", "Shikhar");
jsonObject.put("data", new JSONObject(data));
//...
这将返回您想要的输出
如果您需要在没有对象的情况下添加更多字段,请执行以下操作:
JSONObject mainFields = new JSONObject();
mainFields.put("id", "1");
JSONObject secondFields = new JSONObject();
secondFields.put("field1", "some cool");
secondFields.put("field2", "not cool");
mainFields.put("data", secondFields);
这个回报:
{
"id":"1",
"data":{
"field1": "some cool",
"field2": "not cool"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.