alois.wirkes
alois.wirkes

Reputation: 369

Why does Android changes the order of my JSON string?

I have a very simple question... In my Android app i'm forming a JSON string to send to my server... there are no error in my code, but Java (or Android) puts the values in a different order of mine and I don't know why...

I want to solve this issue, because I need to process that JSON string in the server to update some tables of my database... my PHP code in the server uses the same order I used in my app to decode the JSON string, but because of Android (or Java) that changes the order, I'm having troubles to update the tables...

Any ideas? Thanks in advance!

I'm talking about this:

In my app:

json_data.put("id_visit", visits.getString(visits.getColumnIndexOrThrow("id_visit")));
json_data.put("id_form", visits.getString(visits.getColumnIndexOrThrow("id_form")));
json_data.put("id_establishment", visits.getString(visits.getColumnIndexOrThrow("id_establishment")));
json_data.put("id_promoter", visits.getString(visits.getColumnIndexOrThrow("id_promoter")));
json_data.put("actual_date", visits.getString(visits.getColumnIndexOrThrow("actual_date")));
json_data.put("receiver", visits.getString(visits.getColumnIndexOrThrow("receiver")));
json_data.put("observations", visits.getString(visits.getColumnIndexOrThrow("observations")));
json_data.put("gps_coordinates", visits.getString(visits.getColumnIndexOrThrow("gps_coordinates")));

In the LogCat:

{
"id_promoter":"1",
"id_establishment":"5",
"id_visit":"1",
"receiver":"brenda lopez",
"gps_coordinates":"10.4905567 -66.8710966",
"actual_date":"2012-11-27",
"id_form":"1",
"observations":"observaciones"
}

As you can see, its not te same order! Why is this?

I apologize for not taking the time of checking if someone else already asked this, but I'm in a little hurry, so... Sorry!! xD

Upvotes: 1

Views: 958

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234847

Object keys are not ordered in JSON. If you need a specific order, I suggest you use an array:

[
    {"id_promoter":"1"},
    {"id_establishment":"5"},
    {"id_visit":"1"},
    {"receiver":"brenda lopez"},
    {"gps_coordinates":"10.4905567 -66.8710966"},
    {"actual_date":"2012-11-27"},
    {"id_formu":"1"},
    {"observations":"observaciones"}
]

It's gross, but order is what arrays are for.

Another approach is to define an array with the key names in the desired order. Then you can use your original object structure but access it through keys defined by the array. This takes more coding, obviously, but it can also solve your problem.

Upvotes: 4

Related Questions