I need a JSON expert here or someone who knows JSON very well. I have the following JSON structure that I received from an API via http request. The API pre-sorts the data by itemDistance because I specified that in my query. When I receive the data and process it through JSONSerialization, I lose the ordering by itemDistance that the API did. This most likely because it's in dictionary format and it needs to be in an array. I am building an iOS application.
My question is: What exact change(s) need to be made to the structure of the JSON below for order of items by locationDistance to be maintained when I run it through JSONSerialization? I'm struggling with changing the format below so it is in an array. What type of brackets do I need to place and/or remove below and exactly where do they need to be positioned.
}
"items": {
"234683": {
“itemID": "234683",
“itemCategory": “B",
"itemDistance": 8
},
"467528": {
“itemID": "467528",
“itemCategory": “B",
"itemDistance": "10"
},
"417928": {
“itemID": "417928",
“itemCategory": “A",
"itemDistance": "10"
},
…
}
}
By the way, I tried adding square brackets around the list of items in "items" as shown below but that did not help or make a difference.
}
"items": [{
"234683": {
“itemID": "234683",
“itemCategory": “B",
"itemDistance": 8
},
"467528": {
“itemID": "467528",
“itemCategory": “B",
"itemDistance": "10"
},
"417928": {
“itemID": "417928",
“itemCategory": “A",
"itemDistance": "10"
},
…
}]
}
I also did it like this, but this too did not make a difference. The order is still lost when running it through JSONSerialization.
}
"items": [
"234683": {
“itemID": "234683",
“itemCategory": “B",
"itemDistance": 8
},
"467528": {
“itemID": "467528",
“itemCategory": “B",
"itemDistance": "10"
},
"417928": {
“itemID": "417928",
“itemCategory": “A",
"itemDistance": "10"
},
…
]
}
You need the server to return an array of dictionaries, not a dictionary of dictionaries.
You want:
{
"items": [{
"itemID": "234683",
"itemCategory": "B",
"itemDistance": 8
},
{
"itemID": "467528",
"itemCategory": "B",
"itemDistance": "10"
},
{
"itemID": "417928",
"itemCategory": "A",
"itemDistance": "10"
}
]
}
Or, if you can't change the API to remove the unnecessary dictionary, you can wrap each dictionary into another dictionary and then put those dictionaries into an array so that the order is preserved.
{
"items": [{
"234683": {
"itemID": "234683",
"itemCategory": "B",
"itemDistance": 8
}
},
{
"467528": {
"itemID": "467528",
"itemCategory": "B",
"itemDistance": "10"
}
}, {
"417928": {
"itemID": "417928",
"itemCategory": "A",
"itemDistance": "10"
}
}
]
}
The other option is to iterate over the dictionary keys, extracting each value dictionary into an array and then sort it in your app.
You might also want to find the programmer who created the server code and administer appropriate corrective action;