首页 > 解决方案 > 使用 Jackson 动态替换 Json 值

问题描述

目前,我正在阅读一个 Json 字符串

{
type = animal,
configurationData = {
    type =  "herbivorous",
    address = "123, Windmill Road"
}

}

现在,我必须在读取某个对象后更改值。所以,更新的值就像

{
type = human,
configurationData = {
    type =  "vegeterian",
    address = "876, Borough Street"
}

}

并且需要将更新后的字符串提交到远程服务。目前,我正在这样做。

  1. 从输入 JSON 字符串手动创建 Java 对象(使用http://www.jsonschema2pojo.org/

  2. 通过调用 setter 手动填充 Java 对象。

  3. 将更新的 Java 对象转换为 JSON 并提交到远程服务。

在这里,我看到在发送到远程服务之前再次进行不必要的读取、填充和写入练习。

我们还有其他方法可以更好地实现这一目标吗?我正在考虑加载 json 模板(使用 ObjectMapper)并仅更新该 Json Map 中所需的键并提交该 Map 以删除服务。

就像是,

    Resource resource = resourceLoader.getResource("classpath:" + myJsonFile);
    InputStream inputStream = resource.getInputStream();

    JsonNode node  = mapper.readTree(inputStream);
    //Search Keys from Json and store in Map. use Map.replace(K,V) to replace value and submit that Map to remote.

但我没有得到正确的地图操作中的搜索和存储。因此,对此的任何帮助都会很有用。

提前致谢。

标签: jsonjackson

解决方案


我同意你的做法。我已经尝试过并为我工作。下面的代码片段对您来说听起来合理吗?

    @Test
    public void test_UpdateJsonString() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = "{\"type\":\"animal\",\"configurationData\": {\"type\":\"herbivorous\",\"address\":\"123, Windmill Road\"}}";
        String targetJsonStr ="{\"type\":\"human\",\"configurationData\":{\"type\":\"vegeterian\",\"address\":\"876, Borough Street\"}}";
        Map<String, Object> mapJson = objectMapper.readValue(jsonStr,new TypeReference<Map<String,Object>>(){});
        Map<String, Object> mapTargetJson = objectMapper.readValue(targetJsonStr,new TypeReference<Map<String,Object>>(){});

        // either update all values or a particular property with mapJson.get(fieldName)
        for (Map.Entry<String,Object> keyVal: mapTargetJson.entrySet()) {
            mapJson.replace(keyVal.getKey(),keyVal.getValue());
        }

        jsonStr = objectMapper.writeValueAsString(mapJson);
        JsonNode jsonNode = objectMapper.readTree(jsonStr);
        String type = jsonNode.get("type").asText();
        assertEquals(type,"human");
    }


推荐阅读