对于Java数据处理程序,我发送了格式正确的JSON,但是Spring、决定如何转换它所看到的内容的Java和框架的组合,我真的不应该go 更改JSON,这样一旦我可以看到它,它就会变成LinkedTreeMap,我需要把它转换成JsonObject. 这不是要将JSON序列化/反序列化为Java对象,它的"最终形式"是一个gson JsonObject,它需要能够处理任何有效的JSON.

{
"key":"value",
"object": {
    "array":[
        "value1", 
        "please work"
        ]
    }
}

是我一直在使用的示例,一旦我看到它,它就是一个链接的 map .toString()s to

{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?

推荐答案

通常需要将对象序列化为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

gson.fromJson(theJson, JsonObject.class);

Json相关问答推荐

Golang JSON Date Tim.Date()测试请求

如何在对象投影(*)上应用滤镜投影([?port==`eth1`])?

褐煤面积图中的分选问题

JOLT转换以基于对象属性过滤JSON数组

Python 将 struct 化文本转换和筛选为对象

将 GEOSwift.JSON 转换为 Swift 中的 struct

如何在 terraform 输出中打印一组用户信息

ETCD 导出为 json 并从 base64 解码所有键/值到人类可读

我需要在 mongodb compass 中检索索引(编号 1)信息

在 PostgreSQL 中 Select 分层 JSON 作为表

Oracle Apex - 将 JSON 对象分配给变量以返回

我无法在 Go - Gin 中解析日期/时间

JQuery,使用 GET 方法发送 JSON 对象

如何对使用转换器的 Grails 服务进行单元测试?

从 Postgres 中的 json 对象中提取键、值

JSON 语法错误:'unexpected number' 或 'JSON.parse: expected ',' or '}' after property value in object'

我应该如何处理 JSON 中的 HATEOAS 链接和引用?

Java循环遍历Json数组?

Newtonsoft 对象 → 获取 JSON 字符串

我如何反序列化以杰克逊为单位的时间戳?