How to convert Object to javax.json.JsonValue?

2.1k views Asked by At

I want to patch a JSON string. I get the 'path' to the field which has to be patched, and the 'value' with which to patch. The value could be anything, String, int, float, boolean, array, or an object.

How do I convert the Object to JsonValue?

The 'replace' method in javax.json.JsonPointer class requires a JsonValue object.

2

There are 2 answers

2
elouanesbg On

Use This

    import com.google.gson.Gson;

    Statue statue = new Statue();//java class
    String json = new Gson().toJson(statue);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);

Json will take the java class structure

1
Andrea Annibali On

You could use Jackson, that with Maven can be added to pom specifying the following dependency:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

With Jackosn you can use the ObjectMapper (import it with import com.fasterxml.jackson.databind.ObjectMapper;). So if you have an object obj of type MyClass, you can do as follow:

MyClass objToCovert = new MyClass();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(obj);

The json must be passed to your method that updates the Json structure to patch. As an Example of a method that can do the update I report the following (tag is the key):

public static JsonStructure updateKeyValue(JsonStructure jsonStructure, String tag, String value) {
    JsonPointer jsonPointer = Json.createPointer("/" + tag);
    JsonString jsonStringValue = (JsonString) jsonPointer.getValue(jsonStructure);
    jsonStructure = jsonPointer.replace(jsonStructure, jsonStringValue);
    return jsonStructure;
}