Here I am posting my Json Response below:
{"ResultSet":
{"Result":[
{"Phone":"(650) 473-9999",
"Distance":"2.59",
"MapUrl":"http://maps.yahoo.com/maps_result?q1=441+Emerson+St+Palo+Alto+CAgid1=28734629",
"Categories":
{"Category":[
{"content":"Salad Restaurants",
"id":"96926225"},
{"content":"Vegetarian Restaurants",
"id":"96926239"},
{"content":"Pizza",
"id":"96926243"},
{"content":"Wine",
"id":"96926864"},
{"content":"Alcoholic Beverages",
"id":"96929810"}]},
"City":"Palo Alto",
"Title":"Patxi's Chicago Pizza",
"State":"CA",
"Rating":
{"LastReviewDate":"1241373758",
"LastReviewIntro":"My husband brought me a slice of their pizza after I had heard glowing reviews from the Sarah and Vinnie morning show on Alice radio (they get theirs from the SF location). Anyway I had been very interested in trying what sounded like very special pizza. My husband and son went during a time when you can buy slices so waiting for the food wasnt an issue. I usually dont like pizza cold but by the time they got it home to me it was very luke warm. NOT A PROBLEM! I was amazed at how yummy it was and was having the hardest time NOT eating it while standing in the kitchen leaning over the pizza-to-go box! Im not sure of what the name of the slice was except that it did have sausage and possibly spinach in it. This was a week ago and Ive been craving it ever since. When we do go back we will either order ahead to save on the wait or go during pizza slice hours. Ive heard they also do NY style for those of you thin crust fans! Check it out!!",
"TotalReviews":"27",
"TotalRatings":"27",
"AverageRating":"4.5"},
"Address":"441 Emerson St",
"Latitude":"37.445242",
"Longitude":"-122.163427"}]}}
Noe I want to have the following data Parsed "Phone", "Distance", "City", "Title", "State" and only "AverageRating" from the Tag "Rating".
Can anybody please help in sorting this particularly.
Thanks,
David
I've written about this subject before here on SO, look at it here:
Json Parsing in Android Application
Posted some code:
String phone = null;
String distance = null;
String city = null;
String title = null;
String state = null;
String aveRat = null;
JSONObject jsonObject = new JSONObject(yourResponse);
JSONArray infoArray = jsonObject.getJSONArray("Result");
JSONArray ratingArray = jsonObject.getJSONArray("Rating");
for (int i = 0; i < infoArray.length(); i++) {
try {
phone = infoArray.getJSONObject(i).optString("Phone");
distance = infoArray.getJSONObject(i).optString("Distance");
city = infoArray.getJSONObject(i).optString("City");
title = infoArray.getJSONObject(i).optString("Title");
state = infoArray.getJSONObject(i).optString("State");
aveRat = ratingArray.getJSONObject(i).optString("AverageRating");
} catch (JSONException e) {
}
}
Related
I work with two Bluetooth beacons and two Philips Hue lights. I have a JSON file which contains the beacon UUID for each region and the light IDs:
{
"features":
[
{
"iot_identifier" : "1",
"iot_beacon_uuid" : "E2C56DB5-DFFB-48D2-B060-D0F5A71096E1"
},
{
"iot_identifier" : "2",
"iot_beacon_uuid" : "E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"
}
]
}
I also have a string in my code which displays the current region UUID. It changes when I enter the other region.
This is my code to control the two lights after reading in the JSON:
List<Feature> listFeatures; //Features from JSON file
int count = listFeatures.size();
for(int i=0; i<count; i++){
// Here I have the UUID (not elegant, but does its work)
String regionString = beaconManager.getMonitoredRegions().toString();
String regionUUID = regionString.substring(6, 43).toUpperCase();
// Here I get the JSON properties for each feature
String iotIdentifierString = listFeatures.get(i).getIotIdentifier();
String iotBeaconUuid = listFeatures.get(i).getIotBeaconUuid();
// need this value as double to associate the JSON-ID with the Hue light ID
double iotIdentifierDouble = Double.parseDouble(iotIdentifierString);
if( /* anything */ ){
// get the light with the ID of the current JSON feature
String lightId = hueLightObjects.getFeatures().get(i).getIotIdentifier();
final PHLight light = bridge.getResourceCache().getLights().get(lightId);
// control the lights, turn on/off
}
}
So the "regionUUID" string changes whenever I switch the region. Currently I am always able to control both lights, no matter in which region I am.
What I am looking for is a way to only control the light that has the current beacon UUID in the JSON file.
Something like:
For regionUUID.equals(iot_beacon_uuid), only control the light with the ID in the feature where regionUUID equals the iot_beacon_uuid.
If I change the region, then I only want to control the other light in the other feature where this statement is true again.
Could someone help me with this?
First of all I believe that your question can be more shorter something like ( A Minimal, Complete, and Verifiable example)
So when I am in the region where the minor ID = 1, I only want to select the lamps, where the property "Minor_ID" is also 1
Your code can achieve that in your case it's depend on how you using it after retrieving process.
But you can do that with current way too:
for (int i=0; i<count; i++) {
if(selectedLamp == iotIdentifierDouble ){
//do what you wish
}
}
Here is my code:
try{
JSONObject jsonObjitem = new JSONObject(jsonString);
JSONArray phrasemaster = jsonObjitem.getJSONArray("phrases");
for(int i = 0; i<phrasemaster.length();i++){
JSONObject scan = phrasemaster.getJSONObject(i);
int id = scan.getInt("id");
if (id == current){
String question = scan.getString("question");
idoutcome1 = scan.getString("idoutcome1");
idoutcome2 = scan.getString("idoutcome2");
idoutcome3 = scan.getString("idoutcome3");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
The user on launch gets random number, when he press the button he is being moved to another fragment where this number is used to pull item from JSON, this number serves as id.
Each item have another three id's. So when I pull my item with this code I also pull 3 id's from that json item. Now what I want is to output the question string from these id's.
{
"phrases": [
{
"id": 1,
"question": "first item",
"idoutcome1": 2,
"idoutcome2": 3,
"idoutcome3": 4
},
{
"id": 2,
"nameofoption": "item 2",
"question": "some question 2",
"idoutcome1": 5,
"idoutcome2": 6,
"idoutcome3": 7
},
{
"id": 3,
"nameofoption": "item 3",
"question": "some question 3",
"idoutcome1": 8,
"idoutcome2": 9,
"idoutcome3": 10
}
]
}
The thing is that I don't understand how I can reach out to these values.
Edit: illustration of what I'm trying to do.
While parsing I take the idoutcome1,2,3 values and output them on my buttons.
However, I want to output the value written in the nameofoption field instead of these numbers. Just like the example, instead of 2 it should show "left".
The problem is that I have this try that searches for id that it got on the previous page and outputs item with corresponding id. How can I implement it within the course of this try that it would go deeper and depending on the idoutcome's of this JSON item display values from the nameofoption field?
I've solved it in a following way, all of the idoutcome's were put in arraylist, then I've reused the same json parsing code to loop through the items with the respective id's and then output them ti the buttons with settext.
That was my first json experience, thanks for the downvotes.
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
i have worked with json name value pair before works fine and great but below is my json object in which there is no name and only value. Can anyone tell is it possible to use this type of json in android if yes then how to extract values from this json object. or any related link will be great.
JSON OBJECT
{
"log_list": [
[
"21",
"doctorFisher",
"Pharmacy 1",
"patientfish",
"test",
"2014-08-25 05:58:18",
"record UCI tech FDNY icky shut rack soon sun TDK tell. ox it'll ohm URL did GCVO dash ugly dog did flood idiot fluff if if rid t-shirts didn't TechTV only chef doc scotch Rebekah an if lb tax scotch am ICN JCB JCB HGV JCB HGV in on pm tax UDC OK red uh HK ohm",
"<img id=\"prescription_image\" onClick=showPrescriptionDetails(\"3c59dc048e8850243be8079a5c74d079\") onmouseover=\"this.style.cursor='pointer'\" src=\"\" width=\"20\" height=\"20\">"
],
[
"20",
"doctortest12345",
"Pharmacy 1",
"testpatient12345",
"test",
"2014-08-25 03:57:32",
"she'd Urdu text scuff uno dad uno each ink why tough days ICO saved USCIS David rig though end FDIC UCI's for USCIS tend did for dog such vidi fly floor exited did DND hand bid GMD.",
"<img id=\"prescription_image\" onClick=showPrescriptionDetails(\"98f13708210194c475687be6106a3b84\") onmouseover=\"this.style.cursor='pointer'\" width=\"20\" height=\"20\">"
]
}
thanks in advance
Yes, that format would work and you can pretty easily use it.
Assuming you have a variable String json which contains that data:
JSONObject jsonObj = new JSONObject(json);
Now log_list would be parsed as a JSONArray like so:
JSONArray logJsonArray = jsonObj.getJSONArray("log_list");
Then you can iterate through that outer array very similar to how you would a normal array or ArrayList:
for(int outerArrayPos = 0; outerArrayPos < logJsonArray.length(); outerArrayPos++){
JSONArray innerArray = logJsonArray.getJSONArray(outerArrayPos);
for(int innerArrayPos = 0; innerArrayPos < innerArray.length(); innerArrayPos++){
String valueAtIndex = innerArray.getString(innerArrayPos); //innerArray
// Do whatever you want with the values here
}
}
That will parse your String, but figuring out how to actually use that data is going to be most of your struggle, so I hope the order in which the information is returned will always be the same for your sake.
If you can, I would definitely recommend using a JSONObject for the data that is currently contained in your inner array. e.g.
{
"log_list": [
{
"id": "21",
"name": "doctorFisher",
.....
}
]
}
I've seen many people do similar to this in order to get the last word of a String:
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
I would like to do similar but get the last few words after the last int, it can't be hard coded as the number could be anything and the amount of words after the last int could also be unlimited. I'm wondering whether there is a simple way to do this as I want to avoid using Patterns and Matchers again due to using them earlier on in this method to receive a similar effect.
Thanks in advance.
I would like to get the last few words after the last int.... as the number could be anything and the amount of words after the last int could also be unlimited.
Here's a possible suggestion. Using Array#split
String str = "This is 1 and 2 and 3 some more words .... foo bar baz";
String[] parts = str.split("\\d+(?!.*\\d)\\s+");
And now parts[1] holds all words after the last number in the string.
some more words .... foo bar baz
What about this one:
String test = "a string with a large number 1312398741 and some words";
String[] parts = test.split();
for (int i = 1; i < parts.length; i++)
{
try
{
Integer.parseInt(parts[i])
}
catch (Exception e)
{
// this part is not a number, so lets go on...
continue;
}
// when parsing succeeds, the number was reached and continue has
// not been called. Everything behind 'i' is what you are looking for
// DO YOUR STUFF with parts[i+1] to parts[parts.length] here
}