not getting perfect value for inner arraylist - java

courseName name is clear and I cannot put any value in model class.
private static List<Country> countries = new ArrayList<>();
private ArrayList<String> courseName = new ArrayList<>();
JSONArray datalist = data.optJSONArray("data_list");
for (int i = 0; i < datalist.length(); i++) {
JSONObject jsonObject = datalist.getJSONObject(i);
/*strTitle.add(jsonObject.optString("cat_name_lan1"));
courceidtitle.add(jsonObject.optString("cat_id"));
courseName.clear();*/
strTitle = jsonObject.optString("cat_name_lan1");
JSONArray courseArray = jsonObject.optJSONArray("courses_array");
if (courseArray != null && courseArray.length() > 0) {
JSONObject courceName;
for (int j = 0; j < courseArray.length(); j++) {
courceName = courseArray.optJSONObject(j);
/*courceidchild.add(courceName.optString("cat_id"));*/
courseName.add(courceName.optString("course_name_lan1"));
}
countries.add(new Country(strTitle, courseName));
} else {
countries.add(new Country(strTitle, courseName));
}
courseName.clear();
}
My JSON,
{
"data": {
"data_list": [
{
"cat_id": "5",
"cat_name_lan1": "Office Productivity",
"cat_name_lan2": "ऑफिस प्रोडक्टिविटी",
"cat_name_lan3": "ઓફિસ પ્રોડક્ટિવિટી",
"cat_name_lan4": null,
"cat_name_lan5": null,
"cat_name_lan6": null,
"courses_array": [
{
"course_id": "6",
"course_name_lan1": "Google Docs Primary Level ",
"course_name_lan2": "गुगल डॉक्स प्राथमिक स्तर",
"course_name_lan3": "ગુગલ ડોક્સ પ્રાથમિક સ્તર",
"course_name_lan4": "",
"course_name_lan5": "",
"course_name_lan6": "",
"course_take": 1
},
{
"course_id": "61",
"course_name_lan1": "Financial Function Excel 2016",
"course_name_lan2": "फाइनैन्शल फंक्शन एक्सेल 2016",
"course_name_lan3": "ફાઇનૈન્શલ ફંક્શન એક્સેલ 2016",
"course_name_lan4": "",
"course_name_lan5": "",
"course_name_lan6": "",
"course_take": 0
}
]
},
{
"cat_id": "4",
"cat_name_lan1": "I.T. & Software",
"cat_name_lan2": "आईटी & सोफ्टवेयर",
"cat_name_lan3": "આઈટી & સોફ્ટવેર",
"cat_name_lan4": null,
"cat_name_lan5": null,
"cat_name_lan6": null,
"courses_array": [
{
"course_id": "18",
"course_name_lan1": "Google Forms",
"course_name_lan2": "गुगल फॉर्म्स ",
"course_name_lan3": "ગુગલ ફોર્મ્સ ",
"course_name_lan4": "",
"course_name_lan5": "",
"course_name_lan6": "",
"course_take": 0
},
{
"course_id": "62",
"course_name_lan1": "Google Drive",
"course_name_lan2": "गुगल ड्राईव",
"course_name_lan3": "ગુગલ ડ્રાઈવ ",
"course_name_lan4": "",
"course_name_lan5": "",
"course_name_lan6": "",
"course_take": 1
}
]
}
],
"status": 0,
"message": "Category and courses tree view."
}
}
courseName array is clear out of for loop hence I am getting blank value in model class.

Update your code to
JSONArray courseArray = jsonObject.optJSONArray("courses_array");
if (courseArray != null && courseArray.length() > 0) {
for (int j = 0; j < courseArray.length(); j++) {
// here you should initialize your courceName
JSONObject courceName = courseArray.optJSONObject(j);
courseName.add(courceName.optString("course_name_lan1"));
}
}
countries.add(new Country(strTitle, courseName));

Try this code,
// Initialize countries list
List<Country> countries = new ArrayList<>();
JSONObject jObj = new JSONObject(json);
JSONObject data = jObj.optJSONObject("data");
JSONArray datalist = data.optJSONArray("data_list");
// Iterate data_list JSONArray
for (int i = 0; i < datalist.length(); i++) {
JSONObject jsonObject = datalist.getJSONObject(i);
String strTitle = jsonObject.optString("cat_name_lan1");
// Initialize courseName here
ArrayList<String> courseName = new ArrayList<>();
JSONArray courseArray = jsonObject.optJSONArray("courses_array");
// Iterate courses_array JSONArray
for (int j = 0; j < courseArray.length(); j++) {
JSONObject courceName = courseArray.optJSONObject(j);
courseName.add(courceName.optString("course_name_lan1"));
}
// Add strTitle and courseNames to countries list
countries.add(new Country(strTitle, courseName));
}

Related

How to get data json from array of the year in array android studio?

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

Android Empty List

I am trying to fill a ListView inside an Async Task!
all_items = gson.toJson(profile);
this is the rest
try {
JSONObject object = new JSONObject(all_items);
JSONArray ja = object.getJSONObject("tree").getJSONArray("children");
for (int i = 0; i < ja.length(); i++) {
JSONObject object1 = ja.getJSONObject(i);
if (object1.has("name") && object1.has("percentage")) {
System.out.println(object1.has("name"));//nothing gets printed
HashMap<String, Object> tmp = new HashMap<>();
tmp.put("name", object1.get("name"));
tmp.put("percentage", object1.get("percentage"));
array_list.add(tmp);
}
}
}catch(JSONException e){
e.printStackTrace();
}
Json Array is in this format:
This new code is not outputing nothing,no lists is shown The Json is in this format
{
"id": "*UNKNOWN*",
"processed_lang": "en",
"source": "*UNKNOWN*",
"tree": {
"children": [
{
"children": [
{
"category": "personality",
"children": [
{
"category": "personality",
"children": [
{
"category": "personality",
"id": "Adventurousness",
"name": "Adventurousness",
"percentage": 0.6317251869427992,
"sampling_error": 0.0550028572
No Error is thrown however the list is still empty.
there are basically 3 more children array inside the children array. Your code just gets the top level children and tries to find the attributes inside it
try {
JSONObject object = new JSONObject(all_items);
JSONArray ja = object.getJSONObject("tree").getJSONArray("children");
for (int k = 0; k < ja.size(); k++) {
JSONObject lvlOne = ja.getJSONObject(k);
JSONArray lvlOneArray = lvlOne.getJSONArray("children");
for (int j = 0; j < lvlOneArray.size(); j++) {
JSONObject lvlTwo = lvlOneArray.getJSONObject(i);
JSONArray lvlTwoArray = lvlTwo.getJSONArray("children");
for (int i = 0; i < lvlTwoArray.length(); i++) {
JSONObject object1 = lvlTwoArray.getJSONObject(i);
if (object1.has("name") && object1.has("percentage")) {
System.out.println(object1.has("name"));//nothing gets printed
HashMap<String, Object> tmp = new HashMap<>();
tmp.put("name", object1.get("name"));
tmp.put("percentage", object1.get("percentage"));
array_list.add(tmp);
}
}
}catch(JSONException e){
e.printStackTrace();
}

How to get values from json String

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

Store JSON array value in HashMap and remove duplicate

I have a JSON response which look something like this( its different from user to user)
{
"success": true, "data":
[
{
"mandatory_tag": "My Company",
"id": "topic_1408946825893148"
},
{
"mandatory_tag": "Partners",
"id": "topic_1408946942491149",
},
{
"mandatory_tag": "Industry",
"id": "topic_1408946996510150",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210454810358",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1408947133657152"
},
{
"mandatory_tag": "Competitors",
"id": "topic_1408947071457151",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210621754362",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210704390363",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210794791364"
}
]
}
I am parsing it and trying to store in HashMap, but the key value is duplicating. Can anyone suggest me how can i store all id with same mandatory_tag in one array?
I am new to this so please consider..thanks
try
{
JSONObject jsonMain = new JSONObject(jsonString);
JSONArray dataArray = jsonMain.getJSONArray("data");
for(int i = 0; i < dataArray.length(); i++)
{
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
List<String> arrayID = new ArrayList<String>();
if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
} else
{
List<String> newArrayID = new ArrayList<String>();
newArrayID.add(id);
myMap.put(mandatory_tag, newArrayID);
}
}
And well i got stuck at this now..any good logic please..
A hashmap allows you to store key-value items. I would suggest the HashMap be of type <String,List<String>> so allowing you to store items with the same mandatory_tag in the same list under 1 key.
For example
HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
if (myMap.containsKey(mandatory_tag)) {
List<String> values = myMap.get(mandatory_tag);
if (values!=null) {
values.add(id)
} else {
values = new List<String>();
values.add(id);
}
}
Update
As I wrote in my comment below, the except you added has an error
List<String> arrayID = new ArrayList<String>();
if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
What you are doing here is, if the map already contains the key you are replacing the value associated with the key with a new list which contains only 1 value. What you need to do is update the list of already existing values. Check the code below and make sure you understand the problem. These are fundamentals of programming and you need to understand the logic of what you're doing to advance.
//Somewhere you have declared your HashMap
HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
//then we continue with your excerpt
try {
JSONObject jsonMain = new JSONObject(jsonString);
JSONArray dataArray = jsonMain.getJSONArray("data");
for(int i = 0; i < dataArray.length(); i++) {
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
if(myMap.containsKey(mandatory_tag)) {
List<String> arrayID = myMap.get(mandatory_tag);
arrayID.add(id);
} else {
List<String> newArrayID = new ArrayList<String>();
newArrayID.add(id);
myMap.put(mandatory_tag, newArrayID);
}
}
Create a POJO called TagValues(or whatver name you would like) with variables mandatory_tag,id and then and create an ArrayList<TagValues> in which you can store all the objects.
Thanks for your response, but with help of you guys, i got the solution
`HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
for(int i = 0; i < dataArray.length(); i++)
{
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
if(myMap.isEmpty())
{
arrayID = new ArrayList<String>();
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
else if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
else
{
arrayID = new ArrayList<String>();
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
}`
In those cases, I'd like to use a custom HashMap:
public MMap getData() {
MMap result = new MMap();
JSONArray array = getJSONArrayFromTotalJSON();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String mtag = obj.getString(MANDATORY_TAG);
String id = obj.getString(ID);
result.put(mtag, id);
}
return result;
}
public class MMap extends HashMap<String, List<String>> {
public void put(String key, String value) {
if (!this.containsKey(key))
this.put(key, new ArrayList<String>());
this.get(key).add(value);
}
}

Parsing Facebook FQL Multiquery in Java

I'm having some trouble with parsing an FQL multiquery for Facebook. I don't know how I need to handle the JSONArray with the same name in the result -> fql_result_set. Here is the FQL JSON I got.
{
"data": [
{
"name": "query1",
"fql_result_set": [
{
"uid": uid1,
"eid": eid1,
"rsvp_status": "attending"
},
{
"uid": uid2,
"eid": eid2,
"rsvp_status": "attending"
},
{
"uid": uid3,
"eid": eid3,
"rsvp_status": "attending"
}
]
},
{
"name": "query2",
"fql_result_set": [
{
"uid": uid1,
"name": "name1",
"pic_square": "pic1"
},
{
"uid": uid2,
"name": "name2",
"pic_square": "pic2"
},
{
"uid": uid3,
"name": "name3",
"pic_square": "pic3"
}
]
}
]
}
Here is what I got at the moment in my Java code, but I get nothing in return. The data I get, will eventually go in an ArrayList.
try {
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
JSONArray data = jso.getJSONArray("data");
for(int i = 0; i < data.length(); i++){
JSONObject o1 = data.getJSONObject(i);
JSONArray rs1 = o1.getJSONArray("fql_result_set");
for(int j = 0; j < rs1.length(); j++){
JSONObject rso1 = rs1.getJSONObject(j);
String uid = rso1.getString("uid");
String eid = rso1.getString("eid");
String rsvp = rso1.getString("rsvp_status");
}
JSONObject o2 = data.getJSONObject(i);
JSONArray rs2 = o2.getJSONArray("fql_result_set");
for(int k = 0; k < rs2.length(); k++){
JSONObject rso2 = rs2.getJSONObject(k);
String name = rso2.getString("name");
String pic = rso2.getString("pic_square");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Does anyone know how I need to parse this JSON result?
Thanks in advance!
Solution
try {
people = new ArrayList<Person>();
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
JSONArray data = jso.getJSONArray("data").getJSONObject(0)
.getJSONArray("fql_result_set");
JSONArray data2 = jso.getJSONArray("data").getJSONObject(1)
.getJSONArray("fql_result_set");
for (int i = 0; i < data.length(); i++) {
Person p = new Person();
JSONObject o1 = data.getJSONObject(i);
uid = o1.getString("uid");
p.setUserId(uid);
p.setRsvp_status(o1.getString("rsvp_status"));
for (int j = 0; j < data2.length(); j++) {
JSONObject o2 = data2.getJSONObject(j);
if (p.getUserId().equals(o2
.getString("uid"))) {
p.setName(o2.getString("name"));
p.setPic(o2.getString("pic_square"));
}
}
people.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
// assign the whole result to a JSON Object
JSONObject result = whatever-variable-name
// get 'data' JSONArray
JSONArray array = result.getJSONArray('data')
// loop
for(i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
**
name = obj.getString('name');
}
** at this point obj is "name": "query1",
"fql_result_set": [
{
"uid": uid1,
"eid": eid1,
"rsvp_status": "attending"
},
{
"uid": uid2,
"eid": eid2,
"rsvp_status": "attending"
},
{
"uid": uid3,
"eid": eid3,
"rsvp_status": "attending"
}
]
and name has the value query1 or query2 depending on the loop count. You could you the methods used so far to gain access to fql_result_set": [
{
"uid": uid1,
"eid": eid1,
"rsvp_status": "attending"
},
{
"uid": uid2,
"eid": eid2,
"rsvp_status": "attending"
},
{
"uid": uid3,
"eid": eid3,
"rsvp_status": "attending"
}
] GLHF!
Try this:
String strEvents = new JSONArray(apiResponse).getJSONObject(0).toString();
String strVenues= new JSONArray(apiResponse).getJSONObject(1).toString();
jsonArray = new JSONObject(strEvents).getJSONArray("fql_result_set");
jsonVenues = new JSONObject(strVenues).getJSONArray("fql_result_set");

Categories