How to convert JAVA Object to JSON Efficiently..?

Ramandeep Singh picture Ramandeep Singh · Mar 15, 2012 · Viewed 9.5k times · Source

I am using Mule. I have a JAVA Object that is populated from my internal Class..It is actually a HashMap<String,Object>. Object can be anything..another HashMap, OR List etc ..Now i have to convert it into JSON (and removing all those keys that have value as NULL)..

When i use a given Mule Transformer , ObjectToJSON, it is converting into appropriate JSON..but not able to remove NULL value..And i could not find any properties to set in Custom-transformer that will remove NULL values..!!


So then, i wrote a custom transformer, that uses the net.sf.json-lib library and i am able to remove NULL values.

But in one of my JAVA Object , i have a HashMap<Integer,String> and since in JSON Object , Integer cannot be keys, net.sf.json library is giving an Exception :

Exception stack is:
1. JSON keys must be strings. (java.lang.ClassCastException)
  net.sf.json.JSONObject:1120 (null)
2. java.lang.ClassCastException: JSON keys must be strings. (net.sf.json.JSONException)
  net.sf.json.JSONObject:1160 (null)
3. java.lang.ClassCastException: JSON keys must be strings. (net.sf.json.JSONException). Message payload is of type: HashMap (org.mule.api.transformer.TransformerMessagingException)

and so it is unable to convert it into JSON..


So what is most viable option..??

Answer

aviad picture aviad · Mar 15, 2012

I would recommend you to try gson it worked like a magic for me.

Collections Examples

Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);

(Serialization)

String json = gson.toJson(ints); ==> json is [1,2,3,4,5]

(Deserialization)

Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);

ints2 is same as ints

Here is an example of how to write a custom serializer for JodaTime DateTime class.

private class DateTimeSerializer implements JsonSerializer<DateTime> {
  public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext  context) {
    return new JsonPrimitive(src.toString());
  }
}