简体   繁体   中英

Object Mapper convert json format to object, java

I have a class:

public class Parent{
   private Child child;

}

public class Child{
  String name;
  String surname;
}

And I got an info body as a json format in two types:

1.

   {
    "child"{
      "name":"TOM"
      "surname":"Finn"
            }
    }
  {
    "name":"TOM"
    " surname": "Finn"
   }

And when I try to do the following: Parent parent = objectmapper.convertvalue(body, Parent.class)

In first type of body it's ok but with second I got error IllegalArgumentException .

How can I fix it that both type of body will be accepted?

You don't have a comma in JSON and have space in surname string. And child must be in brackets too. Try this:

{
  "child": {
    "name":"TOM",
    "surname": "Finn"
  }
}

Read about JSON formatting. There aren't many rules, but you should stick to them.

EDIT:

If you are sure your JSON is correct, you can focus on your classes. ObjectMapper needs getters or setters to work or instead of you have to change the default configuration using setVisibility() .

Second, use the readValue() method instead of convertValue() .

You can read more about ObjectMapper in this article if you still have a problem to handle it.

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