整合JAX-RS和JSON-P

來源:互聯網
上載者:User

整合JAX-RS和JSON-P
整合JAX-RS和JSON-P 一、JSON-P和JSON-B介紹

在Java EE 7中引入了JSON Processing API,即JSON-P規範。JSON-P規範定義了一套標準的API來操縱JSON資料,這一點與JAXP規範相似(操縱XML的API規範)。在Java EE 8中還將引入JSON Binding API,即JSON-B規範。

 

二、JAX-RS 2.0支援JSON-P

JAX-RS 2.0規範是Java EE 7規範的一部分,它同時也支援JSON-P規範,比如對JsonObject類、JsonArray類、JsonStructure類等提供了開箱即用的支援。每一個相容JAX-RS 2.0規範的參考實現都提供了內建的支援以上類的實體Provider,使得JAX-RS應用程式可以輕鬆簡單地交換JSON資料。

 

三、例子1、從JAX-RS資源方法發散JSON數組
@GETpublic JsonArray buildJsonArray(){  return Json.createArrayBuilder().add(jsonp).add(jaxrs).build();}
2、從用戶端接收JSON資料
@POSTpublic void acceptJsonObject(JsonObject payload){  System.out.println(the payload -- + payload.toString());}
3、JsonObject使用的例子

1)JSON資料如下

 {     firstName: John, lastName: Smith, age: 25,     address : {         streetAddress: 21 2nd Street,         city: New York,         state: NY,         postalCode: 10021     },     phoneNumber: [         { type: home, number: 212 555-1234 },         { type: fax, number: 646 555-4567 }     ] }

2)構建JsonObject

 JsonObject value = Json.createObjectBuilder()     .add(firstName, John)     .add(lastName, Smith)     .add(age, 25)     .add(address, Json.createObjectBuilder()         .add(streetAddress, 21 2nd Street)         .add(city, New York)         .add(state, NY)         .add(postalCode, 10021))     .add(phoneNumber, Json.createArrayBuilder()         .add(Json.createObjectBuilder()             .add(type, home)             .add(number, 212 555-1234))         .add(Json.createObjectBuilder()             .add(type, fax)             .add(number, 646 555-4567)))     .build();
四、值得注意的情況

1、無需編寫自訂的MessageBodyReader類或MessageBodyWriter類的實現,正如前面提到的,JAX-RS規範提供了這些API。

2、使用注釋綁定JSON方法的方式目前還不支援(類似於在POJOs類上使用JAXB注釋),等未來的版本吧。GlassFish 4.1 (Jersey)和Wildfly 8.x (RESTEasy)已經支援了注釋綁定JSON方法,但這種使用方式還不是標準,應注意這一點。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.