Back How to parse dynamic and nested JSON in java? - Rest assured API automation framework

20-30
Created By: Fun Doo Testers
Published At: 2020-04-03
Search Query: Java Class Attributes,Java Delete Files,Java File Handling
Tags: Rest Assured Rest API Automation Fun Doo Testers How To Automate Rest Api Using Rest Assured rest api automation using selenium RestAssured rest assured api testing framework how to parse dynamic json in java java json parser java parse json string jackson jsonobject api testing interview questions api testing api testing tutorial for beginners rest assured api testing rest assured api automation framework rest assured tutorial 50 api interview questions
Rest Assured is very popular in API Test Automation. REST Assured API can be used to invoke REST web services and match response content to test them. This video is about how we can parse JSON data to Java Object where keys are dynamically created.


βœ… In this Rest-Assured video, we will be learning,
1. How to parse dynamic JSON?
2. How to parse nested JSON?
3. How to write a recursive Code?
4. Code debugging.


πŸ”₯πŸ”₯πŸ”₯ One to One connect with Fun Doo Testers : https://topmate.io/fundootesters

βœ… If you like my videos, please consider buying me a coffee: https://www.buymeacoffee.com/fundootesters

Good books to read :
βœ… Head First Java: https://amzn.to/2ZQlXqI
βœ… Cracking Coding interviews: https://amzn.to/3bDX8Un


βœ… For business write us on: Contact@fundootesters.com
βœ… Say hello to us, and stay updated!

Facebook: https://www.facebook.com/fundootesters
Instagram: https://www.instagram.com/fundootesters/
LinkedIn: https://www.linkedin.com/company/fundootesters
Blog: https://medium.com/@fundootesters #Restassured #API #fundootesters
GitHub: https://github.com/Fundootesters/RestAssuredFramework



GEAR USE:
β—‹ My Camera: https://amzn.to/3e2UqL7
β—‹ Microphone: https://amzn.to/3bSUvOq
β—‹ Microphone:https://amzn.to/2ZXuo3s
β—‹ Tripod: https://amzn.to/2PqmTQN


DISCLAIMER
Links included in this description might be affiliate links. If you purchase a product or service with the links that I provide I may receive a small commission. There is no additional charge to you! Thank you for supporting me so I can continue to provide you with free content each week!


#Json #RestAssured #FunDooTesters
logo Ask VidTutorAssistant
Comment
or
Question
Your name
Comments with generated responses
@mfs1316
2021-10-08

top class,all youtubers are just validating status becz its easy ,no one is teaching how to parse body becz its difficult even they dont know,after searching found this gem

@FunDooTesters

Glad to hear that. Stay tuned with us for amazing content

VidTutorAssistant (GPT-4)

Hi @mfs1316, thank you for your kind words! We're always aiming to provide detailed content that helps our viewers grow their java programming skills, especially in complex areas like parsing JSON bodies. If you have any specific questions on this topic or if there's something else you'd like us to cover, please let us know. Happy testing and keep watching Fun Doo Testers!


@vinothvijay85
2022-06-18

I have a scenario where i want parse the jsonobject and if id matches (i.e 123) i need to replace the name (ggg) . Input : [{"id":123","name"abc"},{"id"456":"xyz"}] and the output i'm expecting is [{"id":123","name"ggg"},{"id"456":"xyz"}] . I dont want to use to string replace . I need to parse and update the value.

@FunDooTesters

Consider your json as a array. You need to iterate over json. Each element will give you json object. Just check Getting desire id values or not. Org.json lib will help you here

VidTutorAssistant (GPT-4)

Hey @vinothvijay85, excellent question! Your scenario can be addressed using the JSONObject and JSONArray classes. Here is a simple way to do it:

First, parse the JSON input into a JSONArray. Then, loop through each JSONObject in the JSONArray. For each JSONObject, check if the id matches 123, if it does, change the name to 'ggg'. Here's the code snippet:

```java
JSONArray arr = new JSONArray(input); //input is your JSON input.
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
if (obj.get("id").equals(123)){
obj.put("name", "ggg");
}
}
```

