从 json 映射到对象时得到错误的结果
Getting wrong results when mapping from json to object
我正在使用 Spring 和其他框架编写 java 应用程序。我正在尝试使用 GSON 将数据从字符串获取到自定义对象。在我的代码中,我使用 GSON
将字符串映射到自定义对象。我是这样做的:
gson.fromJson(response.getBody(), Hello.class)
在我的 Hello.java
中,我有:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Hello {
@JsonProperty("test1")
List<Test1> test1;
@JsonProperty("test2")
List<Test2> test2;
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Test1 {
@JsonProperty("a")
private String a;
@JsonProperty("b")
private String b;
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Test2 {
@JsonProperty("x")
private Test3 test3;
@JsonProperty("y")
private String y;
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Test3 {
@JsonProperty("l")
private String l;
@JsonProperty("m")
private String m;
}
我的 JSON 看起来有点像这样:
{
"test1": [
{
"a": "a",
"b": "b"
}
],
"test2": [
{
"x": {
"l": "l",
"m": "m"
},
"y": "y"
}
]
}
但是只有 test1 被 Gson 正确加载了所有值,而 test2 完全为空。我在这里做错了什么?
而不是
gson.fromJson(response.getBody(), Hello.class);
使用
String json = new String(response.body().bytes());
gson.fromJson(json , Hello.class)
此外,请检查您的 json
字符串,其中可能存在无效字符,这些字符可能来自网络服务设计不佳,例如:json 字符串的 2 双引号开始和结束。
\"{\"message\":\"hello\"}\"
<= 这是错误的
正确的是
{\"message\":\"hello\"}
或 {"message":"hello"}
并且还使用 @SerializedName
而不是 @JsonProperty
最后检查 json 区分大小写的 键 我的意思是 M
不等于 m
我正在使用 Spring 和其他框架编写 java 应用程序。我正在尝试使用 GSON 将数据从字符串获取到自定义对象。在我的代码中,我使用 GSON
将字符串映射到自定义对象。我是这样做的:
gson.fromJson(response.getBody(), Hello.class)
在我的 Hello.java
中,我有:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Hello {
@JsonProperty("test1")
List<Test1> test1;
@JsonProperty("test2")
List<Test2> test2;
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Test1 {
@JsonProperty("a")
private String a;
@JsonProperty("b")
private String b;
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Test2 {
@JsonProperty("x")
private Test3 test3;
@JsonProperty("y")
private String y;
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Test3 {
@JsonProperty("l")
private String l;
@JsonProperty("m")
private String m;
}
我的 JSON 看起来有点像这样:
{
"test1": [
{
"a": "a",
"b": "b"
}
],
"test2": [
{
"x": {
"l": "l",
"m": "m"
},
"y": "y"
}
]
}
但是只有 test1 被 Gson 正确加载了所有值,而 test2 完全为空。我在这里做错了什么?
而不是
gson.fromJson(response.getBody(), Hello.class);
使用
String json = new String(response.body().bytes());
gson.fromJson(json , Hello.class)
此外,请检查您的 json
字符串,其中可能存在无效字符,这些字符可能来自网络服务设计不佳,例如:json 字符串的 2 双引号开始和结束。
\"{\"message\":\"hello\"}\"
<= 这是错误的
正确的是
{\"message\":\"hello\"}
或 {"message":"hello"}
并且还使用 @SerializedName
而不是 @JsonProperty
最后检查 json 区分大小写的 键 我的意思是 M
不等于 m