Gson(又称Google Gson)是Google公司发布的一个开放源代码的Java库,主要用途为串行化Java对象为JSON字符串,或反串行化JSON字符串成Java对象。
Gson当初是为因应Google公司内部需求而由Google自行研发而来,但自从在2008年五月公开发布第一版后已被许多公司或使用者应用。
解析没有数组数据的JSON数据
{ "name": "coolxing", "age": 24, "male": true, "address": { "street": "huiLongGuan", "city": "beijing", "country": "china" } }
使用GSON框架解析上面的json数据;
public class Person {
private String name;
private int age;
private boolean male;
private Address address;
}
public class Address {
public String street;
public String city;
public String country;
}
public static void main(String... args) {
Gson gson = new Gson();
String json = getJsonString();
Person person = gson.fromJson(json, Person.class);
}
解析带有数组的JSON数据
{ "error": 0, "status": "success", "date": "2014-09-30", "results": [ { "currentCity": "珠海", "weather_data": [ { "date": "周五(今天, 实时:19℃)", "dayPictureUrl": "http://day/dayu.png", "nightPictureUrl": "http://night/dayu.png", "weather": "大雨", "wind": "东南风5-6级", "temperature": "25℃" }, { "date": "周日", "dayPictureUrl": "http://day/zhenyu.png", "nightPictureUrl": "http://night/duoyun.png", "weather": "阵雨转多云", "wind": "西北风4-5级", "temperature": "21 ~ 28℃" } ] } ] }
解析上面的数据:
public class Status {
public String error;
public String status;
public String date;
public List<Results> results;
}
public class Results {
public String currentCity;
public List<Weather> weather_data;
}
public class Weather {
public String date;
public String dayPictureUrl;
public String nightPictureUrl;
public String weather;
public String wind;
public String temperature;
}
public static void main(String[] args) {
Gson gson = new Gson();
Status status = gson.fromJson(readJsonData(), Status.class);
}
使用以上注意属性的值要与json中的数据字段名字一模一样一一对应;
本文读取的是Java工程目录下的文本文件;
@SuppressWarnings("resource")
public static String readJsonData() {
InputStream is = null;
String result = null;
try {
is = new FileInputStream("msg.txt");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
try {
length = is.read(buffer);
while (length != -1) {
arrayOutputStream.write(buffer, 0, length);
length = is.read(buffer);
}
byte[] data = arrayOutputStream.toByteArray();
result = new String(data, "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
本文来自于CSDN博客,转载请联系作者;
注明出处 http://blog.csdn.net/dreamintheworld/article/details/39698555