I have data on this string, but I'm having trouble to access the individual data.
This is my code:
Log.d("Detail Outputss", "" + response.toString());
And this is the string output:
{"futsal_id":"45","info":[{"futsal_id":"45","futsal_name":"Kathmandu Futsal","city":"Kathmandu","address":"Kathmandu","owner_name":"Hari Prasad","owner_address":"Kathmandu","email":"kathmandufutsal#gmail.com","password":"kathmandu","phone_no":"1111111","mobile_no":"9841112233","status":"1"}],"description":[{"futsal_id":"45","futsal_desc":"Futsal is the fever which never ends.\r\nKathmandu futsal is - a platform, a medium of communication for our fraternity. Not just somewhere to host challenges or seek venues, but a place where we can all share and spread the luv! Here, you can find just about anything, do just about anything, and see just about anything. Unbelievable? Believe it."}],"features":[{"futsal_id":"45","futsal_feat":"Free Wifi"},{"futsal_id":"45","futsal_feat":"High Quality Grass"},{"futsal_id":"45","futsal_feat":"Canteen Facility"},{"futsal_id":"45","futsal_feat":"Friendly Environment"}],"dimension":[{"futsal_id":"45","dimension":"40m X 20m"}],"no_of_futsal":[{"futsal_id":"45","number":"1"}],"opening_hrs":[{"futsal_id":"45","open_time_id":"1","open_time":"6am","close_time_id":"15","close_time":"9pm"}],"price_weekdays_price1":[{"futsal_id":"45","price_id":"1","start_time":"6am","end_time":"12pm","price":"1200"}],"price_weekdays_price2":[{"futsal_id":"45","price_id":"2","start_time":"12pm","end_time":"6pm","price":"1000"}],"price_weekdays_price3":[{"futsal_id":"45","price_id":"3","start_time":"6pm","end_time":"9pm","price":"1500"}],"price_weekend_price1":[{"futsal_id":"45","price_id":"1","start_time":"6pm","end_time":"12pm","price":"1500"}],"price_weekend_price2":[{"futsal_id":"45","price_id":"2","start_time":"12pm","end_time":"6pm","price":"1800"}],"price_weekend_price3":[{"futsal_id":"45","price_id":"3","start_time":"6pm","end_time":"9pm","price":"2000"}],"phone_number_address":[{"futsal_id":"45","futsal_name":"Kathmandu Futsal","city":"Kathmandu","address":"Kathmandu","owner_name":"Hari Prasad","owner_address":"Kathmandu","email":"kathmandufutsal#gmail.com","password":"kathmandu","phone_no":"1111111","mobile_no":"9841112233","status":"1"}],"news":[{"futsal_id":"45","news_id":"7","news_title":"asdfasdfasdfasdf","news_description":"asdfashdflahsdlfasdjf;oajsd;ofjaosdijfoaisdjofajsdfja;sjdf;ajsd;fja;ksdjf;kasjd;fkja;sdjf;asjd;fajsd;fjasdjf;asjd;fjas;djf;asdf"},{"futsal_id":"45","news_id":"6","news_title":"awefasdf","news_description":"sdjf;asdf;a;sdf;asjdf;oajsd;fja;sdjf;oajsd;oifjaosdf"},{"futsal_id":"45","news_id":"5","news_title":"asdfasdf","news_description":"sadfasdfasdfasdfa"}]}
I want to get the value of each object futsal_id, futsal_name, city and others, thanks in advance!!
It is JSONArray within a JSONObject
JSONObject json = new JSONObject(response);
JSONArray info = json.getJSONArray("info");
//getting the first value.. loop it if you have more than one
JSONObject infoObject = info.getJSONObject(0);
JSONArray description = json.getJSONArray("description");
JSONObject json = new JSONObject(response);
int fustal_id =Integer.parseInt(json.getString("futsal_id"));
JSONArray inf = json.getJSONArray("info");
JSONObject info = inf.getJSONObject(0);
...
JSONObject responseObject = new JSONObject(response);
JSONArray info = responseObject.getJSONArray("info");
for(int i = 0; i < info.length(); i++) {
JSONObject obj = info.getJSONObject(i);
String futsal_id = obj.getString("futsal_id");
String futsal_name = obj.getString("futsal_name");
//so on
}
Be sure to catch the exceptions.
Related
I'm a android beginner and I'm doing to access a JSON file in and it has an error. I have a problem in parsing this
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray accounts = jsonObject.getJSONArray("account_data");
for(int i=0;i < accounts.length();i++){
JSONObject a = accounts.getJSONObject(i);
sin = a.getString("sin");
account_name = a.getString("account_name");
address = a.getString("address");
status = a.getString("status");
due_date = a.getString("due_date");
total_amount = a.getDouble("total_amount");
sin_lbl.setText(a.getString("account_name"));
}
here is the JSON File
{"account_data":{
"sin":"200111-102 ",
"account_name":"LUMABAN, CRISTOM ",
"address":"352 MABINI ST.,, SABANG, Baliwag ",
"status":"A ",
"due_date":"2019-04-23",
"total_amount":"491.00"
},"code":1101,"message":"Account Info Retrieved"}
I have an error in putting it in array.
Instead of using JSONArray , try to use JSONObject.
String[] array = {json.get("sin"), json.get("account_name"), json.get("address"), json.get("status"), json.get("due_date"), json.get("total_amount") }
{"account_data":{"sin":"200111-102 ","account_name":"LUMABAN, CRISTOM ","address":"352 MABINI ST.,, SABANG, Baliwag ","status":"A ","due_date":"2019-04-23","total_amount":"491.00"},"code":1101,"message":"Account Info Retrieved"}
Actually, it's a json object, not array. So that you can not convert json object to json array
Difference between Json Array and Json Object:
A JSONArray is an ordered sequence of values. A JSONObject is an unordered collection of name/value pairs.
JSONArray: Its external text form is a string wrapped in square brackets with commas separating the values.
JSONObject: Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.
Please use this json parshing
try {
JSONObject jsonObject = new JSONObject(jsonStr);
JSONObject accounts = jsonObject.getJSONObject("account_data");
sin = accounts.getString("sin");
account_name = accounts.getString("account_name");
address = accounts.getString("address");
status = accounts.getString("status");
due_date = accounts.getString("due_date");
total_amount = accounts.getDouble("total_amount");
sin_lbl.setText(a.getString("account_name"));
} catch (Exception e) {
}
if you asked about iterating on json object you could try this one
JSONObject jObject = new JSONObject(jsonStr);
JSONObject menu = jObject.getJSONObject("account_data");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
so now you have your data into as pair of key and value
if you have a json array of this response you could do as following
JSONObject root = new JSONObject("your root");
JSONArray resultArray = root.getJSONArray("your array key");
for (int i = 0; i < resultArray.length(); i++) {
// here to get json object one by one and access every item into it
JSONObject resultObject = resultArray.getJSONObject(i);
posterPath = resultObject.getString("key");
title = resultObject.getString("key");
releaseDate = resultObject.getString("key");
description = resultObject.getString("key");
voteAverage = resultObject.getDouble("key");
}
I am trying to list the JSON array and display in the TextViews, but somehow it shows only last element of the JSON array, please suggest the solution, here is my code.
JSONObject jObj = new JSONObject(response);
JSONObject jsonData = jObj.getJSONObject("data");
JSONArray jsonarr = jsonData.getJSONArray("order_status_list");
for (int i1 = 0; i1 < jsonarr.length(); i1++) {
JSONObject c1 = jsonarr.getJSONObject(i1);
txt_order_datetime.setText(c1.optString("status_datetime"));
txt_order_status.setText(c1.optString("order_status_value"));
txt_order_updatedby.setText(c1.optString("status_updated_by_user"));
}
Thanks
As suggested by #sector11, you can use
txt_order_datetime.append(c1.optString("status_datetime"));
Here is the
string one =[{"ID":5,"Name":"Sai"}]
how i get only id and name from this string
Matcher matcher = Pattern.compile("\\[([^\\]]+)").matcher(one);
List<String> tags = new ArrayList<String>();
int pos = -1;
while (matcher.find(pos+1)){
pos = matcher.start();
tags.add(matcher.group(1));
}
System.out.println("getting data"+tags);
i tried this but it didn't work
List<String> ls = new ArrayList<String>(one);
JSONArray array = new JSONArray();
for(int i = 0; i< array.length(); i++){
JSONObject obj = array.getJSONObject(i);
ls.add(obj.getString("Name"));
}
It's JSON format and it can very easily be read in Android. Here is the sample code:
JSONArray array = new JSONArray(one);
int length = array.length();
for(int i=0;i< length; i++)
{
JSONObject temp = array.getJSONObject(i);
System.out.println(temp.getString("ID"));
System.out.println(temp.getString("Name"));
}
This format of data is called JSON.
Have a look at Go to http://json.org/, scroll to (almost) the end, click on one of the many Java libraries listed.
First of all, your string initialization is wrong.
Wrong:
string one =[{"ID":5,"Name":"Sai"}]
Correct:
String one ="[{\"ID\":5,\"Name\":\"Sai\"}]";
Second, its a JSON formatted data so you can parse it using JSONArray and JSONObject classes, instead of creating any pattern.
Now, in your case its JSONObject inside JSONArray so initially create an object of JSONArray using your string.
For example:
JSONArray arrayJSON = new JSONArray(one); // 'one' is your JSON String
for(int i=0; i<arrayJSON.length(); i++) {
JSONObject objJson = arrayJSON.getJSONObject(i);
String ID = objJson.getString("ID");
.....
.....
// same way you can fetch/parse any string/value from JSONObject/JSONArray
}
it is a json formate Date
use JsonObject class to parse this data
tutorial this
JSONArray jsonArray = new JSONArray("[{\"ID\":5,\"Name\":\"Sai\"}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.println(object.getString("ID"));
System.out.println(object.getString("Name"));
}
i use www.openweathermap.org FORECAST.
thisi the result of forecat: http://api.openweathermap.org/data/2.5/forecast?lat=35&lon=139
JSONObject coordObj = getObject("coord", jObj);
Latitude=getFloat("lat", coordObj);
Longitude=getFloat("lon", coordObj);
JSONObject coordObj = getObject("city", jObj);
id=getFloat("id", coordObj);
name=getFString("name", coordObj);
JSONObject sysObj = getObject("sys", jObj);
Country=getString("country", sysObj);
Sunrise=getInt("sunrise", sysObj));
Sunset=getInt("sunset", sysObj));
JSONObject jlist = jObj.getObject("list");
JSONObject JSONWeather = jArr.getJSONObject(0);
Condition_id==getInt("id", JSONWeather);
condition_description=getString("description", JSONWeather);
condition=getString("main", JSONWeather);
condition_icongetString("icon", JSONWeather);
JSONObject mainObj = getObject("main", jObj);
Humidity=getInt("humidity", mainObj);
Pressure=getInt("pressure", mainObj);
MaxTemp=getFloat("temp_max", mainObj);
MinTemp(getFloat("temp_min", mainObj);
Temp=getFloat("temp", mainObj);
// Wind
JSONObject wObj = getObject("wind", jObj;
Speed=getFloat("speed", wObj);
Deg=getFloat("deg", wObj);
// Clouds
JSONObject cObj = getObject("clouds", jObj);
Perc=getInt("all", cObj);
please how to loop the weather array ?
First, list is not a JsonObject it's an array, so you should get it doing:
JSONArray jlist = (JSONArray) jObj.get("list");
Depending of which library you are using the syntax can change but the logic is the same, I'm explaining using json simple lib.
after that you should iterate your list array, something like this:
for (int i = 0; i < jlist.size(); i++){
// get all your objects and your weather array
// to get your weather array the logic is the same:
JSONArray jArrayWeather = (JSONArray) jObj.get("weather");
for (int j = 0; j < jArrayWeather ; j++){
//and here you can get your id, main, description and icon using j index
JSONObject currentObj = (JSONObject) jArrayWeather.get(j);
String main = (String) currentObj.get("main");
}
}
I didn't test this code, so follow the idea and try to do it yourself. Take a look here as we can see you haven't experience with json
Here is another example. (For a different JSON format though).
try{
JSONArray list=json.getJSONArray("list");
for(int indx=0;indx<MAX_FORCAST_FRAGMENT;indx++) {
JSONArray weather = list.getJSONObject(indx).getJSONArray("weather");
String weatherIconString=setWeatherIcon(weather.getJSONObject(0).getInt("id"),
0,100);
forcastData[indx][0]=weatherIconString;
JSONObject main=list.getJSONObject(indx).getJSONObject("main");
JSONObject wind=list.getJSONObject(indx).getJSONObject("wind");
String detailsFieldString= weather.getJSONObject(0).getString("description").toUpperCase(Locale.US);
String humidityFieldString="Humidity: " + main.getString("humidity") + "%";
String windFieldString= "Wind: " + wind.getString("speed") + " Km/H";
// populate the list view//
int forecastFragmentId=getResources().getIdentifier("forcast_layout_" + (indx+1), "id", getPackageName());
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.details_field);
tv.setText(detailsFieldString);
saveData(F_DETAILS+indx,detailsFieldString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.weather_icon);
tv.setText(weatherIconString);
saveData(F_ICON+indx,weatherIconString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.wind_field);
tv.setText(windFieldString);
saveData(F_WIND+indx,windFieldString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.humidity_field);
tv.setText(humidityFieldString);
saveData(F_HUMIDITY+indx,humidityFieldString);
c = Calendar.getInstance();
int currentDate=c.get(Calendar.DAY_OF_MONTH);
saveTime(LAST_FORCAST_TIME,currentDate);
}
}catch(Exception e){
Log.e("SimpleWeather", "One or more fields not found in the JSON data in renderForecastData");
}
}
I'm trying to take the following string that I got as a json object:
[
{
"id": "picture1",
"caption": "sample caption",
"picname": "sample picture name"
}
]
and turn it into a array so I can populate a list
I've tried turning it into a jsonarray by doing this:
JSONArray myjsonarray = myjson.toJSONArray(string_containing_json_above);
but that didn't seem to work.
==============
Here is full code with the working solution
myjson = new JSONObject(temp);
String String_that_should_be_array = myjson.getString("piclist");
JSONArray myjsonarray = new JSONArray(String_that_should_be_array);
For(int i = 0; i < myjsonarray.length(); i++){
JSONObject tempJSONobj = myjsonarray.getJSONObject(i);
showToast(tempJSONobj.get("caption").toString());
}
temp is the json from the server
Issue is here:
JSONArray myjsonarray = myjson.toJSONArray(temparray);
Solution:
JSONArray myjsonarray = new JSONArray(myJSON);
// myJSON is String
Now here you are having JSONArray, iterate over it and prepare ArrayList of whatever types of you want.
here you get JSONArray so change
JSONArray myjsonarray = myjson.toJSONArray(temparray);
line as shown below
JSONArray jsonArray = new JSONArray(readlocationFeed);
and after
JSONArray jsonArray = new JSONArray(readlocationFeed);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
explrObject.getString("caption");
}
JSONArray isn't working because the JSON you provided is not an array. You can read more about JSON syntax here: http://www.w3schools.com/json/json_syntax.asp
In the meantime, you could manually create your array by paring the JSON one string at a time.
JSONObject strings = new JSONObject(jsonString);
String array[] = new String[5];
if (jsonString.has("id"){
array[0] = jsonString.getString("id");
}
if (jsonString.has("caption"){
array[1] = jsonString.getString("caption");
}
...
etc.