1

Is there a way to merge different String-Collections into one JSON 'String'? I would like to have a JSON String that looks like this:

{"vendor":[Sun, HP, IBM],"product":[bla, bla, bla],"availability":[high, mid, low],"capacity":[bla, bla, bla], ...}

This is a part of my Java Code:

Collection<String> vendor = bh.getAllVendors();
Collection<String> product = bh.getProductsForVendor(vendor);
Collection<String> availability = bh.getAllAvailabilities();
Collection<String> capacity = bh.getCapacityForVendor(vendor);
Collection<String> signaling = bh.getSignalingForVendor(vendor);
Collection<String> backup = bh.getBackupForVendor(vendor);

Gson gson = new Gson();

Any help would be appreciated.

nimrod
  • 5,595
  • 29
  • 85
  • 149

2 Answers2

7

It would be easiest if you add them to a map:

    Gson gson = new Gson();

    Map<String, Collection<String>> map = new HashMap<>();
    map.put("vendor", vendor);
    map.put("product", product);
    //etc

    System.out.println(gson.toJson(map));

produces {"product":["bla","bla","bla"],"vendor":["Sun","IBM","HP"]}

jmruc
  • 5,714
  • 3
  • 22
  • 41
  • Nice. Only trouble is, if later you want to deserialize it, you either need to define a class with 'vendor', 'product' etc as attributes, or you need to write a custom deserializer. More details in one of the answers to [this question](http://stackoverflow.com/questions/2779251/convert-json-to-hashmap-using-gson-in-java) – ArjunShankar Apr 20 '12 at 11:19
2

Create a new class:

Class MyJSONObject
  {
    Collection<String> vendor;
    Collection<String> product;
    Collection<String> availability;
    //...
    //...
  }

Then assign your data to those attributes in an instance of MyJSONObject.

Then serialize that instance:

gson.toJson (myJSONObjectInstance);

Read the 'Object Examples' section of this GSON documentation.

ArjunShankar
  • 23,020
  • 5
  • 61
  • 83