3

so I have an Item class which looks like this(extra stuff excluded):

{
"id": 1,
"item": "something",
"account": {
    "id": 5,
    "name": "somename"
      }
}

I want the owner tap to appear for example like this

{
"id": 1,
"item": "something",
"account": "somename"
}

I know how to do this by changing the way Item is serialized in Jackson, however if I am to change the way I serialize Item, I will have to include all the extra fields it has, also Item is a base class so I have to do something with all the child classes as well, which is too much work (or is it, dunno if anyone has an easy solution how to serialize just one field and include all the rest). So my question is can I just serialize the Account class and make it return a simple String (not a json object or anything like that). I've tried working around with the JsonGenerator to make it look similar but the best I've got to so far is:

{
"id": 1,
"item": "something",
"account": {"account":"somename"}
}

Thanks!

2

2 Answers 2

2

I think what you want is @JsonIdentityInfo from Jackson.

This annotation allows you to specify how a child entity is serialized in a parent entity.

Here is an example:

    @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="productDescription")
@JsonIdentityReference(alwaysAsId=true) // otherwise first ref as POJO, others as id
private Product product;

This tells Jackson that the product bean should be serialized using its "productDescription" field.

You can also check this tutorial:

http://www.baeldung.com/jackson-annotations

Sign up to request clarification or add additional context in comments.

Comments

0

Scratch that, I've found my mistake was that I always started with: jsonGenerator.writeStartObject(); and ended with: jsonGenerator.writeEndObject(); which itself made it return an object. All I had to do is just use the writeString method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.