【问题标题】:How to convert a json type input of a restlet request to a POJO?如何将restlet请求的json类型输入转换为POJO?
【发布时间】:2013-10-13 01:51:00
【问题描述】:

我想编写一个简单的方法来接收代表 POJO 的 json 并使用该 POJO。

示例(接收和返回 POJO):

@Put("json")
public Representation b(JacksonRepresentation<Device> deviceRepresentation)
        throws IOException {
    Device device = deviceRepresentation.getObject();
    // Use the device
    return new JacksonRepresentation<Device>(device);
}

上面的例子抛出了一个异常:Conflicting setter definitions for property "locationRef"...

另一种选择是使用 JsonRepresentation,但我找不到将其转换为 POJO 的方法:

@Put("json")
public Representation b(JsonRepresentation jsonRepresentation) {
    // How to convert the jsonRepresentation to a POJO???
    return new JsonRepresentation(new Device("2", 2));
}

Jackson 听起来是一个更好的工具,因为它具有通用性,因此类型更安全 - 只要它可以工作......

【问题讨论】:

  • 这有点像将外部化形式与编译时逻辑混合在一起。我的下意识反应是将 JSON 转换为 Map,然后通过 util 将该 Map 转换为 POJO,然后将该 POJO 传递给您的简单方法。摆脱所有这些注释的东西。 JSON != 对象。

标签: java json jackson restlet


【解决方案1】:

Ne 需要使用任何表示对象。以下在后台使用 jackson 效果很好:

@Put
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Device b(Device device) {
    // Do something with the POJO!!!
    return device;
}

它转换输入并转换输出。这是它如何工作的 curl 示例:

curl -i -X PUT -H 'Content-Type: application/json' -d '{"port":3,"ip":"3"}' http://localhost:8888/restlet/

结果:

HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Date: Sun, 13 Oct 2013 02:03:48 GMT
Accept-Ranges: bytes
Server: Development/1.0
Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept
Cache-Control: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Content-Length: 19

{"ip":"3","port":3}

【讨论】:

  • 你能贴出使用这个的资源代码吗?这是我想做的事情,但我正试图弄清楚它是如何连接的。是否只有一个 b(Device device) 方法?
  • 当然:public class Device { private String ip;私人 int 端口; @Deprecated public Device() {} public Device(String ip, int port) { super();这个.ip = ip; this.port = 端口; } public String getIp() { return ip; } public int getPort() { 返回端口; } }
  • 看来我可以删除 @Produces@Consumes 注释。它会被自动解析。有关如何执行此操作的示例,请参见以下内容:restlet.org/learn/guide/2.1/introduction/first-steps/…。 curl 会得到相同的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-06
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
相关资源
最近更新 更多