java 反序列化 多个对象_java – 反序列化其中包含多个项的JSON对象

我正在尝试反序列化(使用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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值