【发布时间】:2020-04-26 10:39:48
【问题描述】:
我正在使用 json 文件开发一个 android 应用程序,以便存储应用程序使用的数据。 我在资产文件夹中有一个 Json 文件,其中包括一个对象“植物”。 在 Dashboard.java 文件中,我想将一个对象添加到 json 文件中。 我通过使用 put() 函数尝试了这个,但我似乎没有在实际文件中写入。 仪表板.java:
String name = intent.getStringExtra(AddAPlant.EXTRA_TEXT1);
String description = intent.getStringExtra(AddAPlant.EXTRA_TEXT2);
String url = intent.getStringExtra(AddAPlant.EXTRA_TEXT3);
JSONObject jsonObj= new JSONObject();
try {
jsonObj.put("name", name);
jsonObj.put("description", description);
jsonObj.put("cameralink", url);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
plantArray = new JSONArray();
plantArray.put(jsonObj);
资产文件夹中的Json文件:
{
"plants": [
{
"name": "Pepper",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam1-snapshots/gallery-images/latest.png"
},
{
"name": "Tomatoe",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam2-snapshots/gallery-images/latest.png"
},
{
"name": "Small Tomato",
"decription": "It needs a lot of water",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam3-snapshots/gallery-images/latest.png"
}
]
}
期望的输出:
{
"plants": [
{
"name": "Pepper",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam1-snapshots/gallery-images/latest.png"
},
{
"name": "Tomatoe",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam2-snapshots/gallery-images/latest.png"
},
{
"name": "Small Tomato",
"decription": "It needs a lot of water",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam3-snapshots/gallery-images/latest.png"
},
{
"name": name,
"decription": description,
"CameraLink": url
]
}
【问题讨论】:
-
您首先需要通过从 json 文件中解析其内容来实例化
plantArray。您可以在此问题的答案中找到有关如何操作的说明:How to parse JSON array from file?