7

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?

ecbrodie
  • 11,246
  • 21
  • 71
  • 120

1 Answers1

11

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • 1
    Actually, `@JsonUnwrapped` is available in Jackson 1.9.x (codehaus instead of fasterxml package). Nonetheless, THIS SOLUTION WORKED GREAT! Thanks a lot :D – ecbrodie Dec 13 '12 at 22:25
  • I have the very same issue now, but this annotation did not solve it. My property is private and when I make it public to fit the description, it starts to complain about get methods of the class B. – Sarge Jul 11 '17 at 04:27