我正在尝试反序列化(使用 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
}
},
我该如何处理?我什至不知道该怎么称呼它——这里有多个“项目”,但它不是一个数组。当我尝试将其反序列化为数组时,程序因“预期的 Begin_Array 但发现 Begin_Object”异常而崩溃。当我尝试将其反序列化为 Strong 对象时(请参见下面的类),程序运行但所有字段都返回 null。
这是我尝试将其映射到的类:
class Attachment {
int ID;
String URL;
}
完整的 JSON 文件可以在 这里看到:
编辑:已解决。
@Perception 的解决方案基本上奏效了。由于这个“元素”(仍然想知道这个多条目/非数组 json 元素是什么)嵌入到一个更大的包含数组的 json 对象中,这一事实变得复杂。同样,这个 JSON 不是我的设计——它来自 Wordpress REST API,并且(正如@Perception 所暗示的那样),我认为我遇到的问题说明了它的设计缺陷——即附件元素应该是一个数组,而不是单个对象。尽管如此,
尽管如此,如果其他人需要使用此 API 对给定站点上所有帖子的查询结果进行反序列化,并且还需要访问每个帖子上的附件,您可以这样做:
private class getAll extends AsyncTask <Void, Void, JSONObject> {
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<String> 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();
}