从宁静的Java客户端获取JSON [英] Getting JSON out put from restful java client

查看:132
本文介绍了从宁静的Java客户端获取JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用REST(Jersey 1.8)开发Web服务.目前,我正在使用XML在Java客户端和服务器之间进行通信.

I'm developing a web service using REST (Jersey 1.8). Currently I'm using XML to communicate between the Java client and the server.

我需要将其更改为JSON:我该怎么做?我有一堆从NetBeans自动生成的代码,不知道该怎么做以及如何做.在测试服务时,它会显示JSON数据.我无法做的是在我的main方法中处理它.

I need to change it to JSON: how can I do that? I have bunch of auto generated code from NetBeans, and have no idea what to do and how. When the testing the service it shows the JSON data. What I'm unable to do is deal with it within my main method.

这些是我遵循的教程

  • http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/RESTfulWebServices/RESTfulWebservices.htm
  • http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/RESTfulWebServices_Part2/RESTfulWebservicesPart2.htm
  • http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/RESTfulWebServices_Part3/RESTfulWebservicesPart3.htm

我的Java客户端main方法:

My Java client main method:

public class SOATestClient {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        PersonJerseyClient client = new PersonJerseyClient();
        ClientResponse response = client.findAll_XML(ClientResponse.class);


        GenericType<List<Person>> genericType = new GenericType<List<Person>>() {
        };
// Returns an ArrayList of Players from the web service
        List<Person> data = new ArrayList<Person>();
        data = (response.getEntity(genericType));
        System.out.println("Retreiving and Displaying Players Details");
        for (Person person : data) {
            System.out.println("FirstName: " + person.getName());
            System.out.println("ID : " + person.getId());
            System.out.println(" Age : " + person.getAge());
        }
        client.close();
    }
}

personjerseycilent

personjerseycilent

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jerseyclients;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;

/**
 * Jersey REST client generated for REST resource:PersonFacadeREST
 * [entity.person]<br>
 *  USAGE:
 * <pre>
 *        PersonJerseyClient client = new PersonJerseyClient();
 *        Object response = client.XXX(...);
 *        // do whatever with response
 *        client.close();
 * </pre>
 *
 * @author rj45
 */
public class PersonJerseyClient {
    private WebResource webResource;
    private Client client;
    private static final String BASE_URI = "http://localhost:8080/SOATestService/resources";

    public PersonJerseyClient() {
        com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig();
        client = Client.create(config);
        webResource = client.resource(BASE_URI).path("entity.person");
    }

    public void remove(String id) throws UniformInterfaceException {
        webResource.path(java.text.MessageFormat.format("{0}", new Object[]{id})).delete();
    }

    public String countREST() throws UniformInterfaceException {
        WebResource resource = webResource;
        resource = resource.path("count");
        return resource.accept(javax.ws.rs.core.MediaType.TEXT_PLAIN).get(String.class);
    }

    public <T> T findAll_XML(Class<T> responseType) throws UniformInterfaceException {
        WebResource resource = webResource;
        return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
    }

    public <T> T findAll_JSON(Class<T> responseType) throws UniformInterfaceException {
        WebResource resource = webResource;
        return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
    }

    public void edit_XML(Object requestEntity) throws UniformInterfaceException {
        webResource.type(javax.ws.rs.core.MediaType.APPLICATION_XML).put(requestEntity);
    }

    public void edit_JSON(Object requestEntity) throws UniformInterfaceException {
        webResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(requestEntity);
    }

    public void create_XML(Object requestEntity) throws UniformInterfaceException {
        webResource.type(javax.ws.rs.core.MediaType.APPLICATION_XML).post(requestEntity);
    }

    public void create_JSON(Object requestEntity) throws UniformInterfaceException {
        webResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(requestEntity);
    }

    public <T> T findRange_XML(Class<T> responseType, String from, String to) throws UniformInterfaceException {
        WebResource resource = webResource;
        resource = resource.path(java.text.MessageFormat.format("{0}/{1}", new Object[]{from, to}));
        return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
    }

    public <T> T findRange_JSON(Class<T> responseType, String from, String to) throws UniformInterfaceException {
        WebResource resource = webResource;
        resource = resource.path(java.text.MessageFormat.format("{0}/{1}", new Object[]{from, to}));
        return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
    }

    public <T> T find_XML(Class<T> responseType, String id) throws UniformInterfaceException {
        WebResource resource = webResource;
        resource = resource.path(java.text.MessageFormat.format("{0}", new Object[]{id}));
        return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
    }

