简体   繁体   中英

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

I have some String, like:

String value = "123";

And when i serialize this string to json via ObjectMapper:

objectMapper.writeValueAsString(value);

Output is:

"123"

Is it possible to write String using either string name and string value? Desired output:

"value" : "123"

PS: i dont want to create DTO object with one field for serializing one String value.

you can also use the 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.

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.

Create a Map:

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

and you will get: {"value":"123"}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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