简体   繁体   English

Jackson ObjectMapper从String序列化为JSON作为名称-值

[英]Serialize to JSON as name-value from String by Jackson ObjectMapper

I have some String, like: 我有一些String,例如:

String value = "123";

And when i serialize this string to json via ObjectMapper: 当我通过ObjectMapper将此字符串序列化为json时:

objectMapper.writeValueAsString(value);

Output is: 输出为:

"123"

Is it possible to write String using either string name and string value? 是否可以使用字符串名称和字符串值来编写String? Desired output: 所需的输出:

"value" : "123"

PS: i dont want to create DTO object with one field for serializing one String value. PS:我不想用一个字段来序列化一个String值的DTO对象。

you can also use the Jackson JsonGenerator 您还可以使用Jackson JsonGenerator

try (JsonGenerator generator = new JsonFactory().createGenerator(writer)) {
     generator.writeStartObject();
     generator.writeFieldName("value");
     generator.writeString("123");
     generator.writeEndObject();
  }
}

If you have a plain string you'll get out a plain string when serialised. 如果您有纯字符串,则序列化时会得到纯字符串。 If you want to wrap it in an object then use a map for the simplest solution. 如果要将其包装在一个对象中,请使用地图作为最简单的解决方案。

String value = "123";
Map<String, String> obj = new HashMap<>();
obj.put("value", value);

Passing that through the mapper will produce something like this: 将其传递给映射器将产生以下内容:

{ "value": "123" }

If you change the map to <String, Object> you can pass in pretty much anything you want, even maps within maps and they'll serialise correctly. 如果将地图更改为<String, Object> ,则几乎可以传递任何您想要的内容,即使地图内的地图也可以正确序列化。

If you really can't have the enclosing curly braces you can always take the substring but that would be a very weird use case if you're still serialising to JSON. 如果确实没有封闭的花括号,则可以始终使用子字符串,但是如果您仍要序列化为JSON,那将是一个非常奇怪的用例。

Create a Map: 创建地图:

Map<String, String> map = new HashMap<>();
map.put("value", value);
String parsedValue = ObjectMapper.writeValueAsString(map);

and you will get: {"value":"123"} 您将获得: {"value":"123"}

如果您使用的是Java 8,并且希望以自动化的方式进行操作而无需创建地图或手动放置字符串变量名称“值”,则需要遵循以下链接:

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

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