项目中经常会有String转Object以及Object转Json字符串的等其他的转化需求,合理的使用Json工具类会很方便转换。


JsonUtil —— toList(前端与后端之间传递)

场景: 

  • form表单数据结构如下
form: {
    params:{sectionData:''},
    id:'',
    peopleName: '',
}
  • 转化:JSON.stringify(this.sections)
            submitEvent() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        this.form.params.sectionData = JSON.stringify(this.sections);
                        this.http.postJson('/admin/peopleInfo', this.form).then(resp => {
                            this.requested = false;
                            if (resp.status != 200) {
                                this.$message.error("操作失败");
                            } else {
                                this.$message.success("操作成功");
                                setTimeout(() => {
                                    this.$router.go(-1);
                                }, 500);
                            }
                        });
                    } else {
                        return false;
                    }
                });
                return false;
            },
  • 后台接收:JsonUtil.toList(dataMap.get("sectionData").toString(), People.class)
        Map dataMap = returnResult.getParams();
        if (dataMap.containsKey("sectionData") && !ObjectUtils.isEmpty(dataMap.get("sectionData"))) {
            //保存people相关信息
            List<People> peopleList = JsonUtil.toList(dataMap.get("sectionData").toString(), People.class);
            for (People bean: peopleList) {
                bean.setPeopleName(result.getPeopleName());
                bean.setLinkId(result.getLinkId());
                peopleService.save(bean);
            }
        }

JsonUtil.java源码 —— toList

public static <T> List<T> toList(String json, Class<T> valueType) {
        Validate.notBlank(json);
        Validate.notNull(valueType);
        JavaType javaType = getObjMapper().getTypeFactory().constructParametricType(ArrayList.class, new Class[]{valueType});

        try {
            return (List)getObjMapper().readValue(json, javaType);
        } catch (Exception var4) {
            throw new RuntimeException(var4);
        }
    }

 

JsonUtil —— toJson、toObject(后端之间传递)

 场景: ActiveMQ消息传递

public class TestInfo implements Serializable {
    /** 消息标识 */
    private String msgId; 
    /** 消息内容 */
    private Map data;
}

传递:将需要传递的实体类,转换为JsonString形式传递

TestInfo testInfo = new TestInfo();
testInfo.setMsgId(UUID.randomUUID().toString().replaceAll("-", ""));

Map map = new HashMap();

List<MessageInfo> lists = new ArrayList<>();
// 装载 lists...

// toJson需要接收的是一个Serializable的值,下面有源码
map.put("messageInfo", JsonUtil.toJson((Serializable) lists));
testInfo.setData(map);

//发送AMQ消息给平台
producer.sendMessage(null, JsonUtil.toJson(testInfo ));

接收:转化为一个TestInfoDto接收

    /**
     * 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
     */
    @JmsListener(destination = "...")
    public void receiveQueue(String text) {
        logger.info("Consumer收到的报文为:" + text);
        try {
            TestInfoDto testInfoDto = JsonUtil.toObject(message, TestInfoDto.class);

        } catch (Exception e) {
            e.printStackTrace();
        }

源码:toJson、toObject

    public static String toJson(Serializable value) {
        try {
            return getObjMapper().writeValueAsString(value);
        } catch (JsonProcessingException var2) {
            throw new RuntimeException(var2);
        }
    }

    public static <T> T toObject(String json, Class<T> valueType) {
        Validate.notBlank(json);
        Validate.notNull(valueType);

        try {
            return getObjMapper().readValue(json, valueType);
        } catch (Exception var3) {
            throw new RuntimeException(var3);
        }
    }

 

 

 

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