我花了半天的时间疯狂地让我的泽西服务接受并操纵JSON。
这是我正在做的事情: 在PHP中使用Zend Framework:
$client = new Zend_Http_Client("http://localhost:8080/api/");
$data = array("city"=> "Paris", "zip" => "1111");
$json = json_encode($data);
$client->setHeaders("Content-type", "application/json");
$client->setRawData($json, 'application/json')->request("GET");
API方法:
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response getAPI( Address addr) {
JSONObject out = new JSONObject();
out.put("city test",addr.getCity());
Response response = null;
return response.ok(out.toString()).header("Accept", "application/json").build();
}
在一个单独的文件中,我有一个带注释的类:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Address
{
@XmlElement(name="city")
public String city;
@XmlElement(name="zip")
public String zip;
public String getCity() {
return city;
}
}
我收到了不受支持的媒体类型错误:
Zend_Http_Response Object
(
[version:protected] => 1.1
[code:protected] => 415
[message:protected] => Unsupported Media Type
[headers:protected] => Array
(
[Server] => Apache-Coyote/1.1
[Content-type] => text/html;charset=utf-8
[Content-length] => 1117
[Date] => Tue, 29 May 2012 17:55:03 GMT
[Connection] => close
)
[body:protected] =>
我错过了什么?
谢谢大家, 丹尼尔
答案 0 :(得分:1)
我认为你已经过度复杂了。由于您的bean已注释,因此无需为其创建json对象。这是为你完成的。
return Reponse.ok(addr).build();