我正在尝试反序列化(使用gson)一个看起来像这样的JSON对象:
"attachments": {
"40": {
"ID": 40,
"URL": "http:\/\/drewmore4.files.wordpress.com\/2013\/02\/wreckit.jpg",
"guid": "http:\/\/drewmore4.files.wordpress.com\/2013\/02\/wreckit.jpg",
"mime_type": "image\/jpeg",
"width": 287,
"height": 400
},
"3": {
"ID": 3,
"URL": "http:\/\/drewmore4.files.wordpress.com\/2013\/02\/frankenweenie2bposter.jpg",
"guid": "http:\/\/drewmore4.files.wordpress.com\/2013\/02\/frankenweenie2bposter.jpg",
"mime_type": "image\/jpeg",
"width": 273,
"height": 400
}
},
我该如何处理?我甚至不知道该怎么称呼 – 这里有多个“项目”,但它不是一个数组.当我尝试将其反序列化为数组时,程序在“Expected Begin_Array但发现Begin_Object”异常时崩溃.当我尝试将其反序列化为Strong对象(请参阅下面的类)时,程序会运行但字段都返回null.
这是我试图将它映射到的类:
class Attachment {
int ID;
String URL;
}
完整的JSON文件可以看到here:
编辑:已解决.
@ Perception的解决方案基本上有效.由于这个“元素”(仍然想知道这个多入口/非数组json元素是什么)嵌入到包含数组的较大json对象中,这一点很复杂.同样,这个JSON不是我的设计 – 它来自Wordpress REST API,并且(正如@Perception所暗示的那样),我认为我已经解决了它的一个设计缺陷 – 即附件元素应该是一个数组而不是单个对象.尽管如此,
尽管如此,如果其他任何人需要使用此API反序列化给定网站上所有帖子的查询结果,并且还需要访问每个帖子上的附件,请按以下步骤操作:
private class getAll extends AsyncTask {
private static final String url = "https://public-api.wordpress.com/rest/v1/sites/drewmore4.wordpress.com/posts/";
@Override
protected JSONObject doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.addHeader("accept", "application/json");
JSONObject returned = new JSONObject();
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
returned =new JSONObject(result);
instream.close();
}
}
catch (ClientProtocolException | IOException | JSONException e) { e.printStackTrace();}
return returned;
}
@Override
protected void onPostExecute (JSONObject returned){
Gson gson = new Gson();
//posts is the element within the JSONObject that is an array of post objects
try {
JSONArray posts = returned.getJSONArray("posts");
for (int curr = 0; curr < posts.length(); curr++){
String s = posts.get(curr).toString();
Article a = gson.fromJson(s, Article.class);
JSONObject attachments = new JSONObject(s).getJSONObject("attachments");
final Iterator keys = attachments.keys();
while(keys.hasNext()) {
final String key = keys.next();
a.attached.add(gson.fromJson(attachments.getJSONObject(key).toString(), Attachment.class));
}
stories.add(a);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}