项目场景:
请求第三方应用 返回json数据问题描述:
第三方返回的数据中,存在java关键词,无法直接使用原属性名进行对应 例如(class、interface等)使用@JsonProperty注解不能返回正确的结果
@Data
static class User{
@JsonProperty( "class")
private String userClass;
@JsonProperty("interface")
private String userInterface;
}
public static void main(String[] args) {
Map<String,Object> map = new HashMap<>();
map.put("class","测试");
map.put("interface","测试1");
String mapStr = JSONObject.toJSONString(map);
System.out.println(mapStr);
User user = JSONObject.parseObject(mapStr, User.class);
System.out.println(user);
}
正常情况来讲 @JsonProperty 注解完全够用,可以成功解析出想要的结果。
但往往事情并不是那么简单
执行结果 :
{"interface":"测试1","class":"测试"}
User(userClass=null, userInterface=null)
可以看出并没有成功映射到想要的数据
原因分析:
具体原因感兴趣的同学可以看下 JSONObject.parseObject 的源码
解决方案:
解决方法有两种
1、修改属性名称,使用原属性名 + “_”
@Data
static class User{
@JsonProperty( "class")
private String class_;
@JsonProperty("interface")
private String interface_;
}
public static void main(String[] args) {
Map<String,Object> map = new HashMap<>();
map.put("class","测试");
map.put("interface","测试1");
String mapStr = JSONObject.toJSONString(map);
System.out.println(mapStr);
User user = JSONObject.parseObject(mapStr, User.class);
System.out.println(user);
}
执行结果 :
{"interface":"测试1","class":"测试"}
User(class_=测试, interface_=测试1)
2、使用fastjson @JSONField注解
@Data
static class User{
@JSONField(name = "class")
private String userClass;
@JSONField(name = "interface")
private String userInterface;
}
public static void main(String[] args) {
Map<String,Object> map = new HashMap<>();
map.put("class","测试");
map.put("interface","测试1");
String mapStr = JSONObject.toJSONString(map);
System.out.println(mapStr);
User user = JSONObject.parseObject(mapStr, User.class);
System.out.println(user);
}
执行结果:
{"interface":"测试1","class":"测试"}
User(userClass=测试, userInterface=测试1)