简体   繁体   English

在Jackson中,如何将非Map Iterable序列化为数组?

[英]In Jackson, how do I serialize a non-Map Iterable as an array?

Basically, what is the easiest way to make this test pass without changing the asymptotic runtime (ie, please don't tell me to copy set1 and set2 into a list because the whole point of Iterables.concat() is to avoid the copy): 基本上,在不更改渐近运行时的情况下,通过此测试的最简单方法是什么(即,请不要告诉我将set1set2复制到列表中,因为Iterables.concat()是避免复制) :

@Test
public void jacksonObjectMapperSerializesIterableAsList() throws IOException {
  SortedSet<String> set1 = new TreeSet<>();
  set1.add("a");
  set1.add("b");
  set1.add("c");
  SortedSet<String> set2 = new TreeSet<>();
  set2.add("d");
  set2.add("e");
  set2.add("f");

  ObjectMapper mapper = new ObjectMapper();

  // This part passes.
  StringWriter set1Writer = new StringWriter();
  mapper.writeValue(set1Writer, set1);
  assertEquals("[\"a\",\"b\",\"c\"]", set1Writer.toString());

  // This part fails.
  // The actual value is: {"empty":false}
  StringWriter setsWriter = new StringWriter();
  mapper.writeValue(setsWriter, com.google.common.collect.Iterables.concat(set1, set2));
  assertEquals("[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]", setsWriter.toString());
}

Apparently the solution is to configure the ObjectMapper with the GuavaModule : 显然,解决方案是使用GuavaModule配置ObjectMapper

ObjectMapper mapper = new ObjectMapper().registerModule(new GuavaModule());

I think this was the relevant issue/fix: https://github.com/FasterXML/jackson-datatype-guava/issues/46 我认为这是相关的问题/修复: https : //github.com/FasterXML/jackson-datatype-guava/issues/46

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

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