【发布时间】: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