Java- Processing Json array based on keys - java

I'm getting this string (from webservice) into a JSONArray,
[{
"textinput": [{
"position": 0,
"dependency": "no",
"id": 0,
"Itype": "textinput"
}, {
"position": 2,
"dependency": "no",
"id": 1,
"Itype": "textinput"
}]
}, {
"textarea": [{
"position": 1,
"type": "textarea",
"dependency": "no",
"id": 0
}]
}]
I need to sort the array by ascending order based on key-"position"
I am using org.json library, the below code is the one so far the code i used
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
Collections.sort( jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get("position");
valB = (String) b.get("position");
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonList.get(i));
}
AALso tried other links in the site.
please help

Try TreeMap, it will automatically sort the array for you. All you have to do is make "position" the Key of TreeMap and JSONObject the value. The treemap will arrange the values in ascending order of the keys.And then you can retrieve the JSONObject values from the treemap.
private TreeMap<Integer,JSONObject> sortedarray = new TreeMap<Integer,JONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
sortedarray.put(Integer.parseInt(jsonArray.getJSONObject(i).get("position")+""),jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
Now if you want it to be a jsonArray only..
JSONArray sortedJsonArray = new JSONArray();
for(int x = 0; x<sortedarray.size();x++)
{
//assuming that positions you get in JSON are always complete like 1,2,3,4,....,10,...,100.
sortedJsonArray.put(sortedarray.get(x));
//assuming that positions you get in JSON are not always complete like 1,3,4,..,10,13,...,100.( misses a few numbers in between like 2 and 11 in this case)
sortedJsonArray.put(sortedarray.get(Integer.parseInt(advanceplay.get(advanceplay.keySet().toArray()[i]))));
}

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

Transform a JsonArray into an ArrayList

I have this json that i got using the YoutubeAPI :
{
"items": [
{
"id": {
"videoId": "ob1ogBV9_iE"
},
"snippet": {
"title": "13 estrellas ",
"description": "Pueden encontrar estas "
}
},
{
"id": {
"videoId": "o9vsXyrola4"
},
"snippet": {
"title": "Rayos CoĢsmicos ",
"description": "Este es un programa piloto "
}
}
]
}
i want to save the fiel "id" on an ArrayList but i have some problems this is the code im using:
JSONArray jsonArray = myResponse.getJSONArray("items");
In this line im creating an JSONarray with the JSONobject i created first
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
list.add(json.getString("videoID"));
} catch (JSONException e) {
e.printStackTrace();
}
}
My question is how can i access to this field? and how can i save it
You've got two main issues. The first is that "videoID" and "videoId" are not the same string. So you're checking for a key that doesn't exist.
Your second problem is that the "videoId" key doesn't exist in the top level object, it's inside the "id" object, so you need to drill down an extra layer to get it:
JSONArray jsonArray = myResponse.getJSONArray("items");
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
JSONObject id = json.getJSONObject("id");
list.add(id.getString("videoId"));
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println(list); // [ob1ogBV9_iE, o9vsXyrola4]
Try with correct case for videoId, like
list.add(json.getString("videoId"));

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

Java Android - How to sort a JSONArray based on keys

I'm getting this string (from a webservice) into a JSONArray like this,
[
{
"lat": "-16.408545",
"lon": "-71.539105",
"type": "0",
"distance": "0.54"
},
{
"lat": "-16.4244317845",
"lon": "-71.52562186",
"type": "1",
"distance": "1.87"
},
{
"lat": "-16.4244317845",
"lon": "-71.52562186",
"type": "1",
"distance": "0.22"
}
]
I need to sort it by the distance key to show the nearest first and farthest last. I didn't try any code because I really don't have any ideas. I'm not using the GSON library, I'm using org.json.JSONArray.
First parse your array in a list
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
then use collection.sort to sort the newly created list
Collections.sort( jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get("distance");
valB = (String) b.get("distance");
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
Insert the sorted values in your array
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonList.get(i));
}
Parse your json object into a model say array-List and sort it using comparator.
ArrayList<ClassObject> dataList = new ArrayList<String>();
JSONArray array = new JSONArray(json);
for(Object obj : jsonArray){
dataList.add(//your data model);
}
Please refer this link for sorting of array-list
http://java2novice.com/java-collections-and-util/arraylist/sort-comparator/
Try this. It should work
ArrayList<JSONObject> array = new ArrayList<JSONObject>();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
try {
array.add(jsonArray.getJSONObject(i));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Collections.sort(array, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
// TODO Auto-generated method stub
try {
return (lhs.getDouble("distance").compareTo(rhs.getDouble("distance")));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
});
And after this you can convert sorted ArrayList array into JSONArray.
JSONArray jsonArray = new JSONArray(array);
String jsonArrayStr = jsonArray.toString();
In kotlin you can do as below
Parse your array in a list
val sortedJsonArray = JSONArray()
val jsonList = ArrayList<JSONObject>()
for (i in 0 until jsonArray.length()) {
jsonList.add(jsonArray.getJSONObject(i))
}
Sort the newly created list
jsonList.sortWith { a, b ->
var valA = String()
var valB = String()
try {
valA = a.get("distance") as String
valB = b.get("distance") as String
} catch (e: JSONException) {
e.printStackTrace()
}
valA.compareTo(valB)
}
Insert the sorted values in your json array
for (i in 0 until jsonArray.length()) {
sortedJsonArray.put(jsonList[i])
}
Thanks to #crysis for his answer.

Categories