I want to know is there any way to receive JsonArray as a response from a post request. The problem is my response is a JSONObject type. I know how to get response from String type response, I want to know the method to get response from a JSONObject type response.
this is the JSONArray I want to get as response.
{
"attendanceID": 237674,
"attendeeUserID": 46114,
"batchId": 1466,
"departmentId": null,
"organizationId": 4,
"leaveTypeId": null,
"attandanceType": 1,
"absentDate": "2017-06-12T00:00:00",
"comment": null,
"subjectId": null,
"isAbsent": true,
"markedBy": 2780,
"isDeleted": false,
"dateTimeStampIns": "2017-06-12T13:11:50.9457068+05:30",
"dateTimeStamp": "2017-06-12T13:11:50.9457068+05:30",
"attandeeName": null,
"businessDays": 0,
"templateId": 1,
"message": "Your ward #### is absent today WITHOUT PRIOR INFORMATION. Kindly send the Leave Letter - ####",
"message1": null,
"isHalfDay": null
}
You can always parse to json. But first make that string properly formatted:
[{ "attendanceID": 237674, "attendeeUserID": 46114, "batchId": 1466, "departmentId": null, "organizationId": 4, "leaveTypeId": null,
"attandanceType": 1, "absentDate": "2017-06-12T00:00:00", "comment":
null, "subjectId": null, "isAbsent": true, "markedBy": 2780,
"isDeleted": false, "dateTimeStampIns":
"2017-06-12T13:11:50.9457068+05:30", "dateTimeStamp":
"2017-06-12T13:11:50.9457068+05:30", "attandeeName": null,
"businessDays": 0, "templateId": 1, "message": "Your ward #### is
absent today WITHOUT PRIOR INFORMATION. Kindly send the Leave Letter -
####", "message1": null, "isHalfDay": null },{//this will be second row"attendanceID": 455435,"attendeeUserID": 46114, "batchId": 1466, "departmentId": (...)}]
EDIT: How to substract:
var text = '[{"description":"about_text","value":"test1","patience":"over9000"}]';
obj = JSON.parse(text);
var yourvar_description = obj[0].description;
var yourvar_value = obj[0].value ;
var yourvar_patience = obj[0].patience;
(in javascript)
To do it in android:
Already answered here
Related
I want to receive emoticon from emoji-datasource site as json file and show it in android. How do you do it? The file in json format is:
[
{
"name": "HASH KEY",
"unified": "0023-FE0F-20E3",
"non_qualified": "0023-20E3",
"docomo": "E6E0",
"au": "EB84",
"softbank": "E210",
"google": "FE82C",
"image": "0023-fe0f-20e3.png",
"sheet_x": 0,
"sheet_y": 0,
"short_name": "hash",
"short_names": [
"hash"
],
"text": null,
"texts": null,
"category": "Symbols",
"sort_order": 132,
"added_in": "0.0",
"has_img_apple": true,
"has_img_google": true,
"has_img_twitter": true,
"has_img_facebook": false
},
{
"name": null,
"unified": "002A-FE0F-20E3",
"non_qualified": "002A-20E3",
"docomo": null,
"au": null,
"softbank": null,
"google": null,
"image": "002a-fe0f-20e3.png",
"sheet_x": 0,
"sheet_y": 1,
"short_name": "keycap_star",
"short_names": [
"keycap_star"
],
"text": null,
"texts": null,
"category": "Symbols",
"sort_order": 133,
"added_in": "0.0",
"has_img_apple": true,
"has_img_google": true,
"has_img_twitter": true,
"has_img_facebook": false
},
...
]
Link is here : https://www.npmjs.com/package/emoji-datasource.
I tried the following but it didn't work.
textView.text = String(Character.toChars(0x002AFE0F20E3))
I want to show the user all the emoticons available on the Android device.
Oh, I solved it. Just use in json file google name code.
I dont know that this would serve as a solution but I did something different and wanna share it here so everyone knows.
Content that I create from Android app gets encoded using this. When fetching from server, I decode this using the same method. Content includes emojis as well and they appear perfectly in all devices without knowing the names of the emojis.
I'm trying to use the New york times api to show the headline and an image in a listview on android. I'm already getting the data for headline and date and outputting to log cat. The real problem is: whenever I put the extra field to get the mulimedia (images url) the "GC_FOR_ALLOC freed 1902K (64), 22% free 11931K/15156K" is shown
I've seen that the api always sends fixed number of 10 nyt articles, but each of the 10 has a multiple multimedia urls and json with arrays nested and the app freezes. I'll learn to put the data on listview on my own, my real question is, whats the best approach to fix the crash, I only want 1 url image per article.
//THE RETURNED JSON WITH ONLY "MULTIMEDIA" FIELD QUERY.
{
"status": "OK",
"copyright": "Copyright (c) 2018 The New York Times Company. All Rights
Reserved.",
"response": {
"docs": [
{
"multimedia": [
{
"rank": 0,
"subtype": "xlarge",
"caption": null,
"credit": null,
"type": "image",
"url": "images/2018/09/07/opinion/07Parcak/merlin_143215881_20cecc31-7c8d-4b8f-8541-773170c1822c-articleLarge.jpg",
"height": 400,
//MORE CODE HERE.. THEN NEXT ARRAY BELOW
{
"multimedia": [
{
"rank": 0,
"subtype": "xlarge",
"caption": null,
"credit": null,
"type": "image",
"url": "images/2018/09/03/world/03xp-brazil-promo/03xp-brazil-promo-articleLarge.jpg",
"height": 400,
"width": 600,
"legacy": {
"xlarge": "images/2018/09/03/world/03xp-brazil-promo/03xp-brazil-promo-articleLarge.jpg",
"xlargewidth": 600,
"xlargeheight": 400
},
"subType": "xlarge",
"crop_name": "articleLarge"
},
// Goes on forever.
What do you use to get the data, what kind of REST client are you using?
For example if you are parsing the response by yourself you can put some logic like
JSONObject obj = new JSONObject(" .... ");
JSONArray arr = obj.getJSONArray("multimedia");
JSONObject firstMultimedia = null;
if (arr.length() > 0){
firstMultimedia = arr.getJSONObject(0);
}
I'm trying to parse in android studio a JSON, that containts this :
"stops":
[
{
"num": 1,
"time": "2016-04-27T06:15:00.000Z",
"title":"Flight to London",
"desc":"Barcelona BCN-London-Gatwick LGW",
"type":"0",
"subtype":0
},
{
"num": 2,
"time": "2016-04-27T10:35:00.000Z",
"title":"Gatwick express",
"desc":"From Airport to London",
"type":"0",
"subtype":1
},
{
"num": 3,
"time": "2016-04-27T12:15:00.000Z",
"title":"Pub the black horse",
"desc":"From Airport to London",
"type":1,
"subtype":1,
"location": "51.476334, -0.062700",
"images": [ "https://fitzrovianews.files.wordpress.com/2011/01/black_horse_rathbone_pl.jpg"
]
},
{
"num": 4,
"time": "2016-04-27T12:16:47.000Z",
"title":"The Tower Bridge",
"desc":"# The Tower Bridge Facts\n## Architecture\n**Tower Bridge** is a combined bascule and suspension bridge in London built in _1886–1894_. The bridge crosses the River Thames close to the Tower of London and has become an iconic symbol of London. Tower Bridge is one of five London bridges now owned and maintained by the Bridge House Estates, a charitable trust overseen by the City of London Corporation. \n>It is the only one of the Trust's bridges not to connect the City of London directly to the Southwark bank, as its northern landfall is in Tower Hamlets.\n## The bridge Exhibition\nThis must-see London attraction invites you to step inside the most famous bridge in the world to explore its iconic structure, spectacular views and glass floor, modern exhibitions and magnificent Victorian Engine Rooms! ",
"type":1,
"subtype":6,
"location": "51.507792, -0.087786",
"images": [
"https://i.ytimg.com/vi/nby0Mr2LfBQ/hqdefault.jpg",
"http://raindropsofsapphire.com/wp-content/uploads/2011/10/london-bridge.jpg",
"http://www.londonforfree.net/gizmo/wp-content/uploads/2015/02/southwark-bridge.jpg"
]
},
{
"num": 5,
"time": "2016-04-27T12:18:10.000Z",
"title":"St. Paul Cathedral",
"desc":"# HISTORY \nSt **Paul's Cathedral**, London, is an _Anglican cathedral_, the seat of the _Bishop of London_ and the mother church of the Diocese of London. \n * It sits on Ludgate Hill at the highest point of the City of London and is a Grade 1 listed building. \n * Its dedication to Paul the Apostle dates back to the original church on this site, founded in AD 604.",
"type":1,
"subtype":6,
"location": "51.513825, -0.098351",
"images": [
"https://d1wgio6yfhqlw1.cloudfront.net/sysimages/product/resized6/Interior_St_Pauls_Cathedral_132_12992.jpg",
"https://d1kioxk2jrdjp.cloudfront.net/resized/486x324/48-st_pauls_ctahedral_millenirm_bridge.jpg",
"http://i4.mirror.co.uk/incoming/article8299330.ece/ALTERNATES/s615b/LOND-2016-052-HMQ-St-Pauls-Thanks-Giving-704JPG.jpg"
]
}
]
The problem is, i don't know how to deal with the field "location" or "images" which are optional. I know how to deal with the first "stop", i'm doing this :
JSONArray stops = jsonObj.getJSONArray("stops");
for (int i = 0; i < stops.length(); i++) {
JSONObject c = stops.getJSONObject(i);
String num = c.getString("num");
String time = c.getString("time");
String title = c.getString("title");
String descripcion = c.getString("desc");
String type = c.getString("type");
String subtype = c.getString("subtype");
......
}
But i don't know how to check it here is a elment location or a jsonArray "images"...
best way to handle optional fields in JSON is to use opt instead of get
opt provides the parsed value if exist or default value for that datatype if requested key does not exist.
best thing is, it don't even need a try catch block since it always returns a value and in case of any error from server, it will not let your app crash or prevent other values from being parsed.
String location = response.optString("location");
if location exist in response, then it will initialize with the value or it will leave the string null. in case of int or long default is 0, in case of boolean default is false. read about opt for more details.
Use has() method
JSONArray stops = jsonObj.getJSONArray("stops");
for (int i = 0; i < stops.length(); i++) {
JSONObject c = stops.getJSONObject(i);
String num = c.getString("num");
String time = c.getString("time");
String title = c.getString("title");
String descripcion = c.getString("desc");
String type = c.getString("type");
String subtype = c.getString("subtype");
if(c.has("location") && !c.isNull("location")){
// parse location
}
if(c.has("images") && !c.isNull("images")){
// parse images
}
.....
}
you should use Retrofit and Google Gson, where you do not have to do lot of work,
they will do the job for you.
look at these
https://guides.codepath.com/android/Consuming-APIs-with-Retrofit
http://www.vogella.com/tutorials/Retrofit/article.html
In my android app, I want users to be able to enter a twitter username and from there the twitter app launches on the entered username's page. I did some research and found out the link needed to open the twitter app from another app is twitter://user?user_id=id_num I was wondering if there is a way to get the user's twitter id from a twitter username in Android so I can make this happen. Any help would be greatly appreciated, thank you.
You should read through the Twitter API, in particular the section about user lookups
Edit: Links updated to current Twitter API docs though answer remains targeted at API v1.1 as when asked.
That particular request has optional fields to search by id or screen_name and will return a list of matches which you can parse for user ids. So you can search by screen_name and read the response to get an id.
The request you are (were) looking for is:
GET https://api.twitter.com/1/users/lookup.json?screen_name=somename
The provided response in the API examples is (was):
[
{
"name": "Twitter API",
"profile_sidebar_border_color": "87bc44",
"profile_background_tile": false,
"profile_sidebar_fill_color": "e0ff92",
"location": "San Francisco, CA",
"profile_image_url": "http://a3.twimg.com/profile_images/689684365/api_normal.png",
"created_at": "Wed May 23 06:01:13 +0000 2007",
"profile_link_color": "0000ff",
"favourites_count": 2,
"url": "http://apiwiki.twitter.com",
"contributors_enabled": true,
"utc_offset": -28800,
"id": 6253282,
"profile_use_background_image": true,
"profile_text_color": "000000",
"protected": false,
"followers_count": 160752,
"lang": "en",
"verified": true,
"profile_background_color": "c1dfee",
"geo_enabled": true,
"notifications": false,
"description": "The Real Twitter API. I tweet about API changes, service issues and appily answer questions about Twitter and our API. Don't get an answer? It's on my website.",
"time_zone": "Pacific Time (US & Canada)",
"friends_count": 19,
"statuses_count": 1858,
"profile_background_image_url": "http://a3.twimg.com/profile_background_images/59931895/twitterapi-background-new.png",
"status": {
"coordinates": null,
"favorited": false,
"created_at": "Tue Jun 22 16:53:28 +0000 2010",
"truncated": false,
"text": "#Demonicpagan possible some part of your signature generation is incorrect & fails for real reasons.. follow up on the list if you suspect",
"contributors": null,
"id": 16783999399,
"geo": null,
"in_reply_to_user_id": 6339722,
"place": null,
"source": "TweetDeck",
"in_reply_to_screen_name": "Demonicpagan",
"in_reply_to_status_id": 16781827477
},
"screen_name": "twitterapi",
"following": false
},
{
"name": "Twitter",
"profile_sidebar_border_color": "EEEEEE",
"profile_background_tile": false,
"profile_sidebar_fill_color": "F6F6F6",
"location": "San Francisco, CA",
"profile_image_url": "http://a1.twimg.com/profile_images/878669694/twitter_bird_normal.jpg",
"created_at": "Tue Feb 20 14:35:54 +0000 2007",
"profile_link_color": "038543",
"favourites_count": 2,
"url": "http://twitter.com",
"contributors_enabled": true,
"utc_offset": -28800,
"id": 783214,
"profile_use_background_image": true,
"profile_text_color": "333333",
"protected": false,
"followers_count": 3305606,
"lang": "en",
"verified": true,
"profile_background_color": "ACDED6",
"geo_enabled": true,
"notifications": false,
"description": "Always wondering what's happening. ",
"time_zone": "Pacific Time (US & Canada)",
"friends_count": 257,
"statuses_count": 774,
"profile_background_image_url": "http://s.twimg.com/a/1276896641/images/themes/theme18/bg.gif",
"status": {
"coordinates": null,
"favorited": false,
"created_at": "Tue Jun 22 16:40:19 +0000 2010",
"truncated": false,
"text": "9 cool things to do with your Twitter account (via #pastemagazine) http://example.com",
"contributors": [
16739704
],
"id": 16783169544,
"geo": null,
"in_reply_to_user_id": null,
"place": null,
"source": "web",
"in_reply_to_screen_name": null,
"in_reply_to_status_id": null
},
"screen_name": "twitter",
"following": false
}
]
So you can access the id from the results by parsing that JSON response for the "id" field.
Note however that the returned is a JSON array of results and not just a single definitive answer. You will need to work out yourself which is the correct one (order is not guaranteed either so do not assume the first entry is the most likely).
Also worth noting is that even though this is documented as returning 'id' and an integer value, the current preferred usage of ids is to supply 'id_str' and a string representation of the integer. This is due to inconsistencies in how various platforms handle and limit integers. So even if you receive 'id' you should use 'id_str' for future interactions.
Assuming you have a bearer token from the Twitter Developer Platform, you can get the id for a given username with the Twitter API v2 users lookup endpoint.
So for example, if I send an authorized GET request to
https://api.twitter.com/2/users/by?usernames=TwitterDev,TwitterAPI
Response:
{
"data": [
{
"id": "2244994945",
"name": "Twitter Dev",
"username": "TwitterDev"
},
{
"id": "6253282",
"name": "Twitter API",
"username": "TwitterAPI"
}
]
}
Python Code Example:
import requests
bearer_token = '<YOUR_TWITTER_BEARER_TOKEN_HERE>'
headers = {"Authorization": f"Bearer {bearer_token}"}
params = {"usernames": "TwitterDev,TwitterAPI"}
url = "https://api.twitter.com/2/users/by"
# Get list of twitter follows
r = requests.get(url, params=params, headers=headers, timeout=20)
if r.status_code != 200:
raise Exception(
"Request returned an error: {} {}".format(
r.status_code, r.text
)
)
json_response = r.json()
for u in json_response['data']:
username = u['username']
id = u['id']
print(f"The user id for {username} is {id}")
Output:
The user id for TwitterDev is 2244994945
The user id for TwitterAPI is 6253282
See also:
Twitter Developer Platform - Users lookup
Twitter APIv2 sample code - get_users_with_bearer_token.py
TweeterID - Twitter ID and username converter
I am trying to read JSON file from asset folder. But I get the following exception
org.json.JSONException: Expected literal value at character 550
I searched lot of stuff but didn't find anything relative. Here is my JSON file.
I find JSON object on 550 is "names": ["Santosh","Sandip","Arvind"],. I am trying to solve it but don't know what happens in my code.
Here is my code.
I also debug my code but when control goes on JSONObject jsonObject = new JSONObject(text); it throw exception and goes in first catch block.
Please give me any reference or hint to solve this problem.
Any help appreciated.
your JSON is invalid.your JSON should look like this
{
"resultCount": 3,
"SearchedTerm": "Wada Pav",
"results": [
{
"locationname": "Mahableshwar Hotel",
"locationid": "12345",
"locationaddress": "baner, Pune",
"dishrating": "4",
"dishname": "Wada Pav",
"dishid": "234",
"dishcategory": "Snacks",
"dishnotes": "Spicy Wada Pav",
"dishpreviewurl": "http://xxx.yyy.zzz/mahableshwar/1.jpg",
"dishtotalvotes": "9999",
"friendslistvoted": {
"friendscount": "3",
"names": [
"Santosh",
"Sandip",
"Arvind"
]
},
"dishimageurl": "http://xxx.yyy.zzz/mahableshwar/2.jpg",
"mylastrating": "4"
}
]
}
try using a JSON validator before using it (like JSLint).
I'm using following to get standard JSON format.
This one is better.
public static String convertStandardJSONString(String data_json) {
data_json = data_json.replaceAll("\\\\r\\\\n", "");
data_json = data_json.replace("\"{", "{");
data_json = data_json.replace("}\",", "},");
data_json = data_json.replace("}\"", "}");
return data_json;
}
I use jsoneditoronline online tool that works pretty good.
this works for me
public static String convertJSONString(String data) {
data = data.replace("\\", "");
return data; }