简体   繁体   中英

Java remove “parent”:“somevalue” from flattened json if “parent”:“somevalue” and there also exists a “parent.new”: “somevalue” in same json

I Have json like this :

{
"lastModifiedBy" :"value",
"lastModifiedBy.$oid": "1234567189",
"displayedBy" : 0,
"displayedBy.one" : "Abhi",
"displayedBy.one.new" : "Sammy",
"displayedBy.two":"random_value3",
"a.b":null,
"b.c":null,
"d.e.f":null
}

I only want to keep the longest keys and not the previous state parent without affecting the other keys output I need:

{
"lastModifiedBy.$oid": "1234567189",
"displayedBy.one.new" : "Sammy",
"displayedBy.two":"random_value3",
"a.b":null,
"b.c":null,
"d.e.f":null
}

Is there a way to do this in Jackson or any other java package.?

If you are able to convert it into an ArrayList, remove all keys you dont need. For example with foreach.

If you are able to convert it into an String split at ":" and "," remove the "s create an ArrayList and populate it by using index 0,2,4... as key and 1,3,5... as value and do the thing mentioned above.

Try this.

    Map<String, String> map = new HashMap<>();
    map.put("lastModifiedBy", "value");
    map.put("lastModifiedBy.$oid", "1234567189");
    map.put("displayedBy", "0");
    map.put("displayedBy.one", "Abhi");
    map.put("displayedBy.one.new", "Sammy");
    map.put("displayedBy.two", "random_value3");
    map.put("a.b", null);
    map.put("b.c", null);
    map.put("d.e.f", null);
    List<String> removes = new ArrayList<>();
    for (String parent : map.keySet())
        for (String child : map.keySet())
            if (parent != child && child.startsWith(parent)) {
                removes.add(parent);
                break;
            }
    for (String key : removes)
        map.remove(key);
    System.out.println(map);

output:

{a.b=null, d.e.f=null, displayedBy.one.new=Sammy, b.c=null, displayedBy.two=random_value3, lastModifiedBy.$oid=1234567189}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM