To Parse A Json Array - android

I'm trying to parse a json array, where a partcular node, under some conditions comes as a array and sometimes as object.
Example:
{
"children":
{
"id":"3",
"subject":"dddd",
"details":"dddd",
"beginDate":"2012-03-08T00:00:00+01:00",
"endDate":"2012-03-18T00:00:00+01:00",
"campus":
{
"id":"2",
"name":"paris"
}
}
}
and sometimes as:
{"children":
[{
"id":"1",
"subject":"android",
"details":"test",
"beginDate":"2012-03-26T00:00:00+02:00",
"endDate":"2012-04-09T00:00:00+02:00",
"campus":{
"id":"1",
"name":"lille"
}
},
{
"id":"2",
"subject":"lozlzozlo",
"details":"xxx",
"beginDate":"2012-03-14T00:00:00+01:00",
"endDate":"2012-03-18T00:00:00+01:00",
"campus":{
"id":"1",
"name":"lille"
}
}]
}
I have tried using this,
if (jobj123 instanceof JSONArray) {
// It's an array
Log.i("It's an array", "It's an array");
} else if (jobj123 instanceof JSONObject) {
// It's an object
Log.i("It's an object", "It's an object");
}
But the 'if' condition always fails and else loop is executed, Can anyone help me solving this issue.

JSONObject children_sub_category_object = children
.getJSONObject(j).optJSONObject("children");
if (children_sub_category_object != null) {
children_sub_jsonobject = children.getJSONObject(j)
.getJSONObject("children");
Log.e("Object", "Object");
} else {
children_sub_category = children.getJSONObject(j)
.getJSONArray("children");
Log.e("Array", "Array");
}
Try that out. That worked for me well. Let me know what happens.

You have to retrieve and check the type of the the "children" object.
Try this:
if (jobj123.has("children") && jobj123.get("children") instanceof JSONObject) {
// it is a JSONObject
JSONObject children = jobj123.getJSONObject("children");
// handle your children ...
}
else if (jobj123.has("children") && jobj123.get("children") instanceof JSONArray) {
// it is an JSONArray
JSONArray childrenArray = jobj123.getJSONArray("children");
// loop children
for (int i = 0; i < childrenArray.length(); i++)
{
if (childrenArray.get(i) instanceof JSONObject) {
JSONObject children = childrenArray.getJSONObject(i);
// handle your children ...
}
}
}

Pass your String into this function which uses nested try catch. it works:
void parse(String s){
JSONObject jsonObject = null;
try{
jsonObject = new JSONObject(s);
JSONArray jArray = jsonObject.getJSONArray("children");
for(int i = 0;i <jArray.length();i++){
Log.i("array type", jArray.getJSONObject(i).getString("id"));
}
}catch(Exception e){
e.printStackTrace();
try{
JSONObject innerObj = jsonObject.getJSONObject("children");
Log.i("object type",innerObj.getString("id"));
}catch(Exception exx){
exx.printStackTrace();
}
}
}

Related

How to properly parse a Firestore API JSON?

I'm using Google Cloud Firestore API for a project that involves simple retrieval of data from the server database. Having set up everything I can't seem to figure out how to properly parse the returned JSON, as all of my attempts have been unsuccessful.
Using the Firestore package is out of question as this is a defined project.
I have tried the classic approach since Android studio only gets the field part with its HTTPURLConnection.
This is the JSON structure:
{
"documents": [
{
"name": "projects/...",
"fields": {
"name": {
"stringValue": "Q1"
},
"myValues": {
"arrayValue": {
"values": [
{
"stringValue": "First"
}
]
}
},
"index": {
"integerValue": "0"
}
},
"createTime": "2019-05-24T10:07:10.864421Z",
"updateTime": "2019-05-28T07:52:34.445600Z"
}
]
}
Here's my attempt at parsing it:
public ArrayList<Question> parse(String json)
{
ArrayList<Question> list = new ArrayList<Question>();
try {
int indeks=0;
String qName="";
ArrayList<String> answerList= new ArrayList<String>();
JSONObject object = new JSONObject(json);
JSONArray dokumenti = object.getJSONArray("documents");
for (int j = 0; j < dokumenti.length(); j++) {
JSONObject jObject = dokumenti.getJSONObject(j);
if (jObject.has("index")) indeks = jObject.getInt("index");
if (jObject.has("name")) qName= jObject.getString("name");
JSONArray answerArray= jObject.getJSONArray("myValues");
for (int i = 0; i < answerArray.length(); i++) {
try {
String answer= answerArray.getString(i);
answerList.add(answer);
} catch (JSONException e) {
Log.d("OOPS", qName);
}
}
}
list.add(new Question(qName, qName, answerList, answerList.get(indeks), 0));
}
catch(JSONException e)
{
//something
}
return list;
}
Database structure
I expect that all of the documents get parsed and added to the list ArrayList but it seems like nothing happens and I can't find the TAG in the Logcat.
It looks you're trying to get index before accessing its parent fields.
if (jObject.has("index")) indeks = jObject.getInt("index");
In this line you should have gotten before the parent object fields, otherwise you will not have access to index or name.
EDIT
I've been checking your code and you are parsing some things wrong.
Let's go step by step:
You are trying to access to the childs of fields without accessing to their parent.
The solution following your structure would be something like this:
JSONObject jObject = dokumenti.getJSONObject(j);
JSONObject fields = jObject.getJSONObject("fields");
if (fields.has("index") && fields.getJSONObject("index").has("integerValue")) {
indeks = fields.getJSONObject("index").getInt("integerValue");
}
if (fields.has("name") && fields.getJSONObject("name").has("stringValue")) {
qName = fields.getJSONObject("name").getString("stringValue");
}
You're trying to access also the myValues array not respecting the objects hierarchy. The correct way should be something like this:
JSONArray answerArray = fields.getJSONObject("myValues").getJSONObject("arrayValue").getJSONArray("values");
for (int i = 0; i < answerArray.length(); i++) {
try {
String answer = answerArray.getJSONObject(i).getString("stringValue");
answerList.add(answer);
} catch (JSONException e) {
Log.d("OOPS", qName);
}
}
With this changes I have been able to parse the Json you posted without any problem. Here you can find the complete code:
public ArrayList<Question> parse(String json)
{
ArrayList<Question> list = new ArrayList<Question>();
try {
int indeks = 0;
String qName = "";
ArrayList<String> answerList = new ArrayList<String>();
JSONObject object = new JSONObject(json);
JSONArray dokumenti = object.getJSONArray("documents");
for (int j = 0; j < dokumenti.length(); j++) {
JSONObject jObject = dokumenti.getJSONObject(j);
JSONObject fields = jObject.getJSONObject("fields");
if (fields.has("index") && fields.getJSONObject("index").has("integerValue")) {
indeks = fields.getJSONObject("index").getInt("integerValue");
}
if (fields.has("name") && fields.getJSONObject("name").has("stringValue")) {
qName = fields.getJSONObject("name").getString("stringValue");
}
JSONArray answerArray = fields.getJSONObject("myValues").getJSONObject("arrayValue").getJSONArray("values");
for (int i = 0; i < answerArray.length(); i++) {
try {
String answer= answerArray.getString(i);
answerList.add(answer);
} catch (JSONException e) {
Log.d("OOPS", qName);
}
}
}
list.add(new Question(qName, qName, answerList, answerList.get(indeks), 0));
}
catch(JSONException e)
{
//something
}
return list;
}
JavaScript example:
function toValue(field) {
return "integerValue" in field
? Number(field.integerValue)
: "doubleValue" in field
? Number(field.doubleValue)
: "arrayValue" in field
? field.arrayValue.values.map(toValue)
: "mapValue" in field
? toJSON(field.mapValue)
: Object.entries(field)[0][1];
}
function toJSON(doc) {
return Object.fromEntries(
Object.entries(doc.fields ?? {}).map(([key, field]) => [key, toValue(field)])
);
}

How to get 2 json objects at once?

