Iterate through JSONObject from root in json simple - java

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();

Related

How to iterrate through Json Array and return each value

I have a Json file that contains an Array of Json Objects:
[{"id":"939f0080-e93e-4245-80d3-3ac58a4a4335","name":"Micha","date":"2021-04-20T11:21:48.000Z","entry":"Wow"}, {"id":"939f0070-e93f-4235-80d3-3ac58a4a4324","name":"Sarah","date":"2021-04-21T11:21:48.000Z","entry":"Hi"}, {"id":"897f0080-e93e-4235-80d3-3ac58a4a4324","name":"John","date":"2021-04-25T17:11:48.000Z","entry":"Hi how are you"}...]
I'm using Json-simple to get the array, but I'm only able to get the object, but not the values.
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader("j.json");
Object object = jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) object;
//prints the first Object
System.out.println("element 1 is" + jsonArray.get(0));
//prints whole Array
System.out.println(jsonArray);
how do i Iterate trough my file and get the values of each date, name date and entry instead of the object?
I want to get something like :
"id is 939f0080-e93e-4245-80d3-3ac58a4a4335 name is Micha date is 2021-04-20T11:21:48.000Z enry is wow"
"id is 939f0070-e93f-4235-80d3-3ac58a4a4324 name is Sarah 2021-04-21T11:21:48.000Z date is 2021-04-21T11:21:48.000Z"
"name is ..."
What you want is basically this
public static void main(String[] args) {
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("j.json")) {
Object object = jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) object;
for (Object o : jsonArray) {
JSONObject jsonObject = (JSONObject) o;
System.out.printf("id is %s name is %s date is %s entry is %s%n", jsonObject.get("id"), jsonObject.get("name"), jsonObject.get("date"), jsonObject.get("entry"));
// Or if you want all
for (Object key : jsonObject.keySet()) {
System.out.printf("%s is %s", key, jsonObject.get(key));
}
System.out.println();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
You can use getOrDefault in case the attribute is optional. There are also countless other libraries which can transform your json into a java object. This will give you more type safety. E.g. jackson or gson.
JSONArray implements Collection and Iterable, so you can iterate over it with a For loop or using an Iterator or Stream. sadly, the object is not generic typed, so you will always get Objects and have to cast them yourself:
for(Object value : jsonArray) {
// your code here //
}
Hope this helps:
JSONParser jsonParser = new JSONParser();
try {
Object object = jsonParser.parse("[{\"id\":\"939f0080-e93e-4245-80d3-3ac58a4a4335\",\"name\":\"Micha\",\"date\":\"2021-04-20T11:21:48.000Z\",\"entry\":\"Wow\"}, {\"id\":\"939f0070-e93f-4235-80d3-3ac58a4a4324\",\"name\":\"Sarah\",\"date\":\"2021-04-21T11:21:48.000Z\",\"entry\":\"Hi\"}, {\"id\":\"897f0080-e93e-4235-80d3-3ac58a4a4324\",\"name\":\"John\",\"date\":\"2021-04-25T17:11:48.000Z\",\"entry\":\"Hi how are you\"}]");
JSONArray jsonArray = (JSONArray) object;
jsonArray.forEach(x -> {
JSONObject o = (JSONObject) x;
String collect = o.entrySet()
.stream()
.map(e -> e.getKey() + " is " + e.getValue().toString())
.collect(Collectors.joining(" "));
System.out.println(collect);
});
} catch (ParseException e) {
e.printStackTrace();
}

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.

Java GSON: Getting the list of all keys under a JSONObject

I have got GSON as a JSON parser in Java, but the keys aren't always the same.
For example. I have the following JSON:
{ "The Object I already know": {
"key1":"value1",
"key2":"value2",
"AnotherObject": { "anotherKey1":"anotherValue1", "anotherKey2":"anotherValue2" }
}
I have already got the JSONObject "The Object I already know". Now I need to get all of the JSONElements for this Object, this would be "Key1", "Key2" and "AnotherObject".
Thanks in advance.
EDIT: The Output should be a String Array with all the keys for the JSONObject
You can use JsonParser to convert your Json into an intermediate structure which allow you to examine the json content.
String yourJson = "{your json here}";
JsonElement element = JsonParser.parseString(yourJson);
JsonObject obj = element.getAsJsonObject(); //since you know it's a JsonObject
Set<Map.Entry<String, JsonElement>> entries = obj.entrySet();//will return members of your object
for (Map.Entry<String, JsonElement> entry: entries) {
System.out.println(entry.getKey());
}
Since Java 8 you can use Streams as better looking alternative:
String str = "{\"key1\":\"val1\", \"key2\":\"val2\"}";
JsonParser parser = new JsonParser();
JsonObject jObj = (JsonObject) parser.parse(str);
List<String> keys = jObj.entrySet()
.stream()
.map(i -> i.getKey())
.collect(Collectors.toCollection(ArrayList::new));
keys.forEach(System.out::println);
As of Gson 2.8.1 you can use keySet():
String json = "{\"key1\":\"val\", \"key2\":\"val\"}";
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(json).getAsJsonObject();
Set<String> keys = jsonObject.keySet();
String str = "{\"key1\":\"val1\", \"key2\":\"val2\"}";
JsonParser parser = new JsonParser();
JsonObject jObj = (JsonObject)parser.parse(str);
List<String> keys = new ArrayList<String>();
for (Entry<String, JsonElement> e : jObj.entrySet()) {
keys.add(e.getKey());
}
// keys contains jsonObject's keys

How to get dynamically changed Key's value in Json String using java

I'm trying to parse Json string using java, I have stuck up with some scenario.
See below is my JSON String:
"NetworkSettings": {
"Ports": {
"8080/tcp": [ // It will change dynamically like ("8125/udp" and "8080/udp" etc....)
{
"HostIp": "0.0.0.0",
"HostPort": "8080"
}
]
}
}
I try to parse the above json string by using the following code:
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
if(ntw_Ports_obj.has("8080/tcp"))
{
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
JsonObject ntwtcp_obj=arr_ntwtcp.get(0).getAsJsonObject();
if(ntwtcp_obj.has("HostIp"))
{
ntw_HostIp=ntwtcp_obj.get("HostIp").toString();
System.out.println("Network HostIp = "+ntw_HostIp);
}
if(ntwtcp_obj.has("HostPort"))
{
ntw_HostPort=ntwtcp_obj.get("HostPort").toString();
System.out.println("Network HostPort = "+ntw_HostPort);
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
In my code I have used this code
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
to get the value of "8080/tcp"
How can I get the values of dynamically changing key like ("8125/udp","8134/udp", etc...)
Note: I'm using gson library for parsing
After modification
public static void main(String args[])
{
try
{
JsonParser parser = new JsonParser();
JsonObject obj=(JsonObject)parser.parse(new FileReader("sampleJson.txt"));
System.out.println("obj = "+obj);
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
System.out.println("ntw_Ports_obj = "+ntw_Ports_obj);
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
System.out.println(keyObjects instanceof Map); //**** here the statement prints false
if (keyObjects instanceof Map) // *** so controls doesn't enters into the if() condition block *** //
{
Map map = (Map) keyObjects;
System.out.println("Map = "+map);
keys.addAll(map.keySet());
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println("Array List = "+jArray);
}
}
}
catch(Exception e)
{
}
}
You can do something like that (not tested but should be ok) :
if (ntw_Ports_obj.isJsonArray()) {
Iterator it = ntw_Ports_obj.getAsJsonArray().iterator();
while (it.hasNext()) {
JsonElement element = (JsonElement) it.next();
if(element.isJsonArray()){
JsonArray currentArray = element.getAsJsonArray();
// Do something with the new JsonArray...
}
}
}
So your problem is the key 8080/tcp is not fixed and it may change. when this situation you can try like this to get the value of the Dynamic key.
Set<Map.Entry<String, JsonElement>> entrySet = ntw_Ports_obj
.entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
String key = entry.getKey();
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}
Edit:
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
/** for the given json there is a one json object within the 'Ports' so the 'keyObjects' will be the 'Map'**/
if (keyObjects instanceof Map) {
Map map = (Map) keyObjects;
keys.addAll(map.keySet());
/**
* keys is a List it may contain more than 1 value, but for the given
* json it will contain only one value
**/
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}

how to get specific value from json file in java

I have a json file like this:
{
"list": [
{
"ID" : "1",
"value" : "value is one"
}
{
"ID" : "2",
"value" : "value is two"
}
{
"ID" : "3",
"value" : "value is three"
}
{
"ID" : "4",
"value" : "value is four"
}
]
}
what I want to do is read the josn file and returns the message based on the ID i specify. So for example
if (this.list.containsKey("1"))
{
return this.list.get(messageTitle);
}
That's what I tried but it returns all the values and ID.
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("jsonFile.json"));
JSONObject jsonObject = (JSONObject) obj;
// loop array
JSONArray msg = (JSONArray) jsonObject.get("list");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
How try like this,
JSONArray msg = (JSONArray) jsonObject.get("list");
for(int i = 0;i < msg.length();i++ ) {
JSONObject jsonObj = msg.getJSONObject(i);
//now get id & value
int id = jsonObj.getInt("ID");
String value = jsonObj.getString("value");
if (1 == id) {
//now 'value' is what you want
System.out.println(value);
}
}
Note: can break the loop when the result is satisfied.
You can try with TypeReference using ObjectMapper to convert it into appropriate Map object.
sample code:
BufferedReader reader = new BufferedReader(new FileReader(new File("jsonFile.json")));
TypeReference<Map<String, ArrayList<Map<String, String>>>> typeRef = new TypeReference<Map<String, ArrayList<Map<String, String>>>>() {};
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, ArrayList<Map<String, String>>> data = mapper.readValue(reader, typeRef);
ArrayList<Map<String, String>> list = data.get("list");
for (Map<String, String> map : list) {
if (map.get("ID").equals("1")) {
System.out.println(map.get("value"));
}
}
} catch (Exception e) {
System.out.println("There might be some issue with the JSON string");
}
output:
value is one

Categories