I am using Gson for converting between json and java object.
Let's say the json is like this:
{
"name": "John",
"age": 12,
"adult": false
}
The class for the json is:
public class Student {
#Expose
#SerializedName("name")
private String name;
private int age;
private boolean adult;
// setters for all fields above
public void setName(String name) {
this.name = name;
}
...
// getters for all fields above
public String getName() {
return name;
}
...
}
My questions are:
Is it so that all fields showing in json should have #Expose annotation? Does that also mean we can have other fields which are not part of the json string?
Is it so that only if the field name in json and the variable name in java class is different, then use #SerializedName annotation is needed, otherwise it is optional?
Are setter functions necessary in java class for the fields?
The short answers to your questions are 1. yes, 2. yes, 3. no.
Gson has a lot going on under the hood - your Student class needs very little for it to do its work:
data members which match the key values in the JSON (case-sensitive!)
public getter methods
You can have more data members that don't necessarily match the key names in the JSON, they'll just end up getting set to null when Gson processes the data. Gson also does not require any annotations so long as the variable names match the key names in the JSON. You are allowed to have any kind of setter methods if you need them for other functionality (Gson does not). Basically, the only thing that Gson is looking for is data members that match the keys, and the getter methods. Whether your class is more complex is up to you and what your application needs.
edit: All of the values that Gson processes will be of the String type. If you have int and boolean types you will need to process the input as a String and operate on it to convert it to what you are looking for.
Related
I am new to Spring Boot and I am trying to figure out how to parse json data. I see a lot of tutorials on how to map json string object to an annotated Java class and using and object mapper, like this:
json:
{
"UUID": "xyz",
"name": "some name"
}
public class MyClass{
#JsonProperty
private UUID id;
#JsonProperty
private String name;
#JsonAnyGetter
public UUID getId() {
return this.id;
}
#JsonAnySetter
public void setId(UUID id) {
this.id = id;
}
#JsonAnyGetter
public String getName() {
return this.name;
}
#JsonAnySetter
public void setName(String name) {
this.name = name;
}
}
ObjectMapper objectMapper = new ObjectMapper();
MyClass customer = objectMapper.readValue(jsonString, MyClass.class);
The problem is that the system I am getting the json string from does not match the class naming conventions we use (and I cannot change either one). So, instead of having the example json string above, it might look like this:
{
"randomdstring-fieldId": "xyz",
"anotherrandomstring-name": "some name"
}
This use case only has two fields, but my use case has a larger payload. Is there a way to either map the field names from the json object to the field names in the Java class or is there a way to just parse the json string as a key value pair (so that I can just manually add the fields to my Java object)?
In Jackson with #JsonProperty you can customize the field name with it's annotation parameter value
Therefore, you just have to annotate the entity fields with the #JsonProperty annotation and provide a custom JSON property name, like this:
public class MyClass{
#JsonProperty("original_field_name_in_json")
private UUID id;
...
The #JsonProperty will do it for you:
#JsonProperty("name_in_json")
private Long value;
Let's say I have following flat JSON structure:
{
"name": "name",
"validFrom": "2018-01-09",
"validTo": "2018-01-10",
}
and MyPojo class:
public class MyPojo {
private String name;
#JsonUnwrapped
private Validity validity;
}
and Validity class:
public class Validity {
private LocalDate validFrom;
private LocalDate validTo;
}
I created custom unwrapping serializer and it works fine.
I would like to deserialize JSON above into MyPojo class which includes Validity value object.
How should custom deserializer for Validity be implemented?
#JsonProperty does not work as I want to use 2 Json properties for Validity construction
I would recommend a constructor in this case, a lot simpler than a custom deserializer, something like:
#JsonCreator
public MyPojo(#JsonProperty("name") String name,
#JsonProperty("validFrom") String validFrom,
#JsonProperty("validTo") String validTo) {
this.name = name;
this.validity = new Validity(validFrom, validTo);
}
It's implied that LocalDate is parsed from String above but you may have Jackson parse them.
You may skip annotations above if you use Java 8 with parameter names module
That will require an extra annotation on validity, see open Jackson issue here
#JsonProperty(access = JsonProperty.Access.READ_ONLY)
#JsonUnwrapped
private Validity validity;
I've a POJO and I want to create an instance of this class from JSON. I'm using jackson for converting JSON to Object. I want to ensure that JSON will conain all properties of my POJO. The JSON may contain other extra fields but it must contain all the attributes of the POJO.
Example:
class MyClass {
private String name;
private int age;
public String getName(){return this.name;}
public void setName(String name){this.name = name;}
public int getAge(){return this.age;}
public void setAge(int age){this.age = age;}
}
JSON #1
{
"name":"Nayan",
"age": 27,
"country":"Bangladesh"
}
JSON #2
{
"name":"Nayan",
"country":"Bangladesh"
}
Here, I want JSON#1 to be successfully converted to MyClass but JSON#2 should fail. How can I do this? Is there an annotation for this?
Well, there is an annotation that you could apply to your properties that say they are required.
#JsonProperty(required = true)
public String getName(){ return this.name; }
The bad part is, as of right now (2.5.0), validation on deserialization isn't supported.
...
Note that as of 2.0, this property is NOT used by BeanDeserializer: support is expected to be added for a later minor version.
There is an open issue from 2013 to add validation: Add support for basic "is-required" checks on deserialization using #JsonProperty(required=true)
I'm trying to use Gson to map JSON to POJO where the POJO contains a custom field that is not part of JSON. The field gets updated when the setters of other fields are invoked to add the names of the fields that are being updated to a list.
The POJO class looks something like this:
public class myPojo {
private List<String> dirtyFields;
private String id;
private String subject;
private String title;
public myPojo() {
dirtyFields = new ArrayList<String>();
}
public getId() {
return id;
}
public setId(String id) {
this.id = id;
}
public getSubject() {
return subject;
}
public setSubject(String subject) {
this.subject = subject;
dirtyFields.add("subject");
}
// more setter/getters
}
The dirtyFields ivar is not a deserialized field but it is used to keep track of the fields that are being updated.
After mapping, however, the list seems to become an empty list. This was not the case with Jackson.
Is this due to the expected Gson behaviour?
Gson does not call setter/getters during deserialization/serialization. It access, instead, directly to fields (even if private/protected) using reflection. This explains why your dirtyFields ivar is empty.
The possibility of calling setter/getters is not implemented in Gson as far as I know. The reason why Gson acts like this is explained better here. A comparison between Jackson and Gson features can be found here, you may be interested in setter/getter part.
However Gson is quite flexible to add a custom behavior to get what you need, you should start reading Read and write Json properties using methods (ie. getters & setters) bug
Another way to calculate your dirtyFields list could be using reflection and checking if every field of your POJO is null or not. You could start from this.
I have a use case where we have to send different JSONs to different servers.
The difference is only between JSON keys, the meaning the keys carry is same and so is the data.
For example server XYZ wants JSON data to be sent in this format:
{ "firstName":"Sam", "lastName":"Jones"}
Now server ABC wants JSON data to be sent in this format:
{ "fName":"Sam", "lName":"Jones"}
And firstName and lastName data is populated via a POJO.
So, How do I achieve this? I do not want to clutter the code with if-else conditions.
But wnat to have something which would work like a template loaded dynamically and create the JSON data and also retrieve it back to the POJO.
You should create two POJOs. One for each server. Each POJO can have different property names to satisfy each of the server's requirements.
Or the POJOs can have the same property names, but be annotated to generate different JSON properties. A JSON library like Jackson can do this using the JsonProperty annotation.
How about this strategy?
1. Defines the interface to be used as a common..
interface People{
public String getRegularFirstName();
public String getRegularLastName();
}
2. Define each POJO with implemented interface
//class for "{ "firstName":"Sam", "lastName":"Jones"}"
class PeopleData2 implements People{
private String firstName;
private String lastName;
public String getRegularFirstName(){
return firstName;
}
public String getRegularLastName(){
return lastName;
}
//getter setter here..
}
//class for "{ "fName":"Sam", "lName":"Jones"}"
class PeopleData1 implements People{
private String fName;
private String lName;
public String getRegularFirstName(){
return fName;
}
public String getRegularLastName(){
return lName;
}
//getter setter here..
}
3. Make each json format deserved each POJO classes..
It is not dinamically strategy because it need to add class whe new format comes up.
but it will help system scalability