反序列化里面就多个项目的JSON对象

反序列化里面就多个项目的JSON对象

本文介绍了反序列化里面就多个项目的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想反序列化(使用GSON)一个JSON对象,看起来像这样:

 附件:{
            40:{
                ID:40,
                URL:HTTP:\ / \ / drewmore4.files.word press.com \ / 2013 \ / 02 \ /wreckit.jpg
                GUID:HTTP:\ / \ / drewmore4.files.word press.com \ / 2013 \ / 02 \ /wreckit.jpg
                MIME_TYPE:影像\ / JPEG,
                宽:287,
                高度:400
            },
            3:{
                ID:3,
                URL:HTTP:\ / \ / drewmore4.files.word press.com \ / 2013 \ / 02 \ /frankenweenie2bposter.jpg
                GUID:HTTP:\ / \ / drewmore4.files.word press.com \ / 2013 \ / 02 \ /frankenweenie2bposter.jpg
                MIME_TYPE:影像\ / JPEG,
                宽:273,
                高度:400
            }
    },
 

我要如何处理呢?我甚至不知道叫这就是 - 有多个项目再在这里psented $ P $,但它不是一个数组。当我尝试反序列化作为一个数组,程序崩溃的一个预期Begin_Array却发现Begin_Object异常。当我尝试反序列化作为一个强有力的对象(见下面类),该程序运行,但该领域的所有返回null。

下面是类我试图把它映射到:

 类附件{
INT ID;
字符串的URL;
}
 

完整的JSON文件可以看到的

编辑:解决。

@感知的解决方案基本工作。它很复杂,其实,这个元素(还是想知道这是什么多次入境/非数组JSON元)嵌入在确实包含数组较大的JSON对象。同样,这JSON是不是我的设计 - 它来自字preSS REST API,以及(如@Perception提到),我觉得我有这个问题说明了设计缺陷在里面 - 即附件元素应的阵列,而不是一个对象。尽管如此,

不过,如果任何人以往任何时候都需要反序列化使用该API的一个特定网站的所有帖子的查询结果,并进一步需要访问该附件上的每个岗位,这里是你如何做到这一点:

 私有类GETALL扩展的AsyncTask<虚空,虚空,JSONObject的> {
    私有静态最后字符串URL =HTTPS://public-api.word$p$pss.com/rest/v1/sites/drewmore4.word$p$pss.com/posts/;
    @覆盖
    受保护的JSONObject doInBackground(空... PARAMS){

        HttpClient的HttpClient的=新DefaultHttpClient();
        HTTPGET HTTPGET =新HTTPGET(URL);
        httpget.addHeader(接受,应用/ JSON);
        JSONObject的返回=新的JSONObject();
        HTT presponse响应;

        尝试 {
            响应= httpclient.execute(HTTPGET);
            HttpEntity实体= response.getEntity();

            如果(实体!= NULL){
                InputStream的河道= entity.getContent();
                字符串结果= convertStreamToString(河道);

                返回=新的JSONObject的(结果);
                instream.close();
            }
        }
        赶上(ClientProtocolException | IOException异常| JSONException E){e.printStackTrace();}

        返回返回;
    }

        @覆盖
    保护无效onPostExecute(JSONObject的返回){
        GSON GSON =新GSON();

//帖子是的JSONObject中的元素,是后期对象的数组
        尝试 {
        JSONArray帖= returned.getJSONArray(上岗);

        为(中间体CURR = 0; CURR&其中; posts.length(); CURR ++){
            字符串s = posts.get(CURR)的ToString();

            第二十一条= gson.fromJson(S,Article.class);

            JSONObject的附件=新的JSONObject(S).getJSONObject(附件);
            最后的迭代器<字符串>键= attachments.keys();
               而(keys.hasNext()){
                    最终的字符串键= keys.next();
                    a.attached.add(gson.fromJson(attachments.getJSONObject(密钥)的ToString(),Attachment.class));
                }
               stories.add(一);
        }

            }赶上(JSONException E){
                // TODO自动生成的catch块
                e.printStackTrace();
            }
 

解决方案

这是数据的一个例子,可能的应该已序列化为一个数组,但没有。一种解决方案来分析它是利用的JSONObject 直接

 字符串JSON = ...;
最后GSON GSON =新GSON();

最后的名单,其中,附件> attachements =新的ArrayList<附件>(64);
最后的JSONObject jsonObj =新的JSONObject(JSON).getJSONObject(附件);
最后的迭代器<字符串>键= jsonObj.keys();
而(keys.hasNext()){
    最终的字符串键= keys.next();
    attachements.add(gson.fromJson(jsonObj.getJSONObject(密钥)的ToString(),Attachment.class);
}

//做些什么attachements
 


数据的可以也可以看作对ID的一张地图,为附件。它可以被反序列化,例如:

 最后弦乐jsonObj =新的JSONObject(JSON).getJSONObject(附件);
最后GSON GSON =新GSON();
最终的地图<字符串,附件>数据= gson.fromJson(jsonObj.toString()
        新TypeToken<地图<字符串,附件>>(){
        } .getType());
最后的名单,其中,附件>附件=新的ArrayList<附件>(data.values​​());
 

这是实际工作

I'm trying to deserialize (using gson) a JSON object that looks like this:

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

How do I handle it? I don't even know what to call this - There are multiple "items" represented here, but it's not an array. When I try to deserialize it as an array, the program crashes on a "Expected Begin_Array but found Begin_Object" exception. When I try to deserialize it as a Strong object (see class below), the program runs but the fields all return null.

Here is the class I've tried to map it to:

class Attachment {
int ID;
String URL;
}

the full JSON file can be seen here:

EDIT: SOLVED.

@Perception's solution basically worked. It was complicated by the fact that this "element" (still would like to know what this multiple-entry/non-array json element) is embedded in a larger json object that does contain an array. Again, this JSON is not my design - it comes from the Wordpress REST API, and (as @Perception alluded to), I think the issue I've had illustrates a design flaw in it - namely that the attachments element should be an array, rather than a single object. Nonetheless,

Nonetheless, if anyone else ever needs to deserialize the result of a query for all posts on a given site using this API, and further needs access to the attachments on each post, here's how you do it:

  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();
            }
解决方案

This is an example of data that probably should have been serialized as an array, but was not. One solution to parsing it is to utilize a JSONObject directly.

String json = ...;
final Gson gson = new Gson();

final List<Attachment> attachements = new ArrayList<Attachment>(64);
final JSONObject jsonObj = new JSONObject(json).getJSONObject("attachments");
final Iterator<String> keys = jsonObj.keys();
while(keys.hasNext()) {
    final String key = keys.next();
    attachements.add(gson.fromJson(jsonObj.getJSONObject(key).toString(), Attachment.class);
}

// Do something with attachements


The data can also be viewed as a map, of id's to attachments. And it can be deserialized as such:

final String jsonObj = new JSONObject(json).getJSONObject("attachments");
final Gson gson = new Gson();
final Map<String, Attachment> data = gson.fromJson(jsonObj.toString(),
        new TypeToken<Map<String, Attachment>>() {
        }.getType());
final List<Attachment> attachments = new ArrayList<Attachment>(data.values());

This is actuall

这篇关于反序列化里面就多个项目的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 11:15