首页 > 解决方案 > 是否可以在 java spring boot 中使用 json 类型?

问题描述

是否可以像在 javascript 中一样使用 json 类型而不在 java spring boot 中生成 JSONOject?是否可以在不创建 JSONObject 的情况下使用 { } 格式?

标签: javascriptjavajson

解决方案


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.


推荐阅读