How to convert String to JsonObject

2019-02-12 02:26发布

问题:

I am using a httprequest to get Json from a web into a string.

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

How can I do this?

回答1:

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

See docs and examples.



回答2:

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;
}