Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
VinodKumar19
Explorer

Introduction:


In various scenarios, navigating and extracting data from JSON structures is a common task. This can involve responses from API calls or raw data in JSON format. This guide will walk you through the process of parsing and extracting data from JSON using Java mapping.

Scenario:


Imagine you have an API response and you need to retrieve a specific document number from it.

Input (API Response):


{
"d": {
"__metadata": {
"type": "typehere",
"uri": "urihere"
},
"BOLNR": "00170548",
"ToCheck_BOL_SO": {
"results": [
{
"__metadata": {
"type": "typehere",
"uri":"urihere"
},
"DOC_NUM": "0011998",
"BOLNR": "00263334",
"ToCheck_BOL_SO_DN": {
"results": [
{
"__metadata": {
"type": "typeheree",
"uri": "urihere"
},
"DOC_NUM": "0011278",
"DEL_NUM": "0805137",
"SHIP_NUM": "0011716",
"BOLNR": "26300777"
}
]
}
}
]
}
}
}

 

Java Mapping:


To achieve this, we can utilize the ‘org.json' library in Java. Here’s how you can extract the desired document number from the given JSON.
import org.json.JSONArray;
import org.json.JSONObject;

public class readJSON {

public static void main(String[] args) {

String input = <input here in string>;
String output="";

JSONObject jsonObject= new JSONObject(input);
output=jsonObject.getJSONObject("d")
.getJSONObject("ToCheck_BOL_SO")
.getJSONArray("results")
.getJSONObject(0)
.getJSONObject("ToCheck_BOL_SO_DN")
.getJSONArray("results")
.getJSONObject(0)
.getString("DOC_NUM");

System.out.println("Document Number: "+output);
}

}

 

Output:


Document Number: 0011278

Creating a JSON Object:


Additionally, you can create JSON objects using the ‘put' method as demonstrated below:
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("Name", "XYZ");
jsonObject2.put("City", "MyCity");

System.out.println(jsonObject2.toString());

 

Output:


 {"City":"MyCity","Name":"XYZ"}

 

Conclusion:


Parsing and manipulating JSON data is a crucial skill in modern programming. Java, combined with libraries like ‘org.json', makes this task achievable and efficient. With the techniques outlined in this guide, you can confidently navigate complex JSON structures and extract the data you need for your projects
Labels in this area