英文:
Java remove "parent":"somevalue" from flattened json if “parent”:“somevalue” and there also exists a “parent.new”: “somevalue” in same json
问题
{
"lastModifiedBy.$oid": "1234567189",
"displayedBy.one.new": "Sammy",
"displayedBy.two": "random_value3",
"a.b": null,
"b.c": null,
"d.e.f": null
}
是的,在Jackson或其他Java包中是有方法可以做到这一点的。
英文:
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.?
答案1
得分: 1
如果您能将其转换为ArrayList,请删除所有不需要的键。例如,使用foreach。
如果您能将其转换为以":"和","分割的字符串,删除"s,并创建一个ArrayList,然后使用索引0,2,4...作为键,1,3,5...作为值填充它,并执行上述提到的操作。
英文:
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.
答案2
得分: 0
请尝试这样做。
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);
输出:
{a.b=null, d.e.f=null, displayedBy.one.new=Sammy, b.c=null, displayedBy.two=random_value3, lastModifiedBy.$oid=1234567189}
英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论