简体   繁体   中英

How to parse response with Gson

I have an Android application, this application can contact a webservices, that response throught JSON, and send an object. I want to use a Gson library to convert the response in Object. So I have this method but not works.

      private static Impresa getDatiImpresa(String url) throws 
        IOException, MalformedURLException, JSONException
        {
            String result = "";
            Gson gson = new Gson();
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
            HttpResponse response;
            try {
                HttpPost post = new HttpPost(url);
                response = client.execute(post);

                /*Checking response */
                if(response!=null){

                    InputStream source = response.getEntity().getContent(); //Get the data in the entity
                    Reader reader = new InputStreamReader(source);
                    Impresa impresa = gson.fromJson(reader, Impresa.class);
                   return impresa;
                }

            } catch(Exception e) {
                e.printStackTrace();
                //createDialog("Error", "Cannot Estabilish Connection");
            }
            return null;
        }

public class Impresa {
    @SerializedName("pivaImpresa")
    public String partitaIVA;
    @SerializedName("ragioneSociale")
    public String ragioneSociale;
    @SerializedName("centriAziendali")
    public List<CentroAziendale> listaCentroAziendale;

    public String getPartitaIVA() {
        return partitaIVA;
    }
    public void setPartitaIVA(String partitaIVA) {
        this.partitaIVA = partitaIVA;
    }
    public String getRagioneSociale() {
        return ragioneSociale;
    }
    public void setRagioneSociale(String ragioneSociale) {
        this.ragioneSociale = ragioneSociale;
    }
    public List<CentroAziendale> getListaCentroAziendale() {
        return listaCentroAziendale;
    }
    public void setListaCentroAziendale(List<CentroAziendale> listaCentroAziendale) {
        this.listaCentroAziendale = listaCentroAziendale;
    }
}

This method return null everytime.

I have use this code to read the response of web services. This is the code:

StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(source)));
for (String line = r.readLine(); line != null; line = r.readLine()){
   sb.append(line);
}

this is the response of web services:

{"status":1,"message":"Ok","content":[{"pivaImpresa":"05050505055","ragioneSociale":"Azienda Giustina","centriAziendali":[{"pivaImpresa":"05050505055","codiceCentroAziendale":"C001"}]}]}

Your JSON doesn't match your Java object tree at all.

{"status":1,"message":"Ok","content":[{"pivaImpresa":"05050505055","ragioneSociale":"Azienda Giustina","centriAziendali":[{"pivaImpresa":"05050505055","codiceCentroAziendale":"C001"}]}]}

versus

public class Impresa {
    @SerializedName("pivaImpresa")
    public String partitaIVA;
    @SerializedName("ragioneSociale")
    public String ragioneSociale;
    @SerializedName("centriAziendali")
    public List<CentroAziendale> listaCentroAziendale;

Your JSON is a JSON object, with fields status , message and content , where content is a JSON array containing JSON objects that match your Java POJO type. You'll have to deserialize to a type that has status , message and content fields where content is a List or array of type Impresa .

If you deserialize a JSON that is not the same as the class definition with all the required fields, Gson will return null.

So you need to define your class to be the same as the JSON:

public class JsonResponse {
   private int status;
   private String message;
   private List<Impresa> content;
}

Define the setters and that's it. When deserializing it use

JsonResponse json = gson.fromJson(reader, JsonResponse.class);

Go to this site http://www.jsonschema2pojo.org/

Paste your JSON response in the textbox and select Gson for annotation style and click on preview to view the generated files for your response or download the JAR. Import all the classes and do the following for deserialization of the JSON string to an object.

JsonResponse json = gson.fromJson(reader, JsonResponse.class);

Where JsonResponse is an actual class in your implementation. You will appreciate this site when you have complex JSON response .

I hope this helps :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM