skip to Main Content

The solution presented in Convert a string list/set to json objects in java seems not to work any more.

In version 1.1.4 of the javax.json JSONObject is now a subclass of the typed Map<String, JsonValue> .

Hence

    jsonObject.put("key", "value")

leads to an error, because put expects now an Json Object as the second object.

However, I did not find an easy way to convert a simple String into a JsonValue.

What is the best way to create a simple JsonValue?

Wallenstein

2

Answers


  1. javax.json JSONObject extends Map<String, JsonValue>.

    So, you need to convert your String into a JsonValue.

    Try this:

    JsonObject jsonObject = Json.createObjectBuilder()
            .add("key", "yourValue")  // "yourValue" will be handled as a JsonValue
            .build();
    System.out.println(jsonObject);
    
    Login or Signup to reply.
  2. You are wrong in that javax.json.JsonObject has changed, this is how it always worked in its immutable way. See here for more reference: https://stackoverflow.com/a/26346341/471160, this is from 2014.

    Since you reference a link to SO question about jackson you probably mixed code from two different libraries. If you want code like jsonObject.put("key", "value") to work then use jackson:

        // com.fasterxml.jackson.core:jackson-core:2.13.3
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode jsonObject2 = mapper.createObjectNode();
        jsonObject2.put("key", "value");
        System.out.println(jsonObject2);
    

    or org.json

        // org.json:json:20230227
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("key", "value");
        System.out.println(jsonObject);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search