简体   繁体   English

将 Java object 转换为 json 字符串,其中包含 json 字符串已经属性

[英]Convert Java object to json string containing a json string property already

Consider a Java object like following:考虑一个 Java object,如下所示:

class User {

  String name;

  int age;

  String geofenceJson; // this is a json already

  //allArgsConstructor, getters & setters
}

so when we do,所以当我们这样做时,

import com.fasterxml.jackson.databind.ObjectMapper;
....

User user = new User("Max", 13, "{\"latitude\":30.0000,\"longitude\":32.0000}");

new ObjectMapper().writeValueAsString(user)), String.class);

I was expecting something like:我期待类似的东西:

{
  "name": "Max",
  "age": "13",
  "geofenceJson": {"latitude":30.0000, "longitude":32.0000}
}

instead I got it as a json value wrapped into a double quotes and skipped by backslashes as it was double jsonized - if this is actually a verb -相反,我将它作为一个 json 值包裹在双引号并被反斜杠跳过,因为它是双 jsonized - 如果这实际上是一个动词 -

{
  "name": "Max",
  "age": "13",
  "geofenceJson": "{\"latitude\":30.0000, \"longitude\":32.0000}"
}

I managed to overcome this problem by using @JsonRawValue我设法通过使用@JsonRawValue克服了这个问题

From documentation https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonRawValue.html it states the following:从文档https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonRawValue.ZFC35FDC70D5FC69D253EZ888

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.这对于注入已经在 JSON 中序列化的值或将 javascript function 定义从服务器传递到 ZDE9B9ED708E2F91E81 客户端非常有用。 Warning: the resulting JSON stream may be invalid depending on your input value.警告:根据您的输入值,生成的 JSON stream 可能无效。

So by doing,所以通过这样做,

import com.fasterxml.jackson.annotation.JsonRawValue;
....
class User {

  String name;

  int age;

  @JsonRawValue
  String geofenceJson; // this is a json already

  //allArgsConstructor, getters & setters
}

I kinda told Jackson that this is a json value already don't do your job here so same code in post generated the correct json我有点告诉 Jackson 这是一个 json 值已经不在这里做你的工作,所以帖子中的相同代码生成了正确的 json

{
  "name": "Max",
  "age": "13",
  "geofenceJson": {"latitude":30.0000, "longitude":32.0000}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM