JSON Exception when trying to retrieve object string - java

I'm trying to retrieve the "Maxspeed" string from the JSON below.
It iterates through the array, but when it reaches the "tag" object and tries to retrieve the "maxspeed" value, it returns an exception(below).
Would anyone know why this is happening?
Any help would be appreciated.
Thanks.
Exception:
org.json.JSONException: No value for maxspeed
Java:
JSONObject parentObject = new JSONObject(result);
JSONArray speedJSON = parentObject.getJSONArray("elements");
for (int i = 0; i < speedJSON.length(); i++) {
JSONObject element = (JSONObject) speedJSON.get(i);
if (!element.isNull("tags")) {
//JSONObject tags = (JSONObject) speedJSON.getJSONObject(i).get("tags");
String maxspeed = element.getString("maxspeed");
txtSpeed.setText(maxspeed+" here");
} else {
//Your error handling here...
}
}
//txtSpeed.setText(""+);
this.progressDialog.dismiss();
JSON:
{
"version": 0.6,
"generator": "Overpass API",
"osm3s": {
"timestamp_osm_base": "2015-03-16T20:10:02Z",
"copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
},
"elements": [
{
"type": "node",
"id": 768053039,
"lat": 54.9526671,
"lon": -7.7273348
},
{
"type": "node",
"id": 768053040,
"lat": 54.9498094,
"lon": -7.7176056
},
{
"type": "node",
"id": 768053041,
"lat": 54.9497066,
"lon": -7.7173174
},
{
"type": "node",
"id": 768053043,
"lat": 54.9495658,
"lon": -7.7170937
},
{
"type": "node",
"id": 768053044,
"lat": 54.9495035,
"lon": -7.7169816
},
{
"type": "node",
"id": 791492493,
"lat": 54.9494183,
"lon": -7.7168205
},
{
"type": "node",
"id": 795319854,
"lat": 54.9510427,
"lon": -7.7218262
},
{
"type": "node",
"id": 795320324,
"lat": 54.9509153,
"lon": -7.7213706
},
{
"type": "node",
"id": 1922546572,
"lat": 54.9502165,
"lon": -7.7190169
},
{
"type": "node",
"id": 1922546679,
"lat": 54.9504739,
"lon": -7.7199078
},
{
"type": "node",
"id": 1922546692,
"lat": 54.9500860,
"lon": -7.7185174
},
{
"type": "node",
"id": 1922602861,
"lat": 54.9517250,
"lon": -7.7241644
},
{
"type": "node",
"id": 1922622063,
"lat": 54.9514357,
"lon": -7.7231690
},
{
"type": "node",
"id": 2673934802,
"lat": 54.9498543,
"lon": -7.7177617
},
{
"type": "way",
"id": 64273241,
"nodes": [
768053039,
1922602861,
1922622063,
795319854,
795320324
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
},
{
"type": "way",
"id": 64887990,
"nodes": [
795320324,
1922546679,
1922546572,
1922546692,
2673934802,
768053040,
768053041,
768053043,
768053044,
791492493
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
}
]
}

You are trying to get maxspeed from the element, but it's not there. It is inside tags object in the element.
You need something like this
if (!element.isNull("tags")) {
JSONObject tags = element.getJSONObject("tags");
String maxspeed = tags.getString("maxspeed");
txtSpeed.setText(maxspeed+" here");
} else {
//Your error handling here...
}

String maxspeed = element.getString("maxspeed");
to
String maxspeed = element.getJSONObject("tags").getString("maxspeed");

Related

How to retrieve user entered input in adaptive card in java

Attached the JSON of adaptive card I sent in teams.
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.0",
"body": [
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Publish Adaptive Card schema",
"weight": "bolder",
"size": "medium"
},
{
"type": "ColumnSet",
"columns": [
{
"type": "Column",
"width": "auto",
"items": [
{
"type": "Image",
"url": "https://pbs.twimg.com/profile_images/3647943215/d7f12830b3c17a5a9e4afcc370e3a37e_400x400.jpeg",
"size": "medium",
"style": "person"
}
]
},
{
"type": "Column",
"width": "stretch",
"items": [
{
"type": "TextBlock",
"text": "Matt Hidinger",
"weight": "bolder",
"wrap": true
},
{
"type": "TextBlock",
"spacing": "none",
"text": "Created Tuesday, Feb 14, 2017",
"isSubtle": true,
"wrap": true
}
]
}
]
}
]
},
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Now that we have defined the main rules and features of the format, we need to produce a schema and publish it to GitHub. The schema will be the starting point of our reference documentation.",
"wrap": true
},
{
"type": "FactSet",
"facts": [
{
"title": "Board:",
"value": "Adaptive Card"
},
{
"title": "List:",
"value": "Backlog"
},
{
"title": "Assigned to:",
"value": "Matt Hidinger"
},
{
"title": "Due date:",
"value": "Not set"
}
]
}
]
}
],
"actions": [
{
"type": "Action.ShowCard",
"title": "Set due date",
"card": {
"version": "1.0",
"type": "AdaptiveCard",
"body": [
{
"type": "Input.Date",
"id": "dueDate",
"title": "Select due date"
}
],
"actions": [
{
"type": "Action.Submit",
"title": "OK"
}
]
}
},
{
"type": "Action.ShowCard",
"title": "Comment",
"card": {
"version": "1.0",
"type": "AdaptiveCard",
"body": [
{
"type": "Input.Text",
"id": "comment",
"isMultiline": true,
"placeholder": "Enter your comment"
}
],
"actions": [
{
"type": "Action.Submit",
"title": "OK"
}
]
}
},
{
"type": "Action.OpenUrl",
"title": "View",
"url": "http://adaptivecards.io"
}
]
}
After User entered values and click ok, reply from bot is "Echo:"
How can i display the entered value as reply from bot.
I have implemented this to get activity, but this method is not called when use click ok.

