【问题标题】:Read / Parse JSON objects from .ser file in Android从 Android 中的 .ser 文件读取/解析 JSON 对象
【发布时间】:2015-09-12 15:44:44
【问题描述】:

我的 sdcard 中有一个文件,扩展名为 abc.ser,该文件包含 JSON 对象,如

{"music":"abc","highqualityavailable":"true","cacheable":"true"}
{"music":"xyz","highqualityavailable":"false","cacheable":"true"}
{"music":"aaa","highqualityavailable":"true","cacheable":"true"}
{"music":"bbb","highqualityavailable":"false","cacheable":"true"}
{"music":"ccc","highqualityavailable":"true","cacheable":"true"}

该文件包含 JSON 对象但不是 JSON 的正确格式我如何在我的应用程序中读取或解析它我已经读取了文件中的字符串但不知道如何将其转换为 POJO

 String root = Environment.getExternalStorageDirectory().getAbsolutePath();

                File file = new File(root+"/tmp/playerSongsString.ser");

                if (file.exists()) {


                    FileInputStream stream = null;

                    try {

                        stream = new FileInputStream(file);
                        FileChannel fc = stream.getChannel();
                        MappedByteBuffer bb =    fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
                      /* Instead of using default, pass in a decoder. */
                        jString = Charset.defaultCharset().decode(bb).toString();

                        JSONObject object = new JSONObject(jString);

                        Log.d("json:",jString);




                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

【问题讨论】:

  • 如果您可以修复这些文件以获得正确的 JSON 格式数据,这将大大简化您的任务。
  • 是的,我知道,但该文件是由其他应用程序创建的,我无法控制它
  • 如果你确定文件很小,你可以直接使用JSONObject object = new JSONObject("["+jString+"]");
  • 要将 JSONObject 解析为 POJO,您可以参考 this tutorial.

标签: java android json serialization deserialization


【解决方案1】:

首先更改您的 JSON 数据,它的 JSON 格式不正确...

[{"music":"abc","highqualityavailable":"true","cacheable":"true"}, {"music":"xyz","highqualityavailable":"false","cacheable":"true"},{"music":"aaa","highqualityavailable":"true","cacheable":"true" },{"music":"bbb","highqualityavailable":"false","cacheable":"true"},{"music":"ccc","highqualityavailable":"true","cacheable":"真"}]

然后将字符串转换为 JSON 数组。

更多详情:How to parse json parsing Using GSON in android

【讨论】:

  • 我可以附加方括号,但我没有,对象之间也没有逗号
  • 如果你不在两个对象之间附加逗号,那么它不会被视为 JSON 数组。
猜你喜欢
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2019-11-25
相关资源
最近更新 更多