I am having a hard time getting the JSON Key name. Because the whole name is not fixed. I would like to get the media_id_ but the problem is the numbers next to it is not fixed/static.The goal I am trying achieve here is that I want to get the value of the mediaFit but I can't because I have no idea how to find the media_id_xxx.
"media_id_1696320854359": {
"resourceId": "HzXvCFvKQWrf9hpfMi2u3smsvziXpz2Vazvr",
"groupId": "9ff31635-b440-41b2-b147-792aed6e5529",
"orignalId": "HzXvCFvKQWrf9hpfMi2u3smsvziXpz2Vazvr",
"orignalWidth": 1584,
"orignalHeight": 1920,
"horizontal": {
"height": 1080,
"width": 891,
"top": 0,
"left": 514.5
},
"vertical": {},
"custom": {},
"type": "img",
"kenBurns": "forced",
"mediaFit": "fill",
"mediaAlign": "center",
"tags": [],
"name": "helmet.jpg",
"height": 1920,
"width": 1584,
"modifiedAt": "2023-09-28T14:52:31.214Z",
"userId": "9ff31635-b440-41b2-b147-792aed6e5529",
}
Here is my code. This is pretty messy because I keep checking. Pardon.
JSONObject jsonObject = new JSONObject(templatePreviewElements.getPreviewSrcUrl().getAttribute("text"));
System.out.println(jsonObject);
JSONArray jsonArray = jsonObject.getJSONArray("pages");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonObject.getJSONArray("pages").getJSONObject(i);
for (Object key: jsonObject2.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObject2.get(keyStr);
//Print key and value
System.out.println("key: " + keyStr + " value: " + keyvalue);
if (keyStr.contains("media_id")) {
String actualEffect = jsonObject.getJSONArray("pages")
.getJSONObject(i)
.getJSONObject("media_id")
.getString("mediaFit");
System.out.println("Actual Selected Text Effect: " + actualEffect);
System.out.println("Expected Selected Text Effect: " + mediaEffect);
assertEquals(actualEffect, mediaEffect);
System.out.println(keyStr.contains("media_id"));
}
}
}
You seem to have found a way to identifiy the correct propertyname already, but you don't use that propertyname
if (keyStr.contains("media_id")) {
String actualEffect = jsonObject.getJSONArray("pages")
.getJSONObject(i)
.getJSONObject("media_id") //this will retrieve an object with the key "media_id", which doesn't exist
.getString("mediaFit");
...
}
You of course must use keyString
here instead of "media_id"
to get the correct object
if (keyStr.contains("media_id")) {
String actualEffect = jsonObject.getJSONArray("pages")
.getJSONObject(i)
.getJSONObject(keyStr)
.getString("mediaFit");
...
}
Furthermore, you already have isolated the correct wrapper object (ie jsonObject2
) and even the correct mediaIdObject (ie keyvalue
) here. So there is no need you start from scratch again, ie you can just do
if (keyStr.contains("media_id")) {
String actualEffect = ((JSONObject)keyvalue).getString("mediaFit");
...
}
here, if the key fits the condition.