杰克逊“没有单一字符串构造函数/工厂方法”的例外

时间:2013-01-11 13:02:59

标签: json jackson

我有一个实体:

E{
    String screen;
}

我需要将screen-field分配给我作为json字符串

接收的值之一
  

“屏幕”:{ “LDPI”: “1.JPG”, “MDPI”: “2.JPG”, “hdpi的”: “3.JPG”, “xhdpi”: “4.JPG”}

不幸的是,我无法声明容器类而不仅仅是字符串,因为orm系统使用了E类。

为了实现它,我创建了自定义值 - 解串器:

public class DensityDeserializer extends JsonDeserializer<String> {

    public final static int LDPI = 0;
    public final static int MDPI = 1;
    public final static int HDPI = 2;
    public final static int XHDPI = 3;

    private int mDensity = LDPI;

    public DensityDeserializer() {
    }

    public DensityDeserializer(int density) {
        mDensity = density;
    }

    @Override
    public String deserialize(JsonParser jsonparser,
            DeserializationContext deserializationcontext) throws IOException,
            JsonProcessingException {
        ScreenContainer screenContainer = jsonparser
                .readValueAs(ScreenContainer.class);
        switch (mDensity) {
        default:
            return "";
        case LDPI:
            return screenContainer.getLdpi();
        case MDPI:
            return screenContainer.getHdpi();
        case HDPI:
            return screenContainer.getHdpi();
        case XHDPI:
            return screenContainer.getXhdpi();
        }
    }

    public static class ScreenContainer {
        public String ldpi = "";
        public String mdpi = "";
        public String hdpi = "";
        public String xhdpi = "";

        public ScreenContainer() {
            // TODO Auto-generated constructor stub
        }

        public String getLdpi() {
            return ldpi;
        }

        public void setLdpi(String ldpi) {
            this.ldpi = ldpi;
        }

        public String getMdpi() {
            return mdpi;
        }

        public void setMdpi(String mdpi) {
            this.mdpi = mdpi;
        }

        public String getHdpi() {
            return hdpi;
        }

        public void setHdpi(String hdpi) {
            this.hdpi = hdpi;
        }

        public String getXhdpi() {
            return xhdpi;
        }

        public void setXhdpi(String xhdpi) {
            this.xhdpi = xhdpi;
        }
    }
}

当我运行该程序时,它会引发异常:

  

01-11 12:29:06.833:W / System.err(1501):com.fasterxml.jackson.databind.JsonMappingException:无法从JSON字符串实例化类型[simple type,class .DensityDeserializer $ ScreenContainer]的值;没有单字符串构造函数/工厂方法(通过引用链:E。[“screen”])

有什么建议吗?

0 个答案:

没有答案