Java Gson:直接将String转换为JsonObject(无POJO)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4110664/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:43:41  来源:igfitidea点击:

Gson: Directly convert String to JsonObject (no POJO)

javajsongson

提问by 7zark7

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 Stringto JsonObject?

似乎无法弄清楚这一点。我正在 GSON 中尝试 JSON 树操作,但是在转换为JsonObject. 有没有办法直接从 aString转到JsonObject

I've tried the following (Scala syntax):

我尝试了以下(Scala 语法):

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 afails, the JSON is escaped and parsed as a JsonStringonly, and breturns an empty JsonObject.

a失败了,JSON 被转义并解析为JsonStringonly,并 b返回一个空的JsonObject

Any ideas?

有任何想法吗?

采纳答案by Dallan Quass

use JsonParser; for example:

使用 JsonParser;例如:

JsonParser parser = new JsonParser();
JsonObject o = parser.parse("{\"a\": \"A\"}").getAsJsonObject();

回答by Dan Menes

Just encountered the same problem. You can write a trivial custom deserializer for the JsonElementclass:

刚遇到同样的问题。您可以为JsonElement该类编写一个简单的自定义反序列化器:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

GsonBuilder gson_builder = new GsonBuilder();
gson_builder.registerTypeAdapter(
        JsonElement.class,
        new JsonDeserializer<JsonElement>() {
            @Override
            public JsonElement deserialize(JsonElement arg0,
                    Type arg1,
                    JsonDeserializationContext arg2)
                    throws JsonParseException {

                return arg0;
            }
        } );
String str = "{ \"a\": \"A\", \"b\": true }";
Gson gson = gson_builder.create();
JsonElement element = gson.fromJson(str, JsonElement.class);
JsonObject object = element.getAsJsonObject();

回答by maverick

Try to use getAsJsonObject()instead of a straight cast used in the accepted answer:

尝试使用getAsJsonObject()而不是接受的答案中使用的直接转换:

JsonObject o = new JsonParser().parse("{\"a\": \"A\"}").getAsJsonObject();

回答by Purushotham

String jsonStr = "{\"a\": \"A\"}";

Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();

回答by c2willi

Came across a scenario with remote sorting of data store in EXTJS 4.X where the string is sent to the server as a JSON array (of only 1 object).
Similar approach to what is presented previously for a simple string, just need conversion to JsonArray first prior to JsonObject.

在 EXTJS 4.X 中遇到了远程排序数据存储的场景,其中字符串作为 JSON 数组(只有 1 个对象)发送到服务器。
类似于之前为简单字符串提供的方法,只需要在 JsonObject 之前先转换为 JsonArray。

String from client: [{"property":"COLUMN_NAME","direction":"ASC"}]

来自客户端的字符串:[{"property":"COLUMN_NAME","direction":"ASC"}]

String jsonIn = "[{\"property\":\"COLUMN_NAME\",\"direction\":\"ASC\"}]";
JsonArray o = (JsonArray)new JsonParser().parse(jsonIn);

String sortColumn = o.get(0).getAsJsonObject().get("property").getAsString());
String sortDirection = o.get(0).getAsJsonObject().get("direction").getAsString());

回答by Jozef Benikovsky

The simplest way is to use the JsonPrimitiveclass, which derives from JsonElement, as shown below:

最简单的方法是使用JsonPrimitive派生自的类,JsonElement如下所示:

JsonElement element = new JsonPrimitive(yourString);
JsonObject result = element.getAsJsonObject();

回答by Eduardo Chico

I believe this is a more easy approach:

我相信这是一种更简单的方法:

public class HibernateProxyTypeAdapter implements JsonSerializer<HibernateProxy>{

    public JsonElement serialize(HibernateProxy object_,
        Type type_,
        JsonSerializationContext context_) {
        return new GsonBuilder().create().toJsonTree(initializeAndUnproxy(object_)).getAsJsonObject();
        // that will convert enum object to its ordinal value and convert it to json element

    }

    public static <T> T initializeAndUnproxy(T entity) {
        if (entity == null) {
            throw new 
               NullPointerException("Entity passed for initialization is null");
        }

        Hibernate.initialize(entity);
        if (entity instanceof HibernateProxy) {
            entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
                    .getImplementation();
        }
        return entity;
    }
}

And then you will be able to call it like this:

然后你就可以这样调用它:

Gson gson = new GsonBuilder()
        .registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxyTypeAdapter())
        .create();

This way all the hibernate objects will be converted automatically.

这样所有的休眠对象都将自动转换。

回答by Maddy

//import com.google.gson.JsonObject;  
JsonObject complaint = new JsonObject();
complaint.addProperty("key", "value");

回答by Stephen Paul

The JsonParserconstructor has been deprecated. Use the static method instead:

JsonParser构造已被弃用。改用静态方法:

JsonObject asJsonObject = JsonParser.parseString(request.schema).getAsJsonObject();