在Android中从.ser文件读取/解析JSON对象

kuhbmx9i  于 2023-03-24  发布在  Android
关注(0)|答案(2)|浏览(187)

我有一个文件在我的sd卡扩展名是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();
                        }
                    }
5jvtdoz2

5jvtdoz21#

首先更改您的JSON数据,它不是正确的JSON格式...
[{“音乐”:“abc”,“highqualityavailable”:“true”,“可缓存”:“true”},{“音乐”:“xyz”,“highqualityavailable”:“false”,“可缓存”:“true”},{“音乐”:“aaa”,“highqualityavailable”:“true”,“可缓存”:“true”},{“音乐”:“bbb”,“highqualityavailable”:“false”,“可缓存”:“true”},{“音乐”:“ccc”,“highqualityavailable”:“true”,“可缓存”:“true”}]
然后将字符串转换为JSON数组。
更多详情:How to parse json parsing Using GSON in android

vlju58qv

vlju58qv2#

此python代码仅用于将.ser文件转换为.json文件
文件:Opening files from this repository

with open('first-letters-root.ser', encoding="utf8") as f:
    w = f.read()
    
y = w.split('i:')[1:]
d = {}

for k,i in enumerate(y):
    j = i.split(';')[1].split(':')
    d[k] = j[-1]

import json
with open('first-letters-root.json', 'w') as f:
    json.dump(d, f)

info = open('first-letters-root.json')
res = json.load(info)
print(res)

相关问题