how to parse this response using JSONObject - java

I have this response that I get back form server. I want to parse it and get the hospital_name out of it. How would I go about it?
[
{
"Hospital": {
"id": "63083",
"hospital_name": "Colorado Mental Health Inst",
"hospital_add_1": "1600 W 24th St",
"hospital_add_2": null,
"hospital_city": "Pueblo",
"hospital_state": "CO",
"hospital_zip": "81003",
"hospital_phone": "719-546-4000\r",
"hospital_fax": null,
"hospital_description": null,
"callcenter_agent_approval": "0",
"hospital_site": "",
"mdpocket_approval": "0",
"facebook": ""
},
"Floor": [],
"Department": [],
"Image": [],
"Notes": []
},
{
"Hospital": {
"id": "63084",
"hospital_name": "Parkview Medical Center",
"hospital_add_1": "400 W 16th St",
"hospital_add_2": null,
"hospital_city": "Pueblo",
"hospital_state": "CO",
"hospital_zip": "81003",
"hospital_phone": "719-584-4000\r",
"hospital_fax": null,
"hospital_description": null,
"callcenter_agent_approval": "0",
"hospital_site": "",
"mdpocket_approval": "0",
"facebook": ""
},
"Floor": [],
"Department": [],
"Image": [],
"Notes": []
},
{
"Hospital": {
"id": "63085",
"hospital_name": "St Mary-Corwin Medical Center",
"hospital_add_1": "1008 Minnequa Ave",
"hospital_add_2": null,
"hospital_city": "Pueblo",
"hospital_state": "CO",
"hospital_zip": "81004",
"hospital_phone": "719-560-4000\r",
"hospital_fax": null,
"hospital_description": null,
"callcenter_agent_approval": "0",
"hospital_site": "",
"mdpocket_approval": "0",
"facebook": ""
},
"Floor": [],
"Department": [],
"Image": [],
"Notes": []
}
]
EDITED THE JSON
*UPDATED JSON *

