-1

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.?

  • Please turn to the [help] to learn how/what to ask here. Just dropping requirements "this is what I want" isn't appreciated. When you try something yourself, and you get stuck with a specific problem, we will gladly help. But please understand that this place is not intended to give guidance with the possibly many steps required to get you from your vision to a working program. – GhostCat Sep 03 '20 at 11:47

2 Answers2

1

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.

Clashbestie
  • 80
  • 1
  • 9
0

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}