Insert object to nested array

I'm trying to insert an object to a nested array through the java api, but I get the following error
MapperParsingException[object mapping for [X] tried to parse field [null] as object, but found a concrete value]
doing it through Kibana as shown below the same script works.
Any ideas on how to fix this?
The java code is the following
HashMap<String, Object> params = new HashMap<>();
params.put("object", objectAsString);
Script script = new Script(ScriptType.INLINE, "painless", "ctx._source.media.add(params.object)", params);
UpdateResponse result = elasticClient.prepareUpdate(indexName, "Type", documentId).setScript(script).execute().actionGet();
Trhough Kibana
POST index/document/id/_update
{
"script": {
"lang": "painless",
"inline": "ctx._source.media.add(params.object)",
"params": {
"object": {
"description" : "A second image",
"height" : 5,
"weight": 5,
"name" : "Test",
"orientation" : "Vertical",
"url" : "htttp://newurl.jpg",
"tags":["first","second"],
"type":"image"
}
}
}
}
The template mapping is the following:
"mappings": {
"FOLDER_MODULE": {
"properties": {
"name": {
"type": "keyword"
},
"publisherId": {
"type": "keyword"
},
"username": {
"type": "keyword"
},
"media": {
"type": "nested",
"properties": {
"id": {
"type": "text"
},
"name": {
"type": "text"
},
"publisherId": {
"type": "short"
},
"tags": {
"type": "text"
},
"description": {
"type": "text"
},
"url": {
"type": "keyword"
},
"createdDate": {
"format": "strict_date_optional_time||epoch_millis",
"type": "date"
},
"height": {
"type": "float"
},
"width": {
"type": "float"
},
"weight": {
"type": "float"
},
"orientation": {
"type": "keyword"
},
"status": {
"type": "keyword"
},
"type": {
"type": "keyword"
},
"username": {
"type": "keyword"
}
}
}
}
}
}

Precondition on data pipeline

