GSON. How to convert json object to json array?

前端 未结 7 1868
没有蜡笔的小新
没有蜡笔的小新 2021-02-08 15:20

Now I am getting this JSON from API:

{\"supplyPrice\": {
        \"CAD\": 78,
        \"CHF\": 54600.78,
        \"USD\": 20735.52
      }}

But

7条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-08 16:04

    GSON uses POJO classes to parse JSON into java objects.

    Create A java class containing variables with names and datatype same as keys of JSON object. I think the JSON you are getting is not in the right format.

    Class SupplyPrice{
     double CAD;
     double CHF;
     double TRY
    }
    
    Class SupplyPriceContainer{
     ArrayList supplyPrice;
    }
    

    And your JSON should be

     {
        "CAD": 78,
        "CHF": 54600.78,
        "USD": 20735.52
     }
    
    
    
    {
        "supplyPrice": [{
            "CAD": 78,
            "CHF": 0,
            "USD": 0
        }, {
            "CAD": 0,
            "CHF": 54600.00,
            "USD": 0
        }, {
            "CAD": 0,
            "CHF": 0,
            "USD": 20735.52
        }]
     }
    

    Then you can Use GSON's `fromJson(String pJson, Class pClassType) to convert to JAVA object

      Gson gson = new Gson()
      ArrayList suplyPrices = gson.fromJson(pJsonString, SupplyPrice.class);
    

    Now you can use the arraylist to get the data.

提交回复
热议问题