序列化一个 Java Map 使用 Jackson

huangapple go评论70阅读模式
英文:

Serialising a Java Map with Jackson

问题

Sure, here's the translated content:

我正在使用Jackson库进行JSON序列化,

在序列化Java Map时,例如,map<String,String> 包含

{<color, green>,<color, blue>}

我希望将其序列化为

"colormap":[{"key": "color", "value":"green"}, {"key": "color", "value":"blue"}]

但它总是序列化为

"colormap":[{"color":"green"}, {"color":"blue"}]
英文:

I am using Jackson library for serialising JSON,

having Serialising a Java Map, for ex, map&lt;String,String&gt; has

{&lt;color, green&gt;,&lt;color, blue&gt;}

I want this to be serialised as

&quot;colormap&quot;:[{&quot;key&quot;: &quot;color&quot;:, &quot;value&quot;:&quot;green&quot;}, {&quot;key&quot;: &quot;color:, &quot;value&quot;:&quot;blue&quot;}]

but its always serialising as

&quot;colormap&quot;:[{&quot;color&quot;:&quot;green&quot;}, {&quot;color:&quot;blue&quot;}]

答案1

得分: 1

你的输出 JSON 是一个数组,而不是一个映射(map)。在没有查看你的代码的情况下,很难确定底层的数据结构是什么,但为了实现你所需求的功能,你可以考虑使用如下所示的类:

class Thing {
  private String key;
  private String value;
  /// 根据需要添加访问器(accessors)
}

然后将你的颜色映射声明为 `List<Thing>`。这样应该可以按照你的期望对数据进行序列化serialize)。
英文:

Your output JSON is an array, not a map- Without looking at your code it's hard to tell what the underlying data structure is,but to do what you're looking for you might consider a class such as:

class Thing {
  private String key ;
  private String value ;
  /// add accessors as needed
}

and then declare your colormap as List&lt;Thing&gt;. This should seralize your data per your expectation.

huangapple
  • 本文由 发表于 2020年8月15日 06:14:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63420635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定