简体   繁体   中英

How to convert String to JsonObject

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?

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

See docs and examples .

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

I know this is an outdated question and that this answer would not be relevant years back, but still. Using Jackson Library is the easiest technique to solve this problem. Jackson library is an efficient and widely used Java library to map Java objects to JSON and vice-versa. The following statement converts JSON String representing a student into a Java class representing the student.

Student student = new ObjectMapper().readValue(jsonString, Student.class);  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM