Serialize object as Map instead of String using Jackson databind? - java

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

Related

How to skip a map of map when deserialize from Json String to Object using object mapper

I have a map of map in my POJO which is always null. When i convert a json string to java object, then i am getting a deserialization error because of the map. So how can i skip the map while converting the json string to object
one of those will probably solve the problem:
you may define the field transient, like:
private transient Map<String, String> mapOfSomething;
(or) you can add #JsonIgnore annotation, like:
#JsonIgnore
private Map<String, String> mapOfAnotherThing;

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

How to parse json with java language keywords

Is there away to parse json with java keywords like class, case, default etc. to java object using Gson library?
The lines
Gson gson = new Gson();
MyObject myObject = gson.fromJson(json, MyObject.class);
simply parse json to my pojo, but I have key "class" in my json and I can't use the field "class" in java classes.
Yes, annotate your fields with #SerializedName, specifying the name of the field.
#SerializedName("class")
private String classField;
Or use a custom TypeAdapter.
You have to use annotations. These annotations tell Gson which JSON field maps to which Java property:
http://www.javacreed.com/gson-annotations-example/

How to convert JAVA Object to JSON Efficiently..?

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

Categories

Resources