【发布时间】:2020-06-26 04:03:04
【问题描述】:
我拥有的 Json 数据。
[
{
"code": "24",
"name": "Rajsathan",
"districts": [
{"code":"1",
"name":"Jodhpur"},
{"code":"2",
"name":"Nagore"}
]
}
]
从文件中读取数据作为输入流。
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Gson gson = new Gson();
String temp = null;
String total = null;
try {
while((temp = br.readLine()) != null) {
total+=temp;
}
} catch (Exception e){
e.printStactTrace();
}
现在我尝试了许多不同的方法来将此数据转换为 java 对象,但是在从 streamreader 转换每个流时传递完整的字符串总数或格式错误的 json 错误时得到 null。
StatesModel data = gson.fromJson(total, StatesModel.class);
// as its a list of json
Type collectionType = new TypeToken<Collection<StatesModel>>(){}.getType();
Collection<StatesModel> json_data = gson.fromJson(total, collectionType);
但两者都不起作用。
statesModel 的 Java 类定义如下。
public class StatesModel {
@SerializedName("code")
public String code;
@SerializedName("name")
public String name;
@SerializedName("districts")
public List<DistrictModel> districts;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DistrictModel> getDistricts() {
return districts;
}
public void setDistricts(List<DistrictModel> districts) {
this.districts = districts;
}
}
还有区类模型存在。
public class DistrictModel {
@SerializedName("code")
public String code;
@SerializedName("name")
public String name;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
将这些数据转换为可迭代的 javaObjects 的正确方法是什么?
【问题讨论】:
-
将对从文件读取的数据进行改造,我可以选择编辑 json 格式,因为数据存储在本地文件中。
-
为了测试,在你使用 String str = "[{\"code\":\"24\",\"name\"... ";所以你不必担心文件。还要删除所有地区的东西,以使问题更小,更专注于(当前)json问题。