How to ensure field inclusion in Jackson - java

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)

Related

Spring Boot parse JSON data to Java Class with different field names

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;

Java Spring custom Enum to String conversion in JSON Serialization

I'm trying to convert an enum value into a custom string as part of a JSON response in a Java Spring application. I've attempted to override the enum's toString method and create a Spring converter but both attempts don't seem to work.
Sample Controller
#RequestMapping(value = "/test/endpoint", produces = APPLICATION_JSON_VALUE)
#RestController
public class RecommenderController {
...
#GetMapping("test")
public List<MyEnum> test() {
return new ArrayList<>() {{
this.add(MyEnum.SAMPLE);
}};
}
}
Enum
public enum MyEnum {
SAMPLE("sample"), OTHER_SAMPLE("other sample");
private final String name;
public MyEnum(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
This code returns the response ["SAMPLE"] although I want it to return ["sample"]. Is there a way to implement this in Spring?
Assuming you are using the default MappingJackson2HttpMessageConverter, then behind the scenes you are using Jackson's ObjectMapper to perform all the JSON serialization and deserialization. So it's a matter of configuring Jackson for your protocol objects.
In this case, it's probably most straightforward tell Jackson that it can make a single JSON value for your instance of MyEnum with the #JsonValue annotation.
public enum MyEnum {
SAMPLE("sample"), OTHER_SAMPLE("other sample");
private final String name;
public MyEnum(String name) {
this.name = name;
}
#JsonValue
public String getValue() {
return this.name;
}
}
#JsonValue has a bonus, as described in its Javadoc:
NOTE: when use for Java enums, one additional feature is that value returned by annotated method is also considered to be the value to deserialize from, not just JSON String to serialize as. This is possible since set of Enum values is constant and it is possible to define mapping, but can not be done in general for POJO types; as such, this is not used for POJO deserialization.
So if you have the same Enum definition in your application that receives the list, it will deserialize the human readable value back into your Enum.
This can be done by using the #JsonValue annotation in the enum definition:
public enum MyEnum {
...
#JsonValue
public String getName() {
return this.name;
}
}

Jackson also needs getter methods to correctly serialize a bean property using #JsonCreator

I am using Jackson to serialize some beans into JSON, inside an application that is using Spring Boot 1.5.
I noticed that to serialize a bean using the #JsonCreator correctly, I have to declare the getter method for each property, plus the #JsonProperty annotation.
public class Person {
private final String name;
private final int age;
#JsonCreator
public Person(#JsonProperty("name") String name,
#JsonProperty("age") int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
If I remove methods getName and getAge, Jackson does not serialize the associated propertiy. Why does Jackson also need the getter methods?
Jackson uses reflection to access private and protected properties.
As soon as you delete the getter, Jackson doesn't know how to serialize/deserialize the properties (=your private fields).
The used #JsonProperty annotations of the constructor won't help Jackson to find the properties while compile time as your constructor will be used at runtime.
Unintuitively, the getter also makes the private field deserializable as well – because once it has a getter, the field is considered a property.
Paraschiv, Eugen - "Jackson – Decide What Fields Get Serialized/Deserialized"

How can I avoid duplicate #JsonProperty annotations with an immutable object and non-matching property name?

The json I'm dealing with uses underscores in the property names, but I wish to keep camel case in Java. Further, I'm using immutable style POJOs, since that's a best practice our team has long adopted.
Everything works fine if I put duplicate #JsonProperty annotations in the constructor and on the getter, but this adds a lot of unnecessary bloat (in our classes, we have a couple dozen properties.) Is there a way to tell Jackson exactly once how to transform the Java property name to the JSON property name?
public class Foo {
public final String someProperty;
#JsonCreator
public Foo(#JsonProperty("some_property") someProperty) {
this.someProperty = someProperty;
}
#JsonProperty("some_property")
public String getSomeProperty() {
return someProperty;
}
}
You can choose the naming convention used for JSON. In this case you need SNAKE_CASE. It will convert someProperty field to "some_property": "" JSON. Then you don't need the #JsonProperty in the property.
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
In this case, in Foo, you need to provide the field in the constructor, what requires the #JsonProperty in the constructor params:
public class Foo {
public final String someProperty;
#JsonCreator
public Foo(#JsonProperty("some_property") String someProperty) {
this.someProperty = someProperty;
}
public String getSomeProperty() {
return someProperty;
}
}
At least you can get rid of one of the annotations.

How does the Jackson mapper know what field in each Json object to assign to a class object?

Let's say I have a Json object like this:
{
"name": "Bob Dole",
"company": "Bob Dole Industries",
"phone": {
"work": "123-456-7890",
"home": "234-567-8901",
"mobile": "345-678-9012"
}
}
And to help me read it, I use Jackson's Object Mapper with the following class:
public class Contact {
public static class Phone {
private String work;
private String home;
private String mobile;
public String getWork() { return work; }
public String getHome() { return home; }
public String getMobile() { return mobile; }
public void setWork(String s) { work = s; }
public void setHome(String s) { home = s; }
public void setMobile(String s) { mobile = s; }
}
private String name;
private String company;
private Phone phone;
public String getName() { return name; }
public String getCompany() { return company; }
public Phone getPhone() { return phone; }
public void setName(String s) { name = s; }
public void setCompany(String s) { company = s; }
public void setPhone(Phone p) { phone = p; }
}
My question is, how (using the simplest explanation possible), does the Object mapper "deserialize" the Json object? I thought it was matching variable names, but changing them by a few letters didn't affect the output. Then, I tried switching the order of the set() functions, but that didn't do anything. I also tried both, but that was also useless. I'm guessing there's something more sophisticated at work here, but what?
I tried to look in the documentation and past code, but I didn't see an explanation that made sense to me.
Without Annotations:
Without any annotations, it does what is called POJO mapping, it just uses reflection on the instance members and uses some rules about how to map the keys in the json to the names of the instance members. *note: it works on private members as well as public or package protected as well
If it doesn't match the names of the instance members, then it starts trying to match the getXXX and setXXX methods, if it doesn't match anything then it gives up.
With Annotations:
It uses the metadata supplied by the annotations to do the mapping and conversions.
It is always better to explicitly use the annotations when you have the source to add them to, then there is no guess work on what gets mapped to what.
Remember explicit is always better than implicit!
This is all well documented on the WIKI:
Mapping and Annotations
JSON Schema:
I am creating JSON Schema definitions for all my new projects now to document what is and isn't valid JSON according to the schema rules engine. It is a great way to document your data structures and eliminate parsing errors.

Categories