如何用Gson解析复杂的Json数据

 我来答
智者总要千虑
高粉答主

2018-01-09 · 说的都是干货,快来关注
知道顶级答主
回答量:7.9万
采纳率:88%
帮助的人:1.4亿
展开全部
你先定义类,然后使用Gson的fromJson方法转换成类。
下面是我的代码:
public class showapi_res_body {
private cityInfo cityInfo = new cityInfo();

private f1 f1 = new f1();

@Override
public String toString() {
return "showapi_res_body [cityInfo=" + cityInfo.toString() + ", f1=" + f1.toString() + "]";
}

}

public class day_weather_pic {
private int night_air_temperature = 19;
private String night_weather = "多云";
@Override
public String toString() {
return "day_weather_pic [night_air_temperature=" + night_air_temperature + ", night_weather=" + night_weather
+ "]";
}

}

public class f1 {
private String day="20150906";
private int day_air_temperature=3;
private String day_weather= "晴";
private day_weather_pic day_weather_pic = new day_weather_pic();
@Override
public String toString() {
return "f1 [day=" + day + ", day_air_temperature=" + day_air_temperature + ", day_weather=" + day_weather
+ ", day_weather_pic=" + day_weather_pic.toString() + "]";
}

}

public class cityInfo {

private String c2 ="lanzhou";
private String c3 ="兰州";
@Override
public String toString() {
return "cityInfo [c2=" + c2 + ", c3=" + c3 + "]";
}

}

public class showapi {
private int showapi_res_code = 0;
private String showapi_res_error = "";
private showapi_res_body showapi_res_body = new showapi_res_body();
@Override
public String toString() {
return "showapi [showapi_res_code=" + showapi_res_code + ", showapi_res_error=" + showapi_res_error
+ ", showapi_res_body=" + showapi_res_body.toString() + "]";
}

}

public class test {
public static void main(String[] args) {
showapi anObject = new showapi();

Gson gson = new Gson();
String json = gson.toJson(anObject);
System.out.println(json.toString());

showapi a = gson.fromJson(json, showapi.class);

System.out.println(a.toString());
}
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式