2012-05-29 72 views
1

我花了半天的时间疯狂地让我的泽西服务接受并操纵JSON。将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] => 

我错过了什么?

谢谢大家, 丹尼尔

回答

1

我觉得你在这复杂。由于你的bean被注释了,所以不需要为它创建一个json对象。这是为你完成的。

return Reponse.ok(addr).build(); 
+0

感谢您的回答,除了输出,我想我的问题是在输入中获取json。这正是我努力实现的目标! – Daniele

+0

只要你的json输入结构正确,你应该全部设置。编组和解组是为你完成的。如果它不起作用,请尝试添加城市/邮编的设置方法,但我不确定是否需要它们。另外,我假设你在服务类中正确设置了@Path? –