1

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.

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.

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).

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.

Thanks so much!

NullHypothesis
  • 4,286
  • 6
  • 37
  • 79

3 Answers3

2

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;
}
Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69
0

Depending on what the fields are, you can make a model class and set the objects from database. The use Gson and form your Json string using jsonFrom.

Eg.

public class Items{

ArrayList<String> names;

String candy;

//nested custom class if necessary
ArrayList<Companies> companies;

//other fields here 

//getter setter
}  

Now set the values for objects of Items.

Then:

Gson gson = new Gson();
String json = gson.toJson(modelClassObject);  

If i got your requirement right, json is the String you need.

Pararth
  • 8,114
  • 4
  • 34
  • 51
0

To merge JSONs you need to define some conventions of merging. If "Overlay" strategy (replace or add) conforms you, you can find a helpful JSON Merging Library in this answer.

Zon
  • 18,610
  • 7
  • 91
  • 99