我是Android开发的新手。在这里,我正在进行GET
这样的调用 -
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("email", "guest@example.com"));
JSONHttpClient jsonHttpClient = new JSONHttpClient();
ProductDetail[] products = jsonHttpClient.Get(ServiceUrl.PRODUCT, nameValuePairs, ProductDetail[].class);
return null;
}
这是GET
文件中的JSONHttpClient
电话 -
public <T> T Get(String url, List<NameValuePair> params, final Class<T> objectClass) {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Accept-Encoding", "gzip");
httpGet.setHeader("Authorization", "Bearer <code>");
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
InputStream inputStream = httpEntity.getContent();
Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
}
String resultString = convertStreamToString(inputStream);
inputStream.close();
return new GsonBuilder().create().fromJson(resultString, objectClass);
}
return null;
}
这是我的ProductDetail
课程 -
public class ProductDetail {
public int Id;
public String Name;
}
在运行时,我收到以下错误 -
No-args constructor for class com.compa.ProductDetail does not exist. Register an InstanceCreator with Gson for this type to fix this problem.
这是在JSONHttpClient文件中的这一行抛出的 -
return new GsonBuilder().create().fromJson(resultString, objectClass);
有人可以为此提供帮助吗?
在我的web api中,我正在创建这样的json(proddetails是一个C#IEnumerable对象) -
json = JsonConvert.SerializeObject(proddetails);
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(json, Encoding.UTF8, "application/json");
return response;
响应json的结构是 -
[
{
"Id": 1,
"Name": "First"
},
{
"Id": 2,
"Name": "Second"
}
]
答案 0 :(得分:0)
Gson用户指南(https://sites.google.com/site/gson/gson-user-guide)告诉您一个表现良好的类(用于序列化和反序列化)应该有一个无参数构造函数。如果不存在,建议您使用InstanceCreator。
即使你没有构造函数,Gson也会为你的类创建一个ObjectConstructor。但这总是不安全,并且有其自身的局限性。关于SO的这个问题更多地涉及细节:Is default no-args constructor mandatory for Gson?
注意:请注意,如果这是一个内部类,那么它必须有一个构造函数,如文档中所述。
编辑:您的json是一个数组。因此,您需要在包含类中具有指定数量的数组对象。所以你可以做以下事情然后演员:
public class ProductDetailArray {
public ProductDetailArray[] array;
public static ProductDetail {
public ProductDetail() {} // You can also make the constructor private if you don't want anyone to instantiate this
public int Id;
public String Name;
}
}
一旦你像以前一样投射你的json:
ProductDetailArray obj = GsonBuilder.create().fromJson(response, ProductDetailArray.class);
ProductDetail one = obj.array[0];
ProductDetail two = obj.array[1];
然后你可以进行操作..你也应该使用Gson.fromJson()而不是GsonBuilder