2016-10-17 1 views
0

既存の2つのファイルから新しいjsonファイルを作成できます。GSON - jsonファイルを更新する

JSONファイルの最初のリストは、この:

{ 
"Jar_serviceid": "service_v1", 
"Jar_version": "1.0", 
"ServiceId": "srv_v1", 
"ServiceState": "Enable", 
"ServiceVersion": "v1", 
"LicenseRequired": false, 
"ServiceURL": null 
} 

そしてもう一つはこれです:私は2番目の最初を更新していることを望む、両方のファイルにこれを読んだ後

{ 
"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()); 
     } 
    } 

多分それを行うには、いくつかのより良い方法がある:

私はこのような何かを試してみましたか?ありがとう。私たちは、第二JSONの値throgh繰り返すと元のデータに必要な更新を行う必要があり

答えて

1

、これは私はそれを行うだろうかです:

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)); 
} 

私たちは、性質に応じて追加のヌル/型チェックを追加する必要があるかもしれません/受け取っているデータの形式。

+0

それは私のために働く!ループを避けるためにマップを使用することは決して考えなかった。新しいことを学びました。メルシ。 – MissBonbon

関連する問題