Please help me for parsing this json Array response.
This is response json response.
The problem is split "tag_id",tag_name
{
"tag": "allcompanyprofiles",
"success": 1,
"error": 0,
"searchresult": [{
"id": "146",
"name": "SJB Bookkeeping and Accounting",
"slug": "sjb-bookkeeping-and-accounting",
"contact_name": "Bernard Newman",
"category_id": "7",
"description": "hello",
"lon": "-79.787231600000",
"lat": "43.360581400000",
"address": "3425 Harvester unit 206",
"city": "Burlington",
"state": "Ontario",
"postcode": "L7N 3M7",
"country": "CA",
"phone": "905-335-0081",
"email": "sjb#sjbbookkeeping.com",
"time_frame": "Morning,Afternoon,All Day",
"onsite_requirements": "WHIMIS TRAINING",
"position": "Accounting, Administration",
"oyap": "No",
"shsm": "Yes",
"summer": "Yes",
"virtual": "No",
"website": "sjbbookkeeping.com\/",
"user_id": "1",
"title": "Finance\/Accounting",
"dlc_slug": "financeaccounting",
"tag_id": ["47", "79"],
"tag_name": ["administration", "accounting"]
}, {
"id": "145",
"name": "Length Hair Bar",
"slug": "length-hair-bar",
"contact_name": "Amalea",
"category_id": "29",
"description": "hello",
"lon": "-79.394569700000",
"lat": "43.675291300000",
"address": "162A Davenport Road",
"city": "Toronto",
"state": "Ontario",
"postcode": "M5R 1J2",
"country": "CA",
"phone": "416-823-3755",
"email": "lengthhairbar#yahoo.com",
"time_frame": "Morning,Afternoon,All Day",
"onsite_requirements": "WHIMIS TRAINING",
"position": "Hair Stylist Assistant, Customer Service",
"oyap": "Yes",
"shsm": "Yes",
"summer": "Yes",
"virtual": "No",
"website": "",
"user_id": "1",
"title": "Esthetics",
"dlc_slug": "esthetics",
"tag_id": ["178", "177", "179"],
"tag_name": ["stylist", "hair", "esthetics"]
}
]
}
This is my android code.
JSONObject jobjsearch=new JSONObject(strjson);
tag_list=jobjsearch.getString("tag");
success_list=jobjsearch.getString("success");
error_list=jobjsearch.getString("error");
// Total Result Counted
total_count = jobjsearch.getString("totalcount");
Log.v("TagSearch",tag_list);
Log.v("SuccessSearch",success_list);
Log.v("ErrorSearch",error_list);
//JsonArray Working
JSONArray jarr_list =jobjsearch.getJSONArray("searchresult");
for (int i=0; i<jarr_list.length(); i++) {
JSONObject obbj=jarr_list.getJSONObject(i);
/////////////////////////// Tagsid
tagsid_default=obbj.getString("tag_id");
arrtagsid_list.add(tagsid_default);
String CurrentString = "Fruit: they taste good";
String[] separated = CurrentString.split(":");
//Tagsname
tagsname_default=obbj.getString("tag_name");
arrtagsname_list.add(tagsname_default);
/////////////////////////////////
wesite_default=obbj.getString("website");
arrweb_list.add(wesite_default);
email_default=obbj.getString("email");
name_list = obbj.getString("name");
arrname_list.add(name_list);
Log.v("Companyname",name_list);
// allNames.add(name);
address_list = obbj.getString("address");
arraddress_list.add(address_list);
Log.v("Companyaddress",address_list);
city_list = obbj.getString("city");
arrcity_list.add(city_list);
Log.v("Companycity",city_list);
state_list = obbj.getString("state");
arrstate_list.add(state_list);
Log.v("Companystate",state_list);
country_list = obbj.getString("country");
arrcountry_list.add(country_list);
Log.v("Companycountry",country_list);
//categorytitle
categoryid_list=obbj.getString("title");
arrcategoryid_list.add(categoryid_list);
Log.v("category",categoryid_list);
//title_list=obbj.getString("title");
//arrtitle_list.add(title_list);
intro_list=obbj.getString("intro");
arrintro_list.add(intro_list);
///categoryid
str_categoryid=obbj.getString("category_id");
arrcategryid_list.add(str_categoryid);
//get id in integer variable
//pos=obbj.getInt("id");
//arrid_list.add(pos);
//get id in string variable
str_pos=obbj.getString("id");
arrayid_list.add(str_pos);
Log.e("DefaultPosition"+pos,"");
//setset.setId(obbj.getString("id"));
//setset.setName(obbj.getString("name"));
}
Those are JSONArray's. Treat them as a JSONArray.
Change
tagsid_default=obbj.getString("tag_id");
arrtagsid_list.add(tagsid_default);
to
JSONArray tempId = obbj.getJSONArray("tag_id");
for(int i = 0; i< tempId.length(); i++)
{
arrtagsid_list.add(tempId.get(i).toString());
}
And
Change
tagsname_default=obbj.getString("tag_name");
arrtagsname_list.add(tagsname_default);
to
JSONArray tempName = obbj.getJSONArray("tag_name");
for(int i = 0; i< tempName.length(); i++)
{
arrtagsname_list.add(tempName.get(i).toString());
}
Note: I strongly feel you should read about JSON fist before trying to parse it, so that you don't make mistakes like this. Here are basics of JSON
Related
I've been working on making a simple weather app that displays the temperature, a description of the weather and the location. I'm able to get the location but can't figure out how to get the description of the weather from OpenWeatherMap and it's been bugging me for a few hours now. This is the part of the code in which I have this information laid out:
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject weatherDatas = new JSONObject(jsonObject.getString("main"));
double temperature = Double.parseDouble(weatherDatas.getString("temp"));
int tempIn = (int) (temperature*1.8-459.67);
String placeName = (String) jsonObject.get("name");
MainActivity.tempeartureTextView.setText("" + tempIn);
MainActivity.placeTextView.setText(placeName);
Log.i("it made it", "to end of DownloadTask");
//using http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b1b15e88fa797225412429c1c50c122a1 with zip code
} catch (Exception e) {
e.printStackTrace();
}
}
But for the life of me I cannot figure out how to get the description.
The rest of the code is all here: MainActivity: http://pastebin.com/e2NtTSiP
DownloadTask: http://pastebin.com/ScEREz52
I followed a youtube tutorial on this so I don't quite understand everything but I kinda wanna just do it over and over again till I can get it right.
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
MainActivity.descriptionTextView.setText(description);
}
This fixed it for me!
if your JSON response is following :
{
"coord": {
"lon": -122.08,
"lat": 37.39
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
"base": "stations",
"main": {
"temp": 277.14,
"pressure": 1025,
"humidity": 86,
"temp_min": 275.15,
"temp_max": 279.15
},
"visibility": 16093,
"wind": {
"speed": 1.67,
"deg": 53.0005
},
"clouds": {
"all": 1
},
"dt": 1485788160,
"sys": {
"type": 1,
"id": 471,
"message": 0.0116,
"country": "US",
"sunrise": 1485789140,
"sunset": 1485826300
},
"id": 5375480,
"name": "Mountain View",
"cod": 200
}
In order to get weather description from the response,
get "weather" array
for each JSON object present inside weather array, get the "description" property of the JSON object
JSONObject obj = new JSONObject(response);
JSONArray arr = obj.getJSONArray("weather");
for (int i = 0; i < arr.length(); i++) {
JSONObject each = arr.get(i);
each.getString("description");
}
I get JSON
{
"id_servicio": "1",
"id_motoboy": "1",
"nombre": "Juan Alexander",
"apellido": "Osorio Obreque",
"rut": "1111111",
"direccion": "Luis uribe 3690",
"telefono1": "1223214",
"comentario": "lorem ipsum",
"referencia": "Al lado del negocio Don Goyito",
"id_estado": "3",
"fecha_hora": "2015-01-13 19:51:27",
"created_at": "2015-01-13 17:51:27",
"updated_at": "-0001-11-30 00:00:00",
"productos": [
{
"id_producto": "1",
"id_empresa": "1",
"nombre": "Cuenta Rut",
"descripcion": "Mayor de 18 aƱos",
"estado": "1",
"created_at": "2015-01-13 13:04:00",
"updated_at": "-0001-11-30 00:00:00",
"pivot": {
"id_servicio": "1",
"id_producto": "1"
}
},
{
"id_producto": "2",
"id_empresa": "1",
"nombre": "Chilena",
"descripcion": "Sueldo mayor a 300.000.-",
"estado": "1",
"created_at": "2015-01-14 13:59:31",
"updated_at": "-0001-11-30 00:00:00",
"pivot": {
"id_servicio": "1",
"id_producto": "2"
}
}
]
}
So I create button in android with the information of productos
JSONArray jsonArray = new JSONArray(tmp.getString("productos"));
Button bt[] = new Button[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i ++){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
bt[i] = new Button(DetalleServicioActivity.this);
bt[i].setText(jsonArray.getJSONObject(i).getString("nombre"));
bt[i].setTextColor(Color.parseColor("#ffffff"));
bt[i].setBackgroundColor(Color.parseColor("#17498D"));
bt[i].setLayoutParams(params);
bt[i].setEnabled(false);
bt[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
rl.addView(bt[i]);
}
What I need is to save the identifier(id_producto) from the product in the button, of such way to know that button were pressed (selected) by the user.
How can I do that??
You can extends Button to a new class.
public Class CustomButton extends Button {
// Write your own methods & logic here
}
Use btn.setTag(productId) then String productId = (String)btn.getTag()
You can add id in the buttons tag (button[i].setTag(id)...) and in onClick(View v).. you can get the tag to verify which one is clicked by doing ((Button)view).getTag() // will return the id passed before
You can do that in at least two ways:
1 Tag (it's a field where you can store custom data)
bt[i].setTag(jsonArray.getJSONObject(i).getString("id_producto"));
2 Closure (just pass the data to the listener)
bt[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String productId = jsonArray.getJSONObject(i).getString("id_producto");
}
});
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
#Override
protected String doInBackground(String... params) {
try{
JSONParser jParser = new JSONParser();
String url="http://earlykid.com/android/?page=2";
IdArray=jParser.getJSONFromUrl(url);
Log.e("Fetch Data",IdArray.toString());
mLatestList.clear();
for(int i=0;i<IdArray.length();i++){
try{
JSONObject jObject;
mKids=new Kids();
jObject=IdArray.getJSONObject(i);
mKids.SetTotalPages(jObject.getString("totalItems"));
mKids.SetCurrentPage(jObject.getString("currentPage"));
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Log.e("log_tag", "Failed data was:\n" + IdArray);
}
}
}catch(Exception e){
}
return null;
}
#Override
protected void onPostExecute(String result) {
mProgress.dismiss();
}
When i fetch the data from this code.it shows me error.
Logcat here:-
error parsing data org.json.JSONException: Value {"totalItems":38,"currentPage":"2","items":[{"id":"Atb1lE9_wzk","title":"ABCD Alphabets Song - Songs for Kids","category":"Education","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/Atb1lE9_wzk\/hqdefault.jpg"},{"id":"UXeeSU0QNro","title":"The rich man and his sons story - Animated Stories for Kids","category":"Education","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/UXeeSU0QNro\/hqdefault.jpg"},{"id":"HmiyKDYrELk","title":"Here we go round the mulberry bush - Nursery Rhyme for Kids","category":"Education","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/HmiyKDYrELk\/hqdefault.jpg"},{"id":"9TLnCurMs5c","title":"Old Mac Donald had a farm - Nursery Rhymes for Kids","category":"Education","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/9TLnCurMs5c\/hqdefault.jpg"},{"id":"DPQ_5GR_MMo","title":"Five Little Monkeys jumping on the bed - Nursery Rhymes","category":"Education","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/DPQ_5GR_MMo\/hqdefault.jpg"},{"id":"CvwHp2xFlJw","title":"Rain Rain go away - Nursery Rhyme","category":"Education","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/CvwHp2xFlJw\/hqdefault.jpg"},{"id":"WEVA9iF6i3s","title":"I'm a little teapot Nursery Rhyme with lyrics","category":"Education","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/WEVA9iF6i3s\/hqdefault.jpg"},{"id":"TQHyRssAM5Y","title":"Ten little fingers ten little toes - Nursery Rhyme","category":"Education","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/TQHyRssAM5Y\/hqdefault.jpg"},{"id":"fDGOlmgF1NE","title":"Jingle Bells Christmas Song","category":"Education","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/fDGOlmgF1NE\/hqdefault.jpg"},{"id":"Y83fbhN6FBk","title":"Pussy Cat Pussy Cat where have you been? - Nursery Rhyme","category":"Film","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/Y83fbhN6FBk\/hqdefault.jpg"},{"id":"UuqNHZEIwEI","title":"Thank you for the world so sweet - Kids Song","category":"Film","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/UuqNHZEIwEI\/hqdefault.jpg"},{"id":"g0u1iWUmg8Q","title":"Ding dong bell - Nursery Rhyme","category":"Film","thumbnail":"http:\/\/www.earlykid.com\/android\/timthumb.php?w=600&h=330src=http:\/\/i1.ytimg.com\/vi\/g0u1iWUmg8Q\/hqdefault.jpg"}]
What you are getting is a JSONObject from this url http://earlykid.com/android/?page=2
You have this
IdArray=jParser.getJSONFromUrl(url); // wrong. you get a json object
{ represents a json object node
[ represents a json array node
Your json
{
"totalItems": 38,
"totalPages": 3,
"itemsPerPage": 12,
"currentPage": "2",
"items": [
{
"id": "Atb1lE9_wzk",
"category": "Education",
"title": "ABCD Alphabets Song - Songs for Kids",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/Atb1lE9_wzk/hqdefault.jpg"
},
{
"id": "UXeeSU0QNro",
"category": "Education",
"title": "The rich man and his sons story - Animated Stories for Kids",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/UXeeSU0QNro/hqdefault.jpg"
},
{
"id": "HmiyKDYrELk",
"category": "Education",
"title": "Here we go round the mulberry bush - Nursery Rhyme for Kids",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/HmiyKDYrELk/hqdefault.jpg"
},
{
"id": "9TLnCurMs5c",
"category": "Education",
"title": "Old Mac Donald had a farm - Nursery Rhymes for Kids",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/9TLnCurMs5c/hqdefault.jpg"
},
{
"id": "DPQ_5GR_MMo",
"category": "Education",
"title": "Five Little Monkeys jumping on the bed - Nursery Rhymes",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/DPQ_5GR_MMo/hqdefault.jpg"
},
{
"id": "CvwHp2xFlJw",
"category": "Education",
"title": "Rain Rain go away - Nursery Rhyme",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/CvwHp2xFlJw/hqdefault.jpg"
},
{
"id": "WEVA9iF6i3s",
"category": "Education",
"title": "I'm a little teapot Nursery Rhyme with lyrics",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/WEVA9iF6i3s/hqdefault.jpg"
},
{
"id": "TQHyRssAM5Y",
"category": "Education",
"title": "Ten little fingers ten little toes - Nursery Rhyme",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/TQHyRssAM5Y/hqdefault.jpg"
},
{
"id": "fDGOlmgF1NE",
"category": "Education",
"title": "Jingle Bells Christmas Song",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/fDGOlmgF1NE/hqdefault.jpg"
},
{
"id": "Y83fbhN6FBk",
"category": "Film",
"title": "Pussy Cat Pussy Cat where have you been? - Nursery Rhyme",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/Y83fbhN6FBk/hqdefault.jpg"
},
{
"id": "UuqNHZEIwEI",
"category": "Film",
"title": "Thank you for the world so sweet - Kids Song",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/UuqNHZEIwEI/hqdefault.jpg"
},
{
"id": "g0u1iWUmg8Q",
"category": "Film",
"title": "Ding dong bell - Nursery Rhyme",
"thumbnail": "http://www.earlykid.com/android/timthumb.php?w=600&h=330src=http://i1.ytimg.com/vi/g0u1iWUmg8Q/hqdefault.jpg"
}
]
}
Parsing
try {
JSONObject jb = new JSONObject(myjsonstring);
String totalitems = jb.getString("totalItems");
Log.i("......", "" + totalitems);
String totalpages = jb.getString("totalPages");
String itemsPerPage = jb.getString("itemsPerPage");
String currentPage = jb.getString("currentPage");
JSONArray jarr = jb.getJSONArray("items");
for (int i = 0; i < jarr.length(); i++) {
JSONObject jb1 = jarr.getJSONObject(i);
String id = jb1.getString("id");
String categoy = jb1.getString("category");
String title = jb1.getString("title");
String pic = jb1.getString("thumbnail");
Log.i("........", id);
}
} catch (Exception e) {
}
Try this :
JsonObject oJsonObject = new JSONObject(myjsonstring);
if(oJsonObject.has("items"))
{
oJsonArray = oJsonObject.getJSONArray("items");
for(int i = 0; i < oJsonArray.length(); i++)
{
String id = oJsonArray.getJSONObject(i).getString("id");
String title = oJsonArray.getJSONObject(i).getString("title");
String category = oJsonArray.getJSONObject(i).getString("category");
String thumbnail = oJsonArray.getJSONObject(i).getString("thumbnail");
}
}
Actually in your JSON you have missed a } at the end of JOSN data so it is not a vlid JSON which you have posted over here
user can add items to cart and simultaneously an url will be fired and an json will be returned..user can add any number of products..each product has an unique product_id.now each product can have many suppliers..suppliers also have unique supplier_id..for all the items added into the cart supplier may be common for few..say we have 5products into cart and..supllier1(having unique id) supplies 3products and supplier2(having unique id) supplies 2products..now i have found out and added unique supplier_id's in a array list..in each json object there is a field called price..I have to add the prices for a unique supplier..so for 2suppliers 2 seperate prices will be shown..(1st for supplier1 by adding prices of 3products he supplies)and other for supplier2..
part of json is
{
"BasketItemID": "4455",
"BasketID": "11",
"ProductID": "12909",
"Qty": "1",
"SupplierID": "7",
"Code": "END10-001",
"Name": "ENDO STOPPERS (100)",
"Price": "5.72",
"GST": "0.64",
"PriceGST": "6.36",
"Brand": "DENT AMERICA",
"Thumbnail": null,
},
{
"BasketItemID": "4464",
"BasketID": "11",
"ProductID": "12914",
"Qty": "1",
"SupplierID": "7",
"Code": "INS52-361",
"Name": "AMALGAM GUN CVD 45' PLASTIC",
"Price": "17.00",
"GST": "1.70",
"PriceGST": "18.70",
"Brand": "LARIDENT",
"Thumbnail": null,
},
{
"BasketItemID": "4465",
"BasketID": "11",
"ProductID": "13863",
"Qty": "1",
"SupplierID": "5",
"Code": "9516068",
"Name": "Tofflemire Bands #3 0015 Pkt 12",
"Price": "2.24",
"GST": "0.22",
"PriceGST": "2.47",
"Brand": "Rand",
"Thumbnail": null,
},
so how can i add the prices?
If your problem revolves around parsing a JSON array you may want to check out the example here. Then you would filter by supplier, feel free to let me expand if you want to make your requirements more explicit.
It would look something like this (not tested)
Integer id;
Map<Integer, Double> sums;
...
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("SupplierID")) {
id = reader.nextInt();
} else if (name.equals("Price")) {
if(!sums.containsKey(id)){
sums.put(id, reader.nextDouble());
}
else{
Double f = (Double) sums.get(id);
sums.put(id, f+reader.nextDouble());
}
} else {
reader.skipValue();
}
}
I'm trying to create a list of "events" for an agenda.
To do this, I recieve a JSON response which contains several month objects, which in turn contain an array of event-objects.
When I receive my response, all months are ordered, as shown below:
{
"Agenda/Future": {
"November 2011/0": [
{
"id": "5710",
"eventid": "",
"name": "test7",
"startdate": "nov 9",
"datecompute": "2011-11-09T12:00:00",
"group_month": "November 2011",
"flg_Data": "Database"
},
{
"id": "5707",
"eventid": "",
"name": "test4",
"startdate": "nov 17",
"datecompute": "2011-11-17T12:00:00",
"group_month": "November 2011",
"flg_Data": "Database"
},
{
"id": "5704",
"eventid": "",
"name": "test",
"startdate": "nov 30",
"datecompute": "2011-11-30T12:00:00",
"group_month": "November 2011",
"flg_Data": "Database"
}
],
"December 2011/1": [
{
"id": "5705",
"eventid": "",
"name": "test2",
"startdate": "dec 28",
"datecompute": "2011-12-28T12:00:00",
"group_month": "December 2011",
"flg_Data": "Database"
}
],
"November 2013/2": [
{
"id": "5706",
"eventid": "",
"name": "test3",
"startdate": "nov 1",
"datecompute": "2013-11-01T12:00:00",
"group_month": "November 2013",
"flg_Data": "Database"
},
{
"id": "5708",
"eventid": "",
"name": "test5",
"startdate": "nov 15",
"datecompute": "2013-11-15T12:00:00",
"group_month": "November 2013",
"flg_Data": "Database"
},
{
"id": "5709",
"eventid": "",
"name": "test6",
"startdate": "nov 15",
"datecompute": "2013-11-15T12:00:00",
"group_month": "November 2013",
"flg_Data": "Database"
}
]
}
}
First there is November 2011, then December 2011, and finally November 2013.
However after parsing this response, the order has changed to November 2011, November 2013, December 2011.
Like so:
Obviously, this can cause quite some confusion.
My theory is that due to the use of JSONArray eventNames = agenda.names();, which gets the names of the month objects, the order changes to one based on the actual month, not the year. This has been confirmed after adding another event in March 2022, and this event ends up first.
I checked through my code, and nowhere can I find any sort of function that would change the ordering, making the names(); the most probably culprit.
My question is, how can I make sure the objects in my initial JSONArray get ordered by the month + year, rather then just the month. Removing the names() method is not an option, considering the fact that the objectnames for the months are dynamic (based on month+year). I also would rather not change to a different parsing system (GSON, Jackson), since this is the only one that has been succesfull at parsing my reponse (see previous asked questions).
Eventually managed to fix it by looping over an array containing the full names, and then checking whether that name contained any of the parts from the ordered list (the one containing the years + id). If the string contains that part, add it to a new array on the position of the year+id it contained. Code can be found below
String[] test = new String[eventNames.length()];
String[] test2;
for (int x = 0; x < eventNames.length(); x++){
//System.out.println(eventNames.get(x).toString());
String[] xx = eventNames.get(x).toString().split(" ");
test[x] = xx[1];
}
Arrays.sort(test);
String[] test3 = new String[eventNames.length()];
for(int q = 0; q < eventNames.length(); q++){
String str = eventNames.get(q).toString();
for(int p = 0; p < test.length; p++){
if(str.contains(test[p])){
test3[p] = str;
}
}
}
System.out.println(test.toString());
for (int x = 0; x < eventNames.length(); x++){
System.out.println("maand :"+x+" "+test3[x]);
}
I woudl speculate that JSON Object is backed with map, and names does merely Map.keys() - order of keys is undefined. At leas API spec says nothing about any sorting / ordering of individual fields - so you will have to order those entries yourself - defining comparator based on split(" ") is not that difficult