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?
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();
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);
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());
}
}
javax.json.JsonObject
. I can't find such object in this answer.