1

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

In version 1.1.4 of the javax.json JSONObject is 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

1
  • 4
    The question and solution you have linked are about jackson, not javax.json, why do you expect that solution to work? Commented Oct 11, 2024 at 9:58

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

javax.json.JSONObject extends Map<String,JsonValue> since the first version. The jsonObject.put("key", "value") example uses Jackson, as Chaosfire already mentioned. Your answer is still a good solution though.
Ouch. I didn't check it. I saw the wrong object type and gave advice for a bad question. Bad in the sense of unclear. Maybe @marcinj has a better solution for the questioner.
Given that he questioner is using javax.json I think your answer is excellent. What marcinj suggest requires a different JSON library, which may require a lot of refactoring.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.