I did some set of activities on json script. Need to add precondition on it.
how to use precondition on json script.
In precondition, i need to check the mysql db field. once flag as 'Y',
start execution else should be stop the execution.
You can use a ShellCommandPrecondition for this which will let you write a custom precondition.
{
"objects": [
{
"schedule": {
"ref": "DefaultSchedule"
},
"resourceRole": "DataPipelineDefaultResourceRole",
"role": "DataPipelineDefaultRole",
"name": "DefaultResource1",
"id": "ResourceId_dWoZ0",
"type": "Ec2Resource",
"terminateAfter": "1 Hour"
},
{
"name": "DefaultPrecondition1",
"id": "PreconditionId_yA2rV",
"type": "ShellCommandPrecondition",
"command": "<Script to check mysql field>"
},
{
"occurrences": "1",
"period": "1 Day",
"name": "RunOnce",
"id": "DefaultSchedule",
"type": "Schedule",
"startAt": "FIRST_ACTIVATION_DATE_TIME"
},
{
"failureAndRerunMode": "CASCADE",
"schedule": {
"ref": "DefaultSchedule"
},
"resourceRole": "DataPipelineDefaultResourceRole",
"role": "DataPipelineDefaultRole",
"pipelineLogUri": "s3://<mybucket>",
"scheduleType": "cron",
"name": "Default",
"id": "Default"
},
{
"schedule": {
"ref": "DefaultSchedule"
},
"name": "DefaultActivity1",
"runsOn": {
"ref": "ResourceId_dWoZ0"
},
"precondition": {
"ref": "PreconditionId_yA2rV"
},
"id": "ActivityId_gmQ0W",
"type": "ShellCommandActivity",
"command": "echo 'Hello world'"
}
],
"parameters": []
}

Parsing a Nested JSON output

What i am doing::I have a Json Structure I want to extract Bangalore having key adminArea5
{
"results": [
{
"locations": [
{
"latLng": {
"lng": 77.620949,
"lat": 12.931088
},
"adminArea4": "Bangalore Urban",
"adminArea5Type": "City",
"adminArea4Type": "County",
"adminArea5": "Bangalore",
"street": "Sarjapur Road",
"adminArea1": "IN",
"adminArea3": "Karnataka",
"type": "s",
"displayLatLng": {
"lng": 77.617502,
"lat": 12.928883
},
"linkId": 0,
"postalCode": "560095",
"sideOfStreet": "N",
"dragPoint": false,
"adminArea1Type": "Country",
"geocodeQuality": "ADDRESS",
"geocodeQualityCode": "L1AAA",
"mapUrl": "http://open.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur2d0821,8s=o5-9arwha&type=map&size=225,160&pois=purple-1,12.931088,77.620949,0,0|&center=12.931088,77.620949&zoom=15&rand=981886032",
"adminArea3Type": "State"
}
],
"providedLocation": {
"latLng": {
"lng": 77.620949,
"lat": 12.931088
}
}
}
],
"options": {
"ignoreLatLngInput": false,
"maxResults": -1,
"thumbMaps": true
},
"info": {
"copyright": {
"text": "© 2014 MapQuest, Inc.",
"imageUrl": "http://api.mqcdn.com/res/mqlogo.gif",
"imageAltText": "© 2014 MapQuest, Inc."
},
"statuscode": 0,
"messages": []
}
}
What i have done so far::
HttpGet httpget = new HttpGet(Const.URL_JSON_OBJECT);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
jsonobject = new JSONObject(Content);
Log.d("Content", Content.toString());
myString=jsonobject.getString("results").toString();
With the code above :: I have the JSON Structure
[
{
"providedLocation": {
"latLng": {
"lat": 12.931088,
"lng": 77.620949
}
},
"locations": [
{
"latLng": {
"lat": 12.931088,
"lng": 77.620949
},
"adminArea5Type": "City",
"adminArea4": "Bangalore Urban",
"adminArea5": "Bangalore",
"adminArea4Type": "County",
"street": "Sarjapur Road",
"adminArea1": "IN",
"adminArea3": "Karnataka",
"type": "s",
"displayLatLng": {
"lat": 12.928883,
"lng": 77.617502
},
"linkId": 0,
"postalCode": "560095",
"dragPoint": false,
"sideOfStreet": "N",
"adminArea1Type": "Country",
"geocodeQuality": "ADDRESS",
"geocodeQualityCode": "L1AAA",
"adminArea3Type": "State",
"mapUrl": "http://open.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur2d0821,8s=o5-9arwha&type=map&size=225,160&pois=purple-1,12.931088,77.620949,0,0|&center=12.931088,77.620949&zoom=15&rand=-1939275403"
}
]
}
]
Question:: How to get Bangalore having key adminArea5
It looks like that you've an JSONArray() within your JSONObject.
Try to get the JSONOBject result, pick out the
JSONArray jsonArray = new JSONArray(jsonObject.get("results")).
In your JSONArray you can parse out your required data.

Navigate array inside object, Android Java

