如何在Java中阅读JsonArray(gson)

时间:2018-01-12 18:02:05

标签: java json gson

我得到以下Json回复

  

[{"符号":" ETHBTC"" bidPrice":" 0.09086600"" bidQty" :" 10.96000000"" askPrice":" 0.09095200"" askQty":" 43.49600000"}, {   ....

使用com.google.gson.JsonArray。到目前为止我做了什么:

JsonArray askbid = new BinanceApi().allBookTickers();

for (JsonElement obj : askbid)
{
    JsonObject jobj = obj.getAsJsonObject();
    ???
}

我不知道如何继续。没有选项可以获得我需要的参数。我该怎么办?

3 个答案:

答案 0 :(得分:0)

使用GSON的fromJSON方法并将CryptoDTO[].class作为方法参数传递,将JSON转换为DTO的ArrayList。

    public CryptoDTO[] convertJsonToList(String json){
     GSON gson=new GSON();
     return gson.fromJson(json, CryptoDTO[].class);
 }

答案 1 :(得分:0)

JavaDocs for Gson非常清楚JsonObject类上存在哪些getter方法:

JsonElement   get(String memberName) // Returns the member with the specified name.
JsonArray     getAsJsonArray(String memberName) // Convenience method to get the specified member as a JsonArray.
JsonObject    getAsJsonObject(String memberName) // Convenience method to get the specified member as a JsonObject.
JsonPrimitive getAsJsonPrimitive(String memberName) // Convenience method to get the specified member as a JsonPrimitive element.

答案 2 :(得分:0)

我明白了。

 JsonArray askbid = new BinanceApi().allBookTickers();

 for (JsonElement obj : askbid)
 {
         JsonObject jobj = obj.getAsJsonObject();
         String symbol = jobj.get("symbol").toString();
         String bidPrice = jobj.get("bidPrice").toString();
         String bidQty = jobj.get("bidQty").toString();
         String askPrice = jobj.get("askPrice").toString();
         String askQty = jobj.get("askQty").toString();
 }