Convert a JSON to an array

2

My question is this: How can I convert the result object to a list (array) in Java ?.

The JSON is something like the following:

{
    "order_id": "12345",

    "paging": {
        "total": 41,
        "offset": 0,
        "limit": 50
    },
    "results": [{
            "id": "1",
            "title": "Item Title1",
            "price": 330,
            "available_quantity": 1,
            "sold_quantity": 0
        },
        {
            "id": "2",
            "title": "Item Title 2",
            "price": 310,
            "available_quantity": 1,
            "sold_quantity": 0
        }
    ]
}

So far I tried to analyze it with the class Search (which contains a list of elements with the same attributes as those of the JSON ):

arrayreq = gson.fromJson(response.getResponseBody(), Search.class);

And also try this:

arrayreq = gson.fromJson(response.getResponseBody(), String[].class);

I have 2 similar actions running but none of the JSON that parsean has lists.

My class Search.java :

public class Search {
    private String order_id;
    private Paging paging;
    private List<Item> results;//No se si esta bien
    
asked by Figazza1 15.05.2017 в 00:01
source

2 answers

1

Do you mean the Results object does not?

 JSONObject json = new JSONObject(cadenaJSON);
 JSONArray arrayJSON = myjson.getJSONArray("Results");

Now we do the following

int tamanhioArray = arrayJSON.length();
ArrayList<JSONObject> listResults = new ArrayList<JSONObject>();
for (int i = 0; i < tamanhioArray; i++) {
    JSONObject otroObject = listResults.getJSONObject(i);

    listResults.add(otroObject);
}

JSONObject[] jsonsFinally= new JSONObject[listResults.size()];
listResults.toArray(jsonFinally);
    
answered by 15.05.2017 в 01:30
1

You can create a class that we will call Order like this:

class Order {

 @SerializedName("order_id")
 private String order_id;
 @SerializedName("paging")
 private Map<String, int> paging;
 @SerializedName("results")
 private List<Item> results;

}

Then you can use GSON to convert the JSON to an Order object directly

Gson gson = new Gson();
Order order = gson.fromJson(jsonObject, Order.class);

Then simply access order.getResults() and you would already have the array.

Look to see if your problem is that you have not used the @SerializedName or that the Item class is missing too.

    
answered by 15.05.2017 в 09:58