How to maintain the order of a JSONObject

后端 未结 12 1612
栀梦
栀梦 2020-12-11 05:49

I am using a JSONObject in order to remove a certin attribute I don\'t need in a JSON String:

JSONObject jsonObject = new JSONObject(jsonString);
jsonObject.         


        
12条回答
  •  伪装坚强ぢ
    2020-12-11 06:18

    You can use Jsckson library in case to maintain the order of Json keys. It internally uses LinkedHashMap ( ordered ).

    import com.fasterxml.jackson.core.JsonToken;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.node.ObjectNode;
    

    The code to remove a field, the removed JsonToken could itself be read if required.

      String jsonString = "{\"name\":\"abc\",\"address\":\"add\",\"data\":[\"some 1\",\"some 2\",\"some3 3\"],\"age\":12,\"position\":8810.21}";
      ObjectMapper mapper = new ObjectMapper();
      JsonNode node = mapper.readTree(jsonString);
      System.out.println("In original order:"+node.toString());
      JsonToken removedToken = ((ObjectNode) node).remove("address").asToken();
      System.out.println("Aft removal order:"+node.toString());
    

    ObjectNode implementation uses a LinkedHashMap, which maintains the insertion order:

     public ObjectNode(JsonNodeFactory nc) {
       super(nc);
       _children = new LinkedHashMap();
     }
    

提交回复
热议问题