Fetch value from JSON in android - android

I am sending request to the server and it gives me a response and giving data in JSON formats, now i want to fetch some specific value from that JSON format, so hot to do it.
{
"education": [
{
"school": {
"id": "2009305",
"name": "FG boys public high school Bannu Cantt "
},
"type": "High School"
},
{
"school": {
"id": "109989",
"name": "University of Engineering & Technology"
},
"type": "College"
}
],
"id": "xxxxxxx"
}
Now i need the school names from this xml,

Try this..
You response is in Json format not xml.
JSONObject json = new JSONObject(response);
JSONArray education = json.getJSONArray("education");
for(int i = 0; i < education.length(); i++){
JSONObject con_json = education.getJSONObject(i);
String school_type = con_json.getString("type");
JSONObject school_json = con_json.getJSONObject("school");
String school_name = school_json.getString("name");
}

It is not XML. it is completely in Json Standard format.
first build a JSONobject from your data:
JSONObject jsonObj = new JSONObject(result); //result = your Data String in fetched from server
then you cab retrieve what you want using its key. for example:
jsonObj.getString("id"); // it returns "xxxxxxx". as is in your data

Related

How to retrieve a multidimensional array using json object?

I created an app that stream video from server, on server side (PHP) I use this code to pass the MySQL query result via JSON array contain a result of video title size and views.
$query="select * from video_tble ;";
$result=mysqli_query($con,$query);
$row=mysqli_fetch_all($result,MYSQLI_ASSOC);
$respones_result=array();
$response_result=$row;
echo json_encode(array("server_response_result"=>$response_result));
But I don't know how to retrieve a multidimensional array using JSON object.
JSONObject jsonObject1=new JSONObject(json);
JSONArray jsonArray1=jsonObject1.getJSONArray("server_response_result");
JSONObject JO1=jsonArray1.getJSONObject(0);
String [] title =...?
If it was a name value pair then I follow this strategy:
String title1=JO1.getString("title");
But I don't know what to do on multidimensional array.
Hi you need a for loop like this
for(int i;i<jsonArray1.size();i++){
JSONObject JO1=jsonArray1.getJSONObject(i);
String title1=JO1.getString("title");
}
To parse this json
{
"server_response_result": [{
"videoid": "1",
"videotitle": "Metr‌​o Shoes",
"userid": "7",
"category": "Fashion",
"dou": "0000-00-00",
"rate": "3",
"vstatus": "A",
"vcount": "321",
"location": "adstreamer\\uploads\\ramesh#gmail.com\\1.mp4"
}, {
"videoid": "2",
"videotitle": "Lijn the bus",
"userid": "7",
"category": "App",
"dou": "0000-00-00",
"rate": "4",
"vstatus": "A",
"vcount": "145",
"location": "adstreamer\\uploads\\ramesh#gmail.com\\2.mp4"
}]
}
You have to do following steps (saying you have the server response in jsonObject.
ArrayList<SomeModel> modelList = new ArrayList<>();
JSONArray serverResponseResult = jsonObject.getJsonArray("server_response_result");
for (int i = 0; i < serverResponseResult.length(); i++) {
JSONObject result = serverResponseResult.get(i);
String videoId = result.getString("videoid");
String videoTitle = result.getString("videotitle");
...
// instead of using String, set the values in the model class
modelList.add(/* model */);
}

Retrieve Array value from JSOn to android client Array

i am doing now retrieving JSON array and assigning it to Android Array String but it failed.
My integer "success" already well. Please help, thank you very much.
My JSON information:
{
"details": [
{
"phone": "89898999",
"name": "Maria"
},
{
"phone": "98983555",
"name": "John"
},
{
"phone": "96969677",
"name": "Leo"
},
{
"phone": "97320099",
"name": "Helen"
},
{
"phone": "90063379",
"name": "Judy"
}
],
"success": 1
}
Android code:
String[] titleArray2;
String[] descriptionArray2;
int cs = 0;
.....
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
cs = jsonObject.getInt("success")
JSONArray ja = jsonObject.getJSONArray("details");
for (int i = 0; i < ja.length(); i++)
{
JSONObject jo = (JSONObject) ja.get(i);
titleArray2[i] = jo.getString("phone");
descriptionArray2[i] = jo.getString("name");
}
Your code looks fine, Just try initializing your array
Try like this
JSONArray ja = jsonObject.getJSONArray("details");
titleArray2 =new String[ja.size];
descriptionArray2[i]=new String[ja.size];
and then your for loop.
Mark as right if it works for you. :)

