json - 使用 Jackson 动态替换 Json 值
问题描述
目前,我正在阅读一个 Json 字符串
{
type = animal,
configurationData = {
type = "herbivorous",
address = "123, Windmill Road"
}
}
现在,我必须在读取某个对象后更改值。所以,更新的值就像
{
type = human,
configurationData = {
type = "vegeterian",
address = "876, Borough Street"
}
}
并且需要将更新后的字符串提交到远程服务。目前,我正在这样做。
从输入 JSON 字符串手动创建 Java 对象(使用http://www.jsonschema2pojo.org/)
通过调用 setter 手动填充 Java 对象。
将更新的 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.
但我没有得到正确的地图操作中的搜索和存储。因此,对此的任何帮助都会很有用。
提前致谢。
解决方案
我同意你的做法。我已经尝试过并为我工作。下面的代码片段对您来说听起来合理吗?
@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");
}
推荐阅读
- typescript - TypeScript:将数组传递给变量而不是直接传递给函数时出错
- excel - 识别发生特定模式变化的行
- python - 无法在 Python 中使用 scipy 在凹多边形内生成正确的三角形网格
- javascript - 用于更新 postgresql 数据库的 Knex 查询,其中数组类型列包含特定值
- java - 为什么我的 IF 无法获取我的 ArrayList 的某些索引?
- pyspark - 从数据框创建滚动固定面板
- java - 如何在Android上模拟位置?
- c# - 如何正确连接 DataTable 的列的值?
- android - OnClick 导航抽屉标题图像不起作用
- python - PySerial 无法在只读端口上关闭