Parsing JSON data in Java for Android - java

I hope someone might be able to help me.
I am trying to parse following json file:
{"seminar":[
{"categoryid": "1","cpe": "13","inventory":["Discussion","Value x","Value y"
],"teachers": [
{
"titel": "Dipl.-Ing.",
"company": "XY",
"name": "Test",
"id": "3",
}
],
},...
I am lost with parsing the teachers data in...
...
private static final String TAG_teachers = "teachers";
private static final String TAG_TITLE = "title";
for(int i = 0; i < seminar.length(); i++){
JSONObject c = seminar.getJSONObject(i);
...
teachers = c.getJSONArray(TAG_DOZENTEN);
for(int z = 0; z < teachers.length(); z++){
JSONObject d = teachers.getJSONObject(z);
String title = d.getString(TAG_TITLE);
Log.d("JSONParsingActivity", title);
I get the error System.err(1010): org.json.JSONException: Value null
at teachers of type org.json.JSONObject$1 cannot be converted to
JSONArray.
What did I do wrong? As I understand from the JSON documentation, teachers is an JSON Array and not an Object. Is somebody able to help me?

You have an extra (trailing) comma in teachers (after "3"). Not allowed in JSON. Remove it and see if that helps.

If your JSON is really of the form:
{ ... }, { ... }, { ... }, ...
This is invalid JSON
The root enclosure must either be a single object (in {}) or an array (in []).
If your intent is to send an array of objects, then simply wrap the entire thing with square brackets to make it an array and create a JSONArray object from it.
So it must be like this
[ { ... }, { ... }, { ... }, ... ]
You also need to make sure that you don;t have extra commas, unclosed brackets, etc. Use JSONLint or other similar JSON format checker to save yourself some time in finding syntax problems.

Related

Getting JSONObject from JSONObject parent

All I am getting resources are getting JSONObject from JSONArray. But in this case, I want to get the temperature which is "temp". I don't think it is part of an array. How can I get that?
{
"coord":{
"lon":85.17,
"lat":26.67
},
"weather":[
{
"id":500,
"main":"Rain",
"description":"light rain",
"icon":"10d"
}
],
"base":"stations",
"main":{
"temp":31.09,
"pressure":1004.15,
"humidity":83,
"temp_min":31.09,
"temp_max":31.09,
"sea_level":1010.39,
"grnd_level":1004.15
},
"wind":{
"speed":3.66,
"deg":107.5
},
"rain":{
"3h":0.202
},
"clouds":{
"all":64
},
"dt":1534148929,
"sys":{
"message":0.0048,
"country":"IN",
"sunrise":1534117810,
"sunset":1534165068
},
"id":1273043,
"name":"Dhaka",
"cod":200
}
I have tried- (I am new with JSON)
JSONObject jsonObject = new JSONObject(s);
JSONObject main = jsonObject.getJSONObject("main");
JSONObject temp = main.getJSONObject("temp");
Assuming you're using Android (tagging appropriately helps here, as it depends on the JSON library you're using):
Since you've got JSONObject main = jsonObject.getJSONObject("main");, you should then just be able to do double temp = main.getDouble("temp"); to get the temperature off that main object.
If you have a look at the docs for JSONObject you can see a variety of methods for getting JSON "primitive" fields, such as int, String, etc. - and you need to use those to retrieve said primitive fields, rather than calling getJSONObject().
Get the value from main object using "temp" as key
double temp = main.getDouble("temp");
temp is not a JSonObject. you can get the temperature as String or double. So change the last line of your code with:
String temp = main.getString("temp");
or
double temp = main.getDouble("temp");

Accessing elements in JSON array

I haven't worked much with JSON and I'm using Google Maps Distance Matrix API to get generate some data I'd like to use.
I'd like to pull the number 14147 from duration.
{
"destination_addresses" : [ "Washington, DC, USA" ],
"origin_addresses" : [ "New York, NY, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "226 mi",
"value" : 364089
},
"duration" : {
"text" : "3 hours 56 mins",
"value" : 14147
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I've tried a few different things, here's what I tried last (data is just the array above):
String data = getOutputAsText(geoService);
JSONObject json = new JSONObject(data);
String duration = json.getJSONArray("rows").getString("duration");
Here's the console output:
org.json.JSONException: JSONObject["duration"] not found
I made sure to look around before posting but I haven't found anything that has been able to help me with this particular problem.
I want to pass the value from duration to my own web service, which I can do, I just don't know how to extract the value. Thank you in advance!
First of all, please have a look at this answer. Using org.json you can do smth. like that:
JSONObject obj = new JSONObject("Content of your string here");
JSONArray rows = obj.getJSONArray("rows");
for (int i = 0; i < rows.length(); i++) {
JSONArray elements = rows.getJSONObject(i).getJSONArray("elements");
for(int j = 0; j < elements.length(); j++) {
JSONObject element = elements.getJSONObject(j);
JSONObject duration = element.getJSONObject("duration");
int value = duration.getInt("value");
}
}
The code above has produced following output using your json String: 14147
P.S. You can make use of a library you wish. This one used here was purposed for the demonstrating.

How to Parameterize jsonSurfer collectOne method - Java/Json Parsing

Let's say I have a file sample.json
{"Students":
[
{"Name": "ABC", "id" = "one"},
{"Name": "XYZ", "id" = "two"}
]
}
How do I retrieve an array element object by passing its index number as an argument ?
For example, I want to get array element with variable name ABC. So indexNum is 0 in this case.
I tried below but it doesn't work.
InputStreamReader reader = read("sample.json");
Object obj = jsonSurfer.collectOne(reader,"$.Students[indexNum]");
Not sure if JsonSurfer supports parametrizarion. Any suggestions please. Thanks.
Following code should work:
int indexNum = 0;
String jsonPath = "$.Students["+indexNum+"]";
Object obj = jsonSurfer.collectOne(reader,jsonPath);

Why do I always get JSON Exception?

This Is my first time with parsing JSON data. I am using the Google knowledge graph api. I got the api working and I can get the JSON result. This is Google 's sample return data for a sample query which I'm using now for testing.
{
"#context": {
"#vocab": "http://schema.org/",
"goog": "http://schema.googleapis.com/",
"resultScore": "goog:resultScore",
"detailedDescription": "goog:detailedDescription",
"EntitySearchResult": "goog:EntitySearchResult",
"kg": "http://g.co/kg"
},
"#type": "ItemList",
"itemListElement": [
{
"#type": "EntitySearchResult",
"result": {
"#id": "kg:/m/0dl567",
"name": "Taylor Swift",
"#type": [
"Thing",
"Person"
],
"description": "Singer-songwriter",
"image": {
"contentUrl": "https://t1.gstatic.com/images?q=tbn:ANd9GcQmVDAhjhWnN2OWys2ZMO3PGAhupp5tN2LwF_BJmiHgi19hf8Ku",
"url": "https://en.wikipedia.org/wiki/Taylor_Swift",
"license": "http://creativecommons.org/licenses/by-sa/2.0"
},
"detailedDescription": {
"articleBody": "Taylor Alison Swift is an American singer-songwriter and actress. Raised in Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music. ",
"url": "http://en.wikipedia.org/wiki/Taylor_Swift",
"license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
},
"url": "http://taylorswift.com/"
},
"resultScore": 896.576599
}
]
}
So I want to parse it so that I can get the name, description, detailed description. This is my code but I always seem to get the exception. Any ideas why?
try {
JSONObject object=new JSONObject(gggg);
JSONArray itemListElement = object.getJSONArray("itemListElement");
for(int i=0; i < itemListElement.length();i++){
JSONObject c = itemListElement.getJSONObject(i);
JSONObject results = c.getJSONObject("result");
String name = results.getString("name").toString();
String description = results.getString("description").toString();
String detailedDescription = results.getString("articleBody").toString();
gggg = "Name: "+name+"\n Description: "+description+"\n "+detailedDescription;
}
responseView.append(gggg);
} catch (JSONException e) {
Toast.makeText(MainActivity.this,gggg,Toast.LENGTH_LONG).show();
}
Also the string gggg contains the JSON data. I don't know why but I am always getting the exception. Please tell me what is the error in my code and how to repair it.
Thanks.
"Name: Taylor Swift Description: Singer-songwriter Taylor Alison
Swift is an American singer-songwriter and actress. Raised in
Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the
age of 14 to pursue a career in country music. "
The problem is your String detailedDescription line.
You need to get the detailedDescription object before you retrieve the articleBody.
for(int i=0; i < itemListElement.length();i++){
JSONObject c = itemListElement.getJSONObject(i);
JSONObject results = c.getJSONObject("result");
String name = results.getString("name");
String description = results.getString("description");
JSONObject detailedDescription = results.getJSONObject("detailedDescription");
String articleBody = detailedDescription.getString("articleBody");
String x = "Name: "+name+"\n Description: "+description+"\n "+articleBody;
}
Also your .toString() method calls are redundant as you are calling .getString() on the JSON object.
With in the android json library it has a method called has element, which returns true or false. After successfully checking then access the element. The expection be caused by tring to access an element that isn't there.
Might be worth printing out after each time you create a new object to ensure that the objects are being created. It will also piont to where the expection is happening.

Parsing JSON Android ArrayList

I apologize if the title of my question is a bit misleading.
I created a POJO to hold CholesterolInformation about a user (HDL, LDL, Triglycerides, units, etc...). I now want to use my JSONObject to create an ArrayList so that I can generate some data points.
My JSONObject contains the following:
{
"cholesterol": [
{
"date": "2014-01-01",
"hdl": "56464.0",
"ldl": "46494.0",
"triGlycaride": "0.0",
"uid": "email#email.com",
"unit": "mg"
},
{
"date": "2014-01-01",
"hdl": "5.0",
"ldl": "5.0",
"triGlycaride": "0.0",
"uid": "email#email.com",
"unit": "mg"
},
{
"date": "2014-01-01",
"hdl": "6.0",
"ldl": "6.0",
"triGlycaride": "0.0",
"uid": "email#email.com",
"unit": "mg"
}
]
}
My question is, how would one go about iterating through this JSON Object? I would like to maybe use a for each, and create a new object to add to the ArrayList in each iteration... Do you have any advice or suggestions?
Note: I have never used the JSONObject before, and thus am not too familiar with its usage.
EDIT: Thanks everybody, that was exactly what I was looking for. I need to get more familiar with JSON manipulation. And I will look into GSON as well!
Use GSON as suggested by Eric as you already created POJO.
Gson gson = new Gson();
Type type = new TypeToken<List<POJO>>() {}.getType();
List<POJO> mList = gson.fromJson(your_json_string_here, type);
It's time to learn some JSON manipulation:
JSONArray array = yourJsonObject.optJSONArray("cholesterol");
if (array != null) {
for (int i=0; i< array.length; i++) {
JSONObject object = array.optJSONObject(i);
if (object != null) {
// this is where you manipulate all the date, hdl, ldl...etc
}
}
}
you also should check for null before accessing the json
If I understand you correctly, you want to create an ArrayList of your POJO? I assume you have getters and setters inside your POJO class. Initialize an ArrayList somewhere near the top like this
private ArrayList<CholesterolInformation> mCholesterol;
Now, parse through your json like this
JSONobject data = new JSONObject(jsonStringData);
JSONArray cholesterol = data.getJSONArray("cholesterol");
for(int i = 0; i < cholesterol.length; i++)
{
JSONObject object = cholesterol.getJSONObject(i);
// Create a new object of your POJO class
CholesterolInformation ci = new CholesterolInformation();
// Get value from JSON
String date = object.getString("date");
// Set value to your object using your setter method
ci.setDate(date);
String hdl = object.getString("hdl");
ci.setHdl(hdl);
.....
.....
// Finally, add the object to your arraylist
mCholesterol.add(ci);
}

Categories