JACKSON with JSON: map unrecognized fields [duplicate] - java

This question already has answers here:
Collecting unknown properties with Jackson
(2 answers)
Closed 6 years ago.
I need to convert a JSON string into a Java object. The JSON will have a few known fields and some unknown ones. Here is an example:
public class MyJsonBean {
private String abc;
private String def;
// getters and setters
}
And the JSON I want to parse:
{"abc":"value1","def":"value2","ghi":"value3","jkl":"value4"}
Only fixed fields are "abc" and "def". Other fields are variable.
I'd like Jackson to parse the variable fields and put them into a list/map within the MyJsonBean class. Is there any way to do that?

Use the #JsonAnySetter Called by json deserialization to store non-member elements of the json object. Stores the value in the otherAnnotations field.
Jackson can actually be made to work with such POJOs: here is one way to do it:
public class MyJsonBean
{
// Two mandatory properties
protected final String abc;
protected final String def;
// and then "other" stuff:
protected Map<String,Object> other = new HashMap<String,Object>();
// Could alternatively add setters, but since these are mandatory
#JsonCreator
public MyJsonBean (#JsonProperty("abc") String abc, #JsonProperty("def") String def)
{
this.abc = abc;
this.def = def;
}
public int getId() { return id; }
public String getName() { return name; }
public Object get(String name) {
return other.get(name);
}
// "any getter" needed for serialization
#JsonAnyGetter
public Map<String,Object> any() {
return other;
}
#JsonAnySetter
public void set(String name, Object value) {
other.put(name, value);
}
}
And there we have it: serializes and deserializes nicely.
Share and enjoy... :)

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

Serialize/deserialize immutable objects that carry extra informations with Jackson

I try to use only immutables objects in my application. I've got a REST service that will take arbitrary JSon objects as input.
I've a Java class that map theses objects, and I want to make them immutable + able to deal with extra parameters (just like using #JsonAnySetter).
Here is my java class:
public class Operation {
private final String _id;
private final String state;
private final Map<String, Object> extra;
public Operation(String _id, String state, Map<String,Object> extra) {
this._id = _id;
this.state = state;
this.extra = extra;
}
// getters....
}
Using #JsonAnySetter I would have:
public class Operation {
private final String _id;
private final String state;
private Map<String, Object> extra = new HashMap<>();
public Operation(String _id, String state) {
this._id = _id;
this.state = state;
}
#JsonAnySetter
public void addExtra(String key, Object value) {
this.extra.put(key,value);
}
// getters....
}
But this is not immutable anymore !
This will not work because Jackson do not find any "extra" json attribute to read. I would like that everything that cannot be mapped be added to my map.
Any idea of how to do this ? (or is it just possible :)
Note: I use javac with -parameters option and the ParameterNameModule from jackson so that I don't need #JsonCreator option.
Ok so I respond to myself :)
It seems that it is not possible to do that using only Jackson.
Because I want immutability, I've turned myself to the 'immutables' framework: http://immutables.github.io/
With a little configuration, it will deal with extra parameters as stated in the following report: https://github.com/immutables/immutables/issues/185.
In my situation, I've got the following code:
#Value.Immutable
#JsonSerialize(as = ImmutableOperation.class)
#JsonDeserialize(as = ImmutableOperation.class)
public abstract class Operation {
#JsonAnyGetter
#Value.Parameter
public abstract Map<String, String> extra();
}
Refer to the documentation of immutables for the details.
If you want to deserialize immutable entity with extra arguments you can utilize builder pattern:
#JsonPOJOBuilder
public class OperationBuilder {
private String _id;
private String _state;
private Map<String, Object> extra = new HashMap<>();
#JsonAnySetter
public OperationBuilder addExtra(String key, Object value) {
this.extra.put(key,value);
return this;
}
// setters....
public Operation build() {
return new Operation(...arguments...)
}
And your original class should have this annotation on a class level:
#JsonDeserializer(builder = OperationBuilder.class)
This way all your known and unknown (extra) fields will be populated inside the builder and then Jackson will call build() method at the end of the deserialization.

Jackson Databind - get properties not specified in pojo

I'm trying to figure out how can I bind json to POJO.
When json can sometime contain additional fields depending on various conditions. Basically speaking - some part of json will always contain same properties,
for example: name and age. But sometimes I'll get shoeSize and/or eyeColor. I cant make list of all possible properties that can be passed to me, because some of them are defined by user.
Is there possibility to achieve something like this?
class MyClass
{
public String name;
public Integer age;
public Map<String, String> additionalArguments;
public MyClass(...) {...}
}
After going through documentation (again) I found annotation called JsonAnySetter and process reverting annotation JsonAnyGetter
class MyClass
{
public String name;
public Integer age;
public Map<String, String> additionalArguments = new HashMap<>();
public MyClass(...) {...}
#JsonAnyGetter
public Map<String,Object> getAdditionalProperties() {
return additionalProperties;
}
#JsonAnySetter
public void putAdditionalProperty(String name, Object value) {
additionalProperties.put(name, value);
}
}

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