-3

I have collection where I am able to convert to a json value

Map<String,String> mSizes

Here I am converting to json using and its working

Gson gson = new Gson();
mStruct = gson.toJson(mSizes);

I have another Collection

 Map<String,Map<String,String>> mSizesNested;
 Gson gson = new Gson();
 mStruct = gson.toJson(mSizesNested);

Here I am getting {}, How to resolve this

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Devrath
  • 42,072
  • 54
  • 195
  • 297

3 Answers3

0

You can use this

JSONObject mapToObject = new JSONObject(mSizes);

It can only work for the Map<String, String>

RajatN
  • 223
  • 1
  • 8
  • refer this one https://stackoverflow.com/questions/12155800/how-to-convert-hashmap-to-json-object-in-java – RajatN Sep 05 '17 at 13:00
0

only this your doing wrong is your just calling the Gson class you have to call the GsonBuilder instead .

Gson gson = new GsonBuilder().create();
String json = gson.toJson(mSizesNested);
Waqar Khan
  • 42
  • 6
  • Since when do you need the builder to create a `Gson` instance? Please show some evidence that this is necessary. – Sotirios Delimanolis Sep 05 '17 at 14:34
  • The primary class to use is **Gson** which you can just create by calling new Gson(). There is also a class **GsonBuilder** available that can be used to create a Gson instance with various settings like version control and so on. Moreover GsonBuilder is use when we need to make Custom Serialization and Deserialization . Hope that answer your question for more [link](https://sites.google.com/site/gson/gson-user-guide) – Waqar Khan Sep 06 '17 at 07:18
  • In your snippet, you're not configuring **any** custom serialization/deserialization, so it's unclear why you're suggesting they use the `GsonBuilder` at all. Your answer also suggests that's the entire issue, the use of `Gson` instead of instantiating it through `GsonBuilder` which is entirely wrong. – Sotirios Delimanolis Sep 06 '17 at 14:53
0

Another way of converting a Map to json is

new JSONObject(map);

Now your question is about converting

Map<String,Map<String,String>> mSizesNested;

to json first convert every msize map to jsonobject then map

Map<String,Map<String,jsonobject.toString>> mSizesNested;

Hope this helps.

Chinmay Relkar
  • 467
  • 4
  • 9