The updated JSONArray 'arr' now has the desired changes. Remember to never modify a collection directly while you're iterating it. This can create unexpected results or ConcurrentModificationException. Be sure to ask if you need any more help. Happy Coding!


@viratsuresh5946
2022-10-04

Json string to java object conversion. But my java object has map in it along with other variables.


Map<String, Employee>


In that case how we can achieve it.

@FunDooTesters

Key= employee object I’d
Value= employe object.

If you can share complete data I can help

VidTutorAssistant (GPT-4)

Hello @viratsuresh5946, great question! If your java object has a map in it along with other variables, you can still convert your JSON string to a Java object. Firstly, you need to make sure your Java object Class structure matches your JSON. In the scenario you gave, if you want to map your JSON to the Map, your Employee class should be properly defined. Once you have your class structure ready, you can utilize the Gson library or Jackson API to convert the JSON string into a Java object.

Here's an example with Gson:

```
Gson gson = new Gson();
Type type = new TypeToken(){}.getType();
Map map = gson.fromJson(jsonString, type);
```
In the above code, we are creating a Gson object and indicating the type of our Map which will be deserialized from the JSON string. Then, we use Gson's fromJson() method to convert the JSON string to a Java object, in this case, our map.

Please remember to replace 'jsonString' with your actual JSON string.

I hope this helps! If you have more queries, don't hesitate to ask. Happy coding!


@tanunesta
2021-09-14

Thank you so much for sharing your knowledge with us!
God bless you!

@FunDooTesters

Glad you liked it. You are so kind

VidTutorAssistant (GPT-4)

Thank you so much @tanunesta for your kind words! I'm glad you found the content of the video helpful. Remember, you're always welcome to drop your questions or topics you'd like us to cover. Thanks for watching and Happy Coding! God bless you too!


@Gaurav.Tripathi1
2022-09-07

what is it's advantage over jsonpath ?

@FunDooTesters

Common parsing utility need to develop once and can be used everywhere
Json path every time need to write whenever have to extract data.

Both works well. Can be chosen based on requirements

VidTutorAssistant (GPT-4)

Great question, @Gaurav.Tripathi1! The method of parsing dynamic JSON files, which we discussed in the video, is one way to handle differing JSON structures, especially when they are complex and deeply nested. It provides a good way of navigating through nested objects and arrays, giving us the ability to extract data with great precision.

Compared to JSONPath, working directly with JSON objects using JAVA can give us greater control and flexibility since the JAVA language is more flexible and extensively used. JSONPath, while being absolutely handy and easy to use for straightforward data extraction tasks, might exhibit limited functionality when the JSON structure gets overly complex or unforeseen changes in structure occur.

However, there's no one-size-fits-all here. The choice really depends on the complexity of the JSON data, the requirements at hand, and your comfort level with the tool. Always evaluate the pros and cons before deciding.

I hope this clears up your query. Do not hesitate to ask if you have further questions! βŒ¨οΈπŸŽ¬πŸ”


@mariemzarai3969
2022-07-04

Great explanation, thank you. but i have a problem.

I need to read dynamically a swagger definition (complex json file)

Then I will assign values retrieved from the JSONfile to ATTRIBUTES OF XML elements.

I have to retrieve data and keep dependencies between objects.

For example, I have to know all operationId and for each operation want to keep its information (responses, path, get or post..) and it referred to which tag.

THE JSON FORMAT IS AS BELOW



"paths": {

"/api/v1/users": {

"get": {

"tags": [

"user-controller"

],

"operationId": "getAllUsers",

"responses": {

"200": {}

"post": {

"tags": [

"user-controller"

],

"operationId": "getAllUsers",

"responses": {

"200": {}

"/api/v1/post": {

"get": {

"tags": [

"user-controller"

],

"operationId": "getAllUsers",

"responses": {

"200": {}



PLEASE WHAT CAN I DO ? thanks in advance

@FunDooTesters

Hi Mariem,

I understood problem statement. You will get solutions from google β€œextract data from swagger json”. Basically you need to understand mapping of data. You will find inbuilt methods to extract data. This is bit different thn json parsing

We are also planning to cover such topics but it takes time. You can write me again if you have any doubts.

Thanks,
Nishant

VidTutorAssistant (GPT-4)

Hi @mariemzarai3969, thanks for your kind words and your interesting question!

Dealing with complex JSON structures like your swagger definition could be a bit daunting. I'm happy to offer some guidance!

Firstly, you'll need to parse through your JSON file. To do this, we'll iterate over this JSON object to retrieve the data you require. This is similar to the steps covered in the video to parse dynamic JSON file. The methods mentioned like 'get key' will be instrumental for this.

For parsing your JSON file format specifically, we should look for the "paths" object, then inside this you can traverse through each path (like "/api/v1/users"), and then process the "get" or "post" pertaining to each path. Each of these blocks will have their own "tags", "operationId" and "responses" which you can retrieve quite easily.

As for hooking the JSON data to the XML attributes, this will widely depend on how your XML is structured. But the idea is, once you've parsed and retrieved the relevant JSON data, you can then use it to populate your XML elements' attributes.

Also, you pointed out that you need to maintain dependencies between objects. This can be achieved by pulling all the information for a specific operationId into a combined data structure, such as a map or a POJO (Plain Old Java Object) where all related details (responses, path, get or post) and the relevant tag would be grouped together under the operationId.

Please make sure you watch the code flow in case of nested JSON objects, as they may complicate the structure - here recursive parsing can be useful.

I hope this broad overview helps you get started on your task. If you run into any particular issue, don't hesitate to point it out in the comments section.

Remember: JSON parsing and then tying it to XML is quite doable with Java, but specifics largely depend on how complex and nested your JSON and XML data structures are. Do debug your solution step by step to better understand the flow!

Happy coding! πŸš€


@sridharraju3249
2021-08-16

Great work Nishant! Expecting more Java videos like this scenario from you! thanks :)

@FunDooTesters

Glad you liked it. I’m planning for new series on java after completing current on software testing. Stay tuned with fun doo testers

VidTutorAssistant (GPT-4)

Thanks a ton, @sridharraju3249! Your support means a lot. Absolutely, we're planning many more such practical Java/content scenario videos to help all of you out. Stay tuned and keep learning. Happy coding! :)


@suhailakhtar1707
2022-08-26

this video is very helpful. thanks bhaiya!!!!

@FunDooTesters

Thank you πŸ™

VidTutorAssistant (GPT-4)

I'm glad you found the video helpful, @suhailakhtar1707! We're always here to make complex topics like parsing dynamic and nested JSON easier for you. Remember if you have any queries, don't hesitate to drop them in the comment section. Keep testing and happy coding, bhaiya! Thanks for your support!


@ajaiyapandey5058
2020-07-04

Hi Nishant, Thx for this lecture . Can you explain how to remove all attributes from the JsonObject if that contains as some specific value or empty or null value present ?

@FunDooTesters

Hi Ajaiya Pandey,
thanks for watching the video. In this case first you have to validate null/specific values using iterating entire json. and then you can remove that attributes. .remove() method is available for the same.

VidTutorAssistant (GPT-4)

Hi @ajaiyapandey5058, thank you for liking the lecture. Let's dismantle your question. So, you want to remove all attributes from the JsonObject if a specific, empty or null value is present. In Java, you can achieve this by iterating through the keys of the JsonObject using the keySet() method. Meanwhile, you can use the get() method to check the value of each key. If the value is empty, null, or matches your specific value, you can use the remove() method. Keep in mind though, to avoid ConcurrentModificationException, you may need to create a separate list of keys to remove, then remove them after the iteration. Please give it a try and let me know if you face any problems. Happy coding!


@yelloverz5537
2020-05-23

Sooper cool... But it is more better if you can adjust the subtitle... It will improves the readability..

@FunDooTesters

Sure i will update

VidTutorAssistant (GPT-4)

Hey @yelloverz5537, Thanks for your valuable feedback! You're absolutely correct - subtitles can significantly improve understanding, especially when dealing with complex topics like JSON parsing. I'll definitely look into making the subtitles more precise to enhance readability in upcoming videos. I appreciate your support, and stay tuned for more fun with Java programming. Happy coding!