[ // json array node
{ // json object node
"Hospital": { // json object Hospital
To parse
JSONArray jr = new JSONArray("jsonstring");
for(int i=0;i<jr.length();i++)
{
JSONObject jb = (JSONObject)jr.getJSONObject(i);
JSONObject jb1 =(JSONObject) jb.getJSONObject("Hospital");
String name = jb1.getString("hospital_name");
Log.i("name....",name);
}
Log
02-18 03:09:43.950: I/name....(951): Colorado Mental Health Inst
02-18 03:09:43.950: I/name....(951): Parkview Medical Center
02-18 03:09:43.950: I/name....(951): St Mary-Corwin Medical Center

You won't- its invalid JSON. You're missing most of your "" around field names.

Try this..
JSONArray tot_array = new JSONArray(response);
for(int i = 0; i< tot_array.length(); i++){
JSONObject obj = tot_array.getJSONObject(i);
JSONObject hospital_obj = obj.getJSONObject("Hospital");
String hospital_name = hospital_obj.getString("hospital_name");
}

I recommend you use the fastjson (https://github.com/alibaba/fastjson).

Checkout this cool libray for parsing JSOn in Android its called GSON https://code.google.com/p/google-gson/ . Via this parsing this very simple.

Your string is not a valid JSON object. Check out jsonlint before trying to parse a string as JSON. After which, you can read about parsing JSON in Android. It's easy enough with the built-in org.json, but should be much easier if you use one of the many Java libraries out there that simplifies it further. You can look into Jackson or google-gson, two of the most capable utilities for your purpose.

Related

Parsing JSON response when returned as Array

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
This is the error I continue to get while attempting to parse my incoming JSON response data. I'm utilizing the OkHttp library to create and call, and the API I'm getting results from returns everything in an Array as follows:
[
{
"id": 4256,
"image_url": "https://cdn.pandascore.co/images/league/image/4256/OMEN_Challenger_Series_2019.png",
"live_supported": false,
"modified_at": "2019-10-30T10:02:42Z",
"name": "OMEN Challenger",
"series": [
{
"begin_at": "2019-11-01T03:30:00Z",
"description": null,
"end_at": null,
"full_name": "2019",
"id": 1932,
"league_id": 4256,
"modified_at": "2019-10-30T09:11:40Z",
"name": null,
"prizepool": "50000 United States Dollar",
"season": null,
"slug": "cs-go-omen-challenger-2019",
"winner_id": null,
"winner_type": null,
"year": 2019
}
],
"slug": "cs-go-omen-challenger",
"url": "https://omengaming.co/omen_cs/",
"videogame": {
"current_version": null,
"id": 3,
"name": "CS:GO",
"slug": "cs-go"
}
},
{...},
{...},
{...},
{...},
]
I found a lot of folks recommending Gson to parse it into a custom class, but the following code, in theory, should work and it isn't. The parsing doesn't even begin due to it expecting BEGIN_OBJECT and it being BEGIN_ARRAY:
String jsonData = response.body().string();
Gson gson = new Gson();
EventInfo test = gson.fromJson(jsonData, EventInfo.class);
class EventInfo {
String imageURL;
String name;
JSONArray series;
}
You are trying to parse it into an object. But in your response, you can clearly see that it's a list. The parent POJO should have been a list. And inside that list, you should have created another POJO.
In your response parent is found as array but you need to add first parent as JSON object and child as a array or object.
You need response like this
{
"YourArrayName":[
"YourChildObjName":{
"id": 4256,
"image_url": "https://cdn.pandascore.co/images/league/image/4256/OMEN_Challenger_Series_2019.png",
"live_supported": false,
"modified_at": "2019-10-30T10:02:42Z",
"name": "OMEN Challenger",
"series": [
{
"begin_at": "2019-11-01T03:30:00Z",
"description": null,
"end_at": null,
"full_name": "2019",
"id": 1932,
"league_id": 4256,
"modified_at": "2019-10-30T09:11:40Z",
"name": null,
"prizepool": "50000 United States Dollar",
"season": null,
"slug": "cs-go-omen-challenger-2019",
"winner_id": null,
"winner_type": null,
"year": 2019
}
],
"slug": "cs-go-omen-challenger",
"url": "https://omengaming.co/omen_cs/",
"videogame": {
"current_version": null,
"id": 3,
"name": "CS:GO",
"slug": "cs-go"
}
},
{...},
{...},
{...},
{...},
]
}
I hope this can help You!
Thank You
So, I figured it out. Originally I was receiving the same error at a later point; namely when it got to the series key value in the first JSONObject. The original error occurred because I was trying to parse series as a JSONArray, rather than a List<JSONObject> The corrections are below:
String jsonData = response.body().string();
Gson gson = new Gson();
Type listType = new TypeToken<List<EventInfo>>() {}.getType();
List<EventInfo> test = gson.fromJson(jsonData, listType);
And the EventInfo class:
class EventInfo {
String imageURL;
String name;
List<JSONObject> series;
}
Thank you for the advice everyone!

Converting a normal String to JSON in java

i've been searching a lot for a way to convert a normal String, not an Array, and i'm stuck in my code. I've programmed an API that return me the following json
[{
"Id": "6d052279342d66d1ae4d4a84da0f98b80313277a3faeca4d7e822076c9dd4316",
"Names": ["/elegant_bartik"],
"Image": "alpine",
"ImageID": "sha256:3fd9065eaf02feaf94d68376da52541925650b81698c53c6824d92ff63f98353",
"Command": "/bin/sh",
"Created": 1525954440,
"Ports": [],
"Labels": {},
"State": "running",
"Status": "Up About an hour",
"HostConfig": {
"NetworkMode": "default"
},
"NetworkSettings": {
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "430ff6d43b361b0a2f45046c575862ca4785216a0242e72d145c269f3ef326df",
"EndpointID": "a7a2012d7841af6b5b76e24f57b13a5057252b511e8dbfb48e74aa1cc19e30b4",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null
}
}
},
"Mounts": []
}]
The problem is, I need to put it into an JSONObject, is there any function or sequence of functions that could do that? Or do I need to break the whole String?
I've tried JSONParse, Gson(from Google) and a lot more, but none of then works.
Thanks!
The JSON you have posted is an array (denoted by []) containing a single object (denoted by {})
You will first need to parse the JSON into an array, for example (using GSON):
JsonArray arr = new Gson().fromJson(string, JsonArray.class)
And then you can access the first object in the array:
JsonElement ele = arr.get(0);
First, the json array string looks okay. you will have to read it as a jsonArray, then loop through each getting the jsonObjects.
JSONArray jsonArray = new JSONArray(readlocationFeed);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
I hope this helps.
That's a JSONArray. You first need to get the root json array. Then you can get the first object from that.

Parse json response of rest API and delete certain jsonObjects - JAVA

I have a json file as below which I am getting as a response from rest API:
{
"label": " MARA LEYZIN",
"ClassCode": "PROFESSIONAL",
"actvFlg": "A",
"name": "MARA LEYZIN",
"Typ": {
"label": "C_TYP_LU",
"TypCode": "PROFESSIONAL "
},
"Address": {
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item": [
{
"label": "Address",
"addrTypFk": {
"label": "C_ADDRESS_TYPE_LU",
"addrTypCd": "INDUSTRY",
"addrTypDesc": "Industry"
}
}
]
}
I am trying to parse this in Java and to remove some unwanted json objects. Like I want the following string to be replaced by blank:
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item":
To achieve this I am trying the following approach:
String jsonStr = new String(Files.readAllBytes(Paths.get(inputFile)));
System.out.println(jsonStr);
jsonStr.replaceAll("link", "");
But it is not replacing the required string with blanks. Please help me in this.
string object is immutable , so basically if do you want to replace something
System.out.println(jsonStr.replaceAll("link", "")); this will print the replaced string but it will not affect the original string, however if you do this
jsonStr=jsonStr.replaceAll("link", "");
System.out.println(jsonStr); this will print the replaced string
First of all:
Your JSON is not validate. You're missing a closing curly bracket at the end of it.
{
"label": " MARA LEYZIN",
"ClassCode": "PROFESSIONAL",
"actvFlg": "A",
"name": "MARA LEYZIN",
"Typ": {
"label": "C_TYP_LU",
"TypCode": "PROFESSIONAL "
},
"Address": {
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item": [{
"label": "Address",
"addrTypFk": {
"label": "C_ADDRESS_TYPE_LU",
"addrTypCd": "INDUSTRY",
"addrTypDesc": "Industry"
}
}]
}
}
Second of all you should just change order of your commands to this:
jsonStr.replaceAll("link", "");
System.out.println(jsonStr);
Important addition:
And I would suggest you to use org.json library or even better JACKSON to parse JSON files.
Here's tutorial how to use jackson and it's my warmest suggestion.
You will save a lot of time and you can do whatever you like.

