How can I sort a JSONArray in JAVA [duplicate] - java

This question already has answers here:
Android how to sort JSONArray of JSONObjects
(6 answers)
Closed 9 years ago.
How to sort a JSONArray of objects by object's field?
Input:
[
{ "ID": "135", "Name": "Fargo Chan" },
{ "ID": "432", "Name": "Aaron Luke" },
{ "ID": "252", "Name": "Dilip Singh" }
];
Desired output (sorted by "Name" field):
[
{ "ID": "432", "Name": "Aaron Luke" },
{ "ID": "252", "Name": "Dilip Singh" }
{ "ID": "135", "Name": "Fargo Chan" },
];

Try this:
//I assume that we need to create a JSONArray object from the following string
String jsonArrStr = "[ { \"ID\": \"135\", \"Name\": \"Fargo Chan\" },{ \"ID\": \"432\", \"Name\": \"Aaron Luke\" },{ \"ID\": \"252\", \"Name\": \"Dilip Singh\" }]";
JSONArray jsonArr = new JSONArray(jsonArrStr);
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArr.length(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
Collections.sort( jsonValues, new Comparator<JSONObject>() {
//You can change "Name" with "ID" if you want to sort by ID
private static final String KEY_NAME = "Name";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_NAME);
valB = (String) b.get(KEY_NAME);
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
//if you want to change the sort order, simply use the following:
//return -valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArr.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
The sorted JSONArray is now stored in the sortedJsonArray object.

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

how i can get data from Json object and array

I get the request but i can't get the jsonarray from json object.
JSONObject ob = JSONObject.fromObject(response.toString());
JSONArray arr = ob.getJSONArray("results");
for (int i = 0; i < arr.size(); i++) {
JSONObject jsonAuth = arr.getJSONObject(i);
String PREFIX = jsonAuth.get("PREFIX").toString();
}
my json:
{
"d": {
"results": [{
"__metadata": {
"type": "ceodo.cco.loc_do.OdataV2.SecuenciasType",
"uri": "com:443/ceodo/cco/loc_do/OdataV2.xsodata/Secuencias('d76fffbe-8c3b-4c66-bd7f-16c9d099d143')"
},
"SEC_ID": "d76fffbe-8c3b-4c66-bd7f-16c9d099d143",
"PREFIX": "B",
"TIPO_NCF": "01",
"NUM_FROM": 50,
"NUM_TO": 100,
"NUM_CURRENT": 25,
"VALID_UNTIL": "\/Date(1556582400000)\/",
"CAJA": "b1c913fc-e319-476f-8295-64782b77de52"
}, {
"__metadata": {
"type": "ceodo.cco.loc_do.OdataV2.SecuenciasType",
"uri": "com:443/ceodo/cco/loc_do/OdataV2.xsodata/Secuencias('f3323600-6bf2-4e90-8856-56390595d748')"
},
"SEC_ID": "f3323600-6bf2-4e90-8856-56390595d748",
"PREFIX": "B",
"TIPO_NCF": "02",
"NUM_FROM": 1,
"NUM_TO": 100,
"NUM_CURRENT": 35,
"VALID_UNTIL": "\/Date(1554249600000)\/",
"CAJA": "c90030fb-030b-4a99-929a-adc72eaf082f"
}]
}
}
Well, you can call the 'd' object first.
The sequence of your json file should be from a d(JSONObject) tag to a results(JSONArray) tag.
Here is code by using another json library
import org.json.JSONArray;
import org.json.JSONObject;
... skip ...
//JSONObject ob = JSONObject.fromObject(resBuf.toString());
JSONObject ob = new JSONObject(resBuf.toString());
if(ob.has("d"))
{
JSONObject dobj = ob.getJSONObject("d");
if(dobj.has("results"))
{
JSONArray arr = dobj.getJSONArray("results");
System.out.println(arr.length());
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonAuth = arr.getJSONObject(i);
String PREFIX = jsonAuth.get("PREFIX").toString();
System.out.println(PREFIX);
}
}
}

Not able to parse JSON Array properly

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

How can i print json objects and array values?

In the Result String i have entire data for that i'm parsing ,i need to print Current Conditions inside values.
current_condition": [ {"cloudcover": "75", "humidity": "71", "observation_time": "06:55 AM", "precipMM": "0.6", "pressure": "1009", "temp_C": "32", "temp_F": "90", "visibility": "10", "weatherCode": "116", "weatherDesc": [ {"value": "Partly Cloudy" } ], "weatherIconUrl": [ {"value": "http:\/\/cdn.worldweatheronline.net\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png" } ], "winddir16Point": "S", "winddirDegree": "170", "windspeedKmph": "9", "windspeedMiles": "6" } ]
This is my json array ,here i need cloudcover ,weatherDescarrays inside values,how can i print those values.
Here what i did is
JSONParser parser = new JSONParser();
Object obj1 = parser.parse(Result);
JSONObject jobj = (JSONObject) obj1;
JSONObject dataResult = (JSONObject) jobj.get("data");
JSONArray current_condition = (JSONArray) dataResult.get("current_condition");
//out.println(current_condition);
for (int i = 0; i < current_condition.size(); i++) {
}
inside for loop how to repeat and print values ,could anybody help me,thanks in advance.
Assuming that you are using org.json, I would iterate over the array as follows:
public static void main(String[] args) {
String json = "{ \"data\": { \"current_condition\": [ {\"cloudcover\": \"75\", \"humidity\": \"71\", \"observation_time\": \"06:55 AM\", \"precipMM\": \"0.6\", \"pressure\": \"1009\", \"temp_C\": \"32\", \"temp_F\": \"90\", \"visibility\": \"10\", \"weatherCode\": \"116\", \"weatherDesc\": [ {\"value\": \"Partly Cloudy\" } ], \"weatherIconUrl\": [ {\"value\": \"http:\\/\\/cdn.worldweatheronline.net\\/images\\/wsymbols01_png_64\\/wsymbol_0002_su‌​nny_intervals.png\" } ], \"winddir16Point\": \"S\", \"winddirDegree\": \"170\", \"windspeedKmph\": \"9\", \"windspeedMiles\": \"6\" } ]}}";
try {
JSONObject jObj = new JSONObject(json);
JSONObject dataResult = jObj.getJSONObject("data");
JSONArray jArr = (JSONArray) dataResult.getJSONArray("current_condition");
for(int i = 0; i < jArr.length();i++) {
JSONObject innerObj = jArr.getJSONObject(i);
for(Iterator it = innerObj.keys(); it.hasNext(); ) {
String key = (String)it.next();
System.out.println(key + ":" + innerObj.get(key));
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
Are you using json simple?, if yes, then try :
for (JSONObject object : current_condition) {
System.out.println("cloudcover : " + object.get("cloudcover"));
System.out.println("humidity : " + object.get("humidity"));
}

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