Java Gson .add函数没有采用String参数(maven项目)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Gson .add函数没有采用String参数(maven项目)相关的知识,希望对你有一定的参考价值。
所以这是我在intellij中遇到的一个非常非常奇怪的错误,如果我实例化一个JsonArray(在gson库中),它只有一个.add方法,需要一个JsonElement作为它的参数。
JsonArray foo = new JsonArray();
for (String bar : this.baz) {
foo.add(bar); // .add throws this error: java: incompatible types: java.lang.String cannot be converted to com.google.gson.JsonElement
}
顺便说一下,这是一个使用以下gson依赖关系的maven存储库:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>LATEST</version>
<scope>compile</scope>
</dependency>
答案
如果add()
需要JsonElement
,那么使用:
foo.add(new JsonPrimitive(bar))
Gson 2.8.2提供了接收简单字符串的add()
的重载版本。
以上是关于Java Gson .add函数没有采用String参数(maven项目)的主要内容,如果未能解决你的问题,请参考以下文章