【问题标题】:How do I implement a custom @JsonDeserialize method on an endpoint class?如何在端点类上实现自定义 @JsonDeserialize 方法?
【发布时间】:2013-10-03 20:01:49
【问题描述】:

我有一个类,其中有一个自定义反序列化器注释:

@JsonDeserialize(using = ConvertToNullDeserializer.class)
public void setObject(Integer pObj) {
    this.pObj = pObj;
}

当这个对象通过 ajax 发送到云端点时,我希望触发自定义脱轨器,但我只是得到:

{
  "error" : {
"message" : "com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: Can not construct instance of java.lang.Integer from String value 'null': not a valid Integer value\n at [Source: N/A; line: -1, column: -1] (through reference chain: 
"code" : 400,
"errors" : [ {
  "domain" : "global",
  "reason" : "badRequest",
  "message" : "com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: Can not construct instance of java.lang.Integer from String value 'null': not a valid Integer value\n at [Source: N/A; line: -1, column: -1] (through reference chain: 
   } ]
 }
}

谢谢!

【问题讨论】:

  • 我不确定我是否完全理解您的问题,云端点通常会为您处理序列化和反序列化。也许 @JsonDeserialize 注释不是您想要采用的路径,因为使用端点您将 json 相关的东西委托给系统。你的反序列化器是做什么的?

标签: java google-app-engine jquery google-cloud-endpoints


【解决方案1】:

端点不支持@JsonDeserialize,但您可以改用@ApiTransformer

标记一个类进行转换:

import com.google.api.server.spi.config.ApiTransformer;

@ApiTransformer(BarTransformer.class)
public class Bar {
  private final int x;
  private final int y;

  public Bar(int x, int y) {
    this.x = x;
    this.y = y;
  }

  public int getX() {
    return x;
  }

  public int getY() {
    return y;
  }
}

示例转换器:

import com.google.api.server.spi.config.Transformer;

public class BarTransformer implements Transformer<Bar, String> {
  public String transformTo(Bar in) {
    return in.getX() + "," + in.getY();
  }

  public Bar transformFrom(String in) {
    String[] xy = in.split(",");
    return new Bar(Integer.parseInt(xy[0]), Integer.parseInt(xy[1]));
  }
}

【讨论】:

  • 这适用于大多数情况,但当您有一个破坏模型的动态 json 请求(即可以是字符串或对象的字段)时会失败
猜你喜欢
  • 2020-03-11
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 1970-01-01
  • 2018-09-06
  • 2017-06-30
  • 2018-02-11
相关资源
最近更新 更多