Is it possible to work with json type as in javascript without generating JSONOject in java spring boot? Is it possible to work with the { } format without creating a JSONObject?
Asked
Active
Viewed 448 times
0
-
JSON = JavaScript Object Notation. The Java syntax does not support JSON. So no, we cannot use JSON to declare objects in Java. We can, however, convert a `String` that contains a JSON-String into a `JSONObject`. See [this question](https://stackoverflow.com/questions/5245840/how-to-convert-jsonstring-to-jsonobject-in-java) from [dogbane](https://stackoverflow.com/users/7412/dogbane) for details. – Turing85 Nov 09 '21 at 19:31
-
Thank you for your response. – Oya Nov 09 '21 at 19:42
-
Why don't you want to use a JSONObject? It sounds like you want the format of JSON data and the JSON file extension without... using JSON? – TylerH Nov 09 '21 at 19:45
1 Answers
1
JSON stands for "JavaScript Object Notation". The Java Syntax does not support JSON. Therefore, we cannot use JSON to declare any object in Java like
MyAwesomeObject object = { "name": "foo", "age": 42 };
We can, however, convert a String
that contains a JSON-string into a JSONObject
. See this question by dogbane for details.
If we use, for example, jackson, we can convert a String
to an object through jackson's ObjectMapper
:
final String json = "{ \"name\": \"foo\", \"age\": 42 }";
try {
MyAwesomeObject object = objectMapper.readValue(json, MyAwesomeObject.class);
} catch (IOException e) {
...
}
For more details on jackson, I recommend reading this tutorial from baeldung.com
.

Turing85
- 18,217
- 7
- 33
- 58
-
You can use JSON in Java with the help of one of several libraries, FWIW. See https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java – TylerH Nov 09 '21 at 19:46