How to parse Complex JSON data of spreadsheet in android? - android

I am new to android, As I am trying to parse the Google's spreadsheet data and it is somewhat complex to me, I have to fetch $t of gsx$tag and $t of gsx$datetime,
This is the link from which we can get the JSON data
https://spreadsheets.google.com/feeds/list/1_AR0zX6Jv0NI_R1HBULbPEIUuJ2mqVbLoHVvLqOwu1I/1/public/values?alt=json
Data look like this
{
"version":"1.0",
"encoding":"UTF-8",
"feed":{
"xmlns":"http://www.w3.org/2005/Atom",
"xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/",
"xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended",
"id":{ },
"updated":{ },
"category":[ ],
"title":{ },
"link":[ ],
"author":[ ],
"openSearch$totalResults":{ },
"openSearch$startIndex":{ },
"entry":[
{
"id":{ },
"updated":{ },
"category":[ ],
"title":{ },
"content":{ },
"link":[ ],
"gsx$id":{
"$t":"1"
},
"gsx$datetime":{
"$t":"3/28/2017"
},
"gsx$tag":{
"$t":"21"
}
},
{ Data here },
{ Data here }
]
}
}
and below is the code I am trying
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject mainObj = new JSONObject(jsonStr);
Log.e(TAG,"JSon Data"+mainObj);
if (mainObj != null) {
Log.e(TAG,"JSon before feed"+mainObj.toString());
JSONArray a = mainObj.getJSONArray("feed");
Log.e(TAG,"JSon after feed"+a.toString());
JSONObject entru= new JSONObject((Map) a);
JSONArray list = entru.getJSONArray("entry");
// JSONArray entryarray = list.getJSONArray("entry");
if (list != null) {
for (int i = 0; i < list.length(); i++) {
JSONObject elem = list.getJSONObject(i);
if (elem != null) {
JSONArray prods = elem.getJSONArray("gsx$tag");
if (prods != null) {
for (int j = 0; j < prods.length(); j++) {
JSONObject innerElem = prods.getJSONObject(j);
if (innerElem != null) {
String sku = innerElem.getString("$t");
Log.e(TAG, "$t" + sku);
HashMap<String, String> contact = new HashMap<>();
contact.put("$t Datetime", sku);
// adding contact to contact list
contactList.add(contact);
}
}
}
}
}
}
}
Help Me in this regards, Thank you in advance

JSONArray a = mainObj.getJSONArray("feed");
Log.e(TAG,"JSon after feed"+a.toString());
JSONObject entru= new JSONObject((Map) a);
replace this 3 lines with the below one
JSONObject entru= mainObj.getJSONObject("feed");
also replace this line
JSONArray prods = elem.getJSONArray("gsx$tag");
with this one
JSONObject prods = elem.getJSONObject("gsx$tag");
I think this is the correct code.
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject mainObj = new JSONObject(jsonStr);
Log.e(TAG,"JSon Data"+mainObj);
if (mainObj != null) {
Log.e(TAG,"JSon before feed"+mainObj.toString());
JSONObject entru= mainObj.getJSONObject("feed");
JSONArray list = entru.getJSONArray("entry");
//JSONArray entryarray = list.getJSONArray("entry");
if (list != null) {
for (int i = 0; i < list.length(); i++) {
JSONObject elem = list.getJSONObject(i);
if (elem != null) {
JSONObject prods = elem.getJSONObject("gsx$tag");
if (prods != null) {
for (int j = 0; j < prods.length(); j++) {
String sku = prods.getString("$t");
Log.e(TAG, "$t" + sku);
HashMap<String, String> contact = new HashMap<>();
contact.put("$t Datetime", sku);
// adding contact to contact list
contactList.add(contact);
}
}
}
}
}
}
Please try this. If this doesn't work please feel free to ask. will help you

You can try using Gson or Jackson

Related

Unable to parse JsonArray inside JsonArray

