Can I push jackson-mapped #JsonProperties to the "top level"? - java

Given a Java class like the following:
class MyClass {
String value;
Map<String,Object> map;
#JsonProperty("value")
public String getValue() {
return value;
}
#JsonProperty("map")
public Map<String,Object> getMap {
return map;
}
}
Jackson will convert to JSON like so:
{
"value": "abc",
"map": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
}
What I would like instead is to "flatten" the map attribute somehow so its contents appears at the "top-level" of the JSON structure like this:
{
"value": "abc",
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Is that possible declaratively through any combinations of Jackson annotations?
(This is a simplification of my actual problem, so I am not looking for an answer like "write your own custom MyClass serializer." In reality, this class must work with custom ObjectMappers in a scenario out of my direct control.)

you can try #JsonUnwrapped
As per link, this is supposed to remove a layer of wrapping.
(Jackson 1.9+) #JsonUnwrapped (property; i.e method, field) Properties that are marked with this annotation will be "unwrapped", that is, properties that would normally be written as properties of a child JSON Object are instead added as properties of enclosing JSON Object.

Related

Map with object and list of objects to Json

I have got two main model classes: Customer and Product
public class Customer {
String name;
String surname;
int age;
BigDecimal cash;
}
public class Product {
String name;
Category category;
BigDecimal price;
}
I want to build json file with Map<Customer, List<Product>>
When I write to json file data with my method which works correct - I am sure about this - the json file shows this syntax
{
"Customer{name\u003d\u0027Custo1\u0027, surname\u003d\u0027Surname\u0027, age\u003d18, cash\u003d1200}": [
{
"name": "prod1",
"category": "CLOTHES",
"price": 12000
},
{
"name": "prod2",
"category": "ELECTRONIC",
"price": 15000
}
]
}
Then when i want to read this file, the error Exception in thread "main" java.util.NoSuchElementException: No value present occurs so I think that the Customer syntax from json file is not recognized.
So I tried to write data to json file on my own with this syntax below, but it does not work
[
{
"name": "Abc",
"surname": "Def",
"age": 14,
"cash": "2000"
}
:
[
{
"name": "prod1",
"category": "CLOTHES",
"price": 12000
},
{
"name": "prod2",
"category": "ELECTRONIC",
"price": 15000
}
]
]
json converter method:
public void toJson(final T item) {
try (FileWriter fileWriter = new FileWriter(jsonFilename)) {
fileWriter.write(gson.toJson(item));
} catch (Exception e) {
throw new ValidatorException(e.getMessage());
}
}
#Tom is right on the issues you've faced with. I'll explain why and suggest one more solution.
Your first JSON is technically a valid JSON but it cannot be deserialized, because the map keys are results of the Customer.toString() method Gson uses by default. This is why it looks weird, acts like a debug string, and can't be deserialized back: there it is almost always no way to restore an object from the toString() result (toString is designed mostly for debugging/logging purposes providing basic information regarding the state of a particular object that does not need to expose its all internals at all).
Your second JSON is invalid JSON. Period.
Tom's suggestion of making the list of products a part of the customer class is totally fine. Having it implemented like that lets you to serialize everything as a list like this:
[
{
"name": "john",
"products": [
{"name": "prod1"},
{"name": "prod2"}
]
}
]
Hint: separating domain objects (Customer and Product) and representation objects for data transfer (CustomerDto and ProductDto) is usually a fine idea too since it allows to create representation for any concrete representation implementation (one for various JSON implementation libraries, two for other-format-oriented tools, third for persistence, four for UI views, etc), so it might be implemented like converting Map<Customer, List<Product>> to List<CustomerDto> and back (possibly by using mapper-generators like MapStruct).
If for whatever reason it is not possible to reorganize your domain classes or create Gson-friendly DTO-mappings, or you're fine to keep it as simple as possible and you're fine with having not that trivial JSON structure (as long as you understand implications of the format in this solution: evolution, distribution, etc), then you can enable special Gson mode to support this kind of maps. It generates valid JSONs that can be serialized and deserialized back, but the way it is implemented looks a bit of anti-pattern to me because of losing semantics due to using arrays as the data container.
#AllArgsConstructor
#EqualsAndHashCode
#ToString
final class Customer {
final String name;
}
#AllArgsConstructor
#EqualsAndHashCode
#ToString
final class Product {
final String name;
}
public final class MapTest {
private static final Gson gson = new GsonBuilder()
.enableComplexMapKeySerialization()
.create();
private static final TypeToken<Map<Customer, List<Product>>> customerToProducts = new TypeToken<Map<Customer, List<Product>>>() {};
#Test
public void test() {
final Map<Customer, List<Product>> ordersBefore = ImmutableMap.of(
new Customer("john"), ImmutableList.of(new Product("prod1"), new Product("prod2"))
);
final String json = gson.toJson(ordersBefore, customerToProducts.getType());
Assertions.assertEquals("[[{\"name\":\"john\"},[{\"name\":\"prod1\"},{\"name\":\"prod2\"}]]]", json);
final Map<Customer, List<Product>> ordersAfter = gson.fromJson(json, customerToProducts.getType());
Assertions.assertEquals(ordersBefore, ordersAfter);
}
}
Note that it generates JSON like this (index 0 means the key, index 1 means the value):
[
[
{"name": "john"},
[
{"name": "prod1"},
{"name": "prod2"}
]
]
]

How to make sure order of map elements inside a #RequestBody of POST REST API is maintained?

The RequestBody entity Person in a POST request has a map as following
class Person {
String name;
int age;
Map<String, String> otherProperties;
}
The above entity is mapped via RequestBody as following:
public void processInput(#RequestBody Person person) {
}
Though the invoker of this API sends following JSON in the input:
{
"name": "nameOfPerson",
"age": 10,
"otherProperties": {
"key1": "val1",
"key2": "val2",
"key3": "val3"
}
}
the spring controller processes it as :
{
"name": "nameOfPerson",
"age": 10,
"otherProperties": {
"key2": "val2",
"key3": "val3",
"key1": "val1",
}
}
The order of the map inside the entity is not maintained.
How to make sure the Spring controller reads and processes the map in the right order as was being sent by the invoker?
LinkedHashMap implementation or other implementation of Map does not guarantee that the input order be maintained.
You could create an object that contains your key and value, and then use a list instead of a map when passing the json object.
class Person {
String name;
int age;
List<PersonProperty> otherProperties;
}
class PersonProperty {
String name;
String value;
}
{
"name": "nameOfPerson",
"age": 10,
"otherProperties": [
{"name":"key1", "value":"val1"},
{"name":"key2", "value":"val2"},
{"name":"key3", "value":"val3"}
]
}

Deserializing JSON with Jackson for polymorphic classes

I am attempting to deserialize JSON which can be either a GroupRule or AttributeRule:
AbstractRule
GroupRule
AttributeRule
I want my models/entities/POJOs to be generic as I also use the same classes in other projects with Snakeyaml or other serialization providers.
Having said that, I stumbled across this: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization
which in the article, it indicates I could do:
{ // Using fully-qualified path
"#class" : "com.fasterxml.beans.EmployeeImpl", ...
}
However, when I do that, I am getting:
Cannot construct instance of `com.walterjwhite.email.organization.api.configuration.rule.AbstractRule` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (FileInputStream); line: 4, column: 10] (through reference chain: com.walterjwhite.email.organization.api.configuration.rule.EmailMatcherRule["rule"])
com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
My configuration is this:
{
"name": "default",
"ordering": "1",
"rule": {
"#class": "com.walterjwhite.email.organization.api.configuration.rule.GroupRule",
"criteriaType": "Should",
"rules": [
{"#class": "com.walterjwhite.email.organization.api.configuration.rule.AttributeRule",
"emailMessageField": "Subject",
"values": ["default"]
}
]
},
"matchType": "ContainsIgnoreCase",
"actionClassNames": [
"com.walterjwhite.email.organization.plugins.count.CountAction",
"com.walterjwhite.email.organization.plugins.index.IndexAction",
"com.walterjwhite.email.organization.plugins.reply.MoveAction"
]
}
On the Java side of things, I am doing this generally:
mapper.readValue(inputStream, entityType);
Now, the entityType in this case is EmailMatcherRule which inside it has a rule field which can either be attribute or group. Inputstream is just the fileInputStream I am passing in ...
I am using Jackson 2.10.1. I also converted the above JSON from YAML which was working fine via Snakeyaml. Note that it automatically embeds the classes into the YAML, so this was a non-issue with it.
Is my JSON correct - according to the documentation, I should be able to add the #class attribute to specify the class I want to use, right?
I tried below and it worked without any configuration. Not sure if thats what you want to achieve:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String groupRuleStr = "{\"parentId\":\"parent\",\"groupId\":\"group\"}";
String attributeRuleStr = "{\"parentId\":\"parent\",\"attributeId\":\"attribute\"}";
GroupRule groupRule = mapper.readValue(groupRuleStr, GroupRule.class);
AttributeRule attributeRule = mapper.readValue(attributeRuleStr, AttributeRule.class);
System.out.println(groupRule.groupId);
System.out.println(attributeRule.attributeId);
}
static abstract class AbstractRule {
public String parentId = "parent";
}
static class GroupRule extends AbstractRule {
public String groupId = "group";
}
static class AttributeRule extends AbstractRule {
public String attributeId = "attribute";
}
I had to do this:
objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator());
Now, my JSON looks like this (NOTE: this is a different test entity, but you get the idea):
{
"name": "default",
"ordering": "1",
"rule": [
"com.walterjwhite.email.organization.api.configuration.rule.GroupRule",
{
"criteriaType": "Should",
"rules": ["java.util.HashSet",[[
"com.walterjwhite.email.organization.api.configuration.rule.AttributeRule",
{
"emailMessageField": ["com.walterjwhite.email.organization.api.configuration.rule.EmailMessageField", "Subject"],
"values": ["java.util.HashSet", [
"default"
]],
"matchType": ["com.walterjwhite.email.organization.api.configuration.rule.MatchType","ContainsIgnoreCase"]
}]]
]
}
],
"actionClassNames": ["java.util.ArrayList",[
"com.walterjwhite.email.organization.plugins.count.CountAction",
"com.walterjwhite.email.organization.plugins.index.IndexAction",
"com.walterjwhite.email.organization.plugins.reply.MoveAction"
]
]
}
So, the reference documentation I saw with #class seems inaccurate. I am not really happy about adding all this extra information especially when some of it isn't needed - java.util.ArrayList.

