How to validate every object and key values of json - java

I need to validate this JSON in the following method.
{
"DOG":{
"displayName":"DOGGY",
"description":"Has for legs",
"classification":"Lab"
},
"CAT":{
"displayName":"CATHY",
"description":"Has for legs",
"classification":"xxxxxx"
}
}
Now I need to validate the above json by validating each fields suchs as
displayName
description
classification
And also get key such as DOG, CAT
Now the above things should be validating.
But I am unable to get the keys such as DOG, CAT.
JSONObject jsonObject = new JSONObject(useCase.asString());
Iterator<String> keys = jsonObject.keys();
Map<String, String> myMap = new LinkedHashMap<String, String>();
Map<Object, Object> anotherMap = new LinkedHashMap<>();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
myMap.put(((JSONObject) jsonObject.get(key)).getString("displayName")), ((JSONObject) jsonObject.get(key)).getString("classification"));
}
}
anotherMap.forEach((k, v) -> myMap.put(k.toString(), v.toString()));
myMap.forEach((k, v) -> System.out.println(k + " : " + v));*/
Goal is to validate it against json response.

Related

How can I convert LinkedHashMap to JSONObject

ArrayList entries, and this entries is of LinkedHashMap type, I want to convert this into jsonOject for the use, how can I do this?
for(Object entry : entries){
JSONObject entryToProcess = (JSONObject) entry;
}
Hi this conversion utility should do.
What happens here is that you call the method .getKeys() on the LinkedHashMap object to get all the keys. Then for each key you retrieve the information from the LinkedHashMap and you put it inside the JSONObject
// Your input LinkedHashMap
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();
// Providing general values for the test
linkedHashMap.put("First key", "First value");
linkedHashMap.put("Second key", "Second value");
linkedHashMap.put("Third key", "Third value");
// Initialization of the JSONObject
JSONObject jsonObject = new JSONObject();
// for-each key in the LinkedHashMap get the value and put both of
// them into the JSON
for (String key : linkedHashMap.keySet()) {
jsonObject.put(key, linkedHashMap.get(key));
}
The part you care about should be the for loop.
Cheers,
Simple JSONObject constructor would do the trick
for(Object entry : entries){
JSONObject entryToProcess = new JSONObject((LinkedHashMap)entry);
}
Sample:
LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("A",1);
linkedHashMap.put("some key","some value");
Map<String, String> someMap = new HashMap<>();
someMap.put("map-key-1","map-value-1");
someMap.put("map-key-2","map-value-2");
linkedHashMap.put("another key",someMap);
JSONObject jsonObject = new JSONObject(linkedHashMap);
System.out.println(jsonObject.toJSONString());
Output:
{
"another key": {
"map-key-1": "map-value-1",
"map-key-2": "map-value-2"
},
"A": 1,
"some key": "some value"
}

Convert Json string into Hashmap of hashmap in java

