Each news entry has three things : title,contentand date.
The entries are retrieved from a database and I would like to read them in my application using JSONObject and JSONArray. However, I do not know how to use these classes.
Here is my JSON string:
[
{
"news":{
"title":"5th title",
"content":"5th content",
"date":"1363197493"
}
},
{
"news":{
"title":"4th title",
"content":"4th content",
"date":"1363197454"
}
},
{
"news":{
"title":"3rd title",
"content":"3rd content",
"date":"1363197443"
}
},
{
"news":{
"title":"2nd title",
"content":"2nd content",
"date":"1363197409"
}
},
{
"news":{
"title":"1st title",
"content":"1st content",
"date":"1363197399"
}
}
]
Your JSON string is a JSONArray of JSONObject which then contain an inner JSONObject called "news".
Try this for parsing it:
JSONArray array = new JSONArray(jsonString);
for(int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
JSONObject innerObject = obj.getJSONObject("news");
String title = innerObject.getString("title");
String content = innerObject.getString("content");
String date = innerObject.getString("date");
/* Use your title, content, and date variables here */
}
First of all, your JSON structure is not ideal. You have an array of objects, with each object having a single object in it. However, you could read it like this:
JSONArray jsonArray = new JSONArray (jsonString);
int arrayLength = jsonArray.length ();
for (int counter = 0; counter < arrayLength; counter ++) {
JSONObject thisJson = jsonArray.getJSONObject (counter);
// we finally get to the proper object
thisJson = thisJson.getJSONObject ("news");
String title = thisJson.getString ("title");
String content = thisJson.getString ("content");
String date = thisJson.getString ("date");
}
However!
You could do better if you change your JSON to look like the following:
[
{
"title": "5th title",
"content": "5th content",
"date": "1363197493"
},
{
"title": "4th title",
"content": "4th content",
"date": "1363197454"
}
]
Then, you could parse it as follows:
JSONArray jsonArray = new JSONArray (jsonString);
int arrayLength = jsonArray.length ();
for (int counter = 0; counter < arrayLength; counter ++) {
// we don't need to look for a named object any more
JSONObject thisJson = jsonArray.getJSONObject (counter);
String title = thisJson.getString ("title");
String content = thisJson.getString ("content");
String date = thisJson.getString ("date");
}
Related
I have problem when I try to get data from a JSON array in Android Studio.
I want to get data from year 2015, 2016 and 2018 populate them in different textviews.
This is my JSON:
"data": [
{
"id": "7",
"kecamatan": "Blambangan Umpu",
"year": {
"2015": {
"id": "27",
"value": "60200"
},
"2016": {
"id": "41",
"value": "61516"
},
"2018": {
"id": "7",
"value": ""
}
},
"avg": 2.14
},
and this is my mainactivity
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("data");
// JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i ++) {
JSONObject o = array.getJSONObject(i);
String id = o.getString("id");
String kec = o.getString("kecamatan");
String avg = o.getString("avg");
String tahun = o.getString("year");
// JSONArray array2 = o.getJSONArray("year");
// for (int j = 0; j<array2.length(); j++) {
// JSONObject p = array2.getJSONObject(j);
// String value = p.getString("value");
ListItem item = new ListItem(id, kec, avg, tahun, avg);
listItems.add(item);
// }
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
year is a JSONObject with 2015,2016 and 2018 as keys and JSONObject as values, So get year JSONObject and then get keys and values by iterating it
for (int i = 0 ; i<array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String id = o.getString("id");
String kec = o.getString("kecamatan");
String avg = o.getString("avg");
JSONObject yearObject = o.JSONObject("year"); //get JSONObject
Iterator<String> itr = yearObject.keys();
while(itr.hasNext()) {
String year = itr.next();
JSONObject obj = o.get("year"); //2015
System.out.println(obj.getString("id")); //27
System.out.println(obj.getString("value")); //60200
}
//Add required fields into `ListItem`
ListItem item = new ListItem(id,kec,avg,tahun,avg);
listItems.add(item);
}
I have been using the the Json library to try and parse the following Json data:
{"dailygameschedule": {
"lastUpdatedOn": "2016-12-19 12:32:56 AM",
"gameentry": [
{
"id": "37705",
"date": "2016-04-03",
"time": "1:30PM",
"awayTeam": {
ID: "133",
City: "St. Louis",
Name: "Cardinals"
Abbreviation: "STL"
},
"homeTeam": {
"ID": "132",
"City": "Pittsburgh",
"Name": "Pirates",
"Abbreviation": "PIT"
},
"location": "PNC Park"
},
...
]
}
I cant figure out how to get the "gameentry" array. I was looking at other threads for guidance but it is not quite working for me. Heres what I have so far:
JSONObject obj = new JSONObject(todaysGames);
String pageName = obj.getJSONObject("dailygameschedule").getString("lastUpdatedOn");
System.out.println("2 asdfasdf "+ pageName);
JSONArray arr = obj.getJSONArray("gameentry");
for (int i = 0; i < arr.length(); i++)
{
//String post_id = arr.getJSONObject(i).getString("id");
System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
}
There error that im getting is:
Exception in thread "main" org.json.JSONException:
JSONObject["gameentry"] not found.
Thanks!
Try this,
JSONArray arr=obj.getJSONObject("dailygameschedule").getJSONArray("gameentry");
for (int i = 0; i < arr.length(); i++)
{
JSONObject obj = arr.getJSONObject(i);
String id = obj.getString("id");
JSONObject awayTeam_obj=obj.getJSONObject("awayTeam");
String awayTeam_ID = awayTeam_obj.getString("ID");
String awayTeam_City = awayTeam_obj.getString("City");
String awayTeam_Name = awayTeam_obj.getString("Name");
JSONObject homeTeam_obj=obj.getJSONObject("homeTeam");
String homeTeam_ID = homeTeam_obj.getString("ID");
String homeTeam_City = homeTeam_obj.getString("City");
String homeTeam_Name = homeTeam_obj.getString("Name");
}
gameentry array is a member of dailygameschedule object, so you need to access it first.
JSONArray arr = obj.getJSONObject("dailygameschedule").getJSONArray("gameentry");
for (int i = 0; i < arr.length(); i++)
{
//String post_id = arr.getJSONObject(i).getString("id");
System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
}
That's not a valid JSON object, Just add '}' and gameentry not a root element you should get dailygamesschedule first and then get the gameentry
I have a json string string from which I want to get the values. It is in key pair form so I want the values for each key.
I tried to get the values but I am not getting it.
Json String is like :
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
I want to get values of "Name", "Address", "Company" etc.
I tried to get like this:
JSONArray array;
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
array = object.getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(i);
edt_FirstName.setText(object.getString("Name"));
}
} catch (JSONException e) {
}
Can anyone help me out please? Thank you..
EDIT:
I tried to check values like this:
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(0);
String type = subObject1.getString("type");
String value = subObject1.getString("value");
if (type.equals("Name")) {
edt_FirstName.setText(value);
}
if(type.equals("Address"))
{
edt_address.setText(value);
}
if(type.equals("Company"))
{
edt_company.setText(value);
}
if(type.equals("Mobile"))
{
edt_Mobile.setText(value);
}
}
I want to get all the values from field array and set to the text view, but I am getting only the Name value and not the others.
Also I could get one field as twice like Mobile I can get twice, so I want to combine both the Mobile values and show it.
So your json object is as follow:
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
You first need to get "document" as JSONObject and then get "businessCard" as JSONObject and then you can get "field" as JSONArray:
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
JSONArray array = object.getJSONObject("document").getJSONObject("businessCard").getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject = array.getJSONObject(i);
String type = subObject.getString("type");
String value = subObject.getString("value");
if (type.equals("Name")) {
String prevValue = edt_FirstName.getText();
edt_FirstName.setText((TextUtils.isEmpty(prevValue) ? "" : prevValue + ",") + value);
}
}
} catch (JSONException e) { }
}
Try this code, Hope it will help you.
try
{
JSONObject jsonObject = new JSONObject();
JSONObject documentObject = jsonObject.getJSONObject("document");
JSONObject businessCardObject = documentObject.getJSONObject("businessCard");
String imgRotation = businessCardObject.getString("imageRotation");
JSONArray array = businessCardObject.getJSONArray("field");
for (int i = 0; i < array.length() ; i++)
{
JSONObject arrObj = array.getJSONObject(i);
String type = arrObj.getString("type");
String value = arrObj.getString("value");
Log.e(TAG, "type=="+type);
Log.e(TAG, "value=="+value);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
here is code
private void convertJsonToDto(String jsonNewString) {
JSONObject jsonObj = new JSONObject(jsonNewString);
String RecordLocator = (String) jsonObj.get("obj");
String FirstName = (String) jsonObj.getJSONObject("Customer").get("FirstName");
JSONArray array = new JSONObject(jsonNewString).getJSONArray("Array");
JSONObject jsonObject = array.getJSONObject(0);
String str = jsonObject.getString("object");
}
I'm trying to parse a JSON object in java :
{
"poster_path": "/e3QX3tY0fBR1GuxdP0mwpN16cqI.jpg",
"adult": false,
"overview": "In 1950s Pittsburgh, a frustrated African-American father struggles with the constraints of poverty, racism, and his own inner demons as he tries to raise a family.",
"release_date": "2016-12-16",
"genre_ids": [
18
],
"id": 393457,
"original_title": "Fences",
"original_language": "en",
"title": "Fences",
"backdrop_path": "/jNlCIAcheh0iOuL3kz9x1Wq9WLG.jpg",
"popularity": 10.976374,
"vote_count": 290,
"video": false,
"vote_average": 6.7
},
But I get a JSONException when I try to access the values for poster_path(org.json.JSONException: No value for poster_path) and release_date(org.json.JSONException: No value for release_date)
ArrayList<MovieModel> results = new ArrayList<MovieModel>();
String streamAsString = result;
try{
JSONObject jsonObject = new JSONObject(streamAsString);
JSONArray array = (JSONArray) jsonObject.get("results");
for (int i = 0; i < array.length(); i++) {
JSONObject c = array.getJSONObject(i);
JSONObject jsonMovie = array.getJSONObject(i);
MovieModel movieModel= new MovieModel();
movieModel.setMovieTitle(jsonMovie.getString("title"));
movieModel.setMovieGenre("na");;
String strImgURL=jsonObject.getString("poster_path").substring(2);
movieModel.setImgURL("");
movieModel.setMovieYear(jsonObject.getString("release_date"));
results.add((movieModel));
}
}
catch(JSONException j)
{
System.err.println(j);
Log.d(DEBUG_TAG, "Error parsing JSON. String was: " + j.toString());
}
Not sure what could be causing this error
You're trying to get the poster_path and release_date values from the outer JSONObject, the one that has everything (including the JSONArray that contains the individual movies).
In the loop, just use jsonMovie instead of jsonObject:
for (int i = 0; i < array.length(); i++) {
JSONObject jsonMovie = array.getJSONObject(i);
MovieModel movieModel= new MovieModel();
movieModel.setMovieTitle(jsonMovie.getString("title"));
movieModel.setMovieGenre("na");
String strImgURL=jsonMovie.getString("poster_path").substring(2);
movieModel.setImgURL("");
movieModel.setMovieYear(jsonMovie.getString("release_date"));
results.add((movieModel));
}
I am getting the following as a String response from a webserveice:
[
[
{
"dgtype": "adhoc",
"subtypename": "Person",
"subtypedesc": "null",
"summary": "Junaid (Self)",
"subtype": "person",
"birthdate": "1995-1-23 ",
"name": "Junaid (Self)"
},
{
"dgtype": "adhoc",
"subtypename": "Job",
"subtypedesc": "null",
"summary": "Exa",
"subtype": "person",
"birthdate": "2010-01-30",
"name": "Junaid (Self)"
}
]
]
In Java I am trying to do the following:
JSONArray jArray = new JSONArray(result);
System.out.println("Response: "+jArray);
for(int i = 0; i<= jArray.length(); i++){
try {
JSONObject oneObject = jArray.getJSONObject(i);
String dgtype = oneObject.getString("dgtype");
String subtypename = oneObject.getString("subtypename");
String subtypedesc = oneObject.getString("subtypedesc");
String summary = oneObject.getString("summary");
String subtype = oneObject.getString("subtype");
String birthdate = oneObject.getString("birthdate");
String name = oneObject.getString("name");
System.out.println(i);
System.out.println("dgtype: "+dgtype);
System.out.println("subtypename: "+subtypename);
System.out.println("subtypedesc: "+subtypedesc);
System.out.println("summary: "+summary);
System.out.println("subtype: "+subtype);
System.out.println("birthdate: "+birthdate);
System.out.println("name: "+name);
} catch (JSONException e) {
System.out.println("JSON Exception: "+e);
}
}
However I am getting the following exception:
JSON Exception: org.json.JSONException: Value
[
{
"dgtype": "adhoc",
"subtypename": "Person",
"subtypedesc": "null",
"summary": "Junaid (Self)",
"subtype": "person",
"birthdate": "1995-1-23 ",
"name": "Junaid (Self)"
},
{
"dgtype": "adhoc",
"subtypename": "Job",
"subtypedesc": "null",
"summary": "Exa",
"subtype": "person",
"birthdate": "2010-01-30",
"name": "Junaid (Self)"
}
]
at 0 of type org.json.JSONArray cannot be converted to JSONObject
JSON Exception: org.json.JSONException: Index 1 out of range [0..1)
I am following this example. Where am I going wrong? Also notice the missing long brackets in the exception snippet.
You have two arrays, one is within another:
[
[
//Your objects
]
]
You could either change data format so it only has one array, or modify your code:
JSONArray outer = new JSONArray(result);
JSONArray jArray = outer.getJSONArray(0);
jArray JSONArray contain another JSONArray which contain JSONObeject so first get JSONArray and then get all JSONObject from it:
JSONArray oneArray = jArray.getJSONArray(i);
for(int j = 0; j<= oneArray.length(); j++){
JSONObject oneObject = oneArray.getJSONObject(j);
// get dgtype,subtypename,subtypedesc,.. from oneObject
}
As it says, 'JSONArray cannot be converted to JSONObject', You have an array in another array, so
JSONArray jArray1 = new JSONArray(result);
then
JSONArray jArray = jArray1.getJSONArray(0);
Now it will work.
for(int i = 0; i<= jArray.length(); i++){
final JSONArray innerArray = jArray.getJSONArray(i);
for (int a = 0; a < innerArray.length(); a++) {
try {
final JSONObject oneObject = innerArray.getJSONObject(i);
String dgtype = oneObject.getString("dgtype");
String subtypename = oneObject.getString("subtypename");
String subtypedesc = oneObject.getString("subtypedesc");
String summary = oneObject.getString("summary");
String subtype = oneObject.getString("subtype");
String birthdate = oneObject.getString("birthdate");
String name = oneObject.getString("name");
System.out.println(i);
System.out.println("dgtype: "+dgtype);
System.out.println("subtypename: "+subtypename);
System.out.println("subtypedesc: "+subtypedesc);
System.out.println("summary: "+summary);
System.out.println("subtype: "+subtype);
System.out.println("birthdate: "+birthdate);
System.out.println("name: "+name);
} catch (JSONException e) {
System.out.println("JSON Exception: "+e);
}
}
}