我正在创建一个导入和导出相同键的JSON的应用程序。导入JSON文件会经常更改,我不想每次JSON文件添加新密钥时都更新应用程序。
这是针对Java Swing应用程序的。用户将能够修改存在的导入JSON字段并将其应用于导出JSON。
Fruit.java
public class Fruit {
private String name;
private String description;
private int price;
private String[] colors;
public Fruit(JSONObject obj) {
this.name = obj.optString("name");
this.description = obj.optString("description");
this.price = obj.optInt("price");
JSONArray jArr = obj.optJSONArray("colors");
String[] sArr = new String[jArr.length()];
for(int i = 0; i < sArr.length; i++) {
sArr[i] = jArr.optString(i);
}
this.colors = sArr;
}
}
初始导入JSON
{
"name": "Apple",
"description":"It is delicious",
"price": 20,
"colors":["red","green","yellow"]
}
未来导入JSON
{
"name": "Apple",
"description":"It is delicious",
"price": 20,
"colors":["red","green","yellow"],
"fruit": true,
"types": ["gala", "fuji", "golden delicious", "honeycrisp"],
"soldAt": ["Corner Store", "Farmers Market", "Walmart"]
}
注意:导出JSON将具有与导入JSON完全相同的格式。
未来导出的JSON
{
"name": "Apple",
"description":"It is very delicious",
"price": 5,
"colors":["red","green","yellow"],
"fruit": true,
"types": ["gala", "fuji", "golden delicious", "honeycrisp", "red delicious"],
"soldAt": ["Corner Store", "Farmers Market"]
}
我想知道使用org.json库将新密钥添加到导出JSON的最佳方法是什么?