简体   繁体   English

如何用Gson解析响应

[英]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. 我有一个Android应用程序,该应用程序可以联系Web服务,通​​过JSON进行响应,并发送对象。 I want to use a Gson library to convert the response in Object. 我想使用Gson库在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. 此方法每次都返回null。

I have use this code to read the response of web services. 我已使用此代码读取Web服务的响应。 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: 这是Web服务的响应:

{"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. 您的JSON与Java对象树根本不匹配。

{"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. JSON是一个JSON对象,具有statusmessagecontent字段,其中content是一个JSON数组,其中包含与Java POJO类型匹配的JSON对象。 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 . 您必须将反序列化为具有statusmessagecontent字段的类型,其中contentImpresa类型的List或数组。

If you deserialize a JSON that is not the same as the class definition with all the required fields, Gson will return null. 如果使用所有必填字段反序列化与类定义不同的JSON,则Gson将返回null。

So you need to define your class to be the same as the JSON: 因此,您需要将您的类定义为与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/ 转到此网站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. 将您的JSON响应粘贴到文本框中,然后选择Gson作为注释样式,然后单击预览以查看响应所生成的文件或下载JAR。 Import all the classes and do the following for deserialization of the JSON string to an object. 导入所有类,然后执行以下操作以将JSON字符串反序列化到对象。

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

Where JsonResponse is an actual class in your implementation. JsonResponse是实现中的实际类。 You will appreciate this site when you have complex JSON response . 当您有复杂的JSON响应时,将不胜感激此站点。

I hope this helps :). 我希望这有帮助 :)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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