我希望能够从现有的两个json文件中创建一个新的json文件。
第一个json文件列表:
{
"Jar_serviceid": "service_v1",
"Jar_version": "1.0",
"ServiceId": "srv_v1",
"ServiceState": "Enable",
"ServiceVersion": "v1",
"LicenseRequired": false,
"ServiceURL": null
}
第二个是这个:
{
"Include":[
{
"Jar_serviceid":"service_v1",
"Jar_version":"1.0",
"ServiceState":"null"
}
],
"Exclude":"rtm_v2"
}
读完这两个文件之后,我希望第二个更新第一个文件。在这种情况下,我想在最后得到这样的东西:
{
"Jar_serviceid": "service_v1",
"Jar_version": "1.0",
"ServiceId": "srv_v1",
"ServiceState": "null",
"ServiceVersion": "v1",
"LicenseRequired": false,
"ServiceURL": null
}
所以每个条目来自第二个json文件,同时编辑第一个。你有入门点吗?
我试过这样的事情:
if (secondconfig != null) {
if (secondconfig .getInclude() != null) {
for (ServiceList service : secondconfig.getInclude()) {
for (int i = 0; i < firstconfig.length; i++) {
ServiceList serv = gson.fromJson(firstconfig[i], ServiceList.class);
if(serv.getServiceId().equalsIgnoreCase(service.getJar_serviceid())){
// update
}
}
}
}
if (updatedconfig.getExclude() != null) {
System.out.println("Execlude: " + updatedconfig.getExclude());
}
if (updatedconfig.getVin() != null) {
System.out.println("VIN: " + updatedconfig.getVin());
}
}
也许有更好的方法可以做到这一点?感谢。
答案 0 :(得分:1)
我们需要迭代第二个json的throgh值并对原始数据进行必要的更新,这就是我要做的:
public static void main(String[] args) {
Gson gson = new Gson();
Map<String, Object> data = gson.fromJson("{\"Jar_serviceid\": \"service_v1\",\"Jar_version\": \"1.0\",\"ServiceId\": \"srv_v1\",\"ServiceState\": \"Enable\",\"ServiceVersion\": \"v1\",\"LicenseRequired\": false,\"ServiceURL\": null}", Map.class);
Map<String, Object> newValues = gson.fromJson("{\"Include\":[{\"Jar_serviceid\":\"service_v1\",\"Jar_version\":\"1.0\",\"ServiceState\":\"null\"}],\"Exclude\":\"rtm_v2\"}", Map.class);
if(null != newValues
&& newValues.containsKey("Include")
&& newValues.get("Include") instanceof List){
Map<String,Object> firstValue = ((List<Map>) newValues.get("Include")).get(0);
if(null == data){
data = new HashMap<>(firstValue);
}else{
for(String key : firstValue.keySet()){
data.put(key, firstValue.get(key));
}
}
}
System.out.println(gson.toJson(data));
}
我们可能需要根据我们收到的数据的性质/格式添加额外的空/类型检查。