简体   繁体   中英

json parsing with jackson

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.

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 {
....
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM