java - Android:如何将 JSON 数组解析为字符串

标签 java android json string parsing

我需要使用的 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() 并将其用作数组的值。

您的选择是:

  1. Person 上实现类似 toJSONObject() 的东西,它返回 PersonJSONObject 表示>(例如,一个 JSONObject,当转换为 JSON 时,结果类似于 {"fName":"Bob","lName":"Smoe","info":"is高”)。然后,使用 put(peopleList.get(i).toJSONObject() 填充 JSONArray

  2. 使用比 org.json 类更复杂的东西,例如 Gson。

此外,Andreas 的注释是正确的。您没有解析 JSON。您正在生成 JSON。解析 JSON 会将包含 JSON 的 String 转换为 Person 对象。

关于java - Android:如何将 JSON 数组解析为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38964515/

相关文章:

java - 由于主键,数据库插入速度慢

android - 通过相机点击后如何将图片保存在 ImageView 中?

C: JSON 处理器

java - 存储具有多个元素的元素

java - 使用公共(public)方法更改 Java 中的私有(private)字段

安卓 2.1 : windowSoftInputMode ="adjustResize" not working properly with ListView

java - 无法实例化 Activity ComponentInfo; java.lang.NullPointerException

JSON 嵌套动态结构 Go 解码

python - django orm 组按 json 字段中的 json 键

java - 需要清理 Java 8 中的 ResponseEntity 主体