I am new to json processing, below is the json string our clients send us, I want to
read this json string into a hashmap of hasmap so that even for the "Client"/"params" key below
I can access its key and value set and process them .
var incomingMessage =
"{
\"dev1\":\"NULL\",
\"devkp2\":\"val\",
\"compression\":\"NULL\",
\"subcode\":\"P_CODE\",
\"code\":\"PEB_USER\",
\"Client\":{
\"first_name\":\"Perf FN 422677\",
\"client_last_name\":\"DP_PSL\",
\"clientid\":\"780A832\",
\"email\":\"DP_PS#airb.com\"
},
\"clientsrc\":\"dev.client.notvalid\",
\"params\":{
\"Name\":\"ABC_PR\",
\"client_ID\":\"PSL\",
\"domain\":\"airb.com\"
}
}"
This is my current code which works fine for non-nested json strings (that is without the Client.params key in above json string):
public static void convertJsonStringToMap(String incomingMessage) {
HashMap<Object, Object> map = new HashMap<Object, Object>();
JSONObject jObject = new JSONObject(incomingMessage);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
for (Map.Entry<Object, Object> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
I want to be able to similarly read nested keys like Client and params. I am using jdk11. I am fine with using jackson or google gson, both approaches would work.
Please help me with processing these nested json string.
A valid JSON string can be easily converted to a Map using Jackson ObjectMapper.
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> parsedMap = mapper.readValue(incomingMessage, Map.class);
It works for nested elements as well -
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String someJsonString = "{" +
"\"A\":\"1\"," +
"\"B\":2," +
"\"C\":" +
"{" +
"\"D\":\"4\"" +
"}" +
"}";
Map<String, Object> outputMap = mapper.readValue(someJsonString, Map.class);
System.out.println(outputMap);
}
Output:
{A=1, B=2, C={D=4}}

Get all the keys in a JSON string JsonNode in java

I have a json string which I need to validate and find any other keys other than in a list is there in the json string. The sample json string is
{
"required" : true,
"requiredMsg" : "Title needed",
"choices" : [ "a", "b", "c", "d" ],
"choiceSettings" : {
"a" : {
"exc" : true
},
"b" : { },
"c" : { },
"d" : {
"textbox" : {
"required" : true
}
}
},
"Settings" : {
"type" : "none"
}
}
To allow only predifined keys is exsist in the json string I want to get all the keys in the json string. How can I obtain all the keys in the json string. I am using jsonNode. My code till now is
JsonNode rootNode = mapper.readTree(option);
JsonNode reqiredMessage = rootNode.path("reqiredMessage");
System.out.println("msg : "+ reqiredMessage.asText());
JsonNode drNode = rootNode.path("choices");
Iterator<JsonNode> itr = drNode.iterator();
System.out.println("\nchoices:");
while (itr.hasNext()) {
JsonNode temp = itr.next();
System.out.println(temp.asText());
}
How to get all the keys from the json string using JsonNode
forEach will iterate over children of a JsonNode (converted to String when printed) and fieldNames() gets an Iterator<String> over keys. Here are some examples for printing elements of the example JSON:
JsonNode rootNode = mapper.readTree(option);
System.out.println("\nchoices:");
rootNode.path("choices").forEach(System.out::println);
System.out.println("\nAllKeys:");
rootNode.fieldNames().forEachRemaining(System.out::println);
System.out.println("\nChoiceSettings:");
rootNode.path("choiceSettings").fieldNames().forEachRemaining(System.out::println);
You'll probably need fields() at some point that returns an Iterator<Entry<String, JsonNode>> so you can iterate over key, value pairs.
This should do it.
Map<String, Object> treeMap = mapper.readValue(json, Map.class);
List<String> keys = Lists.newArrayList();
List<String> result = findKeys(treeMap, keys);
System.out.println(result);
private List<String> findKeys(Map<String, Object> treeMap , List<String> keys) {
treeMap.forEach((key, value) -> {
if (value instanceof LinkedHashMap) {
Map<String, Object> map = (LinkedHashMap) value;
findKeys(map, keys);
}
keys.add(key);
});
return keys;
}
This will print out result as
[required, requiredMsg, choices, exc, a, b, c, required, textbox, d, choiceSettings, type, Settings]
The accepted answer works out great but issues a warning, "Type safety: The expression of type Map needs unchecked conversion to conform to Map <String, Object>"
This answer led me to change that line to the following to eliminate the warning:
Map<String, Object> treeMap = mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
List in the json was not supported in the accepted solution. Here is what I propose:
public List<String> getAllNodeKeys(String json) throws JsonProcessingException {
Map<String, Object> treeMap = objectMapper.readValue(json, new TypeReference<>() {
});
return findKeys(treeMap, new ArrayList<>());
}
private List<String> findKeys(Map<String, Object> treeMap, List<String> keys) {
treeMap.forEach((key, value) -> {
if (value instanceof LinkedHashMap) {
LinkedHashMap map = (LinkedHashMap) value;
findKeys(map, keys);
} else if (value instanceof List) {
ArrayList list = (ArrayList) value;
list.forEach(map -> findKeys((LinkedHashMap) map, keys));
}
keys.add(key);
});
return keys;
}

How to check if an item in a JsonElement exists in a seperate JsonArray?

I have a JsonElement:
JsonElement testCaseParametersJson = batchItem.getTestCase().getToolParameters().get("testCaseParameters");
of which assigns the following:
["dessert", "place", "tvShow"]
And I have a JsonArray:
JsonObject testParametersJson = batchItem.getTestParameters().getAsJsonObject();
of which assigns the following:
{"dessert": "cookies", "tvShow": "survivor", "color" : "blue"}
I'd appreciate some advice on how to check if the key in the JsonArray exists as an item in the JsonElement.
Using Gson library, you can get the String values from your JSONElement / JSONObject and do the following:
String jsonObject = "{\"dessert\": \"cookies\", \"tvShow\": \"survivor\", \"color\" : \"blue\"}";
String jsonArray = "[\"dessert\", \"place\", \"tvShow\"]";
Map<String, String> objMap = new Gson().fromJson(jsonObject, new TypeToken<HashMap<String, String>>() {}.getType());
List<String> arrayVals = new Gson().fromJson(jsonArray, new TypeToken<List<String>>(){}.getType());
for(Entry<String, String> entry : objMap.entrySet()) {
for (String val : arrayVals) {
if (entry.getKey().equals(val)) {
System.out.println("Found value in key set: " + val);
}
}
}
Code can be summarized, and if using Java 8, you can try "forEach" loop according to your needs.

Iterate through JSONObject from root in json simple

I am trying to iterate over a json object using json simple. I have seen answers where you can do a getJSONObject("child") from
{ "child": { "something": "value", "something2": "value" } }
But what if I just have something
{
"k1":"v1",
"k2":"v2",
"k3":"v3"
}
And want to iterate over that json object. This:
Iterator iter = jObj.keys();
Throws:
cannot find symbol
symbol : method keys()
location: class org.json.simple.JSONObject
Assuming your JSON object is saved in a file "simple.json", you can iterate over the attribute-value pairs as follows:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("simple.json"));
JSONObject jsonObject = (JSONObject) obj;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
You can do like this
String jsonstring = "{ \"child\": { \"something\": \"value\", \"something2\": \"value\" } }";
JSONObject resobj = new JSONObject(jsonstring);
Iterator<?> keys = resobj.keys().iterator();
while(keys.hasNext() ) {
String key = (String)keys.next();
if ( resobj.get(key) instanceof JSONObject ) {
JSONObject xx = new JSONObject(resobj.get(key).toString());
Log.d("res1",xx.getString("something"));
Log.d("res2",xx.getString("something2"));
}
}
In Java 8 we can use lambdas
void handleJSONObject(JSONObject jsonObject) {
jsonObject.keys().forEachRemaining(key -> {
Object value = jsonObject.get(key);
logger.info("Key: {0}\tValue: {1}", key, value);
}
}
Below is the code to iterate through org.google.jso.JsonElemet set and filter out the specific JsonElement by key:
Predicate<Map.Entry<String, JsonElement>> keyPredicate = a -> a.getKey().equalsIgnoreCase(jsonAttributeKey);
Predicate<Map.Entry<String, JsonElement>> valuePredicate = a -> a.getValue()!= null && !a.getValue().isJsonNull();
return responseJson.getAsJsonObject().entrySet().stream()
.filter(keyPredicate.and((valuePredicate)))
.findAny()
.orElseThrow(() -> {
System.out.println(jsonAttributeKey +" tag not exist in the json");
return NGPExceptionFactory.getNGPException(errorCode);
})
.getValue();

Categories