Httpresponse java

Asked

Viewed 375 times

1

how to handle the server’s json response?

HttpResponse responsePOST = client.execute(post);  

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

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

How I Turn This String into Strings?

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 Google’s GSON library. It uses Reflection for popular POJO objects from JSON. But I believe this approach already solves the problem.

More information from a look at the documentation: http://developer.android.com/reference/org/json/JSONObject.html

  • Good @Wakim worked great! thank you very much man.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.