1. 程式人生 > >JsonUtil工具類簡介及應用

JsonUtil工具類簡介及應用

 專案中經常會有String轉Object以及Object轉Json字串的等其他的轉化需求,合理的使用Json工具類會很方便轉換。


JsonUtil.java應用 —— toList

        Map dataMap = returnResult.getParams();
        if (dataMap.containsKey("peopleData") && !ObjectUtils.isEmpty(dataMap.get("peopleData"))) {
            //儲存people相關資訊
            List<People> peopleList = JsonUtil.toList(dataMap.get("peopleData").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);
        }
    }