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/
Related
This question has been asked multiple time, I have a Java POJO class which I would like to serialize by excluding some attributes. In order to do this, I am using #Expose from GSON. The problem is that it does not seem to work.
Even if I use this: Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
It does not work.
I am reluctant to use transient because it disables both serialization and deserialization of the given attribute.
you can use transient
private transient String property;
Make sure you initialize your Gson object properly. You should call excludeFieldsWithoutExposeAnnotation method in your GsonBuilder if you want to use the Exclude annotation.
For example
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Gson javadoc description of excludeFieldsWithoutExposeAnnotation
I am trying to to convert JSON to POJO class. This JSON I am getting from third party REST API call and I want to convert it into POJO class. For this I am using jackson-databind jar and below is part of my code.
ObjectMapper mapper = new ObjectMapper();
Object modelObject; // object in which I want to convert my JSON object
mapper.writeValue(request.getShipmentDataJson(), modelObject);
Here for now instead of POJO class I declared modelObjcet variable of Object type and my question is do we need to create POJO class with required fields and getter setter methods before converting JSON to POJO?
If yes, then how should we create this POJO class from JSONSchema and when it get created?
Please explain me this concept. My understanding is we POJO should get create directly from JSONSchema but when and how that I don't know. And I think once POJO get created then I can use my above code to store JSON object to POJO.
You need an object with fields corresponding to incoming JSON (names and datatypes) - so jackson can populate and instantiate it. There are tools like this:
http://www.jsonschema2pojo.org/
to generate java code from JSON
I am using GSON to parse a JSON file and i want to map this JSON object to a POJO class. The problem is the property name in JSON doesn't have camel-case but my java POJO object having camel-case property name.
Is there any idea without having any performance hit?
Eg: attribute name in JSON file is 'OrderNumber', But in my POJO class , Instead ordernumber, i have 'salesNumber' as attribute name. Now how can we map that OrderNumber from JSON to salesNumber of POJO class?
Thanks in advance!
You can use #SerializedName annotation in this case.
private class SomeObject {
#SerializedName("OrderNumber")
private String salesNumber;
}
I've started using Jackson as a JSON generator, as an alternative to google GSON. I've run into an issue where Jackson is generating object: null if the object is indeed null. GSON on the other hand generates NO entry in JSON, which is the behavior I want. Is there a way to stop Jackson from generating null object/value when an object is missing?
Jackson
ObjectMapper mapper = new ObjectMapper();
StringWriter sw = new StringWriter();
mapper.writeValue(sw, some_complex_object);
String jackson = sw.getBuffer().toString();
System.out.println("********************* START JACKSON JSON ****************************");
System.out.println(jackson);
System.out.println("********************* END JACKSON JSON ****************************");
generates this:
{"eatwithrustyspoon":{"urlList":null,"device":"iPad","os":"iPhone OS","peer_id":
and GSON looks like this:
Gson gson = new Gson();
String json = gson.toJson(some_complex_object);
System.out.println("********************* START GSON JSON ****************************");
System.out.println(json);
System.out.println("********************* END GSON JSON ****************************");
and it generates this (which is what I want - note that "urlList":null was not generated) :
{"eatwithrustyspoon":{"device":"iPad","os":"iPhone OS","peer_id"
From the Jackson FAQ:
Can I omit writing of Bean properties with null value? ("how to prevent writing of null properties", "how to suppress null values")
Yes. As per JacksonAnnotationSerializeNulls, you can use:
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
// or (for older versions):
objectMapper.configure(SerializationConfig.WRITE_NULL_PROPERTIES, false);
and voila, no more null values. Note that you MUST configure mapper before beans are serialized, since this setting may be cached along with serializers. So setting it too late might prevent change from taking effect.
my issue was bit different actually i was getting Null values for the properties of POJO class.
however i solved the problem by giving mapping to properties in my pojo class like this :
#JsonProperty("PROPERTY_NAME")
thought it may help someone :)
The following solution saved me.
objectMapper.setSerializationInclusion(Include.NON_NULL);
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