Shawn
Shawn

Reputation: 5260

Java JsonNode remove one container in the middle

I have an the following Json

{
    "Parent": {
        "pk1": "pv1",
        "pk2": "pv2",
        "Child": {
            "*": {
                "ck1": "cv1",
                "ck2": "cv2"
            }
        }
    }
}

Now I want to remove "*":{} but keep its content. The expected output is like this.

{
    "Parent": {
        "pk1": "pv1",
        "pk2": "pv2",
        "Child": {
            "ck1": "cv1",
            "ck2": "cv2"
        }
    }
}

How can I use Java Jackson to achieve this?

Upvotes: 0

Views: 2730

Answers (1)

m4gic
m4gic

Reputation: 1513

See the manipulation below

    ObjectMapper mapper = new ObjectMapper();
    String file = "src/main/resources/yourjson.json";
    JsonNode object = mapper.readTree(new File(file));
    ObjectNode child = (ObjectNode) object.path("Parent").path("Child");
    JsonNode star = child.path("*");
    child.remove("*");
    Iterator<String> startFieldNames = star.fieldNames();
    while (startFieldNames.hasNext()) {
        String startFieldName = startFieldNames.next();
        child.set(startFieldName, star.get(startFieldName));
    }
    System.out.println(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(object));

Upvotes: 1

Related Questions