I'm using volley to get json object, I'm getting data like this
{"resultUser":19}
{"resultUser2":13}
How to get either the second one (resultuser2) or both?
try {
JSONObject o = new JSONObject(response);
String data = (String) o.get("resultUser2");
if (!data.equals("")) {
Toast.makeText(getApplicationContext(), "user2 id" + data, Toast.LENGTH_LONG).show();
//UserDetailsActivty.this.finish();
} else {
Toast.makeText(getApplicationContext(), "Ohh! Sorry,,Signing Up Failed ", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
you can use JsonArray to iterate through all the jsonobjects like this
try {
JSONArray jsonArray = new JSONArray(response);
for (int i =0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.get(i);
//do whatever you want to do with the data
}
} catch(Exception e) {
}

Android : How to access a JSONObject

I'm new to Android and I have tried so many options to access the JSONObject which returns from an API call but I couldn't succeed as any of the solutions i looked for didn't work for me.
What i want is to access the JSONObject and keep the Id & Name in a Array. And then populate the Names in a AutoCompleteTextView. How do i properly access the JSONObject. Please help me with this. I'm stuck on this for more than a day.
Following is my Code handling the JSONObject.
#Override
public void processFinish(JSONObject output) {
Toast.makeText(MainActivity.this,"ProcessFinish",Toast.LENGTH_SHORT).show();
allStations = output;
if(output != null){
Toast.makeText(MainActivity.this,output.toString(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this," Connection Failed!",Toast.LENGTH_SHORT).show();
}
}
Following is a sample output of my JSONObject
{
"SUCCESS": true,
"MESSAGE": "Found 398 Results!",
"NOFRESULTS": 3,
"RESULTS": {
"stationList": [
{
"stationCode": "ABN",
"stationID": 3,
"stationName": "ABLA"
},
{
"stationCode": "ADLA",
"stationID": 410,
"stationName": "ADLA"
},
{
"stationCode": "ANM",
"stationID": 11,
"stationName": "AHAMA"
}]
},
"STATUSCODE": "2000"
}
try this
try {
JSONObject obj= output.getJSONObject("RESULTS");
JSONArray dataArray= obj.getJSONArray(“stationList“);
for(int i=0;i<dataArray.length();i++)
{
JSONObject object1=dataArray.getJSONObject(i);
Strind id = object1.getString("stationID");
}
} catch (JSONException e) {
e.printStackTrace();
}
In This code output is your JSONObject result
try this
try {
JSONObject jsonObject = new JSONObject("response");
boolean status= jsonObject.getBoolean("SUCCESS");
String MESSAGE= jsonObject.getString("MESSAGE");
String NOFRESULTS= jsonObject.getString("NOFRESULTS");
String STATUSCODE= jsonObject.getString("STATUSCODE");
JSONObject obj=jsonObject.getJSONObject("RESULTS");
JSONArray jsonarray = obj.optJSONArray("stationList");
for (int i = 0; i < jsonarray.length(); i++){
JSONObject json_data = jsonarray.getJSONObject(i);
Log.e("stationCode",json_data.getString("stationCode"));
Log.e("stationID",json_data.getString("stationID"));
Log.e("stationName",json_data.getString("stationName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried using a JSON Array? For example you could use this method for storage:
JSONObject wgroup = new JSONObject(); //FINAL json object
try { //put initial data
wgroup.put("id", "2");
wgroup.put("user", "someone");
wgroup.put("stime", "2017-02-06 16:30:13");
wgroup.put("etime", "2017-02-06 19:30:13");
wgroup.put("real_dur", 3600);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray1 = new JSONArray(); //Create an array to store ALL Variables
for (int y=0; y< your_array.length ; y++ ){ //loop through your information array
JSONObject output = new JSONObject(); //CREATE a json object to put 1 workout
try {
wgroup.put("id", "2");
wgroup.put("name", "sam");
wgroup.put("age", "3");
wgroup.put("gender", "male");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray2 = new JSONArray(); //CREATE a json array to put 1 array
jsonArray1.put(output); //insert this OBJECT into the ARRAY
}
wgroup.put(jsonArray1);//insert the workouts ARRAY into the original object

Android parse json force stopped

I am parsing a json url: http://www.json-generator.com/api/json/get/bQmwsOmYeq?indent=2 but I failed to make it happen. I am getting an error. What's wrong with this code?
public void parseJsonResponse(String result) {
Log.i(TAG, result);
pageCount++;
try {
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("name");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
CountryInfor country = new CountryInfor();
country.setId(jObject.getString("id"));
country.setName(jObject.getString("name"));
countries.add(country);
}
adapter.notifyDataSetChanged();
if (dialog != null) {
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Replace
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("name");
these two lines by
JSONArray jArray = new JSONArray(result);
Also change
country.setId(jObject.getString("id"));
by
country.setId(jObject.getInt("id") + "");
Because id is of type int not a String.
And it will work fine.
You are getting response like
[
{
"id": ​1,
"name": "Vietnam"
},
{
"id": ​2,
"name": "China"
},
{
"id": ​3,
"name": "USA"
},
{
"id": ​4,
"name": "England"
},
{
"id": ​10,
"name": "Russia"
}
]
So the response is JSONArray and not JSONObject.
Hope it'll help.
Edit
#Override
protected String doInBackground(Void... params) {
// call load JSON from url method
if(loadJSON(this.url) != null) {
return loadJSON(this.url).toString();
}
Log.d("LoadJSONFromUrl", "Failed to get JSONObject.");
return null;
}
You are getting JSONObject null, so the error is.
- You should know what is NullPointerException
the issue is with this line
JSONArray jArray = json.getJSONArray("name");
There is no array with name name. it is failing here. Correct this part to obtain the array properly. Rest looks fine.

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));
}
}
}
}

Categories

Resources