将 Java 对象转换为包含 json 字符串 属性 的 json 字符串
Convert Java object to json string containing a json string property already
考虑一个 Java 对象,如下所示:
class User {
String name;
int age;
String locationJson; // this is a json already
//allArgsConstructor, getters & setters
}
所以当我们这样做时,
import com.fasterxml.jackson.databind.ObjectMapper;
....
User user = new User("Max", 13, "{\"latitude\":30.0000,\"longitude\":32.0000}");
new ObjectMapper().writeValueAsString(user)), String.class);
我期待的是:
{
"name": "Max",
"age": "13",
"locationJson": {"latitude":30.0000, "longitude":32.0000}
}
相反,我将它作为 json 值 包裹在双引号中 并且 被反斜杠跳过 因为它是双引号jsonized - 如果这实际上是一个动词 -
{
"name": "Max",
"age": "13",
"locationJson": "{\"latitude\":30.0000, \"longitude\":32.0000}"
}
我使用 @JsonRawValue
成功解决了这个问题
Marker annotation that indicates that the annotated method or field should be serialized by including literal String value of the property as is, without quoting of characters. This can be useful for injecting values already serialized in JSON or passing javascript function definitions from server to a javascript client.
Warning: the resulting JSON stream may be invalid depending on your input value.
所以通过这样做,
import com.fasterxml.jackson.annotation.JsonRawValue;
....
class User {
String name;
int age;
@JsonRawValue
String locationJson; // this is a json already
//allArgsConstructor, getters & setters
}
我有点告诉 Jackson 这是一个 json 的价值,不要在这里做你的工作
所以 post 中的相同代码生成了正确的 json
{
"name": "Max",
"age": "13",
"locationJson": {"latitude":30.0000, "longitude":32.0000}
}
考虑一个 Java 对象,如下所示:
class User {
String name;
int age;
String locationJson; // this is a json already
//allArgsConstructor, getters & setters
}
所以当我们这样做时,
import com.fasterxml.jackson.databind.ObjectMapper;
....
User user = new User("Max", 13, "{\"latitude\":30.0000,\"longitude\":32.0000}");
new ObjectMapper().writeValueAsString(user)), String.class);
我期待的是:
{
"name": "Max",
"age": "13",
"locationJson": {"latitude":30.0000, "longitude":32.0000}
}
相反,我将它作为 json 值 包裹在双引号中 并且 被反斜杠跳过 因为它是双引号jsonized - 如果这实际上是一个动词 -
{
"name": "Max",
"age": "13",
"locationJson": "{\"latitude\":30.0000, \"longitude\":32.0000}"
}
我使用 @JsonRawValue
Marker annotation that indicates that the annotated method or field should be serialized by including literal String value of the property as is, without quoting of characters. This can be useful for injecting values already serialized in JSON or passing javascript function definitions from server to a javascript client. Warning: the resulting JSON stream may be invalid depending on your input value.
所以通过这样做,
import com.fasterxml.jackson.annotation.JsonRawValue;
....
class User {
String name;
int age;
@JsonRawValue
String locationJson; // this is a json already
//allArgsConstructor, getters & setters
}
我有点告诉 Jackson 这是一个 json 的价值,不要在这里做你的工作 所以 post 中的相同代码生成了正确的 json
{
"name": "Max",
"age": "13",
"locationJson": {"latitude":30.0000, "longitude":32.0000}
}