[英]Object Mapper convert json format to object, java
I have a class:我有一个 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:我得到了一个
json
格式的信息体,有两种类型:
1. 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)
当我尝试执行以下操作时:
Parent parent = objectmapper.convertvalue(body, Parent.class)
In first type of body it's ok but with second I got error IllegalArgumentException
.在第一种类型的身体中没关系,但在第二种类型中我得到了错误
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.您在 JSON 中没有逗号,并且在
surname
字符串中有空格。 And child
must be in brackets too.并且
child
也必须在括号中。 Try this:尝试这个:
{
"child": {
"name":"TOM",
"surname": "Finn"
}
}
Read about JSON formatting.阅读有关 JSON 格式的信息。 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.如果您确定您的 JSON 是正确的,您可以专注于您的课程。
ObjectMapper
needs getters or setters to work or instead of you have to change the default configuration using setVisibility()
. ObjectMapper
需要 getter 或 setter 才能工作,或者您必须使用setVisibility()
更改默认配置。
Second, use the readValue()
method instead of convertValue()
.其次,使用
readValue()
方法而不是convertValue()
。
You can read more about ObjectMapper
in this article if you still have a problem to handle it.如果您仍然有处理问题,您可以在本文中阅读有关
ObjectMapper
的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.