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.
Related
I'm working on one application in which I want to fill the registration form and pass this data to API.I tried almost all solutions but not solved this issue.
I'm getting this type of data after filling the form
[
{Date of Birth of the Baby: 08/01/1997},
{Gender of the baby: male},
{Time of Birth of the Baby: 12.00 pm},
{Father's Name: Nnn},
{Mother's Name: Hbhh},
{Any Extra Details?: Bnn}
]
and I want this type of data
{
"Date of Birth of the Baby": "08/01/1997",
"Gender of the baby": "male",
"Time of Birth of the Baby": "12.00 pm",
"Father's Name": "Nnn",
"Mother's Name": "Hbhh",
"Any Extra Details?": "Bnn"
}
var fieldsData = [];
final myControllers = [];
mydynamicData() {
for (var i = 0; i <= widget.fieldData.length; i++) {
fieldsData.add({
widget.fieldData[i]['question'],
myControllers[i].text != null || myControllers[i].text != ""
? myControllers[i].text
: ""
});
}
print("fieldsData:${fieldsData}");
}
This is my method i know this issue occurred due to for loop but without for loop I'm not getting all fields data. so please help.
Import:
import 'dart:convert';
then you can use:
json.encode(fieldsData);
As you have a list of objects, it may be necessary to make a for in the list calling json.encode for each item, then encoding the result.
Server response returning three JSON arrays and all the objects are stored in database one by one and optionsGroupList, attributes, assignedattributes.
In the Project I have three tables are named as a group, attribute, and assignedattribute. firstly I have to insert all the elements of optionsGroupList in group table and I'm able to do so, In the second array I'm getting groupid, attributeid, attributename but in the second table I have 4 columns which have
groupid, attributeid,attributename,groupname, but for the groupname I have to get the record of a particular group by group id from group table but my second loop executes first so I'm not able to get the group record because of the loop still inserting records that time my second loop has started before completing first, my second table depends on the first and my third table depends on the second so I need to insert record after one is finished. Sometimes it works correctly
{
"result": 1,
"data": "optionsList",
"merchantid": "MER-07156",
"optionsGroupList": [{
"grouprowid": "3012",
"groupname": "Color",
"isrequired": "0"
}],
"attributes": [{
"attributerowid": "20794",
"grouprowid": "3012",
"attributename": "Red",
"weight": "0"
}],
"assignedattributes": [{
"attributegrouprowid": "154577",
"productrowid": "342702",
"attributerowid": "20794",
"subsku": "",
"quantity": "0",
"pricechange": "4"
},
{
"attributegrouprowid": "154590",
"productrowid": "354723467",
"attributerowid": "20794",
"subsku": "0",
"quantity": "0",
"pricechange": "0"
}
]
}
My Second loop debug statement printing before first.
optionListService().then((onValue) async {
if (onValue.result == 1) {
//Loop 1
for(int i=0;i<onValue.optionsGroupList.length;i++){
_insertOption(onValue.optionsGroupList[i]);
}
//Loop 2
for(int j=0;j<onValue.attributes.length;j++){
debugPrint('Attribute Name:--${ onValue.attributes[j].attributename}');// this is printed first before first loop excuted
List groupIdList=new List<Map<String,dynamic>>();
groupIdList= await dbHelper.queryReadOption(onValue.attributes[j].grouprowid); // here i'm finding group name from group table but i think is executing first.
if(groupIdList.length>0){
_insertOptionAttribute(onValue.attributes[j],groupIdList[0][DatabaseHelper.columnGroupName],groupIdList[0][DatabaseHelper.columnIsRequired]);
}
}
//Loop 3
for(int i=0;i<onValue.assignedattributes.length;i++){
String attr=onValue.assignedattributes[i].attributerowid;
arrtIdList=new List<Map<String,dynamic>>();
arrtIdList= await dbHelper.queryReadAttribute(attr);
if(arrtIdList.length>0){
_insertProductWithAttribute(
onValue.assignedattributes[i],
arrtIdList[0][DatabaseHelper.columnGroupId],
arrtIdList[0][DatabaseHelper.columnGroupName],
arrtIdList[0][DatabaseHelper.columnAttributeName],
arrtIdList[0][DatabaseHelper.columnIsRequired],
arrtIdList[0][DatabaseHelper.columnWeight]
);
}
}}});}
just add second loop in chained "then" block and in first block return "onValue" varibale. like so:
optionListService().then((onValue) async {
if (onValue.result == 1) {
//Loop 1
for(int i=0;i<onValue.optionsGroupList.length;i++){
_insertOption(onValue.optionsGroupList[i]);
}
}
return onValue;
}).then((onValue) {
if (onValue.result == 1) {
//Loop 2
for(int j=0;j<onValue.attributes.length;j++){
// some code
}
}
});
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",
.....
}
]
}
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) {
}
}