I have a response which contains values which I need.
private void getDataFromDistanceMatrixToSaveAndAddToList(
GRATestDataImport place, String response) {
JSONObject responseAsJson = new JSONObject(response).getJSONArray("rows")
.getJSONObject(0)
.getJSONArray("elements")
.getJSONObject(0);
}
'response' in params includes:
{
"destination": [
"54.375,18.59"
],
"origin": [
"54.001,21.721"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "304.4 km",
"value": 304403
},
"duration": {
"text": "3 h 53 min",
"value": 14003
},
"status": "OK"
}
]
}
],
"status": "OK"
}
value: 'responseAsJson' in my method is:
{
"duration": {
"text": "3 h 53 min",
"value": 14003
},
"distance": {
"text": "304.4 km",
"value": 304403
},
"status": "OK"
}
How can I get value from the duration and the distance ?
you'll just have to navigate along
int duration = responseAsJson.getJSONObject("duration").getInt("value");
int distance = responseAsJson.getJSONObject("distance").getInt("value");
public class YourResponse
{
public string duration { get; set; }
public string distance { get; set; }
}
YourResponse response = JsonSerializer.Deserialize<YourResponse>(result);
Related
I have a response received from sharepoint.
{
"d": {
"query": {
"SecondaryQueryResults": {
"__metadata": {
"type": "Collection(Microsoft.Office.Server.Search.REST.QueryResult)"
},
"results": []
},
"SpellingSuggestion": "",
"TriggeredRules": {
"__metadata": {
"type": "Collection(Edm.Guid)"
},
"results": ["e0205660-4971-4574-aa40-af6b4383cadd"]
},
"ElapsedTime": 224,
"__metadata": {
"type": "Microsoft.Office.Server.Search.REST.SearchResult"
},
"Properties": {
"__metadata": {
"type": "Collection(SP.KeyValue)"
},
"results": [{
"ValueType": "Edm.Int32",
"Value": "10",
"Key": "RowLimit"
}, {
"ValueType": "Edm.Guid",
"Value": "8413cd39-2156-4e00-b54d-11efd9abdb49",
"Key": "SourceId"
}, {
"ValueType": "Edm.Guid",
"Value": "7bc4ba9e-80ff-7000-58cf-f7ac556d1e34",
"Key": "CorrelationId"
}, {
"ValueType": "Edm.Boolean",
"Value": "false",
"Key": "WasGroupRestricted"
}, {
"ValueType": "Edm.Boolean",
"Value": "false",
"Key": "IsPartial"
}, {
"ValueType": "Edm.Boolean",
"Value": "false",
"Key": "HasParseException"
}, {
"ValueType": "Edm.String",
"Value": "en",
"Key": "WordBreakerLanguage"
}, {
"ValueType": "Edm.Boolean",
"Value": "false",
"Key": "IsPartialUpnDocIdMapping"
}, {
"ValueType": "Edm.Boolean",
"Value": "true",
"Key": "EnableInterleaving"
}, {
"ValueType": "Edm.Boolean",
"Value": "false",
"Key": "IsMissingUnifiedGroups"
}, {
"ValueType": "Edm.String",
"Value": "i62456",
"Key": "Constellation"
}, {
"ValueType": "Edm.String",
"Value": "<Query Culture=\"en-US\" EnableStemming=\"True\" EnablePhonetic=\"False\" EnableNicknames=\"False\" IgnoreAllNoiseQuery=\"True\" SummaryLength=\"180\" MaxSnippetLength=\"180\" DesiredSnippetLength=\"90\" KeywordInclusion=\"0\" QueryText=\"59055305\" QueryTemplate=\"\" TrimDuplicates=\"True\" Site=\"e297bd2b-597a-4f54-8509-e2febb91b869\" Web=\"d42ff0d1-883b-4545-ab6a-97b0401025d4\" KeywordType=\"True\" HiddenConstraints=\"\" \/>",
"Key": "SerializedQuery"
}]
},
"PrimaryQueryResult": {
"RefinementResults": null,
"SpecialTermResults": null,
"QueryId": "0585a5f1-89bc-43c1-b736-e163b4d7c1dd",
"QueryRuleId": "00000000-0000-0000-0000-000000000000",
"CustomResults": {
"__metadata": {
"type": "Collection(Microsoft.Office.Server.Search.REST.CustomResult)"
},
"results": []
},
"__metadata": {
"type": "Microsoft.Office.Server.Search.REST.QueryResult"
},
"RelevantResults": {
"Table": {
"__metadata": {
"type": "SP.SimpleDataTable"
},
"Rows": {
"results": [{
"__metadata": {
"type": "SP.SimpleDataRow"
},
"Cells": {
"results": [{
"ValueType": "Edm.Double",
"Value": "26.8860855102549",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Rank"
}, {
"ValueType": "Edm.Int64",
"Value": "17594532057853",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "DocId"
}, {
"ValueType": "Edm.Int64",
"Value": "17594531057253",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "WorkId"
}, {
"ValueType": "Edm.String",
"Value": "Customer Request Filling",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Title"
}, {
"ValueType": "Edm.String",
"Value": "Technology Services;svc ECMWise",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Author"
}, {
"ValueType": "Edm.Int64",
"Value": "97182",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Size"
}, {
"ValueType": "Edm.String",
"Value": "https:\/\/xxxxxx.sharepoint.com\/sites\/news\/CUST\/Forms\/Appeals\/Customer Reader.pdf",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Path"
}, {
"ValueType": "Null",
"Value": null,
"__metadata": {
"type": "SP.KeyValue"
},
....
What I am trying to get is the "Path" of "Value" string of that pdf as a snapshot from below (part of section from what was above)
{
"ValueType": "Edm.String",
"Value": "https:\/\/xxxxxx.sharepoint.com\/sites\/news\/CUST\/Forms\/Appeals\/Customer Reader.pdf",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Path"
}
I have tried to use JSONObject to parse it like this.
JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader((httpConn.getInputStream())));
JSONObject folder = (JSONObject)jsonObject.get("d");
JSONObject query = (JSONObject) folder.get("query");
JSONObject properties = (JSONObject) query.get("PrimaryQueryResult");
JSONObject result = (JSONObject) properties.get("RelevantResults");
JSONObject table = (JSONObject) result.get("Table");
JSONObject rows = (JSONObject) table.get("Rows");
....
I was wondering if there is a easier way to do this or what if one of the key is not populated. It would throw null pointer exception so is there a way just to find a key directly inside of this long nested json and how do I get the field "Key" from the json array of the "Cells"
You should consider using a JSON serializer such as Jackson or GSON.
If the underlying JSON response structure will be the same for each call, even if it has missing keys, you can create your own POJO using something like JSONSchema2POJO. This will generate a POJO with Jackson or GSON annotations using a JSON string that you provide. Here's an example using a snippet of your JSON string:
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("ValueType")
#Expose
private String valueType;
#SerializedName("Value")
#Expose
private String value;
#SerializedName("__metadata")
#Expose
private Metadata metadata;
#SerializedName("Key")
#Expose
private String key;
public String getValueType() {
return valueType;
}
public void setValueType(String valueType) {
this.valueType = valueType;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
-----------------------------------com.example.Metadata.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Metadata {
#SerializedName("type")
#Expose
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
This is standard practice when consuming JSON in Java and it allows keys/values to be null when the object is serialized without breaking your code.
If the JSON structure is completely unpredictable, GSON allows you to create Generic types or you can take it a step further and write custom serializers. Jackson likely has similar functionality but I'm only versed in GSON.
You could use quick-json (enter link description here) and have something like this (rapid version not optimized) :
public class Go {
public static void main(String[] args) {
try {
List<String> pdf_list = new ArrayList<>();
JsonParserFactory factory= JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson("/54424034/sharepoint.json", "UTF-8");
//jsonMap.get("d/query/PrimaryQueryResult/RelevantResults/Table/Rows/results");
Map d = (Map) jsonMap.get("d");
Map query = (Map) d.get("query");
Map primaryQueryResult = (Map) query.get("PrimaryQueryResult");
Map relevantResults = (Map) primaryQueryResult.get("RelevantResults");
Map table = (Map) relevantResults.get("Table");
Map rows = (Map) table.get("Rows");
List<Map> results_rows = (ArrayList) rows.get("results");
for (Map result_row : results_rows) {
Map cells = (Map) result_row.get("Cells");
List<Map> results_cells = (ArrayList) cells.get("results");
for (Map result_cell : results_cells) {
String key = (String) result_cell.get("Key");
if ("Path".equalsIgnoreCase(key)) {
pdf_list.add((String) result_cell.get("Value"));
}
}
}
System.out.println(pdf_list);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
It just parses your Json and add all pdf path into a List
I'm trying to get the counts group by the repetitive items in array without distinct, use aggs terms but not work
GET /my_index/_search
{
"size": 0,
"aggs": {
"keywords": {
"terms": {
"field": "keywords"
}
}
}
}
documents like:
"keywords": [
"value1",
"value1",
"value2"
],
but the result is:
"buckets": [
{
"key": "value1",
"doc_count": 1
},
{
"key": "value2",
"doc_count": 1
}
]
how can i get the result like:
"buckets": [
{
"key": "value1",
"doc_count": 2
},
{
"key": "value2",
"doc_count": 1
}
]
finally I modify the mapping use nested:
"keywords": {
"type": "nested",
"properties": {
"count": {
"type": "integer"
},
"keyword": {
"type": "keyword"
}
}
},
and query:
GET /my_index/_search
{
"size": 0,
"aggs": {
"keywords": {
"nested": {
"path": "keywords"
},
"aggs": {
"keyword_name": {
"terms": {
"field": "keywords.keyword"
},
"aggs": {
"sums": {
"sum": {
"field": "keywords.count"
}
}
}
}
}
}
}
}
result:
"buckets": [{
"key": "value1",
"doc_count": 495,
"sums": {
"value": 609
}
},
{
"key": "value2",
"doc_count": 440,
"sums": {
"value": 615
}
},
{
"key": "value3",
"doc_count": 319,
"sums": {
"value": 421
}
},
...]
response:
[
{
"id": "e9299032e8a34d168def176af7d62da3",
"createdAt": "Nov 8, 2017 9:46:40 AM",
"model": {
"id": "eeed0b6733a644cea07cf4c60f87ebb7",
"name": "color",
"app_id": "main",
"created_at": "May 11, 2016 11:35:45 PM",
"model_version": {}
},
"input": {
"id": "df6eae07cd86483f811c5a2202e782eb",
"data": {
"concepts": [],
"metadata": {},
"image": {
"url": "http://www.sachinmittal.com/wp-content/uploads/2017/04/47559184-image.jpg"
}
}
},
"data": [
{
"hex": "#f59b2d",
"webSafeHex": "#ffa500",
"webSafeColorName": "Orange",
"value": 0.0605
},
{
"hex": "#3f1303",
"webSafeHex": "#000000",
"webSafeColorName": "Black",
"value": 0.2085
},
{
"hex": "#a33303",
"webSafeHex": "#8b0000",
"webSafeColorName": "DarkRed",
"value": 0.3815
},
{
"hex": "#000000",
"webSafeHex": "#000000",
"webSafeColorName": "Black",
"value": 0.34275
},
{
"hex": "#f7ce93",
"webSafeHex": "#ffdead",
"webSafeColorName": "NavajoWhite",
"value": 0.00675
}
],
"status": {}
}
]
need to parse this reponse in json. Please help me out.
You can try something like this..
try{
JSONArray array= new JSONArray(Yourresponse);
for(int i=0; i<=array.length();i++){
JSONObject jsonObject=array.getJSONObject(i);
String id= jsonObject.getString("id");
String created_at= jsonObject.getString("createdAt");
String model_id = jsonObject.getJSONObject("model").getString("id");
String app_id=jsonObject.getJSONObject("model").getString("app_id");
//So On... Depends on your requirements. It's just an idea!
}
}
catch (Exception e){
e.printStackTrace();
}
I've got the title, author, and published date from json data to my android app.
I'm trying to get event_start_date and event_location, but failed. can anyone help me how I can get it?
Json:
{
"status": "ok",
"count": 1,
"count_total": 29,
"pages": 29,
"posts": [
{
"id": 2815,
"type": "event",
"slug": "itb-integrated-career-days",
"url": "http://example.com/event/itb-integrated-career-days/",
"status": "publish",
"title": "Title",
"title_plain": "Title",
"content": "<p>test</p>\n",
"excerpt": "<p>test […]</p>\n",
"date": "2015-09-25 01:09:40",
"modified": "2015-09-29 22:52:35",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "john",
"name": "john",
"first_name": "",
"last_name": "",
"nickname": "john",
"url": "",
"description": ""
},
"comments": [],
"attachments": [
{
"id": 2817,
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015.gif",
"slug": "bannertkt102015",
"title": "bannertkt102015",
"description": "",
"caption": "",
"parent": 2815,
"mime_type": "image/gif",
"images": {
"full": {
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015.gif",
"width": 1000,
"height": 563
},
"thumbnail": {
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015-150x150.gif",
"width": 150,
"height": 150
},
"medium": {
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015-300x169.gif",
"width": 300,
"height": 169
},
"large": {
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015.gif",
"width": 1000,
"height": 563
},
"blog-default": {
"url": "http://example.com/wp-content/uploads/2015/09/bannertkt102015-806x300.gif",
"width": 806,
"height": 300
}
}
},
{
"id": 2818,
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008.jpg",
"slug": "2015-09-25_012008",
"title": "2015-09-25_012008",
"description": "",
"caption": "",
"parent": 2815,
"mime_type": "image/jpeg",
"images": {
"full": {
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008.jpg",
"width": 589,
"height": 529
},
"thumbnail": {
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008-150x150.jpg",
"width": 150,
"height": 150
},
"medium": {
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008-300x269.jpg",
"width": 300,
"height": 269
},
"large": {
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008.jpg",
"width": 589,
"height": 529
},
"blog-default": {
"url": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008-589x300.jpg",
"width": 589,
"height": 300
}
}
}
],
"comment_count": 0,
"comment_status": "open",
"thumbnail": "http://example.com/wp-content/uploads/2015/09/2015-09-25_012008-150x150.jpg",
"custom_fields": {
"event_location": [
"New York"
],
"event_start_date": [
"10/23/2015"
],
"event_start_time": [
"09:00 AM"
],
"event_start_date_number": [
"1445590800"
],
"event_address_country": [
"US"
],
"event_address_state": [
"Jawdst"
],
"event_address_city": [
"New York"
],
"event_address_address": [
"Gedung Sasana Budaya Ganesha (Sabuga) Jalan Tamansari 73, New York"
],
"event_address_zip": [
"42132"
],
"event_phone": [
"5345"
],
"post_views_count": [
"23"
]
}
}
]
}
And my function
public void parseJson(JSONObject json) {
try {
info.pages = json.getInt("pages");
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
info.feedList = new ArrayList<PostItem>();
for (int i = 0; i < posts.length(); i++) {
Log.v("INFO",
"Step 3: item " + (i + 1) + " of " + posts.length());
try {
JSONObject post = (JSONObject) posts.getJSONObject(i);
PostItem item = new PostItem();
item.setTitle(Html.fromHtml(post.getString("title"))
.toString());
item.setDate(post.getString("date"));
item.setId(post.getInt("id"));
item.setUrl(post.getString("url"));
item.setContent(post.getString("content"));
if (post.has("author")) {
Object author = post.get("author");
if (author instanceof JSONArray
&& ((JSONArray) author).length() > 0) {
author = ((JSONArray) author).getJSONObject(0);
}
if (author instanceof JSONObject
&& ((JSONObject) author).has("name")) {
item.setAuthor(((JSONObject) author)
.getString("name"));
}
}
if (post.has("tags") && post.getJSONArray("tags").length() > 0) {
item.setTag(((JSONObject) post.getJSONArray("tags").get(0)).getString("slug"));
}
// TODO do we dear to remove catch clause?
try {
boolean thumbnailfound = false;
if (post.has("thumbnail")) {
String thumbnail = post.getString("thumbnail");
if (thumbnail != "") {
item.setThumbnailUrl(thumbnail);
thumbnailfound = true;
}
}
if (post.has("attachments")) {
JSONArray attachments = post
.getJSONArray("attachments");
// checking how many attachments post has and
// grabbing the first one
if (attachments.length() > 0) {
JSONObject attachment = attachments
.getJSONObject(0);
item.setAttachmentUrl(attachment
.getString("url"));
// if we do not have a thumbnail yet, get
// one now
if (attachment.has("images")
&& !thumbnailfound) {
JSONObject thumbnail;
if (attachment.getJSONObject("images")
.has("post-thumbnail")) {
thumbnail = attachment
.getJSONObject("images")
.getJSONObject(
"post-thumbnail");
item.setThumbnailUrl(thumbnail
.getString("url"));
} else if (attachment.getJSONObject(
"images").has("thumbnail")) {
thumbnail = attachment
.getJSONObject("images")
.getJSONObject("thumbnail");
item.setThumbnailUrl(thumbnail
.getString("url"));
}
}
}
}
} catch (Exception e) {
Log.v("INFO",
"Item "
+ i
+ " of "
+ posts.length()
+ " will have no thumbnail or image because of exception!");
e.printStackTrace();
}
if (item.getId() != info.ignoreId)
info.feedList.add(item);
} catch (Exception e) {
Log.v("INFO", "Item " + i + " of " + posts.length()
+ " has been skipped due to exception!");
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
This should do it
JSONObject custom_fields = post.getJSONObject("custom_fields");
JSONArray event_start_date_array = custom_fields.getJSONArray("event_start_date");
JSONArray event_location_array = custom_fields.getJSONArray("event_location");
String event_start_date = event_start_date_array.getString(0);
String event_location = event_location_array.getString(0);
I am going to get facebook read_books
The file is in this format:
{
"data": [
{
"id": "270170479804513",
"from": {
"name": "L I",
"id": "1000022"
},
"start_time": "2014-01-22T09:31:00+0000",
"publish_time": "2014-01-22T09:31:00+0000",
"application": {
"name": "Books",
"id": "174275722710475"
},
"data": {
"book": {
"id": "133556360140246",
"url": "https://www.facebook.com/pages/Pride-and-Prejudice/133556360140246",
"type": "books.book",
"title": "Pride and Prejudice"
}
},
"type": "books.reads",
"no_feed_story": false,
"likes": {
"count": 0,
"can_like": true,
"user_likes": false
},
"comments": {
"count": 0,
"can_comment": true,
"comment_order": "chronological"
}
},
{
"id": "270170328",
"from": {
"name": "h",
"id": "100004346894022"
},
"start_time": "2014-01-22T09:29:42+0000",
"publish_time": "2014-01-22T09:29:42+0000",
"application": {
"name": "Books",
"id": "174275722710475"
},
"data": {
"book": {
"id": "104081659627680",
"url": "https://www.facebook.com/pages/Gulistan-of-Sadi/104081659627680",
"type": "books.book",
"title": "Gulistan of Sa'di"
}
},
"type": "books.reads",
"no_feed_story": false,
"likes": {
"count": 0,
"can_like": true,
"user_likes": false
},
"comments": {
"count": 0,
"can_comment": true,
"comment_order": "chronological"
}
}
],
I need books titles and their URL. I run the below code but I get Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.lang.String
while ((inputLine = in.readLine()) != null)
{
s = s + inputLine + "\r\n";
if (s == null) {
break;
}
t = t + inputLine + "\r\n";
}
in.close();
t = t.substring(0, t.length() - 2);
System.out.println(t);
Object dataObj =JSONValue.parse(t);
System.out.println(dataObj);
JSONObject dataJson = (JSONObject) dataObj;
JSONArray data = (JSONArray) dataJson.get("data");
for (Object o: data)
{
JSONObject indata= (JSONObject) o;
Object indatafirst=(JSONObjec`enter code here`t).get("0");
String inndata=(String) indatafirst.get("data");
System.out.println("inndata"+inndata);
}}
but it is not true
The problem is with the following line:
String inndata=(String) indatafirst.get("data");
The data field in the JSON is not a String, it's a nested JSON object.
"data": {
"book": {
"id": "104081659627680",
"url": "https://www.facebook.com/pages/Gulistan-of-Sadi/104081659627680",
"type": "books.book",
"title": "Gulistan of Sa'di"
}
}
This explains your ClassCastException.
Instead you should do something like:
JSONObject data = (JSONObject) indatafirst.get("data");
JSONObject book = (JSONObject) data.get("book");
String bookTitle = book.get("title");