How to convert JAVA Object to JSON Efficiently..? - java

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..??

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

Have you looked at Gson?
http://sites.google.com/site/gson/gson-user-guide#TOC-Null-Object-Support

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:
Use a custom deserializer Deserializing non-string map keys with Jackson
Use a Tree Model instead of your own Java POJO http://wiki.fasterxml.com/JacksonInFiveMinutes

Related

Serialize object as Map instead of String using Jackson databind?

Normally one does something like this when you want to serialize an object to a JSON string:
String json = objectMapper.writeValueAsString(myObject);
I wonder if it's possible to serialize an object directly into a java.util.Map instead of a String? I.e. something like this (pseudo code):
String json = objectMapper.writeValueAs(myObject, new TypeReference<Map<String,Object>>() {});
I know I can serialize the object to a String first and then deserialize it as a Map<String,Object> but I'm asking if there's is a way to do this without first serializing to a String?
I'm using Jackson 2.11.1.
You can use convertValue method of ObjectMapper to convert Object into Map
Map<String, Object> map = objectMapper.convertValue(myObject, Map.class);

JSONArray to list of objects

I have JSONArray where each element in the array is a json with 5 fields.
I would like to map this JSONArray to a list on Class objects. Each Class object has exact same fields as the json element, plus 3 additional Class fields that I would like to set to null when the object is mapped from the json element.
I tried:
JSONObject jsn = SomeJsonWith2Keys
JSONArray jsn_a = (JSONArray) jsn.get("response");
List<MyClass> tags = (List<MyClass>) objectMapper.readValue(jsn_a.toString(), MyClass.class)
But this is throwing an exception
Cannot deserialize instance of x.x.x.x.MyClass out of START_ARRAY token
The array size is large and I am trying to not do mapping in a loop if possible.
I would appreciate any suggestion on how to do the mapping to the class while setting the 3 additional fields to null
Thank you
You need to specify the type as a List rather than MyClass. You can't do this by just saying List.class, but Jackson provides a com.fasterxml.jackson.core.type.TypeReference class that allows you to supply the fact that you want a list of a specific type.
So assuming your objectmapper is a jackson one you can do the following.
List<MyClass> tags = mapper.readValue(jsn_a.toString(), new TypeReference<List<MyClass>>() {});
If you're OK using an array instead of a list you can specify the array type.
MyClass[] tags = mapper.readValue(jsn_a.toString(), MyClass[].class);

Deserialize JSON in Java by inferring/embedding object type

I am serializing a Map<String, Object> into JSON using Jackson.
Later when I deserialize it, all objects that are not of primitive type get converted to LinkedHashMap's instead of the class that they originally belonged to.
Is there any way to deserialize JSON into a map so that the nested objects are of correct type?
Use constructCollectionType of Typefactory with ArrayList as the CollectionClass & your POJO class as the second argument and read the "List" value using ObjectMapper. Like this:
List<T> list;
ObjectMapper om = new ObjectMapper();
TypeFactory t = TypeFactory.defaultInstance();
list = om.readValue(json, t.constructCollectionType(ArrayList.class,POJO_clazz));
Hope this helps!

Creating Map or Set using GSON

I am using Google's GSON library and want to create a JSON which looks something like this:
{
"teamSet":[],
"classificationMap" : {}
}
Notice that [] and {} are empty Set and Map respectively and are not surrounded with double quotes.
I want to create this Json using the GSON add/addproperty method and not by converting a Java class into JSON using the Gson.toJson() method. The business use-case restricts me from creating specific Java classes as the JSON structure may change overtime. So I cannot use a class like this as this would rigidly tie a JSON structure with a concrete class
class Linkage{
private Set<String> teamSet;
private Map<String, String> classificationMap;
// getter, setter methods follow
...
}
When I use the GSON.addproperty(genericObject, type), it is appending double quotes around [] and {}. I am using couchbase for my DB requirements and the double quotes around [] and {} makes couchbase treat them as string and not as Set/Map. This renders my Map-Reduce views useless and buggy :(
Please let me know if its possible to create such a JSON without having to tie it up with a concrete JAVA class. Thanks !
My current code looks like this:
// create types
Type setType = new TypeToken<Set<String>>() {}.getType();
Type mapType = new TypeToken<Map<String, String>>() {}.getType();
Gson GSON = new Gson();
Set<String> teams = new HashSet<String>();
Map<String, String> classificationMap = new HashMap<String, String>();
JsonObject linkageJson = new JsonObject();
linkageJson.addProperty("teamSet", GSON.toJson(teams, setType));
linkageJson.addProperty("classificationMap", GSON.toJson(classificationMap, mapType));
In the 2.x line of the couchbase java sdk, there is the JsonObject class that could have fit your need.
It is perfect to create Json "by hand" and still have a simple generic object representation, and is the official way of putting json into the database via the sdk.
It would go like this :
JsonObject obj = JsonObject.create();
obj.put("teamSet", JsonArray.from(new ArrayList(teams)))
.put("classificationMap", JsonObject.from(classificationMap));
Granted this is a little bit contrived because arrays and sub-objects can only be constructed from respectively List<?> and Map<String, ?> factory methods. Also the class support a limited set of value types (no custom classes, only String, Number, Boolean, etc...).
i feel somewhere it is storing it toString() representation.
Please refer below link, it might help you.
click here

Dynamically entering class literal as method argument at runtime

I have an application which makes use of an external library (Jackson), and the method I need requires a class literal as an argument. So if I wish to parse my JSON string into a User object:
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("user.json"), User.class);
Now, I wish to use this method dynamically (i.e. parse different JSON strings using the same line of code). For example:
String json1 = "{"type":"jacket",...}";
String json2 = "{"type":"sweater",...}";
Object object = mapper.readValue(json1/json2, ???);
//returns a Jacket object OR Sweater object based on the "type" key
//i.e. use Jacket.class as the 2nd argument if "type" is "jacket"
//OR Sweater.class if "type" is "sweater"
//After getting the deserialized object,
//if object is Jacket, cast as a Jacket
//if object is Sweater, cast as a Sweater
Of course, the JSON string in question can be for any class, so I can't simply hard-code an if-else loop. I've looked at custom serializers, but frankly am quite lost at what it's talking about, and would like some help in how I can go about this.
In summary, I need some way to first define a class literal from a String, and then cast the resulting Object into the specific class (but my focus is on getting readValue to work dynamically).
Looks like you need a mapping somewhere between JSON type variable and Java class type.
Generally result should be something like this map:
Map<String, Class<? extends YourSupertype>> map = new HashMap<>();
map.put("sweater", Sweater.class);
map.put("jacket", Jacket.class);
Just store possible clothing types somewhere in a file, then do something like:
String clothingType = nextEntryFromFile();
String className = constructClassNameFromClothingType(clothingType);
map.put(clothingType, Class.forName(className));
Since version 1.5 Jackson supports Polymorphic Type Handling, check here http://www.cowtowncoder.com/blog/archives/2010/03/entry_372.html
there are examples on how to correctly handle deserialization in those cases.

Categories

Resources