Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson: Serialization to JSON on Objects using nested Objects, merge child fields into owning class

Let's say I have Java classes that looks like this:

public class A {
    public String name;
    public B b;
}

public class B {
    public int foo;
    public String bar;
}

I want to serialize an instance of A into JSON. I am going to use the ObjectMapper class from Jackson:

A a = new A(...);
String json = new ObjectMapper().writeValueAsString(a);

Using this code, my JSON would look like this:

{
    "name": "MyExample",
    "b": {
        "foo": 1,
        "bar": "something"
    }
}

Instead, I want to annotate my Java classes so that the generated JSON will instead look like this:

{
    "name", "MyExample",
    "foo": 1,
    "bar": "something"
}

Any ideas?

like image 763
ecbrodie Avatar asked Dec 13 '12 22:12

ecbrodie


People also ask

How does Jackson read nested JSON?

A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.

How do I map nested values with Jackson?

Mapping With Annotations To map the nested brandName property, we first need to unpack the nested brand object to a Map and extract the name property. To map ownerName, we unpack the nested owner object to a Map and extract its name property.

What is Jackson object serialization?

Jackson is a solid and mature JSON serialization/deserialization library for Java. The ObjectMapper API provides a straightforward way to parse and generate JSON response objects with a lot of flexibility. This article discussed the main features that make the library so popular.

What is the use of Jackson ObjectMapper?

ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.


1 Answers

Personally I think you may be better off mapping structure to structure, and not doing additional transformations.

But if you do want to go with the plan, just use Jackson 2.x, and add @JsonUnwrapped annotation on property b. That should do the trick.

like image 141
StaxMan Avatar answered Sep 20 '22 00:09

StaxMan