如何用Gson解析响应

时间:2015-01-27 15:23:39

标签: java android web-services gson

我有一个Android应用程序,这个应用程序可以联系web服务,通​​过JSON响应,并发送一个对象。我想使用Gson库来转换Object中的响应。所以我有这种方法,但不起作用。

      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;
    }
}

此方法每次都返回null。

我使用此代码来读取Web服务的响应。 这是代码:

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);
}

这是网络服务的回应:

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

3 个答案:

答案 0 :(得分:1)

您的JSON根本与您的Java对象树不匹配。

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

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

您的JSON是一个JSON对象,包含字段statusmessagecontent,其中content是一个JSON数组,包含与您的Java POJO类型匹配的JSON对象。您必须反序列化为具有statusmessagecontent字段的类型contentList或类型为{{1}的数组}。

答案 1 :(得分:1)

如果使用所有必需字段反序列化与类定义不同的JSON,Gson将返回null。

因此,您需要将您的类定义为与JSON相同:

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

定义设置者和它。 反序列化时使用

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

答案 2 :(得分:0)

转到此站点 http://www.jsonschema2pojo.org/

将JSON响应粘贴到文本框中,并选择Gson作为注释样式,然后单击预览以查看生成的响应文件或下载JAR。导入所有类并执行以下操作以将JSON字符串反序列化为对象。

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

其中JsonResponse是您实现中的实际类。当您有复杂的JSON响应时,您将欣赏此站点。

我希望这会有所帮助:)。