Ordered JSONObject

后端 未结 3 533
有刺的猬
有刺的猬 2020-12-03 09:38

I have a servlet which talks with the database then returns a list of ordered (ORDER BY time) objects. At the servlet part, I have

                //access DB, r         


        
相关标签:
3条回答
  • 2020-12-03 09:56

    As JSONObject is order less and internally uses Hashmap. One way to use it to download the all classes from org.json and use in your project directly by changing the internal HashMap implementation to LinkedHashMap in JSONObject.java file. below is the sorted json files https://github.com/abinash1/Sorted-Json-Object

    0 讨论(0)
  • 2020-12-03 09:59

    As mentioned by ghayes , json objects are unordered. There are multiple solutions to this problem.

    1. You can use array and the sort it to get the ordered list.
    2. You can use gson library to get the desired order of elements.

      I would prefer the second option as it is easy to use.
    0 讨论(0)
  • 2020-12-03 10:10

    As JSON objects do not inherently have an order, you should use an array within your JSON object to ensure order. As an example (based on your code):

     jsonObj = 
              { items:
                [ { name: "Stack", time: "..." },
                  { name: "Overflow", time: "..." },
                  { name: "Rocks", time: "..." },
                  ... ] };
    

    This structure will ensure that your objects are inserted in the proper sequence.

    Based on the JSON you have above, you could place the objects into an array and then sort the array.

     var myArray = [];
     var resultArray;
    
     for (var j in jsonObj) {
       myArray.push(j);
     }
    
     myArray = $.sort(myArray, function(a, b) { return parseInt(a) > parseInt(b); });
    
     for (var i = 0; i < myArray.length; i++) {
       resultArray.push(jsonObj[myArray[i]]);
     }
    
     //resultArray is now the elements in your jsonObj, properly sorted;
    

    But maybe that's more complicated than you are looking for..

    0 讨论(0)
提交回复
热议问题