- 对JSON数据格式化,确定层级关系。(以查询汇率为例)
"results": {
"rate": [
{
"id": "CNYUSD",
"Name": "CNY/USD",
"Rate": "0.1529",
"Date": "9/6/2017",
"Time": "8:35am",
"Ask": "0.1530",
"Bid": "0.1529"
},
{
"id": "CNYGBP",
"Name": "CNY/GBP",
"Rate": "0.1173",
"Date": "9/6/2017",
"Time": "8:35am",
"Ask": "0.1174",
"Bid": "0.1173"
}
]
}
- 对照JSON写出相应Java实体类,一般有很多类,按照层级递进的关系一次写对应类,对于[](数组)类型的数据,采用List<>泛型。
属性全为private,不需要的属性可以不写,并写出对应Getter/Setter方法,也可以搜索在线生成JSON转Java实体类。(代码均是片段)
public class Results {
private List<Rate> rate = null;
public Results() {
}
public Results(List<Rate> rate) {
this.rate = rate;
}
public List<Rate> getRate() {
return rate;
}
}
public class Rate {
private String id;
private String Rate;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setRate(String Rate) {
this.Rate = Rate;
}
public String getRate() {
return Rate;
}
- 在主函数里运行(片段)
Gson gson = new Gson();
主实体类 bean = gson.fromJson(jsonString, 主实体类.class);
Query query = bean.getQuery(); //由外到内依次生成实体类对象,Query类没有列出来,他是json数据中results的上一层。
Results results = query.getResults();
List<Rate> rate = results.getRate();
double RMB_To_USD = rate.get(0).getRate();//得到人民币兑美元汇率