android Json Api Key Value Nested how to use - android

Android Json Api Key Nested how to use ?MsgID ,UsrID Repeat how to call? Volley
I have a json which has a number of nested JSONARRAY.
{
"status": "success",
"data": {
"2547": {
"MsgID": "2547",
"UsrID": "352",
"MsgID": "221",
"ThroughUsrID": null,
"MsgID": "1",
"MsgDt": "2016-03-22 11:55:13",
"buscard": {
"UsrID": "221",
"EntID": "7",
"EntID": "1",
"UsrFavorites": 0,
"UsrLinkSts": "connected"
},
}
}

I think you are trying to parse Json data. Try to do something like this:
try {
JSONObject jsonObject = new JSONObject(stringToParse);
JSONObject data = jsonObject.optJSONObject("data");
JSONObject tempData = data.optJSONObject("2547");
String msgID = tempData.optString("MsgID");
// Similarly parse other info
JSONObject busCard = tempData.optJSONObject("buscard");
//Again parse required data from busCard
} catch (JSONException e) {
e.printStackTrace();
}

Related

how to send json array in android retrofit?

I can't send json array to server. When I test in postman raw, it is ok, success return.
Postman Raw;
[
{
"product_id": 2,
"name": "Umbrella",
"price": 200,
"quantity": 1,
"totalprice": 200,
"user_id": 1
},
{
"product_id": 1,
"name": "Apple",
"price": 200,
"quantity": 1,
"totalprice": 200,
"user_id": 1
}
]
APIInterface;
#POST("example/api/order")
Call<JSONArray> postOrder(#Body JSONArray jsonArray);
CartActivity;
try {
JSONArray jsonArray = new JSONArray();
for (Cart cart : cartList) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("product_id", cart.getProduct_id());
jsonObject.put("name", cart.getName());
jsonObject.put("price", cart.getPrice());
jsonObject.put("quantity", cart.getQuantity());
jsonObject.put("totalprice", cart.getTotalprice());
jsonObject.put("user_id", cart.getUser_id());
jsonArray.put(jsonObject);
}
Log.e("JSONArray", String.valueOf(jsonArray));
} catch (JSONException jse) {
jse.printStackTrace();
}
Log;
E/JSONArray: [{"product_id":1,"name":"Umbrella","price":200,"quantity":1,"totalprice":200,"user_id":1},{"product_id":2,"name":"Apple","price":89,"quantity":1,"totalprice":89,"user_id":1}]
Error Message from server;
{"values":[{"nameValuePairs":{"product_id":1,"name":"Umbrella","price":200,"quantity":1,"totalprice":200,"user_id":1}},{"nameValuePairs":{"product_id":2,"name":"Apple","price":89,"quantity":1,"totalprice":89,"user_id":1}}]}
You can directly send the array of objects as parameter. Retrofit will handle the conversion. Change your interface method like this:
#POST("example/api/order")
Call<JSONArray> postOrder(#Body List<Cart> cartList);
Check this link, you will get an idea.
send like this:-
#POST("example/api/order")
Call<JSONArray> postOrder(#Query ("data") JSONArray jsonArray);

How to check the status in json object to get the image from array of object in android

First I need to check the json object status 400 if status 400 to get the image otherwise it shows error. I don't how to check status in JSON empty object in android volley. and also I need some help on how to get image by using banner path and banner name.
My Json
{
"status": "200",
"requestType": "bannerImages",
"basePath": "http:\/\/192.168.0.33\/cartwebsite3\/",
"bannerPath": "http:\/\/192.168.0.33\/cartwebsite3\/cdn-images\/banner\/",
"response": {
"data": [
{
"banner_id": "37",
"banner_name": "1457324300894ac3df08bd3648452703d8412f82c2.jpg",
"banner_link": "",
"banner_blocked": "0",
"banner_created": "admin",
"created_on": "1457324300"
},
{
"banner_id": "36",
"banner_name": "14573242986be953c24858a3c2d787d57e6b77be1f.jpg",
"banner_link": "",
"banner_blocked": "0",
"banner_created": "admin",
"created_on": "1457324298"
},
{
"banner_id": "35",
"banner_name": "1457324295f8d8153fb4f29d3af15276db22435d48.jpg",
"banner_link": "",
"banner_blocked": "0",
"banner_created": "admin",
"created_on": "1457324295"
}
]
},
"request": {
"postData": [],
"getData": {
"type": "bannerImages",
"result": "json"
}
}
}
Thank in Advance
If you just want to get status, try like this:
JSONObject jsonObject = new JSONObject(jsonString);
String status = jsonObject.optString("status");
if you want to parse whole data, I would recommend you to use Gson.
For easy JSON parsing/manipulating/etc use GSON library at android. Example you can make custom objects and straight create new instance of your custom object from parsing and then just check fields or whatever you need to do.
CustomObject object= gson.fromJson(JSON, CustomObject.class);
if(object.bannerPath != null) {
//Do something
}
Here is the GSON in Github
and here for GSON tutorial
//editing Rohit Arya Code little bit
JSONObject jsonObject = new JSONObject(jsonString);
String status = jsonObject.optString("status");
if(status.equalIgnorecase("400")){
try {
JSONObject jsonObject=new JSONObject("yourResponse");
jsonObject1=jsonObject.getJSONObject("response");
JSONArray jsonArray=jsonObject1.getJSONArray("data");
JSONObject jsonObject2;
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i);
String banner_name=c.getString("banner_name");
Log.e("banner_name",banner_name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
// don't download
}

Android JSON org.json.JSONEXCEPTION: No Value for ""

I am trying to use Android get the SpeedLimit value from a JSON server response (HERE API - http://route.st.nlp.nokia.com/routing/6.2/getlinkinfo.json?waypoint=52.5308,13.3846&app_id=your_app_id&app_code=your_app_code):
{
"Response": {
"MetaInfo": {
"MapVersion": "2015Q1",
"ModuleVersion": "0.2",
"InterfaceVersion": "4.2",
"Timestamp": "2015-08-25T16:15:23.540Z"
},
"Link": [
{
"_type": "PrivateTransportLinkType",
"LinkId": "-931447246",
"Shape": [
"52.5309486,13.38447",
"52.5306702,13.38344",
"52.5305786,13.38307"
],
"SpeedLimit": 13.89,
"DynamicSpeedInfo": {
"TrafficSpeed": 8.89,
"TrafficTime": 11.6,
"BaseSpeed": 13.89,
"BaseTime": 7.4
},
"Address": {
"Label": "Invalidenstraße",
"Country": "DE",
"State": "Berlin",
"County": "Berlin",
"City": "Berlin",
"District": "Mitte",
"Street": "Invalidenstraße"
}
}
]
}
}
Here is the code I'm using the get the result out of the JSON:
try {
JSONObject response = new JSONObject(jsonResult);
JSONObject test = response.getJSONObject("Link");
String test1 = test.getString("SpeedLimit");
Toast.makeText(getApplicationContext(), test1,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
I keep getting the following exception:
org.json.JSONEXCEPTION: No Value for Link
I must be asking for the wrong information within the JSON but I can't seem to work this one out.
Thank you everyone!
Link JSONArray is inside Response JSONObject instead of in root JSONObject.
So, first need to get Response JSONObject from response then get Link JSONArray:
// Response JSONObject
JSONObject responseJSONObject = response.getJSONObject("Response");
// get Link JSONArray from responseJSONObject
JSONArray linkJSONArray = responseJSONObject.getJSONArray("Link");
The "Link" is a JSONArray instead of JSONObject.
So the code should be :
try {
JSONObject response = new JSONObject(jsonResult);
JSONArray test = response.optJSONArray("Link");
if (test != null && test.length() > 0) {
JSONObject test = test.optJSONObject(0);
if( test != null) {
String test1 = test.getString("SpeedLimit");
Toast.makeText(getApplicationContext(), test1, Toast.LENGTH_SHORT).show();
return;
}
}
Toast.makeText(getApplicationContext(), "No speed limitation data found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
You also need to consider the situation that there are more than 1 JSONObject included in the Link JSONArray.

Retrieve values from notification using JSON PAYLOAD android

I am in a situation , where my webservice sends me notification which includes
{
"apiKey": "xxxxx-xxx-xxx-xxxx-xxxxxxx",
"appKey": "xxxxx-xxx-xxx-xxxx-xxxxxxx",
"sendAll": true,
"content": {
"subject": "Test Lottery",
"message": "Notification Msg",
"action": {
"type": "DEFAULT",
"data": "url|intent|...",
"labe": "label"
},
"payload": "{'uid':'1','type':'LD'}",
"sound": "default.caf",
"badge": "+1"
}
}
On click of the notification which appeared on top , I need to get the uid and type
I am using Xtify for push notification.....
Try This..
String JSON ="YOUR JSON RESULT STRING";
try {
JSONObject jsonresult = new JSONObject(JSON);
String apiKey= jsonresult.getString("apiKey");
String appKey= jsonresult.getString("appKey");
boolean sendAll= jsonresult.getBoolean("sendAll");
JSONObject contentObject = jsonresult.getJSONObject("content");
String subject= jsonresult.getString("subject");
String message= jsonresult.getString("message");
String sound= jsonresult.getString("sound");
String badge= jsonresult.getString("badge");
JSONObject actionObject = jsonresult.getJSONObject("action");
String type= jsonresult.getString("type");
String data= jsonresult.getString("data");
String labe= jsonresult.getString("labe");
JSONObject payloadObject = jsonresult.getJSONObject("payload");
// do your code..
}
} catch (JSONException e) {
e.printStackTrace();
//catching exceptions if any...
}

How to parse json response 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

Categories

Resources