Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON. How to convert json object to json array?

Now I am getting this JSON from API:

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

But prices are dynamic, that's why I need JSON in this form

{
  "supplyPrice": [
    {
      "name": "CAD",
      "value": "78"
    },
    {
      "name": "TRY",
      "value": "34961.94"
    },
    {
      "name": "CHF",
      "value": "54600.78"
    },
    {
      "name": "USD",
      "value": "20735.52"
    }
  ]
}

How to do this using GSON?

like image 702
Joe Richard Avatar asked Jan 29 '16 11:01

Joe Richard


People also ask

What is difference between fromJson and toJson?

There are two parameters in the fromJson() method, the first parameter is JSON String which we want to parse and the second parameter is Java class to parse JSON string. We can pass one parameter into the toJson() method is the Java object which we want to convert into a JSON string.

Does GSON offer parse () function?

The GSON JsonParser class can parse a JSON string or stream into a tree structure of Java objects. GSON also has two other parsers. The Gson JSON parser which can parse JSON into Java objects, and the JsonReader which can parse a JSON string or stream into tokens (a pull parser).

What does GSON toJson do?

Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.


1 Answers

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> 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<SupplyPrice> suplyPrices = gson.fromJson(pJsonString, SupplyPrice.class);

Now you can use the arraylist to get the data.

like image 139
bpr10 Avatar answered Oct 14 '22 11:10

bpr10