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

mo49yndu  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(106)

我想以编程方式将以下数据放入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(); 
}

wz3gfoph

wz3gfoph1#

只需使用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);
}

字符串

wbrvyc0a

wbrvyc0a2#

在将对象序列化为json格式时,通常需要使用JsonWriter
如果你只是想写一个包含你在这里写的特定内容的文件,你可以使用FileWriter

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

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

字符串

2izufjch

2izufjch3#

我建议你把JSON路径作为输入,用JSPATH更新你的JSONObject,这样你就可以选择把它放在你想要的地方。

相关问题