Removing a json object from a json file in Java

后端 未结 4 1075
孤街浪徒
孤街浪徒 2021-01-22 13:25

I have this json file I downloaded online:

 {
\"price\": 1,
\"empty\": [
  0,
  0,
  0,
  0,
  0
],
\"lowValue\": 0,
\"highValue\": 0
},

and I

4条回答
  •  悲哀的现实
    2021-01-22 13:57

    Use a JSON library like Jackson:

    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.node.ObjectNode;
    
    import java.io.IOException;
    
    public class JsonDelete {
    
        public static void main(String[] args) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            String json = "{\"key\":\"value\",\"empty\":[]}";
    
            ObjectNode node = (ObjectNode) mapper.readTree(json);
            node.remove("empty");
    
            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node));
        }
    
    }
    

    Outputs:

    {
      "key" : "value"
    }
    

提交回复
热议问题