Java 如何将字符串转换为 JsonObject

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

How to convert String to JsonObject

javajsonhttprequest

提问by Sliver

I am using a httprequestto get Json from a web into a string.

我正在使用 ahttprequest将 Json 从网络获取到字符串中。

It is probably quite simple, but I cannot seem to convert this string to a javax.json.JsonObject.

这可能很简单,但我似乎无法将此字符串转换为javax.json.JsonObject.

How can I do this?

我怎样才能做到这一点?

采纳答案by fracz

JsonReader jsonReader = Json.createReader(new StringReader("{}"));
JsonObject object = jsonReader.readObject();
jsonReader.close();

See docsand examples.

请参阅文档示例

回答by Sridhar Sarnobat

Since the above reviewer didn't like my edits, here is something you can copy and paste into your own code:

由于上述审阅者不喜欢我的编辑,您可以将以下内容复制并粘贴到您自己的代码中:

private static JsonObject jsonFromString(String jsonObjectStr) {

    JsonReader jsonReader = Json.createReader(new StringReader(jsonObjectStr));
    JsonObject object = jsonReader.readObject();
    jsonReader.close();

    return object;
}