我想编写一个简单的方法来接收表示 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);
}
上面的示例抛出异常:属性“locationRef”的 setter 定义冲突...
另一个选择是使用 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 听起来是一个更好的工具,因为它具有通用性,因此机械更加类型安全 - 如果它能工作的话......
最佳答案
不需要使用任何表示对象。在后台使用jackson,以下代码运行得非常好:
@Put
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Device b(Device device) {
// Do something with the POJO!!!
return device;
}
它转换输入并转换输出。下面是一个有关其工作原理的示例:
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}
关于java - 如何将reSTLet请求的json类型输入转换为POJO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19341019/