繁体   English   中英

如何以编程方式将数据写入 JSON 文件然后保存?

[英]How to programmatically write data to a JSON file and then save it?

我想以编程方式将以下数据放入 Android Studio 中的 JSON 文件中:

[{
    "title":"Olu4a такси",
    "logo":"Taxi/olu4a.jpg",
    "color":"#FFD916",
    "textcolor":"#000000",
    "number":"7000",
    "bigimage":"Taxi/olu4a_car.jpg",
    "star":"4.0"
},
{
    "title":"Asia Express такси",
    "logo":"Taxi/d.jpg",
    "color":"#E7232D",
    "textcolor":"#ffffff",
    "number":"1616",
    "bigimage":"Taxi/asiaexpress.jpg",
    "star":"3.5"
}]

怎么做到呢?

例子

JSONObject obj = new JSONObject(); 

try { 
     obj.put("id", "3"); 
     obj.put("name", "NAME OF STUDENT"); 
     obj.put("year", "3rd"); 
     obj.put("curriculum", "Arts"); 
     obj.put("birthday", "5/5/1993"); 
} catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
} 

例如,只需使用 FileWriter 保存到 ExternalFilesDir

public void save(Context context, String jsonString) throws IOException {
  File rootFolder = context.getExternalFilesDir(null);
  File jsonFile = new File(rootFolder, "file.json");
  FileWriter writer = new FileWriter(jsonFile);
  writer.write(jsonString);
  writer.close();
  //or IOUtils.closeQuietly(writer);
}

在将对象序列化为 json 格式时,通常需要使用JsonWriter

如果您要做的只是使用您在此处编写的特定内容编写一个文件,您可以使用FileWriter

File file = new File(Environment.getExternalStorageDirectory(), filename);

FileWriter writer = new FileWriter(file);
writer.append(jsonString);
writer.flush();
writer.close();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM