java 如何将 LinkedTreeMap 转换为 gson JsonObject
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38057172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a LinkedTreeMap to gson JsonObject
提问by Bronanaza
For a java data handler, I send properly formatted JSON, but a combination of Spring, Java deciding how to cast what it sees, and frameworks I really shouldn't go changing mangle that JSON so that once I can see it, it's turned into a LinkedTreeMap, and I need to transform it into a JsonObject. This is not to serialize/de-serialize JSON into java objects, it's "final form" is a gson JsonObject, and it needs to be able to handle literally any valid JSON.
对于 Java 数据处理程序,我发送格式正确的 JSON,但是 Spring、Java 决定如何投射它所看到的内容和框架的组合,我真的不应该改变该 JSON,以便一旦我看到它,它就会变成一个 LinkedTreeMap,我需要把它转换成一个 JsonObject。这不是将 JSON 序列化/反序列化为 java 对象,它的“最终形式”是一个 gson JsonObject,它需要能够处理任何有效的 JSON。
{
"key":"value",
"object": {
"array":[
"value1",
"please work"
]
}
}
is the sample I've been using, once I see it, it's a LinkedTreeMap that .toString() s to
是我一直在使用的示例,一旦我看到它,它就是 .toString() 到的 LinkedTreeMap
{key=value, object={array=[value1, please work]}}
where you can replace "=" with ":", but that doesn't have the internal quotes for the
您可以将“=”替换为“:”,但没有内部引号
new JsonParser().parse(gson.toJson(STRING)).getAsJsonObject()
strategy.
战略。
Is there a more direct way to convert LinkedTreeMap to JsonObject, or a library to add the internal quotes to the string, or even a way to turn a sting into a JsonObject that doesn't need the internal quotes?
是否有更直接的方法将 LinkedTreeMap 转换为 JsonObject,或者将内部引号添加到字符串的库,或者甚至是将字符串转换为不需要内部引号的 JsonObject 的方法?
回答by Sotirios Delimanolis
You'd typically have to serialize the object to JSON, then parse that JSON back into a JsonObject
. Fortunately, Gson
provides a toJsonTree
method that kind of skips the parsing.
您通常必须将对象序列化为 JSON,然后将该 JSON 解析回JsonObject
. 幸运的是,Gson
提供了toJsonTree
一种跳过解析的方法。
LinkedTreeMap<?,?> yourMap = ...;
JsonObject jsonObject = gson.toJsonTree(yourMap).getAsJsonObject();
Note that, if you can, just deserialize the JSON directly to a JsonObject
with
需要注意的是,如果可以的话,只需直接反序列化JSON的JsonObject
同
gson.fromJson(theJson, JsonObject.class);