【问题标题】:Getting JSON out put from restful java client从restful java客户端获取JSON输出
【发布时间】:2012-07-08 03:23:52
【问题描述】:

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

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

这些是我遵循的教程

我的Java客户端main方法:

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();
    }
}

个人资料

/*
 * 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 相同的方式处理它,

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

如果您能在这件事上帮助我,我将不胜感激。谢谢!

【问题讨论】:

    标签: java json rest soa webservice-client


    【解决方案1】:

    我解决了同样的问题。 如果您的例外是:意外元素 (uri:"", local:"id").........

    别忘了添加以下代码:

        DefaultClientConfig clientConfig = new DefaultClientConfig();
        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
        Client client = Client.create(clientConfig);
    

    然后是代码:

    return resource.type(MediaType.APPLICATION_JSON_TYPE).get(new GenericType<List<MyClass>>(){});
    

    会好的。

    【讨论】:

    • 我不得不迁移到 php 客户端而不是 java。但这可能对某人有所帮助。谢谢:)
    • 非常可爱的答案为我的案例节省了我的时间,谢谢:)
    • 这很有帮助。当我已经写了accept(MediaType.APPLICATION_JSON_TYPE) 时,我没有想到它可能会尝试将其读取为 XML。
    【解决方案2】:

    1) 生成此错误的人显然在期待 XML 输入。不是 JSON。您需要尽快更改:

     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) 屏幕截图中的内容(大概是泽西岛?)肯定没问题。

    3) 我没有按照整个教程进行操作,您也没有提供足够的信息来说明您误入歧途的地方。

    建议:

    只需回顾您在教程中的步骤,并确保确定您选择的是“JSON”(不是 XML,不是 SOAP)一路走来。

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

    好的 - 感谢更新。这就是我们所处的位置:

    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) 你说这个堆栈回溯来自客户端。

    所以你的服务器是 100% 好的 - 你需要做的唯一的事情就是修复你的客户端。酷:)

    3) 回溯显示客户端期待 XML ...但获取的是 JSON。

    所以唯一你应该解决的事情是告诉你的客户“嘿:阅读 JSON,而不是 XML”。再次 - 很酷:)

    4) 你是怎么做到的?

    嗯,对于初学者,你需要去掉这条线(如果你还没有的话):

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

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

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

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

    注意:

    无论你需要做什么 - 它应该真的简单!请查看链接、查看您的代码和您的测试客户端配置……然后发回您发现的内容!

    提前谢谢你...

    【讨论】:

    • 不,实际上教程很好(工作)。他们在那里使用xml。但我需要改用 JSON。就是这样。
    • @RJ45 - 回溯清楚地显示它是 RECEIVING Json,但它是 EXPECTING XML。这就是你需要解决的问题。问:堆栈回溯到底发生在哪里:您的客户端还是您的服务器?那是你需要修理的人。问:截图是什么:你的客户端,还是你的服务器?他肯定是(发送?接收?)Json。
    • -运行客户端时提示错误。 - 截图取自服务器(点击测试restful服务)。我可以使用 xml 发送或接收,但不能使用 JSON。
    • @RJ45 - 请阅读我上面的“附录”......如果它有效,请告诉我们!祝你好运!
    • 是的。你说的对。这是一个简单的改变。我刚刚更改了 ClientResponse response = client.findAll_XML(ClientResponse.class);进入 ClientResponse 响应 = client.findAll_JSON(ClientResponse.class);并使用 response.getEntity(String.class) 访问它。就这样。谢谢!
    【解决方案3】:

    http://smoothexample.com/webservices/apache_cxf_rest_web_services_client.html

    上面的例子给出了使用 apache cxf 的示例客户端应用程序,这里客户端可以通过提供“Accept”标头来使用 xml 和 json。

    这里还提供了一个 cxf REST Web 服务的简单示例,它甚至可以根据“Accept”标头返回 xml 和 json。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 2012-09-02
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多