java如何使用GSON在对象中插入许多JSON属性
我试图解析一个JSON(http://economia.awesomeapi.com.br/json/all)响应,我不知道为什么要使用Gson()。fromJson()我的对象尚未填充
GetCoinsBalanceJson方法
private void getCoinsBalanceJson() {
String httpURL = "http://economia.awesomeapi.com.br/json/all";
URL myUrl;
StringBuilder coinData = new StringBuilder();
CoinJsonWrapper coinJsonWrapper = new CoinJsonWrapper();
try {
myUrl = new URL(httpURL);
HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
conn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String inputLine;
while ((inputLine = br.readLine()) != null) {
coinData.append(inputLine);
}
Gson g = new Gson();
//CoinJsonWrapper[] enums = g.fromJson(coinData, CoinJsonWrapper[].class);
coinJsonWrapper = g.fromJson(coinData.toString(), CoinJsonWrapper.class); // This Object is not been Populated :(
} catch (Exception e) {
System.out.println("Exception is " + e.getMessage());
}
}
类CoinJsonWrapper
public class CoinJsonWrapper {
@SerializedName("code")
private String code;
@SerializedName("codein")
private String codein;
@SerializedName("name")
private String name;
@SerializedName("high")
private Float high;
@SerializedName("low")
private Float low;
@SerializedName("ask")
private Float ask;
@SerializedName("timestamp")
private Long timestamp;
@SerializedName("create_date")
private String create_date;
public final String get_code() {
return this.code;
}
public final String get_codein() {
return this.codein;
}
public final String get_name() {
return this.code;
}
public final Float get_high() {
return this.high;
}
public final Float get_low() {
return this.low;
}
public final Float get_ask() {
return this.ask;
}
public final Long get_timestamp() {
return this.timestamp;
}
public final String get_create_date() {
return this.create_date;
}
}
我不知道为什么我的目标-->;coinJsonWrapper未使用os Json响应的值填充。 有人能帮我解决这个问题吗
Tks
# 1 楼答案
您没有正确定义模型类,它们应该如下所示:
及
在您的方法getCoinsBalanceJson中:
coinJsonWrapper = g.fromJson(coinData.toString(), CoinsWrapper.class);