有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java写入JSON文件

我正在使用json文件开发一个安卓应用程序,以存储应用程序使用的数据。 我在资产文件夹中有一个Json文件,包括一个对象“plants”。 在仪表板上。java文件,我想向json文件添加一个对象。 我使用put()函数尝试了这个方法,但我似乎没有在实际文件中编写。 仪表板爪哇:

            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

  ]
}

共 (1) 个答案

  1. # 1 楼答案

    我认为不可能在运行时写入/assetscheck this answer

    尝试使用特定于应用程序的文件docs

    对JSON进行更改。从文件(字符串数据)读取并初始化JSONobject

    JSONObject obj = new JSONObject("string from your file")

      JSONObject jsonObject = new JSONObject("data from file");
      JSONArray jsonArray =  jsonObject.getJSONArray("plants");
    
      JSONObject jsonObj = new JSONObject();
      jsonObj.put("name", name);
      jsonObj.put("description", description);
      jsonObj.put("cameralink", url);
    
      jsonArray = jsonArray.put(jsonObj);
      jsonObject = jsonObject.put("plants", jsonArray);
    
      //convert json object to string
      String data = jsonObject.toString();
    
      FileOutputStream fout = context.openFileOutput(filename, Context.MODE_PRIVATE);
      fout.write(data.getBytes());