I have the following JSON object below and I was wondering how to fetch the results of MediaUrl. I found a lot of tutorials on how to parse an array or an object but I can't find anything on how to loop an array inside of an object.
{
"d": {
"results": [
{
"__metadata": {
"uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query='Acanthurus achilles'&Adult='Strict'&ImageFilters='Size:Small+Aspect:Square'&Market='en-US'&$skip=0&$top=1",
"type": "ImageResult"
},
"ID": "17866c98-31f2-4488-9512-e47785301117",
"Title": "acanthurus achilles acanthuridae poissons chirurgiens",
"MediaUrl": "http://www.aquariophilie62.fr/images/poissons-recifal/thumbs/Acanthurus-achilles-.jpg",
"SourceUrl": "http://www.aquariophilie62.fr/fiches-poissons-recifaux/",
"DisplayUrl": "www.aquariophilie62.fr/fiches-poissons-recifaux",
"Width": "100",
"Height": "100",
"FileSize": "19633",
"ContentType": "image/jpeg",
"Thumbnail": {
"__metadata": {
"type": "Bing.Thumbnail"
},
"MediaUrl": "http://ts2.mm.bing.net/th?id=H.4820238373750001&pid=15.1",
"ContentType": "image/jpg",
"Width": "100",
"Height": "100",
"FileSize": "2509"
}
},
{
"__metadata": {
"uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query='Acanthurus achilles'&Adult='Strict'&ImageFilters='Size:Small+Aspect:Square'&Market='en-US'&$skip=1&$top=1",
"type": "ImageResult"
},
"ID": "e2a96fba-f8b2-4212-8477-1bf36131d61c",
"Title": "100x100px-LS-8c425bd7_47876-000676_Acanthurus_achilles.jpg",
"MediaUrl": "http://cdn.saltwaterfish.com/8/8c/100x100px-LS-8c425bd7_47876-000676_Acanthurus_achilles.jpg",
"SourceUrl": "http://forums.saltwaterfish.com/t/346818/humu-humu-trigger-shrimps",
"DisplayUrl": "forums.saltwaterfish.com/t/346818/humu-humu-trigger-shrimps",
"Width": "100",
"Height": "100",
"FileSize": "8185",
"ContentType": "image/jpeg",
"Thumbnail": {
"__metadata": {
"type": "Bing.Thumbnail"
},
"MediaUrl": "http://ts2.mm.bing.net/th?id=H.4781768365638869&pid=15.1",
"ContentType": "image/jpg",
"Width": "100",
"Height": "100",
"FileSize": "2234"
}
},
{
"__metadata": {
"uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query='Acanthurus achilles'&Adult='Strict'&ImageFilters='Size:Small+Aspect:Square'&Market='en-US'&$skip=2&$top=1",
"type": "ImageResult"
},
"ID": "11d79168-8fd1-49d9-9d06-c54208cecf28",
"Title": "acanthurus bahianus acanthuridae poissons chirurgiens",
"MediaUrl": "http://www.aquariophilie62.fr/images/poissons-recifal/thumbs/Acanthurus-bahianus-.jpg",
"SourceUrl": "http://www.aquariophilie62.fr/fiches-poissons-recifaux/",
"DisplayUrl": "www.aquariophilie62.fr/fiches-poissons-recifaux",
"Width": "100",
"Height": "100",
"FileSize": "19105",
"ContentType": "image/jpeg",
"Thumbnail": {
"__metadata": {
"type": "Bing.Thumbnail"
},
"MediaUrl": "http://ts2.mm.bing.net/th?id=H.4820238373749985&pid=15.1",
"ContentType": "image/jpg",
"Width": "100",
"Height": "100",
"FileSize": "2373"
}
}
],
"__next": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query='Acanthurus%20achilles'&Adult='Strict'&ImageFilters='Size:Small+Aspect:Square'&Market='en-US'&$skip=3&$top=3"
}
}
Assuming obj is a JSONObject obtained by parsing the posted String
"results" is the key to a JSONArray that you get from your object using
JSONArray results = obj.getJSONObject("d").getJSONArray("results")
JSONArray has get*(int index) for each type of data you can encounter.
In your case, "results" is an array of JSONObject. You can loop through it using :
for (int i = 0; i < results.length(); i++) {
JSONObject oneResult = results.getJSONObject(i);
}
Once you have the JSONObject, the MediaUrl is just one getString("MediaUrl") away ...

Categories