How do I convert a list represented as a string to a list?

I am building an Android application which reads from themoviedb.org.
What I am trying to do is have the user enter a movie title and use that title to find its id.
When I run the query to search for movies, I get a response like:
{
"page": 1,
"results": [
{
"poster_path": "aaaaa.jpg",
"id": "11",
"description": "MovieDescription"
},
{
"poster_path": "bbbbb.jpg",
"id": "12",
"description": "MovieDescription2"
},
{
"poster_path": "ccccc.jpg",
"id": "13",
"description": "MovieDescription"
}
]
}
Using the Maven JSON library, I can fetch the results key as a string using json.get("results").
returning:
[
{
"poster_path": "aaaaa.jpg",
"id": "11",
"description": "MovieDescription"
},
{
"poster_path": "bbbbb.jpg",
"id": "12",
"description": "MovieDescription2"
},
{
"poster_path": "ccccc.jpg",
"id": "13",
"description": "MovieDescription"
}
]
But I want to convert the first of these results to another JSONObject so that I can get the movie's id from the first result.
I'm thinking that the way to do this is to convert the results value to a list of JSONObject and then use the json.get("id") method on the first object in the list. But I do not know how to do this conversion.
Any help would be appreciated.
You can use JSONObject.getJSONArray to get the result directly as a JSON Array:
JSONArray results = json.getJSONArray("results") // Get results as JSON Array
JSONObject first = results.getJSONObject(0) // Get first object as JSON Object
See: JSONObject#getJSONArray(String)

how to get the value of lat and lng from the json

I have a json response.I want to get the value of lat and lng from the json response.But i didn't get the values.Please Help me.Below is my response.
{
"html_attributions": [],
"results": [
{
"geometry": {
"location": {
"lat": 9.493837,
"lng": 76.338506
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id": "2730a3d7ab068d666e61a02ce6160b4cd21a38c7",
"name": "Nagarjuna",
"place_id": "ChIJr0-U4vSECDsRtiALUlgZOzI",
"reference": "CmRcAAAA4yl72_x5llqvdshRJwuuntunXrYu33qdP5G7-I0CdHzcDsyd6wwqjxdNeqvT6vtRIoDoIk_WGNd62SYSoNEdBrpDrOcf5g5eZMj_vobhmF11mrujsQ_Yc7p-oGxQH0XtEhDNJdjQf_WlK_dRAckBzlA3GhQ_wzXs5RxoaxWDSEurm_R5syuovg",
"scope": "GOOGLE",
"types": [
"hospital",
"establishment"
],
"vicinity": "State Highway 40, Kodiveedu, Alappuzha"
},
{
"geometry": {
"location": {
"lat": 9.500542,
"lng": 76.341017
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id": "d5b6c81a53a346dea1263de7a777703bc72b8796",
"name": "SYDNEY OPTICALS",
"opening_hours": {
"open_now": true,
"weekday_text": []
},
"photos": [
{
"height": 422,
"html_attributions": [],
"photo_reference": "CnRnAAAA_jg-NlSrVKkDOP7wXhPhvFTD8NW4A4aDI_Ptl3F9c_qt9QwdztNTG9Cr51uGIphpEUMyhsTfhhaa-TlfoL8MUEffbguZJ1AhKUwzfe7Mbrvm2KW8Y1EQXVw_3FglxA4LM1hqWJCK_AV4xcvOw1vuHRIQ8_keBYr29H8jK145RQ_PkRoUgPZ0qzcSNdIntc2ZI4WvBIR-TBQ",
"width": 630
}
],
"place_id": "ChIJl9tvIV6ECDsR7Cmf3KkIl-4",
"reference": "CnRjAAAA3qhFUcb8P9akE8xw-KwfF6OU6qvy2cVX4Sg0qK_xCOfeUEyxoFgwof8rk-Z2BBJ7Z4m7ZTbfdp78wqFbeLfojQWPldq7XDfzX0pLScBSysebEp9P4XmrsAO5qyqSUveb5jWcJDkYiOLKgaKMzoWQphIQbldrdJ9iEDHkGiQ7tleNYxoUnjcjcynUDMftaErRUQbOn-GkWj0",
"scope": "GOOGLE",
"types": [
"store",
"hospital",
"health",
"establishment"
],
"vicinity": "Mullakkal, Alappuzha"
}
],
"status": "OK"
}
This is the google api response i used for getting the list of hospitals.Anybode plese help me.Thanks in advance.
Use these steps:
Create a model class for that Json Response
Use Gson to parse the response
Then create an object of the class
using the object get the data variable from the class
I hope I can help.
First, validate your JSON with http://jsonlint.com/
Second, use this site to generate POJO: http://www.jsonschema2pojo.org/
make sure that Annotation GSON and Source type JSON are clicked ON!
Copy your classes in to your project.
Third: use GSON in Android :) (Retrofit is good for this)
Supposing you use the json.org Implementation for Java:
String response = "{\"html_attributions\": [], \"results\": ...";
JSONObject jo = new JSONObject(response);
JSONObject result = jo.getJSONArray("results").getJSONObject(0);
JSONObject location = result.getJSONObject("geometry").getJSONObject("location");
double lat = location.getDouble("lat");
double lng = location.getDouble("lng");
try this
String response = "{\"html_attributions\": [], \"results\": ...";
JSONObject objResponce = new JSONObject(response);
JSONArray arrayResults=new JSONArray(objResponce.getString("results"));
if(arrayResults.length()>0)
{
for(int i=0;i<arrayResults.length();i++)
{
//--- get each json object from array -----
JSONObject objArrayResults = arrayResults.getJSONObject(i);
//--- get geometry json object from each object of array -----
JSONObject objGeometry=new JSONObject(objArrayResults.getString("geometry"));
//--- get location json object from geometry json object -----
JSONObject objLocation=new JSONObject(objGeometry.getString("location"));
System.out.println("Latitude :"+objLocation.getString("lat"));
System.out.println("Longitude :"+objLocation.getString("lng"));
}
}

Categories