MOXy作为您的JAX-RS JSON提供程序–客户端

最近,我发布了如何利用EclipseLink JAXB(MOXy)的JSON绑定来创建RESTful服务。 在本文中,我将演示在客户端利用MOXy的JSON绑定有多么容易。

URI

这篇文章将重点介绍我们在上一篇文章中声明的服务中的以下URI。 以下呼叫将返回居住在“任何城镇”的客户列表。

http://localhost:8080/CustomerService/rest/customers/findCustomersByCity/Any%20Town

Java SE客户端API

在第一个示例中,我们将使用标准的Java SE 6 API。 一些有趣的注意事项:

  • MOXy可以直接封送(第35行)和解封(第28行)往返于JSON数组的集合,而无需包装对象。
  • MOXy没有编译时间依赖性(它是运行时依赖性)。
  • eclipselink.media-type属性用于在unmarshaller(第25行)和marshaller(第33行)上启用JSON绑定。
  • eclipselink.json.include-root属性用于指示@XmlRootElement批注在JSON绑定中应被忽略(第26和34行)。
package example;

import java.io.InputStream;
import java.net.*;
import java.util.List;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.example.Customer;

public class JavaSEClient {

    private static final String MEDIA_TYPE = "application/json";

    public static void main(String[] args) throws Exception {
        String uri = "http://localhost:8080/CustomerService/rest/customers/findCustomersByCity/Any%20Town";
        URL url = new URL(uri);
        HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", MEDIA_TYPE);

        JAXBContext jc = JAXBContext.newInstance(Customer.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setProperty("eclipselink.media-type", MEDIA_TYPE);
        unmarshaller.setProperty("eclipselink.json.include-root", false);
        InputStream xml = connection.getInputStream();
        List<Customer> customers = (List<Customer>) unmarshaller.unmarshal(new StreamSource(xml), Customer.class).getValue();
        connection.disconnect();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty("eclipselink.media-type", MEDIA_TYPE);
        marshaller.setProperty("eclipselink.json.include-root", false);
        marshaller.marshal(customers, System.out);
    }

}

输出量

以下是运行Java SE客户端的输出。 对于那些可能使用JAXB( JSR-222 )实现和Jettison之类的东西来产生/使用JSON的人,以下是一些值得注意的有趣事项:

  • MOXy将集合呈现为JSON数组。
  • MOXy正确表示数字值而不带引号(第26行)。
  • MOXy用方括号正确地包围了大小为1的集合(第28和32行)。
[ {
   "address" : {
      "city" : "Any Town",
      "id" : 1,
      "street" : "1 A Street"
   },
   "firstName" : "Jane",
   "id" : 1,
   "lastName" : "Doe",
   "phoneNumbers" : [ {
      "id" : 2,
      "num" : "555-2222",
      "type" : "HOME"
   }, {
      "id" : 1,
      "num" : "555-1111",
      "type" : "WORK"
   } ]
}, {
   "address" : {
      "city" : "Any Town",
      "id" : 10,
      "street" : "456 Another Road"
   },
   "firstName" : "Sue",
   "id" : 10,
   "lastName" : "Jones",
   "phoneNumbers" : [ {
      "id" : 10,
      "num" : "555-3333",
      "type" : "WORK"
   } ]
} ]

泽西岛客户端API

JAX-RS 2.0( JSR-339 )正在致力于标准化客户端API。 使用JAX-RS 1.0,许多实现都提供了自己的版本。 以下是使用Jersey提供的客户端API的示例。 注意我们如何利用服务器端使用的完全相同的MessageBodyReader / Writer (第14行,将MOXy称为JAX-RS JSON提供程序–服务器端 )。 我还指定了LoggingFilter (第17行),因此我们可以仔细查看该消息。

package example;

import java.util.List;
import org.example.Customer;
import org.example.MOXyJSONProvider;
import com.sun.jersey.api.client.*;
import com.sun.jersey.api.client.config.*;
import com.sun.jersey.api.client.filter.LoggingFilter;

public class JerseyClient {

    public static void main(String[] args) {
        ClientConfig cc = new DefaultClientConfig();
        cc.getClasses().add(MOXyJSONProvider.class);

        Client client = Client.create(cc);
        client.addFilter(new LoggingFilter());

        WebResource resource = client.resource("http://localhost:8080/CustomerService/rest/customers");
        List<Customer> customers = resource.path("/findCustomersByCity/Any%20Town").accept("application/json").get(new GenericType<List<Customer>>(){});

        for(Customer customer : customers) {
            System.out.println(customer.getFirstName());
        }
    }

}

输出量

以下是运行Jersey客户端的输出。

14-Mar-2012 4:08:12 PM com.sun.jersey.api.client.filter.LoggingFilter log
INFO: 1 * Client out-bound request
1 > GET http://localhost:8080/CustomerService/rest/customers/findCustomersByCity/Any%20Town
1 > Accept: application/json
1 > 

14-Mar-2012 4:08:12 PM com.sun.jersey.api.client.filter.LoggingFilter log
INFO: 1 * Client in-bound response
1 < 200
1 < Transfer-Encoding: chunked
1 < Date: Wed, 14 Mar 2012 20:08:12 GMT
1 < Content-Type: application/json
1 < X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.1 Java/Oracle Corporation/1.7)
1 < Server: GlassFish Server Open Source Edition 3.1.1
1 < 
[{"address" : {"city" : "Any Town", "id" : 1, "street" : "1 A Street"}, "firstName" : "Jane", "id" : 1, "lastName" : "Doe", "phoneNumbers" : [{"id" : 1, "num" : "555-1111", "type" : "WORK"}, {"id" : 2, "num" : "555-2222", "type" : "HOME"}]}, {"address" : {"city" : "Any Town", "id" : 10, "street" : "456 Another Road"}, "firstName" : "Sue", "id" : 10, "lastName" : "Jones", "phoneNumbers" : [{"id" : 10, "num" : "555-3333", "type" : "WORK"}]}]

Doe, Jane
Jones, Sue

进一步阅读

如果您喜欢这篇文章,那么您可能也会对以下内容感兴趣:

参考: MOXy作为您的JAX-RS JSON提供程序–来自Java XML和JSON绑定博客的JCG合作伙伴 Blaise Doughan的客户端


翻译自: https://www.javacodegeeks.com/2012/04/moxy-as-your-jax-rs-json-provider_18.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值