How to convert JAVA Object to JSON Efficiently..? How to convert JAVA Object to JSON Efficiently..? json json

How to convert JAVA Object to JSON Efficiently..?


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());  }}


From http://www.ietf.org/rfc/rfc4627.txt

An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string.

I would suggest to modify your initial Java structure to use String as key type.

However with Jackson library you can create fancier solutions:

  1. Use a custom deserializer Deserializing non-string map keys with Jackson

  2. Use a Tree Model instead of your own Java POJO http://wiki.fasterxml.com/JacksonInFiveMinutes