JSON order mixed up

前端 未结 12 1444
感情败类
感情败类 2020-11-22 02:01

I\'ve a problem trying to make my page printing out the JSONObject in the order i want. In my code, I entered this:



        
12条回答
  •  独厮守ぢ
    2020-11-22 02:37

    I agree with the other answers. You cannot rely on the ordering of JSON elements.

    However if we need to have an ordered JSON, one solution might be to prepare a LinkedHashMap object with elements and convert it to JSONObject.

    @Test
    def void testOrdered() {
        Map obj = new LinkedHashMap()
        obj.put("a", "foo1")
        obj.put("b", new Integer(100))
        obj.put("c", new Double(1000.21))
        obj.put("d", new Boolean(true))
        obj.put("e", "foo2")
        obj.put("f", "foo3")
        obj.put("g", "foo4")
        obj.put("h", "foo5")
        obj.put("x", null)
    
        JSONObject json = (JSONObject) obj
        logger.info("Ordered Json : %s", json.toString())
    
        String expectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
        assertEquals(expectedJsonString, json.toString())
        JSONAssert.assertEquals(JSONSerializer.toJSON(expectedJsonString), json)
    }
    

    Normally the order is not preserved as below.

    @Test
    def void testUnordered() {
        Map obj = new HashMap()
        obj.put("a", "foo1")
        obj.put("b", new Integer(100))
        obj.put("c", new Double(1000.21))
        obj.put("d", new Boolean(true))
        obj.put("e", "foo2")
        obj.put("f", "foo3")
        obj.put("g", "foo4")
        obj.put("h", "foo5")
        obj.put("x", null)
    
        JSONObject json = (JSONObject) obj
        logger.info("Unordered Json : %s", json.toString(3, 3))
    
        String unexpectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
    
        // string representation of json objects are different
        assertFalse(unexpectedJsonString.equals(json.toString()))
        // json objects are equal
        JSONAssert.assertEquals(JSONSerializer.toJSON(unexpectedJsonString), json)
    }
    

    You may check my post too: http://www.flyingtomoon.com/2011/04/preserving-order-in-json.html

提交回复
热议问题