[英]Gson merging JsonObject throws java.lang.UnsupportedOperationException
In some special cases I want jsonObjects to be merged in a single object. 在某些特殊情况下,我希望将jsonObjects合并到一个对象中。 I read both objects from a file
我从文件中读取了两个对象
new JsonParser().parse(new FileReader(definitionFile)).getAsJsonObject();
and both files have the same structure. 并且两个文件具有相同的结构。 I try to merge the files with a following code:
我尝试使用以下代码合并文件:
public JsonObject merge(JsonObject firstObject, JsonObject secondObject) throws Exception {
firstObject.getAsJsonObject(BaseGenerator.MEMBER_METHODS).entrySet()
.addAll(secondObject.getAsJsonObject(BaseGenerator.MEMBER_METHODS).entrySet());
return firstObject;
}
But exception is thrown while trying to merge these objects: java.lang.UnsupportedOperationException 但是尝试合并这些对象时会引发异常:java.lang.UnsupportedOperationException
How can I merge those objects? 如何合并这些对象?
The exception is because the EntrySet
implementation for GSON library does not implement the add
function. 例外是因为GSON库的
EntrySet
实现未实现add
函数。
I haven't touch GSON lib for a long time. 我已经很久没有接触GSON lib了。 But, maybe you could try something like this
但是,也许您可以尝试这样的事情
new HashSet(firstObject.getAsJsonObject(BaseGenerator.MEMBER_METHODS).entrySet()).addAll(secondObject.getAsJsonObject(BaseGenerator.MEMBER_METHODS).entrySet())`
It's easy. 这很容易。 Just don't merge them using the
entrySet()
method since sets returned by that method do not implement Set.add
/ Set.addAll
. 只是不要使用
entrySet()
方法合并它们,因为该方法返回的集合不实现Set.add
/ Set.addAll
。
private static void mergeInto(final JsonObject o1, final JsonObject o2) {
for ( final Entry<String, JsonElement> e : o2.entrySet() ) {
o1.add(e.getKey(), e.getValue());
}
}
Also, that method above returns nothing in order to explicitly indicate that the arguments may change their internal state -- the first parameter actually (that is usually a big surprise to anyone who's expecting something new from a methods that returns something). 同样,上面的方法没有返回任何内容,以便明确表明参数可能会更改其内部状态-实际上是第一个参数(通常,对于从返回值的方法中期望新值的人来说,这通常是一个很大的惊喜)。 I would create a new
JsonObject
instance in order not to touch the arguments state, something like: 我将创建一个新的
JsonObject
实例,以免影响参数状态,例如:
private static JsonObject merge(final JsonObject o1, final JsonObject o2) {
final JsonObject merged = new JsonObject();
mergeInto(merged, o1);
mergeInto(merged, o2);
return merged;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.