我希望能够从两个现有文件创建一个新的 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 文件的同时,第二个 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 的值并对原始数据进行必要的更新,这就是我的做法:
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));
}
根据我们接收的数据的性质/格式,我们可能需要添加额外的空/类型检查。
关于java - GSON - 更新 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40091672/