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...
}
Related
I have this json code
{
"status": "success",
"message": null,
"data": {
"19": {
"id": "19",
"created": "2019-01-07 13:26:06",
"createdby": 158,
"touched": "2019-01-07 13:26:06",
"touchedby": 158,
"start": "2019-01-07",
"end": "2019-01-08",
"scoperole": 3,
"scopecorp": 1,
"body": "<p>test</p>",
"language": "en"
},
"20": {
"id": "20",
"created": "2019-01-07 13:26:20",
"createdby": 158,
"touched": "2019-01-07 13:26:20",
"touchedby": 158,
"start": "2019-01-07",
"end": "2019-01-08",
"scoperole": 3,
"scopecorp": 1,
"body": "<p>test1</p>",
"language": "en"
}
},
"error": 0,
"line": 1515,
"debug": null
}
And i want to take the values of "body" (test,test1).
How can i reach them?I left the code that i tried just to see it with //not working next to it.Any ideas please?Also the 19,20 are not the same so i'm not able to get them by just putting the name of a variable(ex JSONObject dataObj =new JSONObject ("data");
Here is my code
private void getJson() {
URL obj = null;
try {
obj = new URL("https://gekon.technologypark.cz/api/v1/notification/");
HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("ApiSecret", LoginInfo.ApiSecret);
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null)
sb.append(output);
JSONObject jsonObj = new JSONObject(sb.toString());
Log.d("test", "response" + jsonObj);
JSONObject dataObj =new JSONObject("data");
JSONObject dataObj19 =dataObj.getJSONObject("22");
String body1 =dataObj19.getString("body");
Log.d("test", "TEST ID" + body1);
pushNotification(notifText);
} catch (Exception e) {
e.printStackTrace();
Log.d("test", "PUSH CATCH" + e);
}
}
Here are my logs
**2019-01-07 14:17:42.778 19712-19712/ibm.gekon.vasileiosvlachakis.gekon D/alekos:
response{"status":"success","message":null,"data":{"22":{"id":"22","created":"2019-01-07
14:11:55","createdby":158,"touched":"2019-01-07
14:11:55","touchedby":158,"start":"2019-01-07","end":"2019-01-08","scoperole":3,"scopecorp":1,"body":"test22</p>","language":"en"}},"error":0,"line":1515,"debug":null}
2019-01-07 14:17:42.785 19712-19712/ibm.gekon.vasileiosvlachakis.gekon
D/alekos: PUSH CATCHorg.json.JSONException: Value data of type
java.lang.String cannot be converted to JSONObject**
Here you can get the value of body key. but this is specific for 19 and 20 JSON object
JSONObject dataObj = new
JSONObject(sb.toString()).getJSONObject("data");
JSONObject dataObj19 =dataObj.getJSONObject("19");
String body1 =dataObj19.getString("body");
JSONObject dataObj20 =dataObj.getJSONObject("20");
String body2 =dataObj20.getString("body");
if Response has multiple JSON object inside data JSON object then you need a loop to retrieve it
JSONObject dataObj =new JSONObject("data");
for(int i=0;i<dataObj.length();i++){
JSONObject data =dataObj.getJSONObject(i);
String body =data .getString("body");
}
JSONObject json = new JSONObject(sb.toString());
String statistics = json.getString("data");
for(Iteraor key=json.keys();key.hasNext();) {
JSONObject keyValue = json.get(key.next());
//now keyValue contains the 19,20 and so on...
String body1 =keyValue.getString("body");
Log.d("test", "TEST ID" + body1);
}
Try this it might work.
best way is to make static key, but you can get all keys and then get value for each one
use
JSONObject dataObj =new JSONObject("data");
Iterator<String> keys=dataObj.keys();
while (keys.hasNext())
{
JSONObject currentObject =dataObj.getJSONObject(keys.next());
String currentBody =currentObject.getString("body");
Log.d("test", "TEST ID" + currentBody);
}`
In JSON response your key should always be static in order to get a particular response from the key.
Here check whether your data JSONObject contains that key or not for error handling.
try {
JSONObject jsonObj = new JSONObject(sb.toString());// assuming this as your main JSONObject
if(jsonObj.has("data")){
JSONObject dataObj =jsonObj.getJSONObject("data");
if(dataObj.has("19")){
JSONObject json19 = dataObj.getJSONObject("19");
// Now here check if the json19 contains the key that you want.
if(json19.has("body")){
String valueBody = json19.getString("body"); // this will give you the value of body
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
How to parse json data with random/unknown value type for keys?In below json data,key data can be a json object or string depending upon response from server.
Response 1(Json object)
{
"responseCode": 2,
"responseMessage": "hi",
"data": {
"key": "Id",
"value": "10312412",
"key2": "Id2",
"key3": "Id3"
}
}
Response 2(String)
{
"responseCode": 2,
"responseMessage": "hi",
"data": "String here"
}
The best you can do is
Object data = response.get("data");
Though, you might be able to try
boolean gotObject = true;
String dataString = null;
// Try to request a JSONObject as a String
dataString = String.valueOf(response.optJSONObject("data"));
// If there wasn't a JSONObject, then try to get a String
if (dataString.isEmpty() || dataString.equals("null")) {
dataString = response.optString("data");
gotObject = false;
}
Then, you can try this
if (gotObject) {
JSONObject data = new JSONObject(dataString);
}
Realistically, you should make a more consistent server API
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 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();
}
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.