gpt4 book ai didi

java - 如何用Gson解析响应

转载 作者:行者123 更新时间:2023-12-02 05:02:05 25 4
gpt4 key购买 nike

我有一个 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。

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

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"}]}]}

最佳答案

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

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

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

定义 setter 就这样了。反序列化时使用

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

关于java - 如何用Gson解析响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28173942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com