使用java在map中更新不同键的多个值

时间:2017-05-17 07:34:14

标签: java json hashmap

我已将JSON文件转换为地图,我需要使用JAVA一次修改不同键的多个值。

以下是地图转换的JSON文件:

{
  "name": "angularwebpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --inline --progress --port 8080",
    "postinstall": "typings install",
    "build": "webpack --config config/webpack.dev.js --progress --profile --bail"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular/common": "^4.1.2",
    "@angular/compiler": "^4.1.2",
    "@angular/core": "^4.1.2",
    "@angular/forms": "^4.1.2",
    "@angular/http": "^4.1.2",
    "@angular/platform-browser": "^4.1.2",
    "@angular/platform-browser-dynamic": "^4.1.2",
    "@angular/router": "^4.1.2",
    "core-js": "^2.4.1",
    "rxjs": "^5.4.0",
    "zone.js": "^0.8.10"
  },
  "devDependencies": {
    "angular2-template-loader": "^0.6.2",
    "awesome-typescript-loader": "^3.1.3",
    "css-loader": "^0.28.1",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "html-loader": "^0.4.5",
    "html-webpack-plugin": "^2.28.0",
    "null-loader": "^0.1.1",
    "raw-loader": "^0.5.1",
    "style-loader": "^0.17.0",
    "to-string-loader": "^1.1.5",
    "typescript": "^2.3.2",
    "typings": "^2.1.1",
    "webpack": "^2.5.1",
    "webpack-dev-server": "^2.4.5",
    "webpack-merge": "^4.1.0"
  }
}

我需要从JSON上面一次更新多个值,我想为以下键添加值:

  • 名称
  • 开始日期
  • 结束日期
  • 计数
  • OWNERNAME

我现在所写的只是更新单个值的方法,它已经是非常线性的: 使用以下一系列功能:

{
    "name": "",
    "numberID": null,
    "StartDate": "",
    "EndDate": "",
    "count": null,
    "level": null,
    "discipline": null,
    "paymentModel": null,
    "ownerName" : null,
    "coursepackType": null,
    "note": null
}   

任何方式来实现我想要的动态,可能传递一个数组列表左右? 如果需要任何其他规格,请告诉我。

2 个答案:

答案 0 :(得分:0)

您可以修改方法以接受其他Map而不是键值对,并使用另一个map中的新值更新现有map,例如

public String updateValue(Map<String,Object> map, Map<String, String> updatedValues) throws JsonProcessingException{
    Map<String, Object> resultMap = new HashMap<>(map);
    resultMap.putAll(updatedValues);
    String convertedJSONFile = new ObjectMapper().writeValueAsString(resultMap);
    return convertedJSONFile;
}

您可以使用Map调用此方法,例如:

Map<String, String> values = new HashMap<>();
values.put("name", "abc");
values.put("foo", "bar");
body = updateValue(mapWithJSONNodes, "name", "abc")

此外,您不应修改请求中传递的地图,而应创建新地图并将其返回(以维持现有map的状态。)

答案 1 :(得分:0)

大部分代码只应执行一次 - 将json文件解析为Map,将更新后的Map序列化为JSON {{ 1}}。

对于您要添加或修改的每个键/值对,只应重复String个语句:

put

如果你有一些数组或File testDataJsonfile = new File("path/xxx.json"); JsonNode testJSONNodes = getJsonNodes(testDataJsonfile); Map<String, Object> mapWithJSONNodes = convertJSONTOMAP(testJSONNodes); mapWithJSONNodes.put ("name", "abc"); mapWithJSONNodes.put (...); ... String body = new ObjectMapper().writeValueAsString(mapWithJSONNodes); 包含你想要添加的键和值,你可以用循环替换List语句,以进一步减少代码。