2012-05-29 108 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? –