API Json response to format of List of maps - java

I am struggling a little bit to get a JSON response from the API server in a readable format.
So here is the page I am currently using for exercises:
https://reqres.in/ Position 4, GET LIST Resource
I am able to retrieve the data from the server in the JSON format which looks like:
{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 1,
"name": "cerulean",
"year": 2000,
"color": "#98B2D1",
"pantone_value": "15-4020"
},
{
"id": 2,
"name": "fuchsia rose",
"year": 2001,
"color": "#C74375",
"pantone_value": "17-2031"
},
and so on. I am able to retrieve one object in the form of String:
[id:1, name:cerulean, year:2000, color:#98B2D1, pantone_value:15-4020]
I have 6 objects like that in an array, I am looping through the JSON response using:
System.out.println("Json Array count: " + count);
for (int i = 0; i<count; i++){
String books = js.getString("data["+i+"]");
System.out.println(books);
}
Is there an easy way to transcribe this data to the list of maps? I.e
K: id, V: 1 and K: name, V: cerulean etc
I am a freshman if it comes for coding.
Here is my whole class:
String baseURI = RestAssured.baseURI = "https://reqres.in";
RequestSpecification rs = given().header("Content-Type","application/json");
Response response = rs.when().get("/api/unknown");
System.out.println(response.getStatusCode());
response.then().statusCode(200);
Assert.assertEquals(200, response.getStatusCode());
String resource = response.prettyPrint();
JsonPath js = new JsonPath(resource);
int count = js.getInt("data.size()");
System.out.println("Json Array count: " + count);
for (int i = 0; i<count; i++){
String books = js.getString("data["+i+"]");
System.out.println(books);
}

Just use generic get of JsonPath in your case like:
public static void main(String[] args) throws URISyntaxException {
String baseURI = RestAssured.baseURI = "https://reqres.in";
RequestSpecification rs = given().header("Content-Type","application/json");
Response response = rs.when().get("/api/unknown");
List<Map> result = response.jsonPath().get("data");
for(Map map: result){
System.out.println(map);
}
}

Related

How to combine two JSONArrays JAVA (special requirements below)

I have a code snippet to combine two JSONArrays into one. Here it is,
for (i = 0; i < cityJArray.length(); i++)
{
resultsJArray.put(cityJArray.getJSONObject(i));
}
It works as it adds the second JSONArray (cityJArray) to the first (resultsJArray). But, my requirement is to add the second one to the first array of the first JSONArray (apologies for I'm not able to explain by words, but I will try to explain using codes down).
This is the JSONObject:
{"results":
[{"id": 248,
"name": "Alternatif Cibubur",
"slug": "alternatif-cibubur",
"status": "active",
"city":
{"id": 11,
"name": "Depok",
"slug": "depok",
},
"longitude": 106.900786}]}
I have already converted it into JSONArray because I have to separate the field 'city' and change its attribute names into 'city_id', 'city_name', 'city_slug'. Because they will create a duplicate as it's already an attribute at 'results' field (see the given JSONObject).
(Purpose: Create a .CSV file from JSONObject)
(Problem begins: When I try to seperate a field from the JSONObject to make it into different columns)
JSONArrays details:
resultsJArray:
[{"id": 248,
"name": "Alternatif Cibubur",
"slug": "alternatif-cibubur",
"status": "active",
"longitude": 106.900786}]
cityJArray:
[{"id": 11,
"name": "Depok",
"slug": "depok"
}]
I want to add this two seperated JSONArrays into one like this (below is the expected output)
[{"id": 248,
"name": "Alternatif Cibubur",
"slug": "alternatif-cibubur",
"status": "active",
"longitude": 106.900786,
"city_id": 11,
"city_name": "Depok",
"city_slug": "depok"}]
This should work as required, I have noted both arrays as Strings initially then converted both to JSONArray.
String resultsString = "[{ 'id': 248, 'name': 'Alternatif Cibubur', 'slug': 'alternatif-cibubur', 'status': 'active', 'longitude': 106.900786 }]";
String cityString = "[{ 'id': 11, 'name': 'Depok', 'slug': 'depok' }]";
try
{
//Convert String into JSONArray for both results and city.
JSONArray resultsJArray = new JSONArray(resultsString);
JSONArray cityJArray = new JSONArray(cityString);
//Get the first and only JSONObject within each of the arrays.
JSONObject resultsJObject = resultsJArray.getJSONObject(0);
JSONObject cityJObject = cityJArray.getJSONObject(0);
//Get the required values from the JSONObject within city.
int city_id = cityJObject.getInt("id");
String city_name = cityJObject.getString("name");
String city_slug = cityJObject.getString("slug");
//Put the values into the results JSONObject.
resultsJObject.put("city_id", city_id);
resultsJObject.put("city_name", city_name);
resultsJObject.put("city_slug", city_slug);
//Print to verify.
System.out.println("Updated resultsJArray: " + resultsJArray);
}
catch (JSONException e)
{
e.printStackTrace();
}
I use the package "com.alibaba.fastjson" , code as follow:
public static void CombinTest(){
String a = "[{\"id\": 248, \n" +
"\"name\": \"Alternatif Cibubur\", \n" +
"\"slug\": \"alternatif-cibubur\", \n" +
"\"status\": \"active\", \n" +
"\"longitude\": 106.900786}]";
String b = "[{\"id\": 11, \n" +
"\"name\": \"Depok\", \n" +
"\"slug\": \"depok\"\n" +
"}]";
JSONArray resultObjArr = JSON.parseArray(a);
JSONArray cityObjArr = JSON.parseArray(b);
for (int i = 0; i < resultObjArr.size(); i++)
{
JSONObject city = cityObjArr.getJSONObject(i);
Set<String> keys = city.keySet();
if(keys.size()>0){
for(String key:keys){
resultObjArr.getJSONObject(i).put("city_"+key,city.get(key));
}
}
}
System.out.println(JSON.toJSONString(resultObjArr));
}

JSON Parsing Nested Array Objects

Using Simple-JSON on the following JSON formatted file, I'm having a lot of trouble understanding how to access the objects within the array under "name".
JSON File:
[
{
"name":{
"firstName": "Developer",
"lastName": "D"
},
"id": 00,
"permissionLevel": 3,
"password": 12345
},
{
"name":{
"firstName": "Bob",
"lastName": "Smith"
},
"id": 01,
"permissionLevel": 2,
"password": 23456
}
]
I'm able to obtain the information for all of the other contents because they're not located in a nested array; However, when I attempt to retrieve the objects under "name", all that is output is the String found in the JSON file.
Current code:
String[] searchData = {
"name",
"firstName",
"lastName",
"id",
"permissionLevel",
"password"
};
jsonArray = (JSONArray)new JSONParser().parse(s);
for(int i = 0; i < jsonArray.size(); i++){
JSONObject jo = (JSONObject)jsonArray.get(i);
for(int j = 0; j < searchData.length; j++){
System.out.println(
searchData[j] + ": " + jo.get(searchData[j]));
}
}
Output:
name: [{"firstName":"Developer","lastName":"D"}]
firstName: null
lastName: null
id: 0
permissionLevel: 3
password: 12345
name: [{"firstName":"Bob","lastName":"Smith"}]
firstName: null
lastName: null
id: 1
permissionLevel: 2
password: 23456
As you can see, "name" outputs a String from the JSON file, and not each individual value.
In the end, I need to write a universal code that can accept new "searchData" tags for each file that's input.
Might someone be able to direct me how to obtain objects held
within nested arrays?
Or perhaps I need to use a different Library? If so, which one is the most efficient for Java? I'm not programming for Android, and I continue to find Library suggestions for Android, constantly.
My apologies if this post is a dupe, but no other posts are aiding me.
You should get your firstname and lastname, like:
jo.get("name").get("firstname");
jo.get("name").get("lastname");
To get the objects held within nested arrays/objects, you will have to write a recursive method and flatten the structure into a map. Below example shows the same:
public static void main(String args[]) throws ParseException {
Object object = new JSONParser().parse("[ { \"name\":{ \"firstName\": \"Developer\", \"lastName\": \"D\" }, \"id\": 00, \"permissionLevel\": 3, \"password\": 12345 }, { \"name\":{ \"firstName\": \"Bob\", \"lastName\": \"Smith\" }, \"id\":01, \"permissionLevel\": 2, \"password\": 23456 }]");
Map<String, Object> pairs = new HashMap<>();
addValues(object, pairs);
System.out.println(pairs);
}
public static void addValues(Object object, Map<String, Object> pairs){
if(object instanceof JSONObject){
JSONObject jsonObject = (JSONObject) object;
for(String key : jsonObject.keySet()){
if(jsonObject.get(key) instanceof JSONObject || jsonObject.get(key) instanceof JSONArray){
addValues(jsonObject.get(key), pairs);
}else{
pairs.put(key, jsonObject.get(key));
}
}
}else if(object instanceof JSONArray){
JSONArray jsonArray = (JSONArray)object;
for(Object element : jsonArray){
addValues(element, pairs);
}
}
}
You can tweak this method to have keys like name.firstname or name.lastname depending on requirements.
I understand that you want the searchData tags to be taken into consideration while parsing the JSON. I would suggest using Google Gson for this case.
You can write a POJO which return the ArrayList<User> for your JSON.
Refer this article on how use Google Gson

how can I get response value (json) to String via Java

I have the json format like following
{
"items": [
{
"id": 0,
"name": "name1"
},
{
"id": 1,
"name": "name2"
}
]
}
I want to filter name from it , Array name = [name1, name2]
#GET (Web service)
#Produces(MediaType.APPLICATION_JSON)
public Response getItem() {
ClientConfig config = new ClientConfig();
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(getUserName(),getUserPassword());
config.register(feature);
Client client = ClientBuilder.newClient(config);
WebTarget service = client.target(getURI() + "/Item");
Response response = service.request().header("Content-Type", "application/json").get();
return response;
}
I have already tried here
http://gotoanswer.com/?q=How+to+Parse+the+this+JSON+Response+in+JAVA
then success.
But how can I do to dynamicaly get json format from Response to string
so that I can input to String jsonString.
When you are parsing your json, the 'items' is an array in your json. So if you try to get the 'items' you will need to type cast it to JSONArray. And iterating on this JSONArray you can get the values of the array using the attributes defined like 'name' and 'id'.
Can you try like this?
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray items = (JSONArray) jsonObject.get("items");
for (int 1 = 0; i < items.length(); i++)
{
System.out.println( items.get(i).get("name");
}
Hope it will help you.

Parsing a JSON object within a JSON object

I have a JSON file which contains an array of item objects:
{
"item": [
{
"title": "TitleA",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
},
{
"title": "TitleB",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
}
]
}
Now I know how to get the "title", but I don't know how I would access the "-url" within "media:content" for example, since it seems to be a JSON object within the Item object. How would I get this value and assign it to a value in my Item class?
try as to get "-url" within "media:content" from current json string :
JSONObject jsonObject = new JSONObject("Your JSON STRING HERE");
JSONArray jsonArray =jsonObject.getJSONArray("item");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectitem=
jsonArray.getJSONObject(i);
// get title or link here
String strtitle=jsonObjectitem.getString("title");
//....get other values in same way
// get media:content json object
JSONObject jsonObjectmediacontent =
jsonObjectitem.getJSONObject("media:content");
// get url,medium,...
String strurl=jsonObjectmediacontent.getString("-url");
//....get other values in same way
}
Write below code to parse -url string, it will solve your problem.
JSONObject mMainJsonObj = new JSONObject("Pass Json Response String Here");
JSONArray mItemJsonArray = mMainJsonObj.getJSONArray("item");
for (int i = 0; i < mItemJsonArray.length(); i++) {
JSONObject mJsonObj1 = mItemJsonArray.getJSONObject(i);
String mTitle = mJsonObj1.getString("title");
String mLink = mJsonObj1.getString("link");
JSONObject mJsonObjGuid = mJsonObj1.getJSONObject("guid");
String mIsPermLink = mJsonObjGuid.getString("-isPermaLink");
String mText = mJsonObjGuid.getString("#text");
JSONObject mJsonObjAtomLink = mJsonObj1.getJSONObject("atom:link");
String mRel = mJsonObjAtomLink.getString("-rel");
String mHref = mJsonObjAtomLink.getString("-href");
JSONObject mJsonObjMediaContent = mJsonObj1.getJSONObject("media:content");
String mUrl = mJsonObjMediaContent.getString("-url");
String mMedium = mJsonObjMediaContent.getString("-medium");
String mHeight = mJsonObjMediaContent.getString("-height");
String mWidth = mJsonObjMediaContent.getString("-width");
}
And see below link for more information.
Json Parsing Example
Solution with Jackson: read your JSON into a JsonNode using an ObjectMapper and retrieve your values like this:
// Since JsonNode implements Iterable of itself and cycles through array elements,
// this works
for (final JsonNode element: node)
doSomethingWith(element.get("media:content").get("-url"));

Nested JSONObject

I am having several problems with JSONObjects and JSONArray.
I would like to parse this json file:
[{
"SourceFile": "AndresIniesta.flv",
"ExifTool": {
"ExifToolVersion": 8.22
},
"System": {
"FileName": "AndresIniesta.flv",
(...)
},
"File": {
"FileType": "FLV",
"MIMEType": "video/x-flv"
},
"Flash": {
"Duration": "04:09",
"Starttime": 0,
"Totalduration": 249.36,
"ImageWidth": 320,
(...)
},
"Composite": {
"ImageSize": "320x240"
}
}]
But not all of them, just the field Flash.
The whole file is an JSONArray, but with just 1 element. I got the Flash filled with this piece of code:
JsonMappingException, IOException {
String a = new String();
InputStream is =
this.getClass().getClassLoader().getResourceAsStream(
"a.json");
String jsonTxt = IOUtils.toString(is);
JSONArray json = (JSONArray) JSONSerializer.toJSON(jsonTxt);
JSONObject flash = json.getJSONObject(0);
System.out.print("flash -> " + flash.getString("Flash"));
But I don't know hoy to access to each one of Flash fild, lis Duration, Starttime... etc.
When I try it like this:
String canseekontime =
flash.getString("Canseekontime");
int starttime =
flash.getInt("Starttime");
Double duration = flash.getDouble("Duration");
I get this error:
net.sf.json.JSONException: JSONObject["Duration"] not found.
Any help??
Thanks in advance
You mean
JSONObject flash = json.getJSONObject(0);
JSONObject Flash = flash.getJSONObject("Flash");
int starttime = Flash.getInt("Starttime");

Categories