我用折叠代码创建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"
}
}发布于 2021-10-15 11:31:40
您只需要添加另一个类型为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"
}
}https://stackoverflow.com/questions/69583970
复制相似问题