使用Spring,Scala和Jackson将JSON反序列化为Map [String,SomeJavaObject]

时间:2014-01-10 01:14:38

标签: java json spring scala jackson

我刚刚开始尝试使用Scala,我正在尝试在Jackson 2.3.1和jackson-module-scala的现有Java / Spring应用程序中使用它。

我正在尝试反序列化JSON(例如以下内容),以Map StringColorMap个对象结束,但是当我运行下面的代码时,我最终得到了一个StringMap的{​​{1}}代替:

{
  "1A-X": {
    "c": 0,
    "m": 0,
    "y": 0,
    "k": 0,
    "r": 255,
    "g": 255,
    "b": 255
  }
}

为什么我的结果Map的值是另一个Map而不是Color对象?

Color是一个现有的Java类,带有@JsonCreator带注释的构造函数。

@RequestMapping(Array("/swatches"))
def setSwatches(@RequestBody swatches: Map[String, Color]) = {
  println(swatches)
  println("Map class " + swatches.getClass + ", key class " + swatches.get("1A-X").get.getClass)
}

将上述JSON传递给此代码的输出如下:

Map(1A-X -> Map(y -> 1, m -> 1, b -> 51, g -> 1, c -> 1, r -> 5, k -> 1))
Map class class scala.collection.immutable.Map$Map1, key class class scala.collection.immutable.HashMap$HashTrieMap

如果我直接将Color输入而没有代码到Color map,反序列化就会按预期工作。

请让我知道如何成功地直接反序列化为Map [String,Color]。

更多详情

Color.java

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;

public final class Color {
  static final Color NOCOLOR = new Color(0f, 0f, 0f, -1f, -1, -1, -1);
  private final float c, m, y, k;
  private final int   r, g, b;

  /** from string in format: CMYKcolor(0,0,0,0) or CMYKRGBcolor(c,m,y,k,r,g,b)*/
  static Color valueOf(final String colorStringFormat) {
    return colorStringFormat == null || colorStringFormat.isEmpty()
    ? NOCOLOR : new Color(colorStringFormat);
  }

  /** from string in format: CMYKcolor(0,0,0,0) CMYKRGBcolor(c,m,y,k,r,g,b)*/
  Color(final String colorStringFormat) {
    this(colorStringFormat.substring(colorStringFormat.indexOf('(') + 1,
      colorStringFormat.indexOf(')')).split(","));
  }

  Color(final String... colors) {
    this(Float.parseFloat(colors[0]), Float.parseFloat(colors[1]),
      Float.parseFloat(colors[2]), Float.parseFloat(colors[3]),
      (colors.length==4)?-1:Integer.parseInt(colors[4]), 
        (colors.length==4)?-1:Integer.parseInt(colors[5]),
          (colors.length==4)?-1:Integer.parseInt(colors[6])); 
  }

  /** all values must be between 0f and 1f inclusive */
  public Color(final float c, final float m, final float y, final float k) {
    this(c, m, y, k, -1, -1, -1);
  }

  /** cmyk values must be between 0f and 1f inclusive; rgb values must be between 0 and 255 inclusive */
  @JsonCreator
  public Color(@JsonProperty("c") final float c, @JsonProperty("m") final float m, @JsonProperty("y") final float y,
    @JsonProperty("k") final float k, @JsonProperty("r") final int r, @JsonProperty("g") final int g,
    @JsonProperty("b") final int b) {
    Preconditions.checkArgument(isValidCMYKValue(c, m, y, k),
      "CMYK values must be a float value between 0 and 1 inclusive. " +
      "Was (%s, %s, %s, %s).", c, m, y, k);
    Preconditions.checkArgument(isValidRGBValue(r, g, b),
      "RBG values must be an int value between 0 and 255 inclusive " +
      "or -1 to indicate no value. Was (%s, %s, %s).", r, g, b);
    this.c = c;
    this.m = m;
    this.y = y;
    this.k = k;
    this.r = r;
    this.g = g;
    this.b = b;                     
  }

  private static boolean isValidCMYKValue(final float c, final float m, final float y, final float k) {
    return
    c >= 0f && c <= 1f &&
    m >= 0f && m <= 1f &&
    y >= 0f && y <= 1f &&
    (k >= 0f && k <= 1f) || k == -1;
  }

  private static boolean isValidRGBValue(final int r, final int g, final int b) {
    return (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255)
    || (r == -1 && g == -1 && b == -1);
  }

  public float getC() { return c; }
  public float getM() { return m; }
  public float getY() { return y; }
  public float getK() { return k; }
  public int   getR() { return r; }
  public int   getG() { return g; }
  public int   getB() { return b; }

  @JsonIgnore
  public boolean isRGBAlternatePresent() {
    return r > -1;
  }

  public boolean isPresent() {
    return k > -1;
  }

}

当我传入以下JSON并使用@RequestBody swatch: Color时,我实际上得到了一个Color对象。在我的故障排除中,我还尝试绑定到ListMap[String, ListMap[String, Object]]以维护密钥排序,但杰克逊仍然最终绑定到HashMap

{
  "c": 0,
  "m": 0,
  "y": 0,
  "k": 0,
  "r": 255,
  "g": 255,
  "b": 255
}

1 个答案:

答案 0 :(得分:2)

此问题的根本原因似乎不是Scala特定的,尽管Scala模块当前不支持它的解决方法。

关于这个主题的另一个问题是,当反序列化泛型类型时,Spring没有向Jackson提供完全指定的类型信息; Spring正在有效地告诉杰克逊将Map[_,_]反序列化。

Map JSON array of objects to @RequestBody List<T> using jackson

此处和其他地方提到的解决方法是创建所需类型的派生类,并将其用作方法参数:

class ColorMap extends java.util.HashMap[String,Color]
@RequestMapping(Array("/swatches"))
def setSwatches(@RequestBody swatches: ColorMap) = ...

这适用于Java集合,但事实证明Scala模块不能正确支持此用例。此缺陷被跟踪为Issue 122

在Scala模块实现奇偶校验之前,或者直到Spring更正其类型传播,您将需要使用Java集合的派生类,如上所示。