创建合并JSON与GSON [英] Create merged JSON with GSON

查看:542
本文介绍了创建合并JSON与GSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现吨的使用GSON转换或者一个单一对象,或者单个对象的列表的例子,其相应的JSON。很容易做到。即使对象有对象作为其属性,这仍然是微不足道的。

I've found tons of examples of using GSON to convert either an single object, or a list of that single object, to its respective JSON. Quite easy to do. Even if the object has objects as its properties, this still is trivial.

但是,让我们说,我有兴趣(姓名,公司,颜色,数字,糖果),5个对象,他们相互之间没有任何关系。所以,我做我的数据库调用,现在已经在我的code 5列出充满了上面的。

But let's say I have 5 objects of interest (names, companies, colors, numbers, candy) and they have no relationship to each other at all. So I make my database calls, and now have 5 lists full of all of the above in my code.

现在,我怎么可能把这些列表成为一个JSON阵列,其父母的名字是项目,其中包含上述所有作为其下的孩子吗?因此,父母一方项目,有5个孩子(每个孩子是彼此的兄弟姐妹)。

Now, how could I put these lists into a JSON Array whose parent name is "items" and contains all of the above as children beneath it? So one parent "items", with 5 children (each child is a sibling of each other).

什么是使用GSON(或不?)来构建这样的树或结构的适当方法? 我注意到有很多在GSON如JSONArray等,但没能找到答案。

What is the appropriate way using GSON (or not??) to construct such a tree or structure? I noticed there is a lot in GSON such as JSONArray and such, but wasn't able to figure it out.

太感谢了!

推荐答案

是的,你可以。你必须先建立自己的序列化。例如:

Yes, you can. You have to build your own serializer first. For instance:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public static String toJson(List<Item> items){

    try{

        JSONObject jsonObj = new JSONObject();

        JSONArray jsonArr = new JSONArray();

        for(Item i : items){
            JSONObject itemObj = new JSONObject();
            itemObj.put("names", i.getName());
            itemObj.put("companies", i.getCompanies());
            itemObj.put("colors", i.getColors());
            itemObj.put("numbers", i.getNumbers());
            itemObj.put("candy", i.getCandy());
            jsonArr.put(itemObj);
        }

        jsonObj.put("items", jsonArr);

        return jsonObj.toString();

    } catch(JSONException ex){
         ex.printStackTrace();
    }

    return null;
}

这篇关于创建合并JSON与GSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