json 转化成实体
是将 userId 赋值给 @JsonProperty(“id”) ,最后返回的是个map结构的数据
@Data
@ApiModel("用户信息")
public class UserInfo {
@JsonProperty("id")
private int userId;
@JsonProperty("name")
private String userName;
@JsonProperty("code")
private String userCode;
public static class Test {
public static void main(String[] args) {
String str =
"{\"shipperInformation\":{\"userId\":true,\"userName\":1,\"userCode\":1}}";
Template template = null;
try {
template = JSON.parseObject(str, Template.class);
}
catch (Exception e) {
e.printStackTrace();
}
Test2 test2 = new Test2(1, "张胜男", "001");
HashMap<String, String> hashMap = EntityToMapUtil.entityToMap(template.getShipperInformation());
System.out.println(JSON.toJSON(hashMap));
}
/**
* 实体类转Map
*
* @param object
* @return
*/
public static HashMap<String, String> entityToMap(Object object) {
HashMap<String, String> map = new HashMap();
for (Field field : object.getClass().getDeclaredFields()) {
try {
boolean flag = field.isAccessible();
field.setAccessible(true);
Object obj = field.get(object);
if (obj != null) {
Field contField = SealSaveFieldSync.class.getDeclaredField(field.getName());
JsonProperty voField = contField.getAnnotation(JsonProperty.class);
String s = voField.value();
map.put(s, obj.toString());
}
field.setAccessible(flag);
}
catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
}
}