mmaceachran
mmaceachran

Reputation: 3348

Remove whitespace from json using jackson

I have a simple JSON like this:

{
  "enums" : [{"someName" : "  someValue   ", etc.. }]
}

Sometimes, someValue has whitespace in it. (ie. " someValue ")

I can't seem to get how to SET each value back to the node. I have this:

        JsonNode values = root.get("enumValues");
        Iterator<Entry<String, JsonNode>> nodes = values.getFields();
        while (nodes.hasNext()) {
             Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodes.next();
             //  what do I do here?
        }   

I know that JsonNodes are imutable, but how do I get the JsonObjects? <String, JsonObject> wont work.

I want to be able to parse this as an object (I eventually want to make in recursive for more complex JSON, but one thing at a time) so that when I print the JSON out it would look like this:

{
  "enums" : [{"someName" : "someValue", etc.. }]
}

Upvotes: 0

Views: 4154

Answers (1)

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

Given a JSON example

{
    "enums" : [{"someName" : "  someValue   ", "a": " b "}]
}

you can do it like this:
(I also added some code to read the JSON input and to print the JSON output, and fixed some flaws in your code to make it compilable)

ObjectMapper objectMapper = new ObjectMapper();
File file = new File("example.json");
JsonNode root = objectMapper.readValue(file, JsonNode.class);
    
ArrayNode arrayNode = (ArrayNode) root.get("enums");
ObjectNode objectNode = (ObjectNode) arrayNode.get(0);      
Iterator<Map.Entry<String, JsonNode>> nodes = objectNode.fields();
while (nodes.hasNext()) {
    Map.Entry<String, JsonNode> entry = nodes.next();
    if (entry.getValue().isTextual()) {
        String s = entry.getValue().asText();  // get string from JSON node
        s = s.trim();                          // remove leading/trailing space
        objectNode.put(entry.getKey(), s);     // put the string back into JSON node
    }
} 

objectMapper.writeValue(System.out, root);

Then you get the JSON output

{"enums":[{"someName":"someValue","a":"b"}]}

Upvotes: 1

Related Questions