[英]How do I convert a LinkedTreeMap to gson JsonObject
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. 对于一个java数据处理程序,我发送格式正确的JSON,但是Spring,Java的组合决定如何构建它所看到的内容,而框架我真的不应该改变JSON这样的状态,以便一旦我能看到它,就会变成一个LinkedTreeMap,我需要将它转换为一个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.
这不是将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 是我一直在使用的样本,一旦我看到它,它是一个LinkedTreeMap,.toString()s到
{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,或者将库内部引号添加到字符串中,甚至是将sting转换为不需要内部引号的JsonObject的方法?
You'd typically have to serialize the object to JSON, then parse that JSON back into a JsonObject
. 您通常必须将对象序列化为JSON,然后将该JSON解析回
JsonObject
。 Fortunately, Gson
provides a toJsonTree
method that kind of skips the parsing. 幸运的是,
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.