创建JSON
package com.vince.json;
import com.google.gson.stream.JsonReader;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
/**
* []是数组开始解析用 ***.beginArray();
* {}是对象开始解析用 ***.beginObject();
*/
public class JSONDemo {
@Test
public void parseJSONNames(){
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/vince/json/names.json");
InputStreamReader in=new InputStreamReader(is);
//JSON的解析工具(解析器)
JsonReader reader=new JsonReader(in);
ArrayList<Name> list=new ArrayList<>();
try {
//开始解析JSON数组
reader.beginArray();
while (reader.hasNext()){
list.add(parseName((reader)));
}
//结束解析数组
reader.endArray();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(Arrays.toString(list.toArray()));
}
//解析对象 Name
private Name parseName(JsonReader jsonReader){
Name name=null;
try {
//开始解析对象
jsonReader.beginObject();
name=new Name();
while (jsonReader.hasNext()){
String attrName = jsonReader.nextName();
if("firstName".equals(attrName)){
name.setFirstName(jsonReader.nextString());//jsonReader.nextString()取值的方法,这里是字符串
}else if("lastName".equals(attrName)){
name.setLastName(jsonReader.nextString());
}else if("email".equals(attrName)){
name.setEmail(jsonReader.nextString());
}
}
//结束解析对象
jsonReader.endObject();
} catch (IOException e) {
e.printStackTrace();
}
return name;
}
}
Name类
package com.vince.json;
public class Name {
private String firstName;
private String lastName;
private String email;
public Name(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public Name() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Name{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
'}';
}
}
测试用例
[
{"firstName":"Vince","lastName":"Ma","email":"987456159@qq.com"},
{"firstName":"Similar","lastName":"Lin","email":"88886666@qq.com"}
]