This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I can't extract JSONObject from saved preference class by using TestCrowd.java class.
My JSON,
{
"success": true,
"message": {
"user": {
"firstName": "aaa",
"lastName": "aaa",
"email": "xxx#gmail.com",
"role": 1,
"profileUrl": ""
},
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjp7ImZpcnN0TmFtZSI6ImFhYSIsImxhc3ROYW1lIjoiYWFhIiwiZW1haWwiOiJ4eHhAZ21haWwuY29tIiwicm9sZSI6MSwicHJvZmlsZVVybCI6IiJ9LCJpYXQiOjE0ODY2MzU3NjUsImV4cCI6MTQ4NjY0NzIwNX0.rRlqKNMoBs_AaDKOUlToT5-D5QKb20IjYMuUBqK9G7c",
"enum": {
"_id": "5889d3f10893a7a42243998e",
"updatedAt": "2017-01-26T10:48:17.233Z",
"createdAt": "2017-01-26T10:48:17.233Z",
"__v": 0,
"mailCategories": [
{
"color": [
"Work",
"Document",
"Social",
"Advertising",
"Client"
],
"value": [
"#1ab394",
"#EF5352",
"#1c84c6",
"#23c6c8",
"#F8AC59"
]
}
],
"folders": [
"Send",
"Draft"
],
"uploadsImageTypes": [
"jpg",
"jpeg",
"png",
"gif"
],
"uploadsFileTypes": [
"jpg",
"jpeg",
"docx",
"pdf",
"txt",
"ppt",
"png",
"gif"
],
"workOrderStatus": {
"color": [
"#A09580",
"#f8ac59",
"#41b0f6",
"#0d71b0",
"#1ab394",
"#067e47",
"#2819bc",
"#0d08f3",
"#ef0c34",
"#ef9aa9",
"#f2830b"
],
"value": [
"Draft",
"Requested",
"Requested Awaiting Approval",
"Assigned",
"Work In Progress",
"Ready",
"Done",
"Closed,Completed",
"Closed,Incompleted",
"On Hold",
"Open"
]
},
"priorities": {
"color": [
"#0B7409",
"#CE9B9B",
"#7CC396",
"#CEBE99"
],
"value": [
"Hard Down",
"High",
"Medium",
"Low"
]
},
"categories": [
"Equipment",
"Cranes",
"Delivery Vehicles",
"Rotating Spares"
],
"projects": [
"Vehicle New",
"System #7865",
"Book Shop",
"Site"
],
"maintenanceTypes": {
"color": "#FFFFFF",
"bg_color": [
"#1c84c6",
"#262626",
"#A09580",
"#ed5565"
],
"value": [
"Electrical",
"Damage",
"Safty",
"Broken"
]
},
"assets": [
"Conveyor Belt 1",
"Cranes",
"Delivery Vehicles",
"Rotating Spares"
],
"assignToUser": [
1,
2,
4,
5,
6
],
"roles": [
"Admin",
"Manager",
"Technician",
"Customer",
"Supplier",
"Engineer",
"Guest"
]
}
}
}
TestCrowd.java
public class TestCrowd extends Application {
private JSONObject roles,priorities;
public JSONObject getRoles() {
return roles;
}
public void setRoles(JSONObject roles) {
this.roles = roles;
}
public JSONObject getPriorities() {
return priorities;
}
public void setPriorities(JSONObject priorities) {
this.priorities = priorities;
}
}
And my main activity called NewWorkOrderActivity.java
try {
JSONObject details = ((TestCrowd) getApplicationContext()).getPriorities();
JSONObject priority = details.getJSONObject("priorities"); /*Where the null value object reference located*/
JSONArray priority_arry = priority.getJSONArray("value");
for (int i = 0; i < priority_arry.length(); i++) {
arraySpinner_1.add(priority_arry.get(i).toString());
}
ArrayAdapter<String> spinnerAdepter_1 = new ArrayAdapter<String>(this,R.layout.spinner_item,arraySpinner_1);
spinner_1.setAdapter(spinnerAdepter_1);
} catch (JSONException e) {
e.printStackTrace();
}
And the error is
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.malith.testcrowd/com.example.malith.testcrowd.NewWorkOrderActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONObject.getJSONObject(java.lang.String)' on a null object reference
I just need to extract priorities->values from the main Json
You are accessing the json object wrongly,
priorities is inside message-->enum-->priorities
JSONObject obj= ((TestCrowd) getApplicationContext()).getPriorities();
JSONObject message= obj.getJSONObject("message");
JSONObject enum= message.getJSONObject("enum");
JSONObject priorities = enum.getJSONObject("priorities");
JSONArray value=priorities .getJSONArray("value")
now do what every you want with value
Convert JSON as string using GSON and save it in Preference get as String and Convert in class object using GSON
check here for example
Related
I am trying to access value of 'cod' from the json string :
{"coord":{"lon":73.86,"lat":18.52},"sys":{"message":0.0293,"country":"IN","sunrise":1428972502,"sunset":1429017681},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":304.301,"temp_min":304.301,"temp_max":304.301,"pressure":951.61,"sea_level":1021.56,"grnd_level":951.61,"humidity":36},"wind":{"speed":2.06,"deg":302.501},
"clouds":{"all":24},"dt":1428996633,"id":1259229,"name":"Pune","cod":200}
But I am not able to get this value from my code. the code I am using to access this value from json string is as:
try{
JSONObject jsObject=(new JSONObject(JsonString)).getJSONObject("coord");
if( jsObject.getInt("cod")==200) {
i.putExtra("jsn", JsonString);
i.putExtra("city", etCity.getText().toString());
startActivity(i);
}
In the if condition, you are trying to access the key "cod" in the array {"lon":73.86,"lat":18.52}. It will throw a JSONException.
Try this :
try{
JSONObject jsonmain = new JSONOBject(JsonString);
if(jsonmain.getInt("cod") == 200) {
i.putExtra("jsn", JsonString);
i.putExtra("city", etCity.getText().toString());
startActivity(i);
}
Your json is:
{
"coord": {
"lon": 73.86,
"lat": 18.52
},
"sys": {
"message": 0.0293,
"country": "IN",
"sunrise": 1428972502,
"sunset": 1429017681
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
}
],
"base": "stations",
"main": {
"temp": 304.301,
"temp_min": 304.301,
"temp_max": 304.301,
"pressure": 951.61,
"sea_level": 1021.56,
"grnd_level": 951.61,
"humidity": 36
},
"wind": {
"speed": 2.06,
"deg": 302.501
},
"clouds": {
"all": 24
},
"dt": 1428996633,
"id": 1259229,
"name": "Pune",
"cod": 200
}
The key "cod" is not nested inside "coord".
Try:
new JSONObject(JsonString)).getInt("cod");
Actually you are trying wrong JSON Object.
String cod=(new JSONObject(JsonString)).getJSONObject("code").toString();
//you may need to try catch block
if( Integer.parseint(cod)==200) {
.... Your logic
}
Heyy guyz I am receiving JSON using google places details api then In that Json I am looking for "reviews" array.But in logcat I am getting system error that No values for reviews.But I checked in Json that there exist reviews array.Where is the problem?Thanx in advance.This is my JSON data:
{
"result" : {
"address_components" : [
{
"long_name" : "Kalyan",
"short_name" : "Kalyan",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Maharashtra",
"short_name" : "Maharashtra",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
},
{
"long_name" : "421301",
"short_name" : "421301",
"types" : [ "postal_code" ]
}
],
"reviews" : [
{
"aspects" : [
{
"rating" : 0,
"type" : "overall"
}
],
"author_name" : "Kunal Korde",
"author_url" : "https://plus.google.com/108837578005055609416",
"language" : "en",
"rating" : 1,
"text" : "it is very bad to call domino one and only kalyan
"time" : 1382351314
},
{
"aspects" : [
{
"rating" : 3,
"type" : "food"
},
{
"rating" : 2,
"type" : "decor"
},
{
"rating" : 1,
"type" : "service"
}
],
"author_name" : "Hits Daiya",
"author_url" : "https://plus.google.com/101565870698816750539",
"language" : "en",
"rating" : 4,
"text" : "wt a excellent food anybody can get here! I wanna to say that wt a
"time" : 1371385367
},
{
"aspects" : [
{
"rating" : 1,
"type" : "overall"
}
],
"author_name" : "nirmit jallawar",
"author_url" : "https://plus.google.com/116255076196839398528",
"language" : "en",
"rating" : 3,
"text" : "Good but a bit more of standard is necessary ",
"time" : 1402139860
},
{
"aspects" : [
{
"rating" : 2,
"type" : "food"
},
{
"rating" : 0,
"type" : "decor"
},
{
"rating" : 1,
"type" : "service"
}
],
"author_name" : "Rutam Mokashi",
"author_url" : "https://plus.google.com/112151348544733227698",
"language" : "en",
"rating" : 3,
"text" : "best place for pizzas in kalyan...",
"time" : 1353151680
},
{
"aspects" : [
{
"rating" : 1,
"type" : "food"
},
{
"rating" : 2,
"type" : "decor"
},
{
"rating" : 2,
"type" : "service"
}
],
"author_name" : "A.A Varghese varghese",
"author_url" : "https://plus.google.com/103110235851606786394",
"language" : "en",
"rating" : 4,
"text" : "nice hotel.",
"time" : 1375596316
}
],
"scope" : "GOOGLE",
"types" : [ "restaurant", "food", "establishment" ],
"url" : "https://plus.google.com/107013844902194125587/about?hl=en-US",
"user_ratings_total" : 32,
"utc_offset" : 330,
"vicinity" : "Plot No. C 1, Ground Floor, Shop No. 2, 3 & 4, Chikanghar, Kalyan",
"website" : "http://www.dominos.co.in/"
},
"status" : "OK"
}
and this my code:
public class Review_activity extends ActivityGroup {
protected static LocalActivityManager mLocalActivityManager;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
ProgressDialog pDialog;
JSONObject json = null;
// Review Listview
ListView list;
String reference;
public static final String TAG_name = "-NA-";
public static final String TAG_rating = "-NA-";
public static final String TAG_text = "-NA-";
public static String reference_value = "reference";
public static String KEY_REFERENCE = "reference";// id of the place
private static final String TEL_PREFIX = "tel:";
ArrayList<HashMap<String, String>> oslist = newArrayList<HashMap<String,String>>();
// public static String url = "";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.review);
oslist = new ArrayList<HashMap<String, String>>();
// Getting listview
list = (ListView) findViewById(R.id.list);
// Getting place reference from the map
reference = getIntent().getStringExtra("reference");
Log.d("yogesh", reference);
String sb ="https://maps.googleapis.com/maps/api/place/details/json?";
String sb1=sb.concat("&reference="+reference);
String sb2=sb1.concat("&sensor=true");
String sb3=sb2.concat("&key=AIzaSyChVcy-8fLkAq5-ZJCuNomF1lIf-Gda7s8");
String url=sb3;
Log.d("URL", url);
new JSONParse().execute(url);
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Review_activity.this);
pDialog.setMessage("Getting Reviews ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
String s = params[0];
Log.d("URL", s);
JSONObject json = jParser.getJSONFromUrl(s);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
JSONArray jArray = json.getJSONArray("reviews");
int k;
k=jArray.length();
k--;
String Alength=String.valueOf(k);
Log.d("Array length", Alength);
//To get the items from the array
int j=0;
for (int i=0;i<=k;i++)
{
JSONObject r1 = jArray.getJSONObject(j);
String aname = r1.getString("author_name");
String arating = r1.getString("rating");
String text = r1.getString("text");
Log.d("review", aname);
Log.d("review", arating);
Log.d("review", text);
j++;
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_name, aname);
map.put(TAG_rating, arating);
map.put(TAG_text,text );
oslist.add(map);
}
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(Review_activity.this, oslist,
R.layout.review_item,
new String[] { TAG_name,TAG_rating, TAG_text }, new int[] {
R.id.textView2,R.id.textView4, R.id.textView6});
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
i found your json is not a valid json
use check if json is valid or not this to check valid json
i correct it and the valid json is here
{
"result": {
"address_components": [
{
"long_name": "Kalyan",
"short_name": "Kalyan",
"types": [
"locality",
"political"
]
},
{
"long_name": "Maharashtra",
"short_name": "Maharashtra",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "India",
"short_name": "IN",
"types": [
"country",
"political"
]
},
{
"long_name": "421301",
"short_name": "421301",
"types": [
"postal_code"
]
}
],
"reviews": [
{
"aspects": [
{
"rating": 0,
"type": "overall"
}
],
"author_name": "Kunal Korde",
"author_url": "https://plus.google.com/108837578005055609416",
"language": "en",
"rating": 1,
"text": "it is very bad to call domino one and only kalyan",
"time": 1382351314
},
{
"aspects": [
{
"rating": 3,
"type": "food"
},
{
"rating": 2,
"type": "decor"
},
{
"rating": 1,
"type": "service"
}
],
"author_name": "HitsDaiya",
"author_url": "https: //plus.google.com/101565870698816750539",
"language": "en",
"rating": 4,
"text": "wtaexcellentfoodanybodycangethere!Iwannatosaythatwta",
"time": 1371385367
},
{
"aspects": [
{
"rating": 1,
"type": "overall"
}
],
"author_name": "nirmitjallawar",
"author_url": "https: //plus.google.com/116255076196839398528",
"language": "en",
"rating": 3,
"text": "Goodbutabitmoreofstandardisnecessary",
"time": 1402139860
},
{
"aspects": [
{
"rating": 2,
"type": "food"
},
{
"rating": 0,
"type": "decor"
},
{
"rating": 1,
"type": "service"
}
],
"author_name": "RutamMokashi",
"author_url": "https: //plus.google.com/112151348544733227698",
"language": "en",
"rating": 3,
"text": "bestplaceforpizzasinkalyan...",
"time": 1353151680
},
{
"aspects": [
{
"rating": 1,
"type": "food"
},
{
"rating": 2,
"type": "decor"
},
{
"rating": 2,
"type": "service"
}
],
"author_name": "A.AVarghesevarghese",
"author_url": "https: //plus.google.com/103110235851606786394",
"language": "en",
"rating": 4,
"text": "nicehotel.",
"time": 1375596316
}
],
"scope": "GOOGLE",
"types": [
"restaurant",
"food",
"establishment"
],
"url": "https: //plus.google.com/107013844902194125587/about?hl=en-US",
"user_ratings_total": 32,
"utc_offset": 330,
"vicinity": "PlotNo C1 GroundFloor ShopNo 2 3 4 Chikanghar Kalyan",
"website": "http: //www.dominos.co.in/"
},
"status": "OK"
}
i found your code seems pretty correct ....
the safer side is first print the response json and check if its valid or not....
Issue is you first to get json object for "result" then use that object to find json array for review.
jsonobject = json.getJsonObject("result");
resultArray = jsonobject.getJsonArray("review");
Json from server
{
"status": 1,
"players": {
"__v": 5,
"_id": "52f719eb31f3b9b20500000c",
"battingStyle": "Left Hand Batsman",
"bowlingStyle": "Facing Batsman",
"dob": "2000-02-09T06:01:49.144Z",
"fname": "Muhammad",
"playingRole": "Bowler",
"sname": "Sami",
"teams": [
{
"__v": 23,
"_id": "52f715b431f3b9b205000004",
"category": "Veterans",
"name": "Golden Eagle",
"rating": 5,
"teamGender": "Men"
},
{
"__v": 17,
"_id": "52f715df31f3b9b205000005",
"category": "Veterans",
"name": "Choudhry Sports",
"rating": 5,
"teamGender": "Men"
}
],
"grounds": [
{
"__v": 2,
"_id": "53381bb5f0bce0bd20000001",
"address": "6046 W Lake Sammamish Way Northeast, Redmond, WA 98052, United States",
"city": "Redmond",
"country": "United States",
"latitude": "",
"longitude": "",
"name": "Marymoor Park"
},
{
"__v": 2,
"_id": "53381bb5f0bce0bd20000001",
"address": "6046 W Lake Sammamish Way Northeast, Redmond, WA 98052, United States",
"city": "Redmond",
"country": "United States",
"latitude": "",
"longitude": "",
"name": "Marymoor Park"
}
]
}
}
And after j son parse Model has contain duplicate id
Player[
id=1,
_id=531029b207987409620000d6,
battingStyle=RHB,
bowlingStyle=RAOS,
dob=2000-02-28T06: 15: 15.264Z,
playingRole=BWL,
sname=QadeerButt,
fname=Tahir,
gallery=[
],
games=[
Game[
id=4,
gameType=T20,
name=TotallyCricketvsLahoreTiger,
totalOvers=20,
dateStarted=2014-06-18T19: 00: 00.000Z,
dateEnded=2014-06-18T19: 00: 00.000Z,
innings=[
],
grounds=[
Ground[
id=26,
address=14835SE18thPl,
Bellevue,
WA98007,
UnitedStates,
city=Bellevue,
country=UnitedStates,
name=RobinswoodPark
],
Ground[
id=26,
address=14835SE18thPl,
Bellevue,
WA98007,
UnitedStates,
city=Bellevue,
country=UnitedStates,
name=RobinswoodPark
]
],
teams=[
Team[
id=30,
name=TotallyCricket,
category=Veterans,
teamGender=Men,
rating=5
],
Team[
id=19,
name=LahoreTiger,
category=Under19,
teamGender=Men,
rating=3
]
]
]
]
]
Just check if the Collection (maybe an arraylist?) already has an object with the id before storing a new one.
Yes, but this is what the JSON shows. An JSON Array which contains duplicate JSON Objects.
You may want to valiate while parsing if the JSONObject already exists and copy it in another.
GSON gson = new GSON();
JSONArray json = new JSONArray(gson.toJson(yourobject));
JSONArray secondJson = new JSONArray();
for (int i = 0; i <= json.length(); i++) {
if (!jsonArrayHasItem(secondJson, json.getInt("id")) {
secondJson.put(jsonArray.getJsonObject(i));
}
}
public boolean jsonArrayHasItem(JSONArray jsonArray, int item) {
for (int i = 0; i <= jsonArray.length(); i++) {
if (jsonArray.getJsonObject(i).has(item)) return true;
}
return false;
}
not tested or compiled at all. just pseudocode.
For example : if the given below is json of the person's profile on facebook got thorugh facebook sdk login through android app , How we will get the School Name fron the education Field in th json data in android . Please Help
Data :
{
"id": "1464730016",
"name": "Ravi Tamada",
"first_name": "Ravi",
"last_name": "Tamada",
"link": "https://www.facebook.com/ravi8x",
"username": "ravi8x",
"birthday": "12/22/1988",
"hometown": {
"id": "112158005464147",
"name": "Baruva"
},
"location": {
"id": "102186159822587",
"name": "Chennai, Tamil Nadu"
},
"bio": "Author: www.androidhive.info\r\nCo-author: www.9lessons.info",
"work": [
{
"employer": {
"id": "179366562092719",
"name": "ByteAlly"
},
"location": {
"id": "102186159822587",
"name": "Chennai, Tamil Nadu"
},
"position": {
"id": "124917314217511",
"name": "Product Head"
}
]
}
],
"favorite_athletes": [
{
"id": "18620649907",
"name": "Virat Kohli"
}
],
"education": [
{
"school": {
"id": "131587206873093",
"name": "Raghu Engineering College (REC)"
},
"degree": {
"id": "140065339390579",
"name": "B.Tech"
},
"year": {
"id": "142963519060927",
"name": "2010"
},
"type": "Graduate School",
"classes": [
{
"id": "192259410803415",
"name": "2010",
"with": [
{
"id": "584960408",
"name": "Santosh Patnaik"
}
],
"from": {
"id": "584960408",
"name": "Santosh Patnaik"
}
}
]
}
],
"gender": "male",
"relationship_status": "Single",
"website": "www.androidhive.info\nwww.9lessons.info\nwww.twitter.com/ravitamada\nwww.about.me/rv",
"timezone": 5.5,
"locale": "en_US",
"languages": [
{
"id": "106059522759137",
"name": "English"
},
{
"id": "107617475934611",
"name": "Telugu"
},
{
"id": "112969428713061",
"name": "Hindi"
},
{
"id": "343306413260",
"name": "Tamil"
}
],
"verified": true,
"updated_time": "2012-03-02T17:04:18+0000"
}
JSONObject jsonResult = new JSONObject(jsonUser);
JSONArray data = jsonResult.getJSONArray("education");
if(data != null)
{
for(int i = 0 ; i < data.length() ; i++)
{
JSONObject c = data.getJSONObject(i);
String type = c.getString("type");
if(type.equalsIgnoreCase("college"))
{
JSONObject school = c.getJSONObject("school");
String id2 = school.getString("id");
String name2 = school.getString("name");
JSONObject year = c.getJSONObject("year");
String id_y = school.getString("id");
String name_y = school.getString("name");
}
}
}
Supposing that you've this json into a jsonObject that you retrieve as response, this is the way:
// Get jsonArray 'education' from main jsonObject
JSONArray jsonArrayEducation = jsonObject.getJSONArray("education");
JSONObject jsonSchool = jsonArrayEducation.getJSONObject("school");
Note that if you are interested only at the name, you can group the two lines above into
JSONObject jsonSchool = jsonObject.getJSONArray("education").getJSONObject("school");
// get school name
String schoolName = jsonSchool.getString("name");
I decided I wanted to try using the Google shopping API out last week, but I had no idea how to parse JCON objects.
After much searching here I was able to get the product information for an item! However, I cannot narrow down to just a string in the product. So for example I want to just get the title of a product.
I have the following:
jsonString:
{
"kind": "shopping#products",
"etag": "\"GKsxsRlaBDslDpMe-MT1O7wqUDE/dMvQ5Pu2C806fWZJbNJ0GjdesJs\"",
"id": "tag:google.com,2010:shopping/products",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products?country=US&restrictBy=gtin:051500240908&startIndex=1&maxResults=25",
"totalItems": 3,
"startIndex": 1,
"itemsPerPage": 25,
"currentItemCount": 3,
"items": [
{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/7585088/9884865157760252836",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/7585088/gid/9884865157760252836",
"product": {
"googleId": "9884865157760252836",
"author": {
"name": "Southeastern Delivery",
"accountId": "7585088"
},
"creationTime": "2011-07-25T00:15:58.000Z",
"modificationTime": "2012-02-11T09:29:00.000Z",
"country": "US",
"language": "en",
"title": "Jif Peanut Butter, Creamy",
"description": "Jif Creamy Peanut Butter. Fresh Roasted Peanut Taste. Look for the flavor seal. Contains no preservatives. No refrigeration required.",
"link": "http://www.southeasterndelivery.com/Jif_Peanut_Butter_00051500240908/",
"brand": "Jif Peanut Butter",
"condition": "new",
"gtin": "00051500240908",
"gtins": [
"00051500240908"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 15.64,
"shipping": 1.56,
"currency": "USD"
}
],
"images": [
{
"link": "http://www.southeasterndelivery.com/images/ProductImages/00051500240908.jpg"
}
]
}
},
],
"requestId": "0CLGzkcKVo64CFRDd5wod4mMAAA"
}
I have the following code in my android app to parse it:
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray itemsArray = jsonObject.getJSONArray("items");
JSONObject productObject = itemsArray.getJSONObject(0);
//String productTitle = productObject.getString("title");
//tv.setText(productTitle);
tv.setText(productObject.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
tv.setText("JSONOBJECT Error: " + e);
e.printStackTrace();
}
setContentView(tv);
The TextView on my Android app will now display (obviously not indented I did that for easy reading):
"product": {
"googleId": "9884865157760252836",
"author": {
"name": "Southeastern Delivery",
"accountId": "7585088"
},
"creationTime": "2011-07-25T00:15:58.000Z",
"modificationTime": "2012-02-11T09:29:00.000Z",
"country": "US",
"language": "en",
"title": "Jif Peanut Butter, Creamy",
"description": "Jif Creamy Peanut Butter. Fresh Roasted Peanut Taste. Look for the flavor seal. Contains no preservatives. No refrigeration required.",
"link": "http://www.southeasterndelivery.com/Jif_Peanut_Butter_00051500240908/",
"brand": "Jif Peanut Butter",
"condition": "new",
"gtin": "00051500240908",
"gtins": [
"00051500240908"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 15.64,
"shipping": 1.56,
"currency": "USD"
}
],
"images": [
{
"link": "http://www.southeasterndelivery.com/images/ProductImages/00051500240908.jpg"
}
]
}
Now if you notice in my Java code I have two lines commented out. If I uncomment those lines and then comment the line:
tv.setText(productObject.toString());
tv gets set to this error: "JSONOBJECT Error: org.json.JSONEception: No value for title". I am not sure why this is true because clearly their is a title in the productObject.
Any help would be great!
I'm using json-smart in my project. It is very small and very fast. To convert your JSON from Sting to the actual object use JSONObjet json = (JSONObject)JSONValue.parse(rawString);
When you have JSONObject you treat it just like a Map. So String title = (String) json.get("title")
You are missing a level of information in your code. The JSON array contains items, which contains products, which have a title.
Your code should look like:
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray itemsArray = jsonObject.getJSONArray("items");
JSONObject itemObject = itemsArray.getJSONObject(0);
JSONObject productObject = itemObject.getJSONObject("product");
String productTitle = productObject.getString("title");