0

I am using the Jackson library for conversion of a JSON string to Java objects

My json is:

{ 
 "human":{ 
 "fname":"anjali",
 "lname":"malhotra"
 }
}

I want this to be converted into a Java class with following structure:

public class Human
{
 String fname;
 String lname;
}

I can successfully convert it into

public class HumanWrapper
{
 Human human;
}

But, I wanted to know if there is a way I can directly convert it into the Human format. I read about custom deserialization but was reluctant for that approach.

Erwin Bolwidt
31.3k15 gold badges59 silver badges81 bronze badges
asked Jul 17, 2019 at 7:07
1

2 Answers 2

1

You could achieve this by configuring ObjectMapper to use DeserializationFeature.UNWRAP_ROOT_VALUE :

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);

and annotatating your Human class with @JsonRootName annotation :

@JsonRootName("human")
public class Human {
....
}
answered Jul 17, 2019 at 7:17
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks.. I will try this out and update the result.
0

You need to have a HumanWrapper class as your human object is defined inside you json object

{
 "human": {
 }
}

If you able to change you API to send just a human object like this

{ 
 "fname":"anjali",
 "lname":"malhotra"
}

Then you woudn't be bothering to have a HumanWrapper

answered Jul 17, 2019 at 7:23

1 Comment

In the current framework in my Organization, changing the API response is not possible. And I felt that adding a wrapper just for this is maybe not the best approach

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.