场景一
没有头的Json数组
“e:/person”文件内容如下,文件中是没有头的json数组
[
{
"id" : 1,
"name" : "lzj",
"age" : 27
},
{
"id" : 2,
"name" : "Bob",
"age" : 20
},
{
"id" : 3,
"name" : "Terry",
"age" : 26
}
]
/*也可用JsonReader来实现*/
@Test
public void test1() throws FileNotFoundException{
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
FileReader fileReader = new FileReader("e:/person");
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(fileReader);
JsonArray asJsonArray = jsonElement.getAsJsonArray();
List<Person> persons = new ArrayList<Person>();
/*JsonArray继承自JsonElement,JsonArray是JsonElement数组形式*/
for(JsonElement elment : asJsonArray){
Person person = gson.fromJson(elment, Person.class);
persons.add(person);
}
System.out.println(persons);
}
运行程序,输出如下:
[Person [id=1, name=lzj, age=27], Person [id=2, name=Bob, age=20], Person [id=3, name=Terry, age=26]]
场景二
有头的Json数组
“e:/person1”文件中json字符串内容如下:
{
"persons" :[
{
"id" : 1,
"name" : "lzj",
"age" : 27
},
{
"id" : 2,
"name" : "Bob",
"age" : 20
},
{
"id" : 3,
"name" : "Terry",
"age" : 26
}
]
}
@Test
public void test2() throws FileNotFoundException{
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
FileReader fileReader = new FileReader("e:/person1");
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(fileReader);
JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("persons");
List<Person> persons = new ArrayList<Person>();
for(JsonElement elment : jsonArray){
Person person = gson.fromJson(elment, Person.class);
persons.add(person);
}
System.out.println(persons);
}
运行程序,输出如下
[Person [id=1, name=lzj, age=27], Person [id=2, name=Bob, age=20], Person [id=3, name=Terry, age=26]]
场景三
Json数组外含有其他Json字符串
“e:/person2”文件中字符串如下
{
"code" : 200,
"persons" :[
{
"id" : 1,
"name" : "lzj",
"age" : 27
},
{
"id" : 2,
"name" : "Bob",
"age" : 20
},
{
"id" : 3,
"name" : "Terry",
"age" : 26
}
]
}
@Test
public void test3() throws FileNotFoundException{
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
FileReader fileReader = new FileReader("e:/person2");
Persons persons = gson.fromJson(fileReader, Persons.class);
System.out.println(persons.getPersons());
}
运行程序,输出内容如下:
[Person [id=1, name=lzj, age=27], Person [id=2, name=Bob, age=20], Person [id=3, name=Terry, age=26]]
也可以用上一示例的方法进行解决,只是去获取“persons”中的内容就可以了。场景二中的代码只需要把读取的文件修改为“e:/person2”,拿过来可以直接使用。
附:
public class Person {
private int id;
private String name;
private int age;
/*省略set/get/toString方法*/
}
public class Persons {
private String code;
private List<Person> persons;
/*省略set/get/toString方法*/
}
*参考文章:
https://www.cnblogs.com/jianyungsun/p/6647203.html*
https://blog.csdn.net/chunqiuwei/article/details/49160321