JSON order mixed up

前端 未结 12 1296
感情败类
感情败类 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:38

    The main intention here is to send an ordered JSON object as response. We don't need javax.json.JsonObject to achieve that. We could create the ordered json as a string. First create a LinkedHashMap with all key value pairs in required order. Then generate the json in string as shown below. Its much easier with Java 8.

    public Response getJSONResponse() {
        Map linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("A", "1");
        linkedHashMap.put("B", "2");
        linkedHashMap.put("C", "3");
    
        String jsonStr = linkedHashMap.entrySet().stream()
                .map(x -> "\"" + x.getKey() + "\":\"" + x.getValue() + "\"")
                .collect(Collectors.joining(",", "{", "}"));
        return Response.ok(jsonStr).build();
    }
    

    The response return by this function would be following: {"A":"1","B":"2","C":"3"}

提交回复
热议问题