Getting value of inner object of json

I am a beginner in android coding. I am working on an app which gets data from php web service in JSON format, but I am not able to correctly parse it.
JSON returned looks like this:
{
"posts": [
{
"post": {
"Id": "1",
"Title": "Captain America",
"Lang": "ENG"
}
}
]
}
Android code:
JSONObject job = new JSONObject(json);//json is the string returned by web service
jObj = job.getJSONArray("posts");
JSONObject c = jObj.getJSONObject(0);
String title = c.getString("Title");
But I get a JSON exception:No value for Title
I cant figure out whats going wrong.
You have
{ //JSONObject job = new JSONObject(json); ok
"posts": [ // jObj = job.getJSONArray("posts"); ok
{ // JSONObject c = jObj.getJSONObject(0) ok
"post": { // forgot about jsonobject post // missed JSONObject post = c.getJSONObject("post")
"Id": "1",
"Title": "Captain America",
Change to
JSONObject c = jObj.getJSONObject(0);
JSONObject post = c.getJSONObject("post");
String title = post.getString("Title");
JSONObject job = new JSONObject(json);//json is the string returned by web service
JSONArray jar=job.getJSONArray("posts");
for (int i=0;i<jar.length();i++)
{
job=jar.getJSONObject(i);
job=jat.getJSONObject("post");
title=job.optString("Title");
}
You forget to get "post" value

Recieving json array and saving in variables. Android

So I am receiving a JSON array in an httpresponse. The array consists of the following objects/variables.
{"sessid":"vxkEXkMBUmBByESRlvaxrxSaFTfhDqd8","session_name":"SESS88cdfb2f1c420898","user":{"uid":"60","name":"abc","theme":"","signature":"","signature_format":"filtered_html","created":"13082976","access":"1386287","login":1386211,"status":"1","timezone":null,"language":"","picture":null,"data":{"mimemail_textonly":0},"roles":{"2":"authenticated user","5":"centre user"},"field_centre_reference":{"und":[{"nid":"256"}]},"field_first_name":{"und":[{"value":"web","format":null,"safe_value":"web"}]},"field_surname":{"und":[{"value":"services","format":null,"safe_value":"services"}]},"bounce_mail_blocked":false,"force_password_change":"0"}}
Now I want to receive all these objects/strings in separate variables. Like i want to store the "sessid" in a variable String session_id. And so on. I can get the first two (i.e. sessid and session_name) in a simple way with the help of the following code.
response = client.execute(httppost);
BasicResponseHandler handler = new BasicResponseHandler();
String data = handler.handleResponse(response);
jObj = new JSONObject(data);
sessid = jObj.getString("sessid");
Log.d("sessid obj", sessid);
session_name = jObj.getString("session_name");
Log.d("session_name", session_name);
But since I am a noob at Android, I don't know how to get the rest of the data to be saved in variables. The upcoming data cannot be saved in a simple way.
Try with this:
JSONObject j_user = jObj.getJSONObject("user");
String uid = j_user.getString("uid");
...
//And so on with the rest of the fields
{ // json object node
"sessid": "vxkEXkMBUmBByESRlvaxrxSaFTfhDqd8",
"session_name": "SESS88cdfb2f1c420898",
"user": { // json object user
"uid": "60", // string
"name": "abc",
"theme": "",
"signature": "",
"signature_format": "filtered_html",
"created": "13082976",
"access": "1386287",
"login": 1386211,
"status": "1",
"timezone": null,
"language": "",
"picture": null,
"data": { // json object data
"mimemail_textonly": 0 //string
},
....// rest of the json
{ represents json object node
[ represents json array node
To parse
JSONObject jObj = new JSONObject(load());
String sessid = jObj.getString("sessid");
Log.d("sessid obj", sessid);
JSONObject user = jObj.getJSONObject("user");
String uid = user.getString("uid");
Log.d("sessid obj", uid);
To parse data
"data": {
"mimemail_textonly": 0
},
JSONObject data= user.getJSONObject("data");
Log.i(".......",""+data.getString("mimemail_textonly"));
To parser field_centre_reference
"field_centre_reference": { // json object field_centre_reference
"und": [ // json array und
{ // json object node
"nid": "256" //string
}
]
},
JSONObject field= user.getJSONObject("field_centre_reference");
JSONArray jr = field.getJSONArray("und");
JSONObject jb1 = (JSONObject) jr.get(0);
Log.i(".......",""+jb1.getString("nid"));
Check out JacksonParser library, it provides annotations which make your work so easy. And it is one of fastest parsing libraries... You can have it here
Edit:
As an example you can take a look at one of my previous question JacksonParser databind and core cause "Found duplicate file for APK"?
You should notice that the JSON you received is a nested JSON. It is like a Map that one of the value of Map is also a Map.
In your case, there is a JSONObject contains sessid and session_name while is only string, but the "user" is also a JSONObject, so you can parse it level by level.
For more details, you can read http://www.vogella.com/articles/AndroidJSON/article.html
Try this..
Getting
"user": {
"uid": "60",
JSONObject obj_user = jObj.getJSONObject("user");
String uid = obj_user.getString("uid");
"user": {
"uid": "60",
"data": {
"mimemail_textonly": 0
}
JSONObject obj_data = jObj.getJSONObject("data");
String mimemail_textonly = obj_user.getString("mimemail_textonly");
JSONObject obj_roles = jObj.getJSONObject("roles");
String two = obj_roles.getString("2");
"field_centre_reference": {
"und": [
{
"nid": "256"
JSONObject obj_field_centre_reference = jObj.getJSONObject("field_centre_reference");
JSONArray ary_und = obj_field_centre_reference.getJSONArray("und");
JSONObject objve = ary_und.getJSONObject(0);
String nid= objve.getString("nid");

Parsing JSON object in android

I have JSON object as follows:
[
{
"Project": {
"id": "1",
"project_name": "name"
},
"AllocationDetail": [
{
"id": "1",
"project_id": "1",
"team_name": "ror",
"week_percentage_work": "50",
"in_today": "1",
"actual_hours": "30",
"remaining_hours": "100",
"time_difference": null,
"created": "2012-01-13 15:48:33",
"modified": "2012-01-13 15:48:33"
},
{
"id": "2",
"project_id": "1",
"team_name": "php",
"week_percentage_work": "40",
"in_today": "2",
"actual_hours": "50",
"remaining_hours": "100",
"time_difference": null,
"created": "2012-01-13 15:49:40",
"modified": "2012-01-13 15:49:40"
}
]
}
]
I want to parse data in android and store it into DB, but i m getting confused in Jsonobject
thanks
the best JSON Tutorial i have seen, I leared json parsing from this tutorial, hope it will help
The following is a snippet code for parsing your json string. Kindly go through it:
String response = <Your JSON String>;
String Project = null;
String AllocationDetail = null;
try {
JSONArray menuObject = new JSONArray(response);
for (int i = 0; i< menuObject.length(); i++) {
Project = menuObject.getJSONObject(i).getString("Project").toString();
System.out.println("Project="+Project);
AllocationDetail = menuObject.getJSONObject(i).getString("AllocationDetail").toString();
System.out.println("AllocationDetail="+AllocationDetail);
}
JSONObject jsonObject = new JSONObject(Project);
String id = jsonObject.getString("id");
System.out.println("id="+id);
String project_name = jsonObject.getString("project_name");
System.out.println("project_name="+project_name);
JSONArray jArray = new JSONArray(AllocationDetail);
for (int i = 0; i< jArray.length(); i++) {
String team_name = jArray.getJSONObject(i).getString("team_name").toString();
System.out.println("team_name="+team_name);
String week_percentage_work = jArray.getJSONObject(i).getString("week_percentage_work").toString();
System.out.println("week_percentage_work="+week_percentage_work);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
There are two ways for parsing JSON
Google GSON
JSON
When your content of JSON is too complex and long enough you can prefer usin GSON its much easier to maintain than JSON parsing each value manually.
Use jsonlint.com to read your json better. It appears that the json that you have copied here is invalid.
String response = <Your JSON String>; // add your Json String here
response = response.replace("[","").replace("]",""); // Just remove all square braces
JSONObject json = new JSONObject(response); //Convert the Json into Json Object
JSONObject jProject = json.getJSONObject("Project"); // get your project object
String project_id = jProject.getString("id"); // Get the value of Id
String project_name = jProject.getString("project_name"); // get the value of Project_name
The above code can be use many times as you want to parse the Json.
I know its too late, but It may help many people who are trying to find the same answer.
I was trying to find the same solution, but it was too hard to use the Accepted answer because of too many lines of codes, But I got the same results with hardly few lines of codes.

Categories

Resources