Jersey:JSON 对象列表

发布于 2024-12-07 20:51:08 字数 2854 浏览 0 评论 0原文

我试图在我的 Jersey 实现资源类中检索如下对象的 post 集合:

@POST
@Path("/send")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String sendEmails(ArrayList<AnyEmail> email) {
    //emailManager.sendEmail(email);
    return "success";
}

我在 `AnyEmail.xml` 上面有 @XmlRootElement

但是,当我使用 REST 客户端工具这样发布时:

 emails : [
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"},
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"}
      ]

我得到:

<html><head><title>Apache Tomcat/7.0.22 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 500 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Exception report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The server encountered an internal error () that prevented it from fulfilling this request.</u></p><p><b>exception</b> <pre>javax.servlet.ServletException: Servlet execution threw an exception
</pre></p><p><b>root cause</b> <pre>java.lang.Error: Error: could not match input
    com.sun.jersey.json.impl.reader.JsonLexer.zzScanError(JsonLexer.java:491)
    com.sun.jersey.json.impl.reader.JsonLexer.yylex(JsonLexer.java:736)

已编辑
现在我尝试了:

 "emails" : [
           {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"},
           {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"}
          ]

我得到:

    SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/API] threw exception
java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.get(ArrayList.java:324)
    at com.sun.jersey.json.impl.reader.JsonXmlStreamReader.valueRead(JsonXmlStreamReader.java:165)
    at com.sun.jersey.json.impl.reader.JsonXmlStreamReader.readNext(JsonXmlStreamReader.java:330)

I am trying to retrieve in my Jersey implementation resource class post collection of objects like this:

@POST
@Path("/send")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String sendEmails(ArrayList<AnyEmail> email) {
    //emailManager.sendEmail(email);
    return "success";
}

I have the @XmlRootElement above `AnyEmail.

However when I post like this with REST client tool:

 emails : [
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"},
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"}
      ]

I get:

<html><head><title>Apache Tomcat/7.0.22 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 500 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Exception report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The server encountered an internal error () that prevented it from fulfilling this request.</u></p><p><b>exception</b> <pre>javax.servlet.ServletException: Servlet execution threw an exception
</pre></p><p><b>root cause</b> <pre>java.lang.Error: Error: could not match input
    com.sun.jersey.json.impl.reader.JsonLexer.zzScanError(JsonLexer.java:491)
    com.sun.jersey.json.impl.reader.JsonLexer.yylex(JsonLexer.java:736)

EDITED
Now I tried:

 "emails" : [
           {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"},
           {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"}
          ]

and I get:

    SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/API] threw exception
java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.get(ArrayList.java:324)
    at com.sun.jersey.json.impl.reader.JsonXmlStreamReader.valueRead(JsonXmlStreamReader.java:165)
    at com.sun.jersey.json.impl.reader.JsonXmlStreamReader.readNext(JsonXmlStreamReader.java:330)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

浮华 2024-12-14 20:51:08

为什么你不使用简单的Java数组???

[
   {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"},
   {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"}
]

然后使用以下方法:

@POST
@Path("/send")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String sendEmails(AnyEmail[] emails) {
    //emailManager.sendEmail(emails);
    return "success";
}

这应该可以解决问题......

Why you don't use a simple Java array???

[
   {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"},
   {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"}
]

And then the following method:

@POST
@Path("/send")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String sendEmails(AnyEmail[] emails) {
    //emailManager.sendEmail(emails);
    return "success";
}

That should do the trick...

伤痕我心 2024-12-14 20:51:08

这应该可行:

{
"anyEmail" : [
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"},
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"}
       ]
}

此外,您可能想要使用 POJO 方法,这是 JSON 的首选方法 - 请参阅此处: https://jersey.java.net/documentation/1.18/json.html

基于 JAXB 的 JSON 支持在某些边缘情况下存在各种问题,因为没有 1: 1 XML之间的映射(JAXB 的设计用途)和 JSON。

This is what should work:

{
"anyEmail" : [
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"},
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"}
       ]
}

Also, you may want to use the POJO approach, which is the preferred one for JSON - see here: https://jersey.java.net/documentation/1.18/json.html

The JSON support based on JAXB has various issues with some edge cases, since there isn't a 1:1 mapping between XML (JAXB as designed for) and JSON.

听你说爱我 2024-12-14 20:51:08

我既不是 Jersey 也不是 Json 专家,但您是否尝试使用完整的 JSON 对象,即:(

{
"emails" : [
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"},
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"}
      ]
}

在电子邮件中添加了大括号和引号)。

I'm neither a Jersey nor Json expert, but did you try using a full JSON object, ie :

{
"emails" : [
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"},
       {"body": "Testing the web service", "header": "Hi", "footer": "<br/>test"}
      ]
}

(added braces, and quotes to emails).

烟织青萝梦 2024-12-14 20:51:08

我也有同样的问题。您必须包装 AnyEmail 类。

这可以帮助您:https://blogs.oracle.com/japod/entry/missing_brackets_at_json_one

I had the same problem. You have to wrap the AnyEmail class.

This can help you: https://blogs.oracle.com/japod/entry/missing_brackets_at_json_one

国粹 2024-12-14 20:51:08

// 客户端

package com.project.rest.model;

import java.util.HashSet;
import java.util.Set;

public class Client {

    private Long id;
    private String email;
    private String lang;

    public Client() {
    }

    public Client(Long id) {
    this.id = id;
    }

    public Client(Long id, String email, String lang) {
    this.id = id;
    this.email = email;
    this.lang = lang;
    }

    public Long getId() {
    return id;
    }

    public void setId(Long id) {
    this.id = id;
    }

    public String getEmail() {
    return email;
    }

    public void setEmail(String email) {
    this.email = email;
    }

    public String getLang() {
    return lang;
    }

    public void setLang(String lang) {
    this.lang = lang;
    }


    @Override
    public String toString() {
    return "Client [id=" + id + ", email=" + email + ", lang=" + lang + "]";
    }

}

//ClientService

package com.project.rest;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.project.rest.model.Client;

@Path("/client")
public class ClientService {

    @POST
    @Path("/sendList")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response consumeJSONList(List<Client> clientList) {

        String output = "consumeJSONList Client : " + clientList.toString() + "\n\n";

        return Response.status(200).entity(output).build();
    }

}

//JerseyClient

package com.project.rest;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.core.MediaType;

import com.project.rest.model.Client;
import com.project.rest.model.Device;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class JerseyClient {

public static void main(String[] args) {

try {

    List<Client> clientList = new ArrayList<Client>();
    clientList.add(new Client(1L, "[email protected]", "es"));
    clientList.add(new Client(2L, "[email protected]", "es"));
    clientList.add(new Client(3L, "[email protected]", "es"));

    ClientConfig clientConfig = new DefaultClientConfig();

    clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    com.sun.jersey.api.client.Client c = com.sun.jersey.api.client.Client.create(clientConfig);

    WebResource webResource = c.resource("http://localhost:8080/project_rest/rest/client/sendList");

    ClientResponse response = webResource.accept("application/json").type("application/json").post(ClientResponse.class, clientList);

    if (response.getStatus() != 200) {
    throw new RuntimeException("Failed sendClientList: HTTP error code : " + response.getStatus());
    }

    String output = response.getEntity(String.class);

    System.out.println("sendClientList... Server response .... \n");
    System.out.println(output);

} catch (Exception e) {

    e.printStackTrace();

}
}
}

//POM.xml

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.8.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-bundle</artifactId>
    <version>1.10-b01</version>
</dependency>

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-servlet</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.18.1</version>
</dependency>
<dependency>
  <groupId>com.owlike</groupId>
  <artifactId>genson</artifactId>
  <version>0.99</version>
</dependency>

// Client

package com.project.rest.model;

import java.util.HashSet;
import java.util.Set;

public class Client {

    private Long id;
    private String email;
    private String lang;

    public Client() {
    }

    public Client(Long id) {
    this.id = id;
    }

    public Client(Long id, String email, String lang) {
    this.id = id;
    this.email = email;
    this.lang = lang;
    }

    public Long getId() {
    return id;
    }

    public void setId(Long id) {
    this.id = id;
    }

    public String getEmail() {
    return email;
    }

    public void setEmail(String email) {
    this.email = email;
    }

    public String getLang() {
    return lang;
    }

    public void setLang(String lang) {
    this.lang = lang;
    }


    @Override
    public String toString() {
    return "Client [id=" + id + ", email=" + email + ", lang=" + lang + "]";
    }

}

//ClientService

package com.project.rest;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.project.rest.model.Client;

@Path("/client")
public class ClientService {

    @POST
    @Path("/sendList")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response consumeJSONList(List<Client> clientList) {

        String output = "consumeJSONList Client : " + clientList.toString() + "\n\n";

        return Response.status(200).entity(output).build();
    }

}

//JerseyClient

package com.project.rest;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.core.MediaType;

import com.project.rest.model.Client;
import com.project.rest.model.Device;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class JerseyClient {

public static void main(String[] args) {

try {

    List<Client> clientList = new ArrayList<Client>();
    clientList.add(new Client(1L, "[email protected]", "es"));
    clientList.add(new Client(2L, "[email protected]", "es"));
    clientList.add(new Client(3L, "[email protected]", "es"));

    ClientConfig clientConfig = new DefaultClientConfig();

    clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    com.sun.jersey.api.client.Client c = com.sun.jersey.api.client.Client.create(clientConfig);

    WebResource webResource = c.resource("http://localhost:8080/project_rest/rest/client/sendList");

    ClientResponse response = webResource.accept("application/json").type("application/json").post(ClientResponse.class, clientList);

    if (response.getStatus() != 200) {
    throw new RuntimeException("Failed sendClientList: HTTP error code : " + response.getStatus());
    }

    String output = response.getEntity(String.class);

    System.out.println("sendClientList... Server response .... \n");
    System.out.println(output);

} catch (Exception e) {

    e.printStackTrace();

}
}
}

//POM.xml

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.8.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-bundle</artifactId>
    <version>1.10-b01</version>
</dependency>

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-servlet</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.18.1</version>
</dependency>
<dependency>
  <groupId>com.owlike</groupId>
  <artifactId>genson</artifactId>
  <version>0.99</version>
</dependency>

别忘他 2024-12-14 20:51:08

我正在使用 Jersey 1.17,可以接收具有以下签名的 JSON 对象列表,并使用 Google 的 gson 库将它们转换为我的 POJO 对象列表,没有任何问题。使用包装器来包装 POJO 对象列表,当然是不自然且不利的。

   @POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces({"application/x-javascript", MediaType.APPLICATION_JSON})
public Response doSomething(@Context HttpServletRequest httpServletRequest, JSONArray listOfJSONObjects) {
    Gson gson = new GsonBuilder().create();
    List < MYPOJOClass > myPojoObjectList = gson.fromJson(listOfJSONObjects.toString(), new TypeToken < List < MYPOJOClass >> () {}.getType());

I am using Jersey 1.17 and can receive list of JSON objects with the following signature and cast them into list of my POJO Objects with Google's gson library, without any issue. Using wrapper to wrap list of POJO objects, is certainly un-natural and not favourable.

   @POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces({"application/x-javascript", MediaType.APPLICATION_JSON})
public Response doSomething(@Context HttpServletRequest httpServletRequest, JSONArray listOfJSONObjects) {
    Gson gson = new GsonBuilder().create();
    List < MYPOJOClass > myPojoObjectList = gson.fromJson(listOfJSONObjects.toString(), new TypeToken < List < MYPOJOClass >> () {}.getType());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文