Json Parsing in android issue - android

I am developiing a android application for the blind and i used the Karios api and everything has worked out great
And i get the output of the api as
{
"images": [
{
"time": 0.86679,
"status": "Complete",
"file": "face_57078c26c5baf.jpg",
"width": 776,
"height": 570,
"faces": [
{
"topLeftX": 94,
"topLeftY": 95,
"width": 189,
"height": 189,
"leftEyeCenterX": 152.275,
"leftEyeCenterY": 172.175,
"rightEyeCenterX": 225.5125,
"rightEyeCenterY": 168.2375,
"noseTipX": 188.83536147895,
"noseTipY": 209.93069059821,
"noseBtwEyesX": 188.69509888285,
"noseBtwEyesY": 163.76829692552,
"chinTipX": 194.90835566598,
"chinTipY": 272.94500076858,
"leftEyeCornerLeftX": 139.748828125,
"leftEyeCornerLeftY": 173.99609375,
"leftEyeCornerRightX": 167.2744140625,
"leftEyeCornerRightY": 173.6638671875,
"rightEyeCornerLeftX": 210.7591796875,
"rightEyeCornerLeftY": 171.3259765625,
"rightEyeCornerRightX": 236.955859375,
"rightEyeCornerRightY": 167.622265625,
"rightEarTragusX": -1,
"rightEarTragusY": -1,
"leftEarTragusX": -1,
"leftEarTragusY": -1,
"leftEyeBrowLeftX": 124.96433022747,
"leftEyeBrowLeftY": 160.66254675843,
"leftEyeBrowMiddleX": 144.98960402463,
"leftEyeBrowMiddleY": 151.01911416052,
"leftEyeBrowRightX": 171.91583787312,
"leftEyeBrowRightY": 155.84335467715,
"rightEyeBrowLeftX": 204.04144319738,
"rightEyeBrowLeftY": 153.33575045711,
"rightEyeBrowMiddleX": 228.74564647717,
"rightEyeBrowMiddleY": 144.48143172972,
"rightEyeBrowRightX": 247.64047899459,
"rightEyeBrowRightY": 149.93257330135,
"nostrilLeftHoleBottomX": 179.40484698779,
"nostrilLeftHoleBottomY": 222.21013668835,
"nostrilRightHoleBottomX": 200.05702183911,
"nostrilRightHoleBottomY": 220.59810540404,
"nostrilLeftSideX": 168.63097309489,
"nostrilLeftSideY": 217.27943710651,
"nostrilRightSideX": 211.08266584481,
"nostrilRightSideY": 213.96581724432,
"lipCornerLeftX": 164.95407560776,
"lipCornerLeftY": 244.11611360475,
"lipLineMiddleX": 192.40075144939,
"lipLineMiddleY": 240.81939551421,
"lipCornerRightX": 219.84742729102,
"lipCornerRightY": 237.52267742366,
"pitch": -1.1481443688526,
"yaw": 0.95481944449499,
"roll": -3.7557902314114,
"attributes": {
"gender": {
"time": 0.06871,
"type": "F",
"confidence": "90%"
}
}
}
]
}
]
}
How can I get to the type value of a face in android? Thanks in advance.

It should be something like this...
private String returnPersonType(String output) {
String type = "";
try {
JSONObject jsonObject = new JSONObject(output);
if (jsonObject.has("images")) {
JSONArray imagesArray = jsonObject.getJSONArray("images");
if (imagesArray.length() > 0 && imagesArray.getJSONObject(0).has("faces")) {
JSONArray facesArray = imagesArray.getJSONObject(0).getJSONArray("faces");
if (facesArray.length() > 0 && facesArray.getJSONObject(0).has("attributes") && facesArray.getJSONObject(0).getJSONObject("attributes").has("gender")) {
type = facesArray.getJSONObject(0).getJSONObject("attributes").getJSONObject("gender").getString("type");
}
}
}
} catch (JSONException e) {
}
return type;
}

In above response
faces is a JSONArray with one value
Get JSONArray of faces
Then Get JSONObject from faces JSONArray of 0 index and get values that you need.

First thing to keep in mind while parsing
{- JSONObject function needs to be called
[- JSONArray function needs to be called
here is the solution to your problem if you only want to reach faces[0] object..
{
....
....
JSONObject jsonRootObject=new JSONObject("/*Your son data as string or any string variable containing your son data*/");
JSONArray jsonArray=jsonRootObject.optJSONArray("images");
JSONObject object0=jsonArray.optJSONObject(0);
JSONArray faces=object0.optJSONArray("faces");
JSONObject face0=faces.optJSONObject(0);
//Now you can call any object data by using its key. following code gets height stored int it
String t=face0.optString("height");
...
...
}
... represents your code which you will write as per your need.
Good luck with your programming.

There is one simple Solution to get it easily.
Convert your Json with This link will convert your json to POJO class
you will get some classes as result.
And by following demo code in your onPostExecute() method , you can get Faces Data,
String json = new Gson().toJson(object);
YourMainPOJO newProjectList = new Gson().fromJson(json,
YourMainPOJO.class);
ArrayList<YourImagePOJO> cpImageData = cp.getImages();
ArrayList<YourFacePOJO> cpFaceData = cpImageData. getFaces();
String topLeftY = cpFaceData.getTopLeftY ();
String topLeftX = cpFaceData.getTopLeftX ();
This is the simple way you can get your result easily, without any hassle.

res.images[0].faces[0].attributes.gender.type
Assuming your response is in res

Related

How to extract values from JSONObject in android

1.I am having json object like this how can i get the access to all values in android
2.before anyone down voting that i want to say i have searched stackoverflow for similar examples but those examples contains JSONObject and then JSONArray
3.Here in my case everything is JSONObject so i'm little bit confused
{
"1":
{"sno":"10","latitude":"31.249441437085455","longitude":"75.70003598928452"},
"2":
{"sno":"11","latitude":"31.249398442090207","longitude":"75.70003397762775"}
}
This is how i made it to JSONObject
1.Below code returned me output like that which is all JSONObject
2.Is there any way to make "1" and "2" as JSONArray ?
$select_rows = "select sno,latitude,longitude from activities where username='$username'";
if ($result = mysql_query($select_rows)) {
$num_of_fields = mysql_num_fields($result);
$num_of_rows = mysql_num_rows($result);
$i = 0;
$j = 1;
while ($retrieved = mysql_fetch_array($result)) {
for ($i = 0; $i < $num_of_fields; $i++) {
$field_name = mysql_field_name($result, $i);
$object[$j][$field_name] = $retrieved[$field_name];
}
$j++;
}
echo json_encode($object);
}
Hope this may help you
JSONObject jsonObject=new JSONObject(result);
jsonObject=jsonObject.getJSONObject("1");
Double lat=jsonObject.getDouble("latitude");
Toast.makeText(getBaseContext(),""+ lat, Toast.LENGTH_LONG).show();
Better create a valid JSONArray to make things easier. When you create the JSON string , don't append the index. I believe your are reading the data from sqlite and generating the JSON string.
Also change the outer { (curly brace) to [ (square bracket) to represent as Array element. So your json string will be like this
[
{
"sno": "10",
"latitude": "31.249441437085455",
"longitude": "75.70003598928452"
},
{
"sno": "11",
"latitude": "31.249398442090207",
"longitude": "75.70003397762775"
}
]
Then , you can simply get its as JSONArray
JSONArray jsonArray = new JSONArray(jsonString);
And then read each element in array item
for(int index = 0;index < jsonArray.length(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
}
To get one of your inner JSONObject elements, you'll need to get it from the outer one using getJSONObject(String key).
Sample code:
JSONObject item1 = myJson.getJSONObject("1");
//item1 now contains {sno:10,latitude:31.2...etc}
//now you can get the individual values out of the resulting JSON Object
//for example, getting the latitude
double lat = item1.getDouble("latitude");

Trying to parse a jsonarray within a jsonarray

I am parsing some json in an app and I have come across arrays that sometimes have information in it:
{
"output": [
{
"id": "1521",
"name": "Apples",
}
]
}
and sometimes has nothing. e.g
{
"output": [
[]
]
}
I was parsing it by
JSONArray output = c.getJSONArray("output");
int outputLength = output.length();
for (int q = 0; q < outputLength; q++)
{
JSONObject d = outputs.getJSONObject(q);
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
but when it gets to the empty array it crashes.
I get the following error then:
01-19 01:08:00.237: W/System.err(17627): org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject
it crashes because it's trying to convert the jsonarray into an object and you can't do that so I tried getting the first array in output with:
JSONArray add = output.getJSONArray(0);
but that will crash as well because in the first output it's an object in it and not an array.
I don't have access or control over the json feed and I'm stuck at the moment as to how to parse the result.
The real answer is: "Fix whatever is generating that horrible JSON".
If that's not an option you're going to have to figure out exactly what you have before trying to access it. The JSONArray.optJSONObject() method can help with this; it returns null if the specified index doesn't contain a JSONObject:
JSONArray output = c.getJSONArray("output");
for (int q = 0; q < outputLength; q++)
{
JSONObject d = output.optJSONObject(q);
if (d != null)
{
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
}
Because you're parsing everything in the enclosing JSONArray as aJSONObject, all the entries would have to be formatted that way. For that to work, your source string would have to look like this:
[
{
"output": [
{
"id": "1521",
"name": "Apples"
}
]
},
{
"output": [
[]
]
}
]
Everything in the top-levelJSONArray is now a JSONObject and can be parsed accordingly. What's inside of those objects is your business (empty arrays are OK). A good resource for checking if a given JSON string is valid is this website.

Android - json parsing

I have a JSON as shown below:
{
"places": [{
"name": "Ankola",
"slug": "ankola",
"category": "beach",
"distance": "521",
"travel_time": "8 hrs, 2 mins",
"days": "3",
"latitude": "14.669456",
"longitude": "74.300952",
"weather": "Summer 21\u00b0-36\u00b0C, Winter 12\u00b0-35\u00b0C",
"todo": "Baskal gudda, Nadibag, Shedikuli, Keni, Belekeri",
"about": "Ankola is a small town surrounded by numerous temples. It is in line with Arabian sea. Ankola is famous for its native breed of mango called ishaad and for cashews harvesting.",
"image": [
"Cm5NXlq.jpg",
"9OrlQ9C.jpg",
"DRWZakh.jpg",
"dFKVgXA.jpg",
"5WO2nDf.jpg"
]
}]
}
I know how to fetch key - value pairs, but i dont know how to parse array inside json to form a string array(image - in my case)
To summarize i want something like this:
I have 5 image names under "image" tag, i want them in a string array. How can i do this?
Use :
JSONArray images = yourJSONObject.getJSONArray("image");
for(int i = 0; i < images.length(); i++){
String image = images.getString(i);
}
This should do the trick as I remember.
Here you go:
JSONArray ja = whatEverYourJsonObject.getJSONArray("image");
for(int i=0; i<ja.length(); j++){
String name = ja.getString(i);
}
You first have to convert the JSON string to a Java object (JSONObject). Then, you obtain your JSONArray and iterate over it.
Example:
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject (jsonString);
JSONArray images = itemObj.getJSONArray ("images");
int length = images.length ();
for (int i = 0; i < length; i++)
Log.d ("Image Filename", images.getString (i));
} catch (JSONException e) {
e.printStackTrace();
}
EDIT: Now I see that your JSON is invalid - you have an object for each image and that object contains only the value part of the data. An example of a valid images array would be as follows:
{
"image": [
"Cm5NXlq.jpg",
"9OrlQ9C.jpg",
"DRWZakh.jpg",
"dFKVgXA.jpg",
"5WO2nDf.jpg"
]
}
I would suggest:
Create your own class which describes your data structure defined
by those json object. As a last resort you can even generate Java
class based on JSON string - look at
jsongen
When you will have your own Java class (let's say MyClass) you can easily parse JSON to your generated Java class using GSON, like:
MyClass myClass = gson.fromJson(jsonString, MyClass.class);

JSON array parsing in android

Here is my JSON object and i want to parse it in android project
{
"second": {
"versionInfo": "0.20.3-dev",
"compileDate": "Mon Mar 12 17:39:23 IST 2012",
"compileUser": "suraj",
"trackname": "tracker_localhost:localhost/127.0.0.1:48418"
},
"href": {
"versionInfo": "null",
"compileDate": "null",
"compileUser": "null",
"trackname": "null"
},
"first": {
"key": "['trackname','versionInfo','compileDate','compileUser']"
}
}
How to compile?
i want to first extract attributes of 'first' and using the attributes and then to extract parameters of 'second' using attributes of 'first'.
Basically it is done like that:
JSONObject jobj = new JSONObject(theString);
JSONObject first = jobj.getJSONObject("first");
JSONObject second = jobj.getJSONObject("second");
If you want more, take a look at the documentation of JSON classes for android.
Edit
Regarding the extraction of the array (in first->key):
String jStr = first.getString("key");
JSONArray jArr = new JSONArray(jStr);

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