Home > Back-end >  Merge two json into one json using Java and validate in karate feature file
Merge two json into one json using Java and validate in karate feature file

Time:02-13

Json1 {"key1" :"one","key2":"two"} Json2 {"FN": "AB","LN":"XY"} I wish to have Json3 {"key1" :"one","key2":"two","FN": "AB","LN":"XY"}

I have used below code but it does not working can someone please help me out.

        JSONObject mergedJSON = new JSONObject();
        try {
            mergedJSON = new JSONObject(json1, JSONObject.getNames(json1));
            for (String Key : JSONObject.getNames(json2)) {
                mergedJSON.put(Key, json2.get(Key));
            }
 
        } catch (JSONException e) {
 
            throw new RuntimeException("JSON Exception"   e);
        }
        return mergedJSON;
    }

      * call defaultCOM {ID: "COM-123"}
        * def defaultResponse = response.data.default
        * def jMap = mergeJSON.toMap(defaultResponse)
Here error comes (language: Java, type: com.intuit.karate.graal.JsMap) to Java type 'org.json.JSONObject': Unsupported target type

CodePudding user response:

All I'll say is that the recommended way to merge 2 JSONs is given in the documentation: https://github.com/karatelabs/karate#json-transforms

* def foo = { a: 1 }
* def bar = karate.merge(foo, { b: 2 })
* match bar == { a: 1, b: 2 }

I'll also say that when you use custom Java code, you should stick to using Map or List: https://github.com/karatelabs/karate#calling-java

And if you use things like JSONObject whatever that is, you are on your own - and please consider that not supported by Karate.

When you have to mix Java and the Karate-style JS code (and this something you should try to avoid as far as possible) you need to be aware of some caveats: https://github.com/karatelabs/karate/wiki/1.0-upgrade-guide#js-to-java

CodePudding user response:

Well, if you just don't care about key collisions this should work:

String jsons01 = "{\"key1\" :\"one\",\"key2\":\"two\"}";
String jsons02 = "{\"FN\": \"AB\",\"LN\":\"XY\"}";
JSONObject jsono01 = new JSONObject(jsons01);
JSONObject jsono02 = new JSONObject(jsons02);
JSONObject merged = new JSONObject(jsono01, Object.getNames(jsono01));
for (String key : JSONObject.getNames(jsono02)) {
    merged.append(key, jsono02.get(key));
}
System.out.println(merged);

Result is: {"key1":"one","FN":["AB"],"key2":"two","LN":["XY"]}

  • Related