    public <T> T find_JSON(Class<T> responseType, String id) throws UniformInterfaceException {
        WebResource resource = webResource;
        resource = resource.path(java.text.MessageFormat.format("{0}", new Object[]{id}));
        return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
    }

    public void close() {
        client.destroy();
    }

}

我尝试通过以下方式访问它,并以与XML相同的方式处理它,

I try to access it with the following, and deal it with same way as XML,

ClientResponse response = client.findAll_JSON(ClientResponse.class);

但这给了我

Exception in thread "main" javax.ws.rs.WebApplicationException: javax.xml.bind.UnmarshalException
 - with linked exception:
[com.sun.istack.internal.SAXParseException2; lineNumber: 0; columnNumber: 0; unexpected element (uri:"", local:"id"). Expected elements are <{}person>]
    at com.sun.jersey.core.provider.jaxb.AbstractListElementProvider.readFrom(AbstractListElementProvider.java:251)
    at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:553)
    at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:523)
    at soatestclient.SOATestClient.main(SOATestClient.java:33)
Caused by: javax.xml.bind.UnmarshalException

如果您能在此问题上为我提供帮助,我将不胜感激.谢谢!

I would be grateful to if you could help me on this matter. Thank you!

推荐答案

1)产生此错误的人显然都希望XML输入.不是JSON.您需要尽快更改该值:

1) Whoever is generating this error, is clearly expecting XML input. Not JSON. You need to change that ASAP:

 javax.ws.rs.WebApplicationException: javax.xml.bind.UnmarshalException
 com.sun.istack.internal.SAXParseException2;
 <= javax.xml.bind and SAXParse are both XML-only: JSON not invited

2)屏幕截图中的内容(大概是泽西岛?)肯定可以.

2) The stuff in your screen shot (presumably Jersey?) is definitely OK.

3)我没有按照整个教程进行操作,并且您还没有提供足够的信息来告诉您误入歧途.

3) I haven't followed the whole tutorial, and you haven't given enough information to tell where you went astray.

建议:

只需追溯本教程中的步骤,并确保确定您选择的是"JSON"( not XML和 not SOAP)每一步.

Just retrace your steps in the tutorial, and make sure you're selecting "JSON" (not XML, and not SOAP) every step of the way.

===========附录==========

=========== ADDENDUM ===========

确定-感谢您进行更新.这是我们的位置:

OK - Thanx for the update. Here's where we're at:

1)这是问题所在:

Exception in thread "main" javax.ws.rs.WebApplicationException: javax.xml.bind.UnmarshalException
 - with linked exception:
[com.sun.istack.internal.SAXParseException2; lineNumber: 0; columnNumber: 0; unexpected element (uri:"", local:"id"). Expected elements are <{}person>]
    at com.sun.jersey.core.provider.jaxb.AbstractListElementProvider.readFrom(AbstractListElementProvider.java:251)
    at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:553)
    at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:523)
    at soatestclient.SOATestClient.main(SOATestClient.java:33)
Caused by: javax.xml.bind.UnmarshalException

2)您说此堆栈回溯来自客户端.

2) You said this stack traceback is coming from the client.

因此您的服务器是100%正常的-您只需要做的 就是修复您的客户端.酷:)

So your server is 100% OK - the ONLY thing you need to do is fix your client. Cool :)

3)追溯显示客户端希望使用XML ...,但改为使用JSON.

3) The traceback shows the client is expecting XML ... but getting JSON instead.

因此,您唯一需要修复的 事情是告诉您的客户端嘿:读取JSON,而不是XML".再次-很酷:)

So the ONLY thing you should need to fix is to tell your client "Hey: read JSON, not XML". Again - cool :)

4)你怎么做到的?

好吧,对于初学者来说,您需要摆脱这一行(如果还没有的话):

Well, for starters, you need to get rid of this line (if you haven't already):

// Bad, bad bad.  Don't do this!|
ClientResponse response = client.findAll_XML(ClientResponse.class);

5)您可能想更改客户端代码的其他部分-我不知道.

5) You might want to change other parts of your client code - I don't know.

您可能还想更改客户端的配置-我也不知道.

You might also want to change your client's configuration - I don't know that, either.

6)建议:查看其他教程-可能会为您指明正确的方向:

6) Suggestion: look at this other tutorial - it might point you in the right direction:

注意:

无论做什么,您都需要做-应当完全简单!请查看链接,查看代码和测试客户端配置...,然后回发找到的内容!

WHATEVER you need to do - it should be REALLY simple! Please review the link, review your code and your test client configuration ... and post back what you find!

提前谢谢...

这篇关于从宁静的Java客户端获取JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