3

I have a object which I want to serialize to JSON. This object is a map with list of a specific objects. This looks similar to it:

Map<String, List<Object>> map = new Map<String, List<Object>>();

I am using FlexJSON. I can work only with flexjson.JSONSerializer. There are my tries:

JSONSerializer jsonSerializer = new JSONSerializer();
//        jsonSerializer.include("map");
//        jsonSerializer.include("map.myList.object");
jsonSerializer.transform(new MapTransformer(), "map");
jsonSerializer.exclude("*.class");

As you can see I am trying now with Transformer classes but I haven't succeeded. The commented lines will work, as I suppose, if my List<Object> has own name for example myList. But it doesn't haven own name, because it is values of my map.

How can I serialize such object to JSON with FlexJSON?

Chad
  • 19,219
  • 4
  • 50
  • 73
woyaru
  • 5,544
  • 13
  • 54
  • 92

2 Answers2

4

Quoi is correct, and most likely the answer you want to use. However, just so you can learn more about how it works you could do this:

new JSONSerializer().include("values.values").serialize( myMap );

Maps and Lists are containers and have special expressions for the elements contained within them. When you want to talk about the path of the values of a container you use "values" expression in the path. Map's two special expressions "keys" and "values". Other Collections have "values".

Another option is to use wildcards like so:

   new JSONSerializer().include("values.*").serialize( myMap );

You can see wildcards used in Quoi's answer as well to exclude the class property.

raffian
  • 31,267
  • 26
  • 103
  • 174
chubbsondubs
  • 37,646
  • 24
  • 106
  • 138
  • The wildcards are the best options in my case. As I have mentioned, I can only operate on `flexjson.JSONSerializer` object. – woyaru Sep 26 '12 at 08:10
  • I tried this for `Map`, with and without `include("values")`, but the json result is the same; I was expecting to see class type data in the json for different `Object` type in the map when using `"values"`? – raffian Oct 09 '13 at 02:42
3

Try

String jsonString = new JSONSerializer().exclude("*.class").deepSerialize(map);

deepSerialize method performs a deep serialization of the target instance. It will include all collections, maps, and arrays by default so includes are ignored except if you want to include something being excluded by an annotation.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103