Gson:直接将String转换为JsonObject(不是POJO) [英] Gson: Directly convert String to JsonObject (no POJO)
本文介绍了Gson:直接将String转换为JsonObject(不是POJO)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在GSON中执行JSON树操作,但是我有一种情况,我不知道或者有一个POJO将字符串转换为<转换为
JsonObject $ c $之前C>。有没有办法直接从 String
到 JsonObject
?
我试过以下(Scala语法):
val gson =(new GsonBuilder).create
$ b $ val a:JsonObject = gson.toJsonTree({a:A,b:true})。getAsJsonObject
val b:JsonObject = gson。 fromJson({a:A,b:true},classOf [JsonObject])
但 a
失败,JSON将被转义并仅解析为 JsonString
,并且 b
返回一个空的 JsonObject
。 任何想法?
解决方案
使用JsonParser;例如:
JsonParser parser = new JsonParser();
JsonObject o = parser.parse({\a \:\A\})。getAsJsonObject();
Can't seem to figure this out.
I'm attempting JSON tree manipulation in GSON, but I have a case where I do not know or have a POJO to convert a string into, prior to converting to JsonObject
. Is there a way to go directly from a String
to JsonObject
?
I've tried the following (Scala syntax):
val gson = (new GsonBuilder).create
val a: JsonObject = gson.toJsonTree("""{ "a": "A", "b": true }""").getAsJsonObject
val b: JsonObject = gson.fromJson("""{ "a": "A", "b": true }""", classOf[JsonObject])
but a
fails, the JSON is escaped and parsed as a JsonString
only, and
b
returns an empty JsonObject
.
Any ideas?
解决方案
use JsonParser; for example:
JsonParser parser = new JsonParser();
JsonObject o = parser.parse("{\"a\": \"A\"}").getAsJsonObject();
这篇关于Gson:直接将String转换为JsonObject(不是POJO)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文