0

In one of my REST(-ish) controller methods i receive a json body like the following:

{
  id: 123,
  otherId: 456,
  // ... other properties
}

I want to automatically map this to a class with the following structure

class Foo {
  int id;
  Bar otherId;
  // ...
}

where Bar is

class Bar {
  int id;
}

So what i want to do is map otherId to id within otherId.id (Bar.id) and simply change my method signature to.

@RequestMapping(...)
public void doThat(@RequestBody @Valid Foo)

Are there any Annotations that can do this for me or do i have to write a wrapping method myself, etc? Is this possible the way i hope it is?

Regards

1 Answer 1

1

You can use the annotation @JsonDeserialize to create your own deserializer like this:

class Foo {
  int id;
  @JsonDeserialize(using = CustomDateDeserializer.class)
  Bar otherId;
  // ...
}

public class CustomDateDeserializer extends StdDeserializer<Bar> {
@Override
    public Item deserialize(JsonParser jp, DeserializationContext ctxt) 
      throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        int id = (Integer) ((IntNode) node.get("id")).numberValue();
        String itemName = node.get("itemName").asText();

        return new Item(id, itemName, new Bar(id));
    }
}

Hope it helps

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

2 Comments

Can you change your code to use @JsonDeserialize and extend StdDeserializer for upcoming help-seekers please? Because this is about JSON->Object
Ok, sorry, no problem.

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.