我正在学习参与并试图让它成为现实。 发现了很多类似的问题和更多的解决方案,但没有任何帮助我
那是我的json
{
"firstName": "name",
"lastName": "last",
"resistances": {
"a1": 1,
"a2": 2,
"a3": 3,
"a4": 4
}
}
Player.class
class Player implements Serializable{
String firstName;
String lastName;
int[] resistances;
public Player(String firstName, String lastName, int[] resistances) {
this.firstName = firstName;
this.lastName = lastName;
this.resistances = resistances;
}
}
以及我如何尝试parce
Gson gson = new Gson();
Player player = gson.fromJson("test.json", Player.class);
SOS
答案 0 :(得分:1)
您的JSON“抵抗”对象应如下所示,以便您的解析代码能够正常工作:
{
"firstName": "name",
"lastName": "last",
"resistances": [
1, 2, 3, 4
]
}
或者,将Java中的resistances变量更改为Map。 Look here for a previous answer - GSON可以将字典JSON对象解析为Map。
class Player implements Serializable {
String firstName;
String lastName;
Map<String, Integer> resistances;
public Player(String firstName, String lastName, Map<String, Integer> resistances) {
this.firstName = firstName;
this.lastName = lastName;
this.resistances = resistances;
}
}
答案 1 :(得分:1)
fromJson(String, Class)解析String本身,在您的情况下test.json
,而不是它所代表的文件。您需要从您尝试解析的文件中创建一个Reader,并将其作为第一个参数传递。
如果test.json在外部存储中:
String fpath = Environment.getExternalStorageDirectory() + "/path/to/test.json";
try {
FileReader fr = new FileReader(fpath));
gson.fromJson(fr, Player.class);
} catch (Exception e1) {
e1.printStackTrace();
}