我有一个json字符串,其中包含一个对象数组(filters数组)。 json字符串也有其他对象和字段,但我只对解析json数组感兴趣。任何人都可以告诉我如何使用Gson做到这一点?
这是我的json文件:
{
name: "test json",
test_ob: {
name: "test"
}
filters[
{
test: 1,
test: 2,
...
}
...
]
}
和我的代码:
Filters filters = new Gson().fromJson(JSONcontent.toString(), Filters.class);
我的过滤器类:
public class Filters {
private List<Filter> filters;
public List<Filter> getFilters() {
return filters;
}
public void setFilters(List<Filter> filters) {
this.filters = filters;
}
}
答案 0 :(得分:0)
你的json有效吗?试试这个:
data.json:
{
name: "test json",
test_ob: {
name: "test"
},
filters: [
{
name: filter1,
value: 1
},
{
name: filter2,
value: 2
}
]
}
Filter.java:
public class Filter {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Data.java:
public class Data {
private List<Filter> filters;
public List<Filter> getFilters() {
return filters;
}
public void setFilters(List<Filter> filters) {
this.filters = filters;
}
}
Test.java:
public static void main(String[] args) {
Gson gson = new Gson();
Object obj;
try {
JsonParser parser = new JsonParser();
obj = parser.parse(new FileReader("C:\\data.json"));
JsonObject jsonObject = (JsonObject) obj;
Data data = gson.fromJson(jsonObject, Data.class);
} catch (JsonIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}