GSON.
GSON 需要用创建gson对象来进行解析。而fastJSON是静态方法用类对象来解析。
Gson gson = new Gson();
Weather weather = gson.fromJson(str, Weather.class);
System.out.println(weather.getResult());
如果遇到{ 1000: 一万} ## 添加注解。
@SerializedName(“10000”)
private String text;
如果对版本进行要求。
在属性前面加注解,
@Since(1.1)
@Until(1.2)
private int error_code;
创建gson对象
Gson gson = new GsonBuilder().setVersion(1.1).create();
Weather weather = gson.fromJson(str, Weather.class);
System.out.println(weather.getResult());
属性的版本包含在创建对象设置的版本时属性才可用。
如果遇到{ location :[ 50, 100]}
直接定义 private int[] location;
如果有Canlendar属性,需要自定义适配器。
写个类继承 extends TypeAdapter<> 。
属性前加注解
@JsonAdapter(CalnlendarTypeAdapter.class)
private Calendar time;
适配器
public class CalnlendarTypeAdapter extends TypeAdapter<Calendar> {
@Override
public void write(JsonWriter jsonWriter, Calendar calendar) throws IOException {
if (calendar == null) {
jsonWriter.nullValue();
} else {
jsonWriter.value(calendar.getTimeInMillis());
}
}
@Override
public Calendar read(JsonReader jsonReader) throws IOException {
if (jsonReader.hasNext()) {
long l = jsonReader.nextLong();
Calendar instance = Calendar.getInstance();
instance.setTimeInMillis(l);
return instance;
}
return null;
}
}
将对象转化成JSON型数据
String s = gson.toJson(weather);