Hi i was trying to parse a json array inside another json array. Help me with this.
my Json Array is
"results":[
{
"percentcompleted":0,
"requirers":[
{
"activityContext":null,
"auditReason":null,
"assignee":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"targetDate":null,
"assignment":{
"id":"stcur000000000003182",
"displayName":null
},
"learningEvent":{
"id":"curra000000000003001",
"displayName":"Studieplan_test för OKQ8"
},
"jobTypeId":null,
"listIds":null,
"assignedOn":1502084325000,
"source":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"required":true,
"actions":null,
"id":"currh000000000014343"
}
],
"basicdetail":{
"revokedOn":null,
"need_recert":false,
"curriculum":{
"id":"curra000000000003001",
"displayName":"Studieplan_test för OKQ8"
},
"recert_window_starts_on":null,
"createdBy":"vrao",
"updatedBy":"vrao",
"createdOn":1502084325000,
"updatedOn":1508357353000,
"status":{
"intStatus":400,
"description":"Assigned",
"displayName":"Assigned"
},
"type":"CURRICULUM",
"path":{
"id":"track000000000003081",
"displayName":"Studieplan"
},
"acquiredOn":null,
"assignee":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"targetDate":null,
"startedOn":null,
"assignedOnDate":1502084325000,
"heldCertNo":"00003787",
"owner":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"id":"stcur000000000003182",
"assigneeAdditionalDetails":{
"person_no":"VRAO",
"username":"VRAO"
}
},
"isgranted":null
},
and my Code to parse the above data is
public class CurriculaParser {
public ArrayList<CurriculaData> getData(String response)
{
ArrayList<CurriculaData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("results");
CurriculaData data;
for(int i = 0;i<array.length();i++)
{
data = new CurriculaData();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requires");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
JSONObject innerObj = reqObj.getJSONObject("learningEvent");
data.setTitle(innerObj.getString("displayName"));
data.setAssignedOn(reqObj.getString("assignedOn"));
}
JSONArray basicDetailArray = resObj.getJSONArray("basicdetail");
for(int k=0;k<basicDetailArray.length();k++) {
JSONObject basicDetailObj = basicDetailArray.getJSONObject(k);
JSONObject statusObj = basicDetailObj.getJSONObject("status");
data.setStatus(statusObj.getString("displayName"));
data.setAcquiredOn(basicDetailObj.getString("acquiredOn"));
JSONObject assignObj = basicDetailObj.getJSONObject("assignee");
data.setAssignedBy(assignObj.getString("displayName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
and finally i got error like
org.json.JSONException: No value for requires
let me know the error what i made and iam a beginner in dealing with jsonarray inside another jsonarray
org.json.JSONException: No value for requires
JSONException
KEY mismatches on lookups
You should pass requirers instead of requires.
JSONArray reqArray = resObj.getJSONArray("requirers");
fixed the requires TYPO error
public class CurriculaParser {
public ArrayList<CurriculaData> getData(String response)
{
ArrayList<CurriculaData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("results");
CurriculaData data;
for(int i = 0;i<array.length();i++)
{
data = new CurriculaData();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requirers");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
JSONObject innerObj = reqObj.getJSONObject("learningEvent");
data.setTitle(innerObj.getString("displayName"));
data.setAssignedOn(reqObj.getString("assignedOn"));
}
JSONArray basicDetailArray = resObj.getJSONArray("basicdetail");
for(int k=0;k<basicDetailArray.length();k++) {
JSONObject basicDetailObj = basicDetailArray.getJSONObject(k);
JSONObject statusObj = basicDetailObj.getJSONObject("status");
data.setStatus(statusObj.getString("displayName"));
data.setAcquiredOn(basicDetailObj.getString("acquiredOn"));
JSONObject assignObj = basicDetailObj.getJSONObject("assignee");
data.setAssignedBy(assignObj.getString("displayName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}

Get value json not in a array

When I'm JSONObject jsonObj = new JSONObject(jsonStr);
I enter in catch because my json is not a array.
How can I get this format ?
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:8080/PFA/crimes";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String day_week = c.getString("day_week");
String naturecode = c.getString("naturecode");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("day_week", day_week);
contact.put("naturecode", naturecode);
// adding contact to contact list
List.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
JSON:
{
"crime": {
"compnos": "zerezrerzerezzr",
"day_week": "rtkeertoeirtj ,ertkierj",
"domestic": "false",
"fromdate": "ekrjtner",
"id": "1",
"location": "etritkjrtoijty",
"main_crimecode": "oijereriotjeroi",
"month": "455",
"naturecode": "zetzeeztet",
"reportingarea": "58",
"reptdistrict": "zorigjrgoijtoi",
"shift": "rektenrloj",
"shooting": "true",
"streetname": "kjrtnerkj",
"ucrpart": "irtjeroitejroirj",
"weapontype": "kejfnergkrtnh",
"x": "11",
"xstreetname": "zekjrnetk",
"y": "11",
"year": "45"
}
}
JsonObject crime = jsonObj.getJsonObject("crime");
JsonObject compnos = crime.getJsonObject("compnos");
.
..
...
There is no jsonArray in your json value. Give up to get jsonArray.
Try this:
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonMetaObject = jsonMasterObject.getJSONObject("crime");
instead of
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray data = jsonObj.getJSONArray("crime");
Because you get jsonObject in key of crime not JsonArray.

JSONArray parsing a multidimensional array

I have an array jArray in the format :
{"users":[
{
"user_id":6,
"user_name":"Ted Vanderploeg",
"email":"test5#test.com",
"additional_info":[["HP","Chief Sales Officer","","",1]]
},
{
"user_id":59,
"user_name":"Lindsay White",
"email":"test12260#test.com",
"additional_info":[["Microsoft","Global Head","","",1]]
}
]
}
Now I need to get the value "Microsoft" from additional_info array. This is what I'm trying :
for(int i=0;i<jArray.length();i++) {
JSONObject jsonObject = new JSONObject(jArray.getString(i));
String workInfo = jsonObject.getString("additional_info");
Log.i("MyActivity", "got work obj as " + workInfo.toString());
}
Now I get workInfo as [["Microsoft","Global Head","","",1]]. Stuck on how to proceed next, to get the value Microsoft.
it looks like a JSONArray inside a JSONArray
for(int i=0;i<jArray.length();i++) {
JSONObject jsonObject = new JSONObject(jArray.getString(i));
JSONArray workinfo = jsonObject.optJSONArray("additional_info");
if (workinfo != null) {
for(int j=0;j<workinfo.length();j++) {
JSONArray values = workinfo.optJSONArray(j);
for(int z=0;z<values.length();z++) {
Log.i("MyActivity", "got work obj as " + values.optString(z));
}
}
}
}

How to get particular values from JSON response by using Android code?

I need to get Particular Object values ( A, B, C, D) and related key values (#"name" ). After getting (A, B, C, D ) object values I need to list out into list view Android. Here below I have posted my sample code and response. Please help me.
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
My JSON Response :
{"response" : [ {
"A" : [ {
"name" : "tango"
},
{
"name" : "ping"
}
],
"B" : [ {
"name" : "tango"
},
{
"name" : "ping"
}
]
} ]}
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
You can get dynamic keys like this
JSONObject responseDataObj = new JSONObject(responseData);
JSONArray responseArray = responseDataObj.getJSONArray("response");
for (int i = 0; i < responseArray.length(); i++) {
nodes = new ArrayList<ArrayList<String>>();//nodes ArrayList<ArrayList<String>> declared globally
nodeSize = new ArrayList<Integer>();//nodeSize ArrayList<Integer> declared globally
JSONObject obj = responseArray.getJSONObject(i);
Iterator keys = obj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
//store key in an arraylist which is A,B,...
// get the value of the dynamic key
JSONArray currentDynamicValue = obj.getJSONArray(currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
int sizeInArrayList = jsonrraySize + 1;
nodeSize.add(sizeInArrayList);
if(jsonrraySize > 0) {
for (int ii = 0; ii < jsonrraySize; ii++) {
nameList = new ArrayList<String>();//nameList ArrayList<String> declared globally
if(ii == 0) {
JSONObject nameObj = currentDynamicValue.getJSONObject(ii);
String name = nameObj.getString("name");
System.out.print("Name = " + name);
//store name in an arraylist
nameList.add(name);
}
}
}
nodes.add(nameList);
}
}
You can use following method to parse your response and handle output as per requirement.
private void parseJson(String res) {
try {
JSONObject mainObject = new JSONObject(res);
JSONArray response = mainObject.getJSONArray("response");
for (int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
JSONArray A = obj.getJSONArray("A");
for (int j = 0; j < A.length(); j++) {
JSONObject objA = A.getJSONObject(j);
String name = objA.getString("name");
// use or store name here
}
JSONArray B = obj.getJSONArray("B");
for (int k = 0; k < B.length(); k++) {
JSONObject objB = B.getJSONObject(k);
String name = objB.getString("name");
// use or store name here
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This may work for you :
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts;
contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
JSONArray jsonArrayA=new JSONArray();
jsonArrayA=c.getJSONArray("A");
for(int j=0;j<jsonArrayA.length();j++){
String name=jsonArrayA.getJSONObject(j).getString("name");
Log.e("Name","name of jsonarray A "+i+" "+name);
}
JSONArray jsonArrayB=c.getJSONArray("B");
for(int k=0;k<jsonArrayB.length();k++){
String name=jsonArrayB.getJSONObject(k).getString("name");
Log.e("Name","name of jsonarray B "+i+" "+name);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}

How to read status from json response

I have a json response below.
{
"Table":[
{
"status":"failed",
"message":"Questions exausted for the Course"
}
]
}
I have to read status from the response. I have tried as below. But I am unable to read. Please help me guys.
if (result != null
&& !result.toLowerCase()
.startsWith("{\"status\":\"invalid") ) {
mysql.setLastRowCount(lastrowcount);
System.out.println("PE result in : " + result);
try {
JSONObject resultJson = new JSONObject(result);
JSONArray resultArray = resultJson.getJSONArray("Table");
String status=resultJson.getString("status");
System.out.println("Ravi Today "+status);
for (int i = 0; i < resultArray.length(); i++) {
try {
JSONObject tempJSONOBJECT = resultArray
.getJSONObject(i);
bean.setQuestion(tempJSONOBJECT
.getString(Constants.TAG_QUESTION));
bean.setOption1(tempJSONOBJECT
.getString(Constants.TAG_OPT1));
bean.setOption2(tempJSONOBJECT
.getString(Constants.TAG_OPT2));
bean.setOption3(tempJSONOBJECT
.getString(Constants.TAG_OPT3));
bean.setOption4(tempJSONOBJECT
.getString(Constants.TAG_OPT4));
bean.setOption5(tempJSONOBJECT
.getString(Constants.TAG_OPT5));
bean.setOption6(tempJSONOBJECT
.getString(Constants.TAG_OPT6));
bean.setOption7(tempJSONOBJECT
.getString(Constants.TAG_OPT7));
bean.setOption8(tempJSONOBJECT
.getString(Constants.TAG_OPT8));
bean.setRightAnswer(tempJSONOBJECT
.getString(Constants.TAG_ANSWER));
bean.setMedia(tempJSONOBJECT
.getString(Constants.TAG_MEDIA));
bean.setNumberOfOptions(tempJSONOBJECT
.getInt(Constants.TAG_NO_OPTIONS));
bean.setOptionMode(tempJSONOBJECT
.getString(Constants.TAG_MULTI_SELECT));
bean.setExplanation(tempJSONOBJECT
.getString(Constants.TAG_EXPLANATION));
bean.setQuestionID(tempJSONOBJECT
.getString(Constants.TAG_QID));
bean.setStatus(tempJSONOBJECT
.getString(Constants.TAG_STATUS));
bean.setMessage(tempJSONOBJECT
.getString(Constants.TAG_MESSAGE));
bean.setSubjectID(subjectid);
mysql.addToQuestionsTable(bean);
} catch (Exception _ex) {
_ex.printStackTrace();
}
if (tablehasrows == false) {
if (mysql.getTableRowCount("questionmastermain",
"SUBJECT_ID", subjectid) > 0) {
mysql.getNextQuestion(subjectid, false);
tablehasrows = true;
}
}
}
Try like below:
JSONObject resultJson = new JSONObject(result);
JSONArray resultArray = resultJson.getJSONArray("Table");
for (int i = 0; i < resultArray.length(); i++) {
JSONObject b = venues.getJSONObject(i);
String status = b.getString("status");
}
Try this,,,
if(result!=null){
try {
JSONObject jsonObj =new JSONObject(result);
tablejsonarray=jsonObj.getJSONArray("Table");
for(int i=0;i<tablejsonarray.length();i++){
JSONObject l=tablejsonarray.getJSONObject(i);
status=l.getInt("status");
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Categories

Resources