41

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?

fracz
  • 20,536
  • 18
  • 103
  • 149
Revils
  • 1,478
  • 1
  • 14
  • 31

4 Answers4

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

See docs and examples.

fracz
  • 20,536
  • 18
  • 103
  • 149
21

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;
}
Sridhar Sarnobat
  • 25,183
  • 12
  • 93
  • 106
-1

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);  
moonchild_
  • 17
  • 10
-1

Using Jackson to parse a string representation of a json object into a JsonNode object.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class J {

  public static void main(String[] args) throws JsonProcessingException {
    var json =
        """
          {
            "candle": {
              "heat": 10,
              "color": "orange"
            },
            "water": {
              "heat": 1,
              "color": null
            }
          }
        """;
    ObjectMapper mapper = new ObjectMapper();
    var node = mapper.readTree(json);
    System.out.println(node.toPrettyString());
  }
}
John Gilmer
  • 864
  • 6
  • 10
  • 1
    The question was how to convert a string to a `javax.json.JsonObject`. I can't find such object in this answer. – yaccob Feb 13 '23 at 17:37