Reputation: 161
I want to be able to create a new json file, from two existing one.
The first one List of json files this:
{
"Jar_serviceid": "service_v1",
"Jar_version": "1.0",
"ServiceId": "srv_v1",
"ServiceState": "Enable",
"ServiceVersion": "v1",
"LicenseRequired": false,
"ServiceURL": null
}
And the second one is this:
{
"Include":[
{
"Jar_serviceid":"service_v1",
"Jar_version":"1.0",
"ServiceState":"null"
}
],
"Exclude":"rtm_v2"
}
After reading out this both file, I want that the second is updating the first. In this case I want to have something like this at the end:
{
"Jar_serviceid": "service_v1",
"Jar_version": "1.0",
"ServiceId": "srv_v1",
"ServiceState": "null",
"ServiceVersion": "v1",
"LicenseRequired": false,
"ServiceURL": null
}
So every entry from second json file, while edit the first one. Do you have an entry point for me?
I tried something like this:
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());
}
}
Maybe there is some better way to do that? Thanks.
Upvotes: 0
Views: 1722
Reputation: 30839
We need to iterate throgh values of second json and make necessary updates to original data, this is how I'd do it:
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));
}
We may need to add additional null/type checks depending on nature/format of data we are receiving.
Upvotes: 1