HttpResponse java

1

How to handle the json response from the server?

HttpResponse responsePOST = client.execute(post);  

String responseBody = EntityUtils.toString(responsePOST.getEntity());

The String "responseBody" comes from php so {"product":[{"id":"21","cliente":"","descricao":""},{"id":"22","cliente":"","descricao":""},{"id":"19","cliente":null,"descricao":"Celular"},{"id":"17","cliente":"Fddh","descricao":"Fdf"}],"success":1}

How do I transform this String into Strings?

    
asked by anonymous 29.08.2014 / 05:14

1 answer

3

Use the Java JSON API. From the String in JSON format, you can build a representation in memory and extract the data you need:

HttpResponse responsePOST = client.execute(post);
String responseBody = EntityUtils.toString(responsePOST.getEntity());

try {
    JSONObject json = new JSONObject(responseBody);

     // Recupera a lista product do JSON
    JSONArray products = json.getJSONArray("product");

    Integer success = json.getInt("success");

    int length = products.length();

    for(int i = 0; i < length; ++i) {
        JSONObject product = products.getJSONObject(i);

        String id = product.getString("id");
        String cliente = product.getString("cliente");
        String descricao = product.getString("descrição");

        // Sua logica com os campos
    }
} catch(JSONException e){}

You can use the Google GSON library. That uses reflection for popular POJO objects from JSON. But I believe this approach already solves the problem.

More information at a glance in the documentation: link

    
29.08.2014 / 06:02