Custom Deserialiser to parse complex Json

I have to deserialise below Json
{
"Student": [
{
"Number": "12345678",
"Name": "abc"
"Country": "IN",
"AreaOfInterest": [
{
“FootBall”: “Yes”,
“Cricket”: “No”
}
]
}
],
"hasMore": false,
"links": [
{
"rel": "self",
"kind": "collection"
}
]
}
into below POJO
class {
private String number;
private String name;
private String footBall;
}
I have written Gson custom deserialiser to lift up AreaOfInterest as below
public List<? extends Student> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
var jsonObject = json.getAsJsonObject();
Stream<JsonElement> student = StreamSupport.stream(jsonObject.getAsJsonArray("Student").spliterator(), true);
Stream<JsonElement> areaOfInterest = StreamSupport.stream(jsonObject.getAsJsonArray("Student").get(0).getAsJsonObject().get("AreaOfInterest").getAsJsonArray().spliterator(), true);
Stream.concat(student,areaOfInterest)
.map(it -> context.deserialize(it, Student.class))
.map(Student.class::cast)
.collect(List.collector())
}
But deserialiser returning two objects of Student instead of one, one is all fields are null except footBall other is actual student except footBall as null, any help how to get single object with all the fields will be of great help, thanks in advance.
This won't be your exact answer, but it might be simpler to use gson to obtain a map and construct your pojo from that map. Alternatively, if you don't like the map, create a pojo that looks like your JSON and map that pojo to the pojo you want.
Background/Reasoning: GSON is the mapper of your choice right now, but might be changed to something else, eg. Jackson, and all of your custom, framework specific mappers will need to be converted/changed if that happens. Using gson to create an object, that looks like the source, and map that to your custom POJO in your controller will make your codes intention clear and your code more resilient to framework changes.

Modify Jackson response

I have two classes:
class A {
int id;
String name;
}
class B {
String property1;
String property2;
String property3;
}
when A extends B
Response:
{
"property1": "value1",
"property2": "value2",
"property3": "value3"
"id":1,
"name": 'my name"
}
Instead, I want to display them as below:
{
"id":1,
"name": 'my name',
"property1": "value1",
"property2": "value2",
"property3": "value3"
}
The order of the fields within JSON object shouldn't matter. As per the spec:
An object is an unordered set of name/value pairs
So what you're asking doesn't really make sense.
You should be able to use JsonPropertyOrder annotation for this.
#JsonPropertyOrder({"id", "name", "property1", "property2", "property3"})
class B {
...

Categories

Resources