How to parse json response android - android

How to parse this below json response. I am developing a booking app. The response i got from the server is
{"HotelInformationResponse": {
"#hotelId": "210985",
"customerSessionId": "0ABAA826-9AAF-5791-3692-A03326791310",
"HotelSummary": {
"#order": "0",
"hotelId": 210985,
"name": "Seattle Marriott Waterfront",
"address1": "2100 Alaskan Way",
"city": "Seattle",
"stateProvinceCode": "WA",
"postalCode": 98121,
"countryCode": "US",
"propertyCategory": 1,
"hotelRating": 4,
"tripAdvisorRating": 4,
"locationDescription": "Near Seattle Aquarium",
"highRate": 645,
"lowRate": 279,
"latitude": 47.61016,
"longitude": -122.34651
},
"HotelDetails": {
"numberOfRooms": 358,
"numberOfFloors": 8,
"checkInTime": "4:00 PM",
"checkOutTime": "12:00 PM",
"propertyInformation": "Pets not allowed Check-in time starts at 4 PM Check-out time is Noon ",
}
Any method is appreciated

I hope this code can help u
public static String Profile_response(String response){
try{
JSONArray jsonarray = new JSONArray("["+response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
parseForcitydetail1(jsonobject.getString("HotelInformationResponse"));
return response;
}catch (Exception e) {
return "\"" + "Access Denied" + "\"";
}
}
public static void parseForcitydetail1(String res){
try{
JSONArray jsonarray1 = new JSONArray(res);
for(int i=0;i<jsonarray1.length();i++){
JSONObject jsonobject = jsonarray1.getJSONObject(i);
Hotal_ID.add(jsonobject.getString("#hotelId"));
customer_ID.add(jsonobject.getString("customerSessionId"));
}
parseForcitydetail2(jsonobject.getString("HotelSummary"));
}catch (Exception e) {
System.out.println(e.toString());
}
}
public static void parseForcitydetail2(String res){
try{
JSONArray jsonarray1 = new JSONArray(res);
for(int i=0;i<jsonarray1.length();i++){
JSONObject jsonobject = jsonarray1.getJSONObject(i);
Order.add(jsonobject.getString("#order"));
hote_ID.add(jsonobject.getString("hotelId"));
Name.add(jsonobject.getString("name")); Address.add(jsonobject.getString("address1"));....
City.add(jsonobject.getString("city"));
StateProvinceCode.add(jsonobject.getString("stateProvinceCode")); PostalCode.add(jsonobject.getString("postalCode"));
CountryCode.add(jsonobject.getString("countryCode"));
PropertyCategory.add(jsonobject.getString("propertyCategory")); HotelRating.add(jsonobject.getString("hotelRating"));....
TripAdvisorRating.add(jsonobject.getString("tripAdvisorRating"));
LocationDescription.add(jsonobject.getString("locationDescription")); Latitude.add(jsonobject.getString("latitude"));
Longitude.add(jsonobject.getString("longitude"));
}
}catch (Exception e) {
System.out.println(e.toString());
}
}
This Same process with "HotelDetails" Parsing
Enjoy !

You may use JSONArray and JSONObject to parse it manually. but its boring and may require extra attention to keys while running in loops. The easiest and highly recommended way is to use Google Gson library to handle this automatically.

Using JSONOBject, JSONArray to contain data like JSONObject, JSONArray
Using methods like: getJSONObject(), getString(), getXXX(). . to get data which you want.
with XXX - data type like int, string
You will understand how to parse JSON in Android easily with the link which describes how to parse JSON clearly (Example):
http://www.technotalkative.com/android-json-parsing/

private JSONObject jObject;
jObject = new JSONObject(your response as string);
//this will give you json object for HotelInformationResponse
JSONObject menuObject = jObject.getJSONObject("HotelInformationResponse");
by this way you can get values
String hotelId = menuObject.getString("#hotelId");
String customerSessionId = menuObject.getString("customerSessionId");
//...rest are same do same thing for HotelDetails
for extra information Check this link

Related

JSON request does not give anything

I have a bug in the code, but I can not find it. I have to read the message and the code from the JSON request below.
try {
Log.d("qwertz", json);
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("win"))
{
showDialog("Du hast etwas gewonnen", message,code);
}
else if (code.equals("false"))
{
showDialog("Du hast leider nichts gewonnen", message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
That is a JSON example
{
"server_response": {
"code": "win",
"message": "Du hast einen PzKpfw S35 739(f) gewonnen"
}
}
I advice you not to process json directly by yourself, instead you can use many libraries that will do the job for you. To mention you can use jackson or gson.
If you still want to correct your code you can try this:
JSONObject response = jsonObject.getJsonObject("server_response");
String code = response.getString("code");

String response separated by "|" to Android JSONObject

I'm getting a HTTP GET response like this:
(yeah, I know it's weird)
1,24,https://www.myweb.com/img/BTMz_shave_club.png|10,21,https://www.myweb.com/img/BTMz_coffee_club.png|30,22,https://www.myweb.com/img/BTMz_coffee_club.png|
I need to split the String by "|". And then split "," and result is something like:
[
{id: 1, qty: 24, img_uri: https://www.myweb.com/img/BTMz_shave_club.png},
{id: 10, qty: 21, img_uri: https://www.myweb.com/img/BTMz_coffee_club.png},
{id: 22, qty: 22, img_uri: https://www.myweb.com/img/BTMz_coffee_club.png}
]
It's a String response, but I need to convert it to an JSONArray.
Thanks for the help.
try something like
private void splitAndMakeJson() {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=null;
String mainString="1,24,https://www.myweb.com/img/BTMz_shave_club.png|10,21,https://www.myweb.com/img/BTMz_coffee_club.png|30,22,https://www.myweb.com/img/BTMz_coffee_club.png|";
String[] mainToken=mainString.split("\\|");
for(int i=0;i<mainToken.length;i++){
String subToken[]=mainToken[i].split(",");
jsonObject=new JSONObject();
try {
jsonObject.put("id",subToken[0].getBytes().toString());
jsonObject.put("qty",subToken[1].getBytes().toString());
jsonObject.put("img_uri",subToken[2].getBytes().toString());
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.e("Json",jsonArray.toString());
}

Troubles with parsing JSON for android

I'm working on parsing some JSON in my android application, this is the code I started off with:
JSONObject jsonObject = **new JSONObject(result);**
int receivedCount = **jsonObject.getInt("CurrentCount");**
However this is causing it to error (The code that would error is surrounded with asterisks) in Android Studio, I tried using the suggestion feature which asked me if I want "Surround with try/catch" which would cause the app to crash when it launched.
This is the suggested code:
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
int receivedCount = 0;
try {
receivedCount = jsonObject.getInt("CurrentCount");
} catch (JSONException e) {
e.printStackTrace();
}
This is the JSON I'm trying to pass:
[{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
Thanks in advance!
J_Dadh I think first of all you should look through the documentation on how to use Json Parser which you can find in the following Link https://www.tutorialspoint.com/android/android_json_parser.htm
EXAMPLE JSON
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
String YourJsonObject = "JsonString"
JSONObject jsonObj = new JSONObject(YourJsonObject);
JSONArray weather = jsonObj.getJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject c = weather.getJSONObject(i);
String id = c.getString("id");
String main= c.getString("main");
String description= c.getString("description");
}
as you pasted your JSON you are using [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
-If we analyze this JSON,This JSON contains a JSON ARRAY [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
having 3 JSON Objects{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}
-But when you are going to parse this JSON, you are accepting it as jsonObject = new JSONObject(result),but you should accept it asJSONArray jsonArray=new JSONArray(result);
and then you iterate a loop(e.g,for loop) on this jsonArray,accepting JSONObjects 1 by 1,then getting the values from the each JSONObject 1 by 1.
-1 more mistake in your JSON is that you are sending the strings as "5" but accepting it as getInt() that's not fair,you should send int to accept it as intas 5 (without double qoutes)
So you final JSON and code like this(as below)
JSON
[{"CurrentCount":5},{"CurrentCount":0},{"CurrentCount":1002}]
Code to Use this JSON
JSONOArray jsonArray = null;
try{
jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray[i];
receivedCount=jsonObject.getInt("CurrentCount");
}
}catch(JSONException e) {
e.printStackTrace();
}

How to read this format of JSON in Android

I have a problem to load this json in a JSONObject, i tried some combinations but it didn't work, for example i was able to load the Openweather JSON format easy but this one i got nothing on my Log as output
this is the format of Json:
{
"marcadores": [
{
"lat": 38.632682,
"id": 1,
"nombre": "Les Urques",
"mar": "appvalenciaplayas/static/images/mar/moderado.svg",
"viento": "appvalenciaplayas/static/images/viento/viento_S2.svg",
"simbolo": "appvalenciaplayas/static/images/cielo_dia/sol.svg",
"imagenTemp": "appvalenciaplayas/static/images/pastillas_temp/temp_25_a_31.svg",
"temperatura": 29,
"lon": 0.032945
},
{
"lat": 40.078478,
"id": 2,
"nombre": "Cala d'Orpesa la Vella",
"mar": "appvalenciaplayas/static/images/mar/debil.svg",
"viento": "appvalenciaplayas/static/images/viento/viento_SE2.svg",
"simbolo": "appvalenciaplayas/static/images/cielo_dia/nube_alta_sol.svg",
"imagenTemp": "appvalenciaplayas/static/images/pastillas_temp/temp_25_a_31.svg",
"temperatura": 31,
"lon": 0.134357
},
{
"lat": 40.008969,
"id": 3,
"nombre": "El Serradal",
"mar": "appvalenciaplayas/static/images/mar/debil.svg",
"viento": "appvalenciaplayas/static/images/viento/viento_SE2.svg",
"simbolo": "appvalenciaplayas/static/images/cielo_dia/nube_alta_sol.svg",
"imagenTemp": "appvalenciaplayas/static/images/pastillas_temp/temp_25_a_31.svg",
"temperatura": 31,
"lon": 0.034107
},
Thanks.
please put your response as a string in JSONObject
i am showing to you how to get all fields values like this
please read my code and apply my code as per your need.
try{
JSONObject json=new JSONObject(yourResponce);
JSONArray jarray=json.getJSONArray("marcadores");
for(int i=0;i<jarray.length;i++)
{
JSONObject jobj=jarray.getJSONObject(i);
String lat=jobj.getString("lat").toString();
String id=jobj.getString("id").toString();
String nombre=jobj.getString("nombre").toString();
String mar=jobj.getString("mar").toString();
String viento=jobj.getString("viento").toString();
String simbolo=jobj.getString("simbolo").toString();
String imagenTemp=jobj.getString("imagenTemp").toString();
String temperatura=jobj.getString("temperatura").toString();
String lon=jobj.getString("lon").toString();
}
}catch(Exception e)
{
e.printStackTrace();
}
Parse your JSON as follows
String str = "your_json_here";
try {
JSONObject jsonObject = new JSONObject(str);
JSONArray jsonArray = jsonObject.getJSONArray("marcadores");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject elementJsonObject = jsonArray.getJSONObject(i);
String id = elementJsonObject.getString("id");
// all fields to be accessed as above
}
} catch (JSONException e) {
e.printStackTrace();
}
Firstly, you need to create a POJO with attributes lat,id,nombre...
Read JSON array elements and convert JSON to Class (You can use jackson or Gson)
Use your object whatever you want
In addition this code piece may help you, but auto convertion is more pretty with some libs.
try{
JSONObject json=new JSONObject(yourResponce);
JSONArray jarray=json.getJSONArray("marcadores");
for(int i=0;i<jarray.length;i++)
{
JSONObject jobj=jarray.getJSONObject(i);
String lat=jobj.getString("lat").toString();
String id=jobj.getString("id").toString();
String nombre=jobj.getString("nombre").toString();
String mar=jobj.getString("mar").toString();
String viento=jobj.getString("viento").toString();
String simbolo=jobj.getString("simbolo").toString();
String imagenTemp=jobj.getString("imagenTemp").toString();
String temperatura=jobj.getString("temperatura").toString();
String lon=jobj.getString("lon").toString();
}}catch(Exception e) { e.printStackTrace(); }
Some other helpful links
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/
http://howtodoinjava.com/best-practices/google-gson-tutorial-convert-java-object-to-from-json/
Happy coding.
you can use Gson framework. You create a model class with the same Json response attributes/structure . This way you do not need to use getString( ) and getObject().
Example: https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html

how to build Below kind of JSON Format to post it as a request in android?

Ineed to post data in JSON format as shown below And the size of the array is not
constant. it depends on the user.
{
"info": [
{
"Name": "foo1",
"Number": 123
},
{
"Name": "foo2",
"Number": 124
},
{
"Name": "foo2",
"Number": 125
}
]
}
I tried to create in the following way
JSONObject parent = new JSONObject();
JSONArray jArray = new JSONArray();
JSONObject childObj = new JSONObject();
childObj.put("Name", etName.getText()).toString();
childObj.put("Number", etNumber.getText()).toString();
jArray.put(childObj);
parent.put("info",jArray);
but i'm unable to get it and I also tried in this way like example 6.1 but there is no method like add for JSONArray. So how can post my data. Please help me.
Thanks.
I'm not sure exactly what your question is but I'd typically do something like this to create the JSON string that you are looking for (the example below is using the org.json reference implementation from http://www.json.org/java/index.html):
JSONObject parent = new JSONObject();
JSONArray infoArray = new JSONArray();
for(int i = 0; i < SOMEARRAY.length; i++)
{
JSONObject childObj = new JSONObject();
childObj.put("Name", etName.getText());
childObj.put("Number", etNumber.getText());
infoArray.put(childObj);
}
parent.put("info", infoArray);
String encodedJsonString = parent.toString();
I don't understand why you're calling toString() after putting stuff into childObj.
Anyway, this code should work:
JSONObject parent = new JSONObject();
JSONArray jArray = new JSONArray();
JSONObject childObj = new JSONObject();
try
{
//create first child
childObj
.put("Name", "foo1")
.put("Number", 123);
//insert it into the array
jArray.put(childObj);
//... repeat for all remaining elements
//attach the array to the parent
parent.put("info",jArray);
}
catch (JSONException e)
{
e.printStackTrace();
}
Then, to get your JSON as a string for POSTing just call parent.toString();

Categories

Resources