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
  • 30,799
  • 15
  • 56
  • 79
Nikita Shah
  • 301
  • 2
  • 9
  • 1
    You can use `DeserializationFeature.UNWRAP_ROOT_VALUE` feature. Examples you can find here: [JSON Jackson deserialization multiple keys into same field](https://stackoverflow.com/questions/57064917/json-jackson-deserialization-multiple-keys-into-same-field), [Jackson - deserialize inner list of objects to list of one higher level](https://stackoverflow.com/questions/54424576/jackson-deserialize-inner-list-of-objects-to-list-of-one-higher-level), [Mapping Json string to map or hashmap field in java](https://stackoverflow.com/questions/9286785/mapping-json-string-to-map-or-hashmap-field-in-java) – Michał Ziober Jul 17 '19 at 07:58

2 Answers2

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 {
....
}
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
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

musooff
  • 6,412
  • 3
  • 36
  • 65
  • 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 – Nikita Shah Jul 17 '19 at 07:42