1)简单的json object 字符串
String jsonObjectStr = "{\"name\":\"zhangsan\",\"age\":\"18\"}";
2)json array 字符串
String jsonArrayStr = "[{\"name\":\"zhangsan\",\"age\":\"18\"},{\"name\":\"lisi\",\"age\":\"28\"}]";
3)稍微复杂点的json object 字符串
String jsonSpecialStr = "{\"school\":\"NanJingDaXue\",\"city\":\"najing\",\"peoples\":[{\"name\":\"zhangsan\",\"age\":\"18\"},{\"name\":\"zhangsan\",\"age\":\"18\"}]}";
1、首先新建一个maven工程,pom文件中引入gson的依赖项:
com.google.code.gson
gson
2.2.2
package com.zgy.json.info;
public class People
{
//name
private String name;
//age
private String age;
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("People [name=");
builder.append(name);
builder.append(", age=");
builder.append(age);
builder.append("]");
return builder.toString();
}
}
package com.zgy.json.info;
import java.util.Arrays;
import com.google.gson.annotations.SerializedName;
public class Students
{
private String school;
@SerializedName("city") //注解,当json字符串中的字段定义和所需的不同时,可用注解标注
private String city;
private People [] peoples;
/**
* @return the school
*/
public String getSchool()
{
return school;
}
/**
* @param school the school to set
*/
public void setSchool(String school)
{
this.school = school;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("Students [school=");
builder.append(school);
builder.append(", city=");
builder.append(city);
builder.append(", peoples=");
builder.append(Arrays.toString(peoples));
builder.append("]");
return builder.toString();
}
}
Code:
String jsonObjectStr = "{\"name\":\"zhangsan\",\"age\":\"18\"}";
Gson gson = new Gson();
People people = gson.fromJson(jsonObjectStr, People.class);
System.out.println(people.toString());
解析结果:
People [name=zhangsan, age=18]
4、json array 字符串的解析
Code:
String jsonArrayStr = "[{\"name\":\"zhangsan\",\"age\":\"18\"},{\"name\":\"lisi\",\"age\":\"28\"}]";
Gson gson = new Gson();
People[] peoples = gson.fromJson(jsonArrayStr, People[].class);
for (People x : peoples)
{
System.out.println(x.toString());
}
解析结果:
People [name=zhangsan, age=18]
People [name=lisi, age=28]
5、第三种复杂json
Code:
String jsonSpecialStr = "{\"school\":\"NanJingDaXue\",\"city\":\"nanjing\",\"peoples\":[{\"name\":\"zhangsan\",\"age\":\"18\"},
{\"name\":\"lisi\",\"age\":\"28\"}]}";
Gson gson = new Gson();
Students students = gson.fromJson(jsonSpecialStr, Students.class);
System.out.println(students.toString());
解析结果:
Students [school=NanJingDaXue, city=nanjing, peoples=[People [name=zhangsan, age=18], People [name=lisi, age=28]]]