GSON

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值