java实现 json属性赋值 实体属性

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;
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值