我需要使用的 JSON 文件格式如下所示
[{"fName":"Bob","lName":"Smoe","info":"is tall"},{"fName":"Claire","lName":"Smoegan","info":"has a big forehead"}]
我有一个添加到 JSON 数组的人员对象列表。代码看起来像这样
for (int i = 0; i < peopleList.size(); i++){
try {
jArray.put(peopleList.get(i));
}catch (Exception e){
e.printStackTrace();
}
}
问题是,我需要将它转换为字符串以写入文件,但是当我使用“jArray.toString()”时它返回
"["com.example.zach.projectFile.Person@21b854e0", "com.example.zach.projectFile.Person@21b854e0", "com.example.zach.projectFile.Person@21b85400"....]
我如何得到它以上面要求的格式返回它?
最佳答案
您没有遵循 JSONArray
上的 put()
规则。该参数应该是:
a JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL, or null. May not be NaNs or infinities. Unsupported values are not permitted and will cause the array to be in an inconsistent state.
com.example.zach.projectFile.Person
不是这些。 JSONArray
正在做的是在您的 Person
对象上调用 toString()
并将其用作数组的值。
您的选择是:
在
Person
上实现类似toJSONObject()
的东西,它返回Person
的JSONObject
表示>(例如,一个JSONObject
,当转换为 JSON 时,结果类似于{"fName":"Bob","lName":"Smoe","info":"is高”
)。然后,使用put(peopleList.get(i).toJSONObject()
填充JSONArray
。使用比
org.json
类更复杂的东西,例如 Gson。
此外,Andreas 的注释是正确的。您没有解析 JSON。您正在生成 JSON。解析 JSON 会将包含 JSON 的 String
转换为 Person
对象。
关于java - Android:如何将 JSON 数组解析为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38964515/