我正在尝试使用GSON将下一个字符串资源映射到我自己的“ Studies” POJO类中。
<string name="b">
{
"Id": 4,
"IdUser": 1,
"PathPics": "G:\\dariop\\SRC\\000.Pers\\007.Tomas Mosquera\\Estudios\\18-001_246",
"Name": "18-001_246",
"Description": "Estudio generado al seleccionar carpeta de imagenes",
"Active": true,
"Sincronizado": false,
"DateUpd": "2018-04-25T08:34:09.607",
"pics": [{
"IdStudiesPic": 26,
"IdStudies": 4,
"Path": "C:\\DRS_Homologacion\\Studies\\18-001_246\\001_CA.jpg",
"Name": "001_CA.jpg",
"Sincronizada": false,
"DateUpd": "2018-05-27T19:27:21.743",
"Id": 26,
"Active": false
}, {
"IdStudiesPic": 27,
"IdStudies": 4,
"Path": "C:\\DRS_Homologacion\\Studies\\18-001_246\\002_TA.jpg",
"Name": "002_TA.jpg",
"Sincronizada": false,
"DateUpd": "2018-05-27T19:27:49.79",
"Id": 27,
"Active": false
}],
"paciente": {
"Id": 246,
"dni": 28095876,
"Name": "Prueba 3",
"Lastname": "Prueba 3",
"Telephone": "11547658900",
"Email": "prueba3@gmail.com",
"Coment": "",
"DateUpd": "2018-04-25T08:33:46",
"Birthday": "1990-05-13T00:00:00",
"GenderType": "M",
"genero": null,
"Active": true,
"fototipo": {
"Id": 2,
"Fototipo": "II",
"TonoPielColorOjos": "Piel clara y ojos azules",
"ColorCabello": "Rubio",
"QuemaduraSolar": "Habitualmente",
"Bronceado": "Ligero, descamación",
"Active": true
},
"IdFototipo": 2
},
"IdPatient": 246,
"Imagen": null,
"Lesiones": null,
"NombrePaciente": null
}
</string>
使用
String b = getResources().getString(R.string.b);
Gson gson = new Gson();
Studies study = gson.fromJson(b, Studies.class);
但是我遇到了这个错误:
MalformedJsonException: Unterminated object at line 1 column 33 path $.PathPics
我知道空格可能是这里的问题,但我无法解决问题(不幸的是,修改字符串不是一种选择)。同样,双\可能会引入一些不良行为。
您能帮助我实现这一目标吗?
答案 0 :(得分:1)
问题是JSON字符串不能放在strings.xml
内。您需要将字符串保存到res/raw
内的 raw 目录中。在目录内创建一个文件,例如: myfile.json 。因此路径将为res/raw/myfile.json
。然后使用以下代码在您的代码中打开它:
// open the resource from raw file
InputStream ins = getResources().openRawResource(R.raw.myfile);
try {
Reader reader = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
Writer writer = new StringWriter();
int size;
char[] buffer = new char[1024];
// read the whole file to a writer.
while ((size = reader.read(buffer)) >= 0) {
writer.write(buffer, 0, size);
}
// now we have the string
String json = writer.toString();
Gson gson = new Gson();
// translate it to the object.
Studies study = gson.fromJson(json, Studies.class);
// Now you have the correct object translated from the json file.
} catch (IOException e) {
e.printStackTrace();
// Error!! Do something here. Please don't ignore me.
}