Mined and Summarized Use Cases For API: org.glassfish.jersey

  1. Is there an event-driven JSON REST client API for Java?

    However to use things in a streaming fashion you may need to get at the underlying HTTP response stream. I am most familiar with Jersey which exposes ClientResponse.html#getEntityInputStream docs/1.5/jersey/com/sun/jersey/api/client/ClientResponse.html#getEntityInputSt ream() It would be used by invoking This provides you with the stream of data coming in. .. details

    1. Client client = Client.create()
    2. WebResource webResource = client.resource("http://...")
    3. ClientResponse response = webResource.accept("application/json") .get(ClientResponse.class)
    4. InputStream is = response.getEntityInputStream()

    Positive Reactions
    1. This is what I meant by "I appreciate I could roll my own implementation of this behaviour with streaming JSON APIs from Jackson, GSON etc."
    Other Reactions
    1. -- however the absence of other suggestions seems to imply that it's the only available route, so thanks.
    2. The method called for each array member is jp.readValueAsTree();.
    3. Look at URL_http://www.ngdata.com/parsing-a-large-json-file-efficiently-and - easily/ , you can mix streaming and tree parsing in Jackson.

    • See Also (8)
    1. What is the fastest way to stand up a REST service using Java?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import com.sun.jersey.api.core.ClassNamesResourceConfig
      3. import javax.ws.rs.*
      4. import javax.ws.rs.core.Response
      5. import javax.xml.bind.annotation.XmlRootElement
      6. @Path("/")
      7. @ApplicationPath("/")
      8. public class TheApplication extends ClassNamesResourceConfig {
      9. public TheApplication() {
      10. super(TheApplication.class)
      11. }
      12. static Foo foo = new Foo()
      13. @GET
      14. @Produces("application/json")
      15. public Foo getFoo() {
      16. return foo
      17. }
      18. @POST
      19. @Consumes("application/json")
      20. public Response setFoo(Foo foo) {
      21. TheApplication.foo = foo
      22. return Response.ok().entity("Stored it!").build()
      23. }
      24. @XmlRootElement
      25. static class Foo {
      26. private String message = "Hello World"
      27. public String getMessage() {
      28. return message
      29. }
      30. public void setMessage(String message) {
      31. this.message = message
      32. }
      33. }
      34. }

    2. UnmarshalException when getting json array with Jersey

      Code for retrieve client) Code for the resource on the server) Code for Item . I solved the Problem by using Jackson like in this answer Matt Ball says Jackson's MessageBodyReader implementation appears to be more well-behaved than the Jersey JSON one. details

      Reactions - Positive 0, Negative 0, Others 0

      1. ClientConfig cfg = new DefaultClientConfig()
      2. cfg.getClasses().add(JacksonJsonProvider.class)
      3. Client client = Client.create(cfg)

    3. Error when trying to convert JSON to POJO using Jersey

      They need to be enabled on server AND client side. Also the library jersey json is necessary to get this to work I hope this helps you further along even though the question is old. details

      Reactions - Positive 0, Negative 0, Others 0

      1. ClientConfig config = new DefaultClientConfig()
      2. ..config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE)
      3. ..Client client = Client.create(config)

      Other Reactions
      1. The right way to enable this feature on the server is to include org.codehaus.jackson.jaxrs in the list of packages for Jersey servlet, see details [here]( URL_http://stackoverflow.com/questions/12883287/how-to-easily-use - jackson-for-jersey).

    4. Getting JSON out put from restful java client

      Thank you. i resolved the same question.if your exception is unexpected element uri:"" local:"id") don't forget add follow code then the code will be ok . details

      Reactions - Positive 2, Negative 0, Others 0

      1. clientConfig = new DefaultClientConfig()
      2. clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE)

      Positive Reactions
      1. Thanks :).
      2. very lovely answer for my casesave my timethanks :).
      Other Reactions
      1. I had to moved to a php client instead of java.
      2. But this might help to somebody.

    5. Getting JSON out put from restful java client

      None details

      Reactions - Positive 0, Negative 0, Others 0

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

    6. Getting JSON out put from restful java client

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Exception in thread "main" javax.ws.rs.WebApplicationException: javax.xml.bind.UnmarshalException - with linked exception:[com.sun.istack.internal.SAXParseException2
      2. lineNumber: 0
      3. columnNumber: 0
      4. 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

    7. JAX-RS Jersey Client marshaling JSON response with POJO MAPPING & Jackson

      can you also show your JSON. To enable POJO mapping on the client side just do . details

      Reactions - Positive 3, Negative 2, Others 0

      1. ClientConfig clientConfig = new DefaultClientConfig()
      2. clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE)
      3. Client client = Client.create(clientConfig)

      Positive Reactions
      1. That's what the first sentence of my question above, "I'm having a bit of an issue using Jersey client (1.11) with JSONConfiguration.FEATURE_POJO_MAPPING set to true" is referring to.
      2. This exact approach works.
      3. Good answer.
      Negative Reactions
      1. This is essential when configuring JerseyTest too, otherwise only the server part of a JerseyTest will work with POJOs and the client in your test class will fail: URL_https://java.net/projects/jersey/lists/users/archive/2011-07/message/43 .
      2. See my amended comments above for the details of what was wrong.
      Other Reactions
      1. I'm already doing all that.

    8. rendering JSON String as JSON Using JAXB within jersey

      You can use a Provider to change default behaviour of JSONJAXBContext. See d4e865 . details

      Reactions - Positive 1, Negative 0, Others 0

      1. import javax.ws.rs.ext.ContextResolver
      2. import javax.ws.rs.ext.Provider
      3. import javax.xml.bind.JAXBContext
      4. import javax.xml.bind.JAXBException
      5. import com.sun.jersey.api.json.JSONConfiguration
      6. import com.sun.jersey.api.json.JSONJAXBContext
      7. @Providerpublic class CustomWoodwingOutputJSONContextProvider implements ContextResolver<JAXBContext> {private JAXBContext context
      8. private Class<?>[] types = { MyClass.class }
      9. public CustomWoodwingOutputJSONContextProvider() throws JAXBException { this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types)
      10. }public JAXBContext getContext(Class<?> objectType) { for (int i = 0
      11. i < this.types.length
      12. i++) if (this.types[i].equals(objectType)) return context
      13. return null
      14. }

      Positive Reactions
      1. I hoped for something more simple.
      Other Reactions
      1. Still maybe it will help someone else.
      2. This is a bit too much for me at the moment.
      3. For my own needs I just left it as a string And I do the json parsing on the client side.

  2. Send file inside JSONObject to REST WebService

    None .. details

    1. @POST@Path("/uploadWeb")@Consumes(MediaType.MULTIPART_FORM_DATA)public Response uploadWeb( @FormDataMultiPart("image") InputStream uploadedInputStream, @FormDataParam("image") FormDataContentDisposition fileDetail ) { int read = 0
    2. byte[] bytes = new byte[1024]
    3. while ((read = uploadedInputStream.read(bytes)) != -1) System.out.write(bytes, 0, read)
    4. return Response.status(HttpStatus.SC_OK).entity(c).build()
    5. }

    • See Also (1)
    1. Send file inside JSONObject to REST WebService

      So you might as well just put the file path directly If you're trying to do a file upload with JSON one way is to read the bytes from the file with Java 7's NIO Base64 encode those bytes and write them as a String in the JSONObject. Using Apache Commons Codec . details

      Reactions - Positive 2, Negative 0, Others 0

      1. Base64.encodeBase64(bytes)
      2. my_data.put("File", new String(bytes))

      Positive Reactions
      1. No need to use Commons Codec; DatatypeConverter is part of the standard (JAXB).
      2. Thanks!
      Other Reactions
      1. I used com.sun.jersey.core.util.Base64 that has Base64.encode(bytes) and Base64.decode(bytes).

  3. Jackson: JsonMappingException deserializing Arrays of JSON objects

    They apparently are not using the same Json format by default. This works like a charm. .. details

    1. final WebResource webResource = resource()
    2. final ClientResponse response = webResource.path( VersionProviderTest.SERVICE_PATH).get(ClientResponse.class)
    3. ConfigData[] list = response.getEntity(ConfigData[].class)

    • See Also (8)
    1. Cannot unmarshal a JSON array of objects using Jersey Client

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.sun.jersey.api.json.JSONJAXBContext
      2. import com.sun.jersey.api.json.JSONUnmarshaller
      3. public static <T> T unmarshalJson(String jsonTxt, Class<T> clazz) throws JAXBException { JSONJAXBContext jctx = new JSONJAXBContext(clazz)
      4. JSONUnmarshaller unm = jctx.createJSONUnmarshaller()
      5. return (T)unm.unmarshalFromJSON(new StringReader(jsonTxt), clazz)
      6. }

    2. Cannot unmarshal a JSON array of objects using Jersey Client

      Make a JAXB context resolver like this 2. Added the context resolver to your client 3. details

      Reactions - Positive 0, Negative 0, Others 0

      1. ClientConfig config = new DefaultClientConfig()
      2. config.getClasses().add(JAXBContextResolver.class)
      3. Client client = Client.create(config)

    3. Cannot unmarshal a JSON array of objects using Jersey Client

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.sun.jersey.api.json.JSONConfiguration
      2. import com.sun.jersey.api.json.JSONJAXBContext
      3. import java.util.ArrayList
      4. import java.util.List
      5. import javax.ws.rs.ext.ContextResolver
      6. import javax.xml.bind.JAXBContext
      7. @Providerpublic
      8. class JAXBContextResolver implements ContextResolver<JAXBContext> {
      9. private JAXBContext context
      10. private Class<?>[] types = {Badge.class}
      11. private List<Class<?>> classes = new ArrayList<Class<?>>()
      12. public JAXBContextResolver() throws Exception {
      13. this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types)
      14. for (Class<?> clazz : types) {
      15. classes.add(clazz)
      16. }
      17. }
      18. public JAXBContext getContext(Class<?> objectType) {
      19. return classes.contains(objectType) ? context : null
      20. }
      21. }

    4. Cannot unmarshal a JSON array of objects using Jersey Client

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. ClientConfig clientConfig = new DefaultClientConfig()
      2. clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE)
      3. Client client = Client.create(clientConfig)
      4. List<Badge> badges = client.resource("/badges").getEntity(new GenericType<List<Badge>>() {})

    5. Cannot unmarshal a JSON array of objects using Jersey Client

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. ClientConfig cfg = new DefaultClientConfig()
      2. cfg.getClasses().add(JacksonJsonProvider.class)
      3. Client client = Client.create(cfg)

    6. Cannot unmarshal a JSON array of objects using Jersey Client

      You can use the JSON Binding extension that is being added to the MOXy component in EclipseLink 2.4 to handle this use case Demo The Jersey client API allows you to leverage the same MessageBodyReader/MessageBodyWriter from the server side on the client side. MOXyJSONProvider Below is a generic MessageBodyReader/MessageBodyWriter that could be used with any server/client to enable MOXy as the JSON binding provider. details

      Reactions - Positive 7, Negative 1, Others 0

      1. package forum9627170
      2. import com.sun.jersey.api.client.*
      3. import com.sun.jersey.api.client.config.*
      4. import java.util.List
      5. public class Demo {
      6. public static void main(String[] args) {
      7. ClientConfig cc = new DefaultClientConfig()
      8. cc.getClasses().add(MOXyJSONProvider.class)
      9. Client client = Client.create(cc)
      10. WebResource apiRoot = client.resource("http://localhost:9000/api")
      11. List<Badge> badges =
      12. apiRoot.path("/badges").accept("application/json").get(new GenericType<List<Badge>>() {})
      13. for (Badge badge : badges) {
      14. System.out.println(badge.getId())
      15. }
      16. }
      17. }

      Positive Reactions
      1. To produce & consume standard JSON into Jersey one have to use Jackson!
      2. This is easy, quick, and was designed as this by the Jersey team.
      3. Oh, interesting.
      4. The stack trace clearly indicated that a JAXB implementation was being used with the JSON and MOXy supports more JAXB annotations than Jackson does.
      5. @BlaiseDoughan Yes, is uses a standard approach to (un)marshall representations but IT IS NOT the standard approach to (un)marshall JSON in Jersey: Jackson is.
      6. This approach uses the standard 'MessageBodyReader/Writer interfaces to interact with the Jersey client API and clearly demonstrates that you do NOT need to use Jackson to produce & consume standard JSON into Jersey.
      7. This approach is NOT the standard one.
      Negative Reactions
      1. I believe it is not working out of the box because your then items in your collection do not have badge as a root element.
      Other Reactions
      1. I'm curious to know _why_ this doesn't work out-of-the-box do you know?
      2. @yvesamsellem by "standard," you mean _de facto_ standard, right?
      3. Thanks, I'll give this a shot.
      4. :).
      5. @MLL - I have updated my answer.
      6. Taking another look at the difference between the JSON I can unmarshall, and the JSON I can't, I see what you mean.
      7. @M LL yes, I mean built in; designed this way by the Jersey developers.
      8. An earlier version of MOXy is already in GlassFish ( URL_http://blog.bdoughan.com/2012/02/glassfish-312-is-full-of - moxy.html), and a version containing the JSON binding will be included in a future GlassFish release.
      9. @yvesamsellem - (-1?)
      10. Also, I knew it was only a matter of time 'til you posted an answer :).
      11. @yvesamsellem - FYI, Tweet from Jersey regarding MOXy: URL_https://twitter.com/gf_jersey/status/218036096758579202 .

    7. Cannot unmarshal a JSON array of objects using Jersey Client

      MOXyJSONProvider Below is a generic MessageBodyReader/MessageBodyWriter that could be used with any server/client to enable MOXy as the JSON binding provider. For More Information MOXy-as-Your-JAX-RS-JSON-Provider---Client-Side MOXy-as-Your-JAX-RS-JSON-Provider---Server-Side Specifying-EclipseLink-MOXy-as-Your-JAXB-Provider UPDATE In GlassFish 4 EclipseLink JAXB MOXy is the default JSON-binding provider used by Jersey . details

      Reactions - Positive 7, Negative 1, Others 0

      1. package forum9627170
      2. import java.io.*
      3. import java.lang.annotation.Annotation
      4. import java.lang.reflect.ParameterizedType
      5. import java.lang.reflect.Type
      6. import javax.ws.rs.*
      7. import javax.ws.rs.core.*
      8. import javax.ws.rs.ext.*
      9. import javax.xml.bind.*
      10. import javax.xml.transform.stream.StreamSource
      11. @Provider
      12. @Produces(MediaType.APPLICATION_JSON)
      13. @Consumes(MediaType.APPLICATION_JSON)
      14. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      15. @Context protected Providers providers
      16. public boolean isReadable(
      17. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      18. return true
      19. }
      20. public Object readFrom(
      21. Class<Object> type,
      22. Type genericType,
      23. Annotation[] annotations,
      24. MediaType mediaType,
      25. MultivaluedMap<String, String> httpHeaders,
      26. InputStream entityStream)
      27. throws IOException, WebApplicationException {
      28. try {
      29. Class domainClass = getDomainClass(genericType)
      30. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      31. u.setProperty("eclipselink.media-type", mediaType.toString())
      32. u.setProperty("eclipselink.json.include-root", false)
      33. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      34. } catch (JAXBException jaxbException) {
      35. throw new WebApplicationException(jaxbException)
      36. }
      37. }
      38. public boolean isWriteable(
      39. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      40. return true
      41. }
      42. public void writeTo(
      43. Object object,
      44. Class<?> type,
      45. Type genericType,
      46. Annotation[] annotations,
      47. MediaType mediaType,
      48. MultivaluedMap<String, Object> httpHeaders,
      49. OutputStream entityStream)
      50. throws IOException, WebApplicationException {
      51. try {
      52. Marshaller m = getJAXBContext(getDomainClass(genericType), mediaType).createMarshaller()
      53. m.setProperty("eclipselink.media-type", mediaType.toString())
      54. m.setProperty("eclipselink.json.include-root", false)
      55. m.marshal(object, entityStream)
      56. } catch (JAXBException jaxbException) {
      57. throw new WebApplicationException(jaxbException)
      58. }
      59. }
      60. public long getSize(
      61. Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      62. return -1
      63. }
      64. private JAXBContext getJAXBContext(Class<?> type, MediaType mediaType) throws JAXBException {
      65. ContextResolver<JAXBContext> resolver =
      66. providers.getContextResolver(JAXBContext.class, mediaType)
      67. JAXBContext jaxbContext
      68. if (null == resolver || null == (jaxbContext = resolver.getContext(type))) {
      69. return JAXBContext.newInstance(type)
      70. } else {
      71. return jaxbContext
      72. }
      73. }
      74. private Class<?> getDomainClass(Type genericType) {
      75. if (genericType instanceof Class) {
      76. return (Class) genericType
      77. } else if (genericType instanceof ParameterizedType) {
      78. return (Class) ((ParameterizedType) genericType).getActualTypeArguments()[0]
      79. } else {
      80. return null
      81. }
      82. }
      83. }

      Positive Reactions
      1. To produce & consume standard JSON into Jersey one have to use Jackson!
      2. This is easy, quick, and was designed as this by the Jersey team.
      3. Oh, interesting.
      4. The stack trace clearly indicated that a JAXB implementation was being used with the JSON and MOXy supports more JAXB annotations than Jackson does.
      5. @BlaiseDoughan Yes, is uses a standard approach to (un)marshall representations but IT IS NOT the standard approach to (un)marshall JSON in Jersey: Jackson is.
      6. This approach uses the standard 'MessageBodyReader/Writer interfaces to interact with the Jersey client API and clearly demonstrates that you do NOT need to use Jackson to produce & consume standard JSON into Jersey.
      7. This approach is NOT the standard one.
      Negative Reactions
      1. I believe it is not working out of the box because your then items in your collection do not have badge as a root element.
      Other Reactions
      1. I'm curious to know _why_ this doesn't work out-of-the-box do you know?
      2. @yvesamsellem by "standard," you mean _de facto_ standard, right?
      3. Thanks, I'll give this a shot.
      4. :).
      5. @MLL - I have updated my answer.
      6. Taking another look at the difference between the JSON I can unmarshall, and the JSON I can't, I see what you mean.
      7. @M LL yes, I mean built in; designed this way by the Jersey developers.
      8. An earlier version of MOXy is already in GlassFish ( URL_http://blog.bdoughan.com/2012/02/glassfish-312-is-full-of - moxy.html), and a version containing the JSON binding will be included in a future GlassFish release.
      9. @yvesamsellem - (-1?)
      10. Also, I knew it was only a matter of time 'til you posted an answer :).
      11. @yvesamsellem - FYI, Tweet from Jersey regarding MOXy: URL_https://twitter.com/gf_jersey/status/218036096758579202 .

    8. multiple actions (CRUD) in one servlet java

      You can add some extra information in your URL. Like parameters And in your servlet you can use the action parameter for decision making Or you can implement your own dispatcher to route request with URL like Or you can override the service method to support PUT DELETE and make your servlet RESTful. details

      Reactions - Positive 2, Negative 0, Others 0

      1. String action = request.getParameter("action")
      2. if(action.equal(...) { /* Your logic here */ }

      Positive Reactions
      1. @hope_is_grim.Thanks for your reply.
      2. You can start by finding some tutorial about creating and working with RESTful Web service.
      Other Reactions
      1. If it doesn't have to be servlet, I think RESTful Web Service is a better solution.
      2. I am building survey app which may be scale in future.
      3. is this better approach or any other suggestion ?

  4. Cannot unmarshal a JSON array of objects using Jersey Client

    MOXyJSONProvider Below is a generic MessageBodyReader/MessageBodyWriter that could be used with any server/client to enable MOXy as the JSON binding provider. For More Information MOXy-as-Your-JAX-RS-JSON-Provider---Client-Side MOXy-as-Your-JAX-RS-JSON-Provider---Server-Side Specifying-EclipseLink-MOXy-as-Your-JAXB-Provider UPDATE In GlassFish 4 EclipseLink JAXB MOXy is the default JSON-binding provider used by Jersey . .. details

    1. package forum9627170
    2. import java.io.*
    3. import java.lang.annotation.Annotation
    4. import java.lang.reflect.ParameterizedType
    5. import java.lang.reflect.Type
    6. import javax.ws.rs.*
    7. import javax.ws.rs.core.*
    8. import javax.ws.rs.ext.*
    9. import javax.xml.bind.*
    10. import javax.xml.transform.stream.StreamSource
    11. @Provider
    12. @Produces(MediaType.APPLICATION_JSON)
    13. @Consumes(MediaType.APPLICATION_JSON)
    14. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
    15. @Context protected Providers providers
    16. public boolean isReadable(
    17. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    18. return true
    19. }
    20. public Object readFrom(
    21. Class<Object> type,
    22. Type genericType,
    23. Annotation[] annotations,
    24. MediaType mediaType,
    25. MultivaluedMap<String, String> httpHeaders,
    26. InputStream entityStream)
    27. throws IOException, WebApplicationException {
    28. try {
    29. Class domainClass = getDomainClass(genericType)
    30. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
    31. u.setProperty("eclipselink.media-type", mediaType.toString())
    32. u.setProperty("eclipselink.json.include-root", false)
    33. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
    34. } catch (JAXBException jaxbException) {
    35. throw new WebApplicationException(jaxbException)
    36. }
    37. }
    38. public boolean isWriteable(
    39. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    40. return true
    41. }
    42. public void writeTo(
    43. Object object,
    44. Class<?> type,
    45. Type genericType,
    46. Annotation[] annotations,
    47. MediaType mediaType,
    48. MultivaluedMap<String, Object> httpHeaders,
    49. OutputStream entityStream)
    50. throws IOException, WebApplicationException {
    51. try {
    52. Marshaller m = getJAXBContext(getDomainClass(genericType), mediaType).createMarshaller()
    53. m.setProperty("eclipselink.media-type", mediaType.toString())
    54. m.setProperty("eclipselink.json.include-root", false)
    55. m.marshal(object, entityStream)
    56. } catch (JAXBException jaxbException) {
    57. throw new WebApplicationException(jaxbException)
    58. }
    59. }
    60. public long getSize(
    61. Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    62. return -1
    63. }
    64. private JAXBContext getJAXBContext(Class<?> type, MediaType mediaType) throws JAXBException {
    65. ContextResolver<JAXBContext> resolver =
    66. providers.getContextResolver(JAXBContext.class, mediaType)
    67. JAXBContext jaxbContext
    68. if (null == resolver || null == (jaxbContext = resolver.getContext(type))) {
    69. return JAXBContext.newInstance(type)
    70. } else {
    71. return jaxbContext
    72. }
    73. }
    74. private Class<?> getDomainClass(Type genericType) {
    75. if (genericType instanceof Class) {
    76. return (Class) genericType
    77. } else if (genericType instanceof ParameterizedType) {
    78. return (Class) ((ParameterizedType) genericType).getActualTypeArguments()[0]
    79. } else {
    80. return null
    81. }
    82. }
    83. }

    Positive Reactions
    1. To produce & consume standard JSON into Jersey one have to use Jackson!
    2. This is easy, quick, and was designed as this by the Jersey team.
    3. Oh, interesting.
    4. The stack trace clearly indicated that a JAXB implementation was being used with the JSON and MOXy supports more JAXB annotations than Jackson does.
    5. @BlaiseDoughan Yes, is uses a standard approach to (un)marshall representations but IT IS NOT the standard approach to (un)marshall JSON in Jersey: Jackson is.
    6. This approach uses the standard 'MessageBodyReader/Writer interfaces to interact with the Jersey client API and clearly demonstrates that you do NOT need to use Jackson to produce & consume standard JSON into Jersey.
    7. This approach is NOT the standard one.
    Negative Reactions
    1. I believe it is not working out of the box because your then items in your collection do not have badge as a root element.
    Other Reactions
    1. I'm curious to know _why_ this doesn't work out-of-the-box do you know?
    2. @yvesamsellem by "standard," you mean _de facto_ standard, right?
    3. Thanks, I'll give this a shot.
    4. :).
    5. @MLL - I have updated my answer.
    6. Taking another look at the difference between the JSON I can unmarshall, and the JSON I can't, I see what you mean.
    7. @M LL yes, I mean built in; designed this way by the Jersey developers.
    8. An earlier version of MOXy is already in GlassFish ( URL_http://blog.bdoughan.com/2012/02/glassfish-312-is-full-of - moxy.html), and a version containing the JSON binding will be included in a future GlassFish release.
    9. @yvesamsellem - (-1?)
    10. Also, I knew it was only a matter of time 'til you posted an answer :).
    11. @yvesamsellem - FYI, Tweet from Jersey regarding MOXy: URL_https://twitter.com/gf_jersey/status/218036096758579202 .

  5. How do I marshal nested lists as JSON using Jersey? I get an array of nulls or an array of one-element dictionaries containing an array

    None .. details

    1. import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider
    2. import org.codehaus.jettison.json.JSONArray
    3. import org.codehaus.jettison.json.JSONException
    4. @Provider
    5. @Produces("*/*")
    6. @Consumes("*/*")
    7. public class ListObjectArrayMessagereaderWriterProvider
    8. extends AbstractMessageReaderWriterProvider<ListWrapper> {
    9. public boolean supports(Class type) {
    10. return type == ListWrapper.class
    11. }
    12. @Override
    13. public boolean isReadable(
    14. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    15. return type == ListWrapper.class
    16. }
    17. @Override
    18. public ListWrapper readFrom(
    19. Class<ListWrapper> type,
    20. Type genericType,
    21. Annotation[] annotations,
    22. MediaType mediaType,
    23. MultivaluedMap<String, String> httpHeaders,
    24. InputStream entityStream)
    25. throws IOException, WebApplicationException {
    26. throw new IllegalArgumentException("Not implemented yet.")
    27. }
    28. @Override
    29. public boolean isWriteable(
    30. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    31. return type == ListWrapper.class
    32. }
    33. @SuppressWarnings("unchecked")
    34. @Override
    35. public void writeTo(
    36. ListWrapper t,
    37. Class<?> type,
    38. Type genericType,
    39. Annotation[] annotations,
    40. MediaType mediaType,
    41. MultivaluedMap<String, Object> httpHeaders,
    42. OutputStream entityStream)
    43. throws IOException, WebApplicationException {
    44. final Iterator<Object[]> iterator = t.iterator()
    45. OutputStreamWriter writer = new OutputStreamWriter(entityStream, getCharset(mediaType))
    46. final JSONArray jsonArrayOuter = new JSONArray()
    47. while (iterator.hasNext()) {
    48. final Object[] objs = iterator.next()
    49. JSONArray jsonArrayInner = new JSONArray(Arrays.asList(objs))
    50. jsonArrayOuter.put(jsonArrayInner)
    51. }
    52. try {
    53. jsonArrayOuter.write(writer)
    54. writer.write("\n")
    55. writer.flush()
    56. } catch (JSONException je) {
    57. throw new WebApplicationException(
    58. new Exception(ImplMessages.ERROR_WRITING_JSON_ARRAY(), je), 500)
    59. }
    60. }
    61. }

All usage scenarios for API org.glassfish.jersey
  • Is there an event-driven JSON REST client API for Java?

    However to use things in a streaming fashion you may need to get at the underlying HTTP response stream. I am most familiar with Jersey which exposes ClientResponse.html#getEntityInputStream docs/1.5/jersey/com/sun/jersey/api/client/ClientResponse.html#getEntityInputSt ream() It would be used by invoking This provides you with the stream of data coming in. details

    Reactions - Positive 1, Negative 0, Others 0

    1. Client client = Client.create()
    2. WebResource webResource = client.resource("http://...")
    3. ClientResponse response = webResource.accept("application/json") .get(ClientResponse.class)
    4. InputStream is = response.getEntityInputStream()

    Positive Reactions
    1. This is what I meant by "I appreciate I could roll my own implementation of this behaviour with streaming JSON APIs from Jackson, GSON etc."
    Other Reactions
    1. -- however the absence of other suggestions seems to imply that it's the only available route, so thanks.
    2. The method called for each array member is jp.readValueAsTree();.
    3. Look at URL_http://www.ngdata.com/parsing-a-large-json-file-efficiently-and - easily/ , you can mix streaming and tree parsing in Jackson.

  • Send file inside JSONObject to REST WebService

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @POST@Path("/uploadWeb")@Consumes(MediaType.MULTIPART_FORM_DATA)public Response uploadWeb( @FormDataMultiPart("image") InputStream uploadedInputStream, @FormDataParam("image") FormDataContentDisposition fileDetail ) { int read = 0
    2. byte[] bytes = new byte[1024]
    3. while ((read = uploadedInputStream.read(bytes)) != -1) System.out.write(bytes, 0, read)
    4. return Response.status(HttpStatus.SC_OK).entity(c).build()
    5. }

  • Send file inside JSONObject to REST WebService

    So you might as well just put the file path directly If you're trying to do a file upload with JSON one way is to read the bytes from the file with Java 7's NIO Base64 encode those bytes and write them as a String in the JSONObject. Using Apache Commons Codec . details

    Reactions - Positive 2, Negative 0, Others 0

    1. Base64.encodeBase64(bytes)
    2. my_data.put("File", new String(bytes))

    Positive Reactions
    1. No need to use Commons Codec; DatatypeConverter is part of the standard (JAXB).
    2. Thanks!
    Other Reactions
    1. I used com.sun.jersey.core.util.Base64 that has Base64.encode(bytes) and Base64.decode(bytes).

  • What is the fastest way to stand up a REST service using Java?

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. package org.example
    2. import com.sun.jersey.api.core.ClassNamesResourceConfig
    3. import javax.ws.rs.*
    4. import javax.ws.rs.core.Response
    5. import javax.xml.bind.annotation.XmlRootElement
    6. @Path("/")
    7. @ApplicationPath("/")
    8. public class TheApplication extends ClassNamesResourceConfig {
    9. public TheApplication() {
    10. super(TheApplication.class)
    11. }
    12. static Foo foo = new Foo()
    13. @GET
    14. @Produces("application/json")
    15. public Foo getFoo() {
    16. return foo
    17. }
    18. @POST
    19. @Consumes("application/json")
    20. public Response setFoo(Foo foo) {
    21. TheApplication.foo = foo
    22. return Response.ok().entity("Stored it!").build()
    23. }
    24. @XmlRootElement
    25. static class Foo {
    26. private String message = "Hello World"
    27. public String getMessage() {
    28. return message
    29. }
    30. public void setMessage(String message) {
    31. this.message = message
    32. }
    33. }
    34. }

  • Jackson: JsonMappingException deserializing Arrays of JSON objects

    They apparently are not using the same Json format by default. This works like a charm. details

    Reactions - Positive 0, Negative 0, Others 0

    1. final WebResource webResource = resource()
    2. final ClientResponse response = webResource.path( VersionProviderTest.SERVICE_PATH).get(ClientResponse.class)
    3. ConfigData[] list = response.getEntity(ConfigData[].class)

  • Cannot unmarshal a JSON array of objects using Jersey Client

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. import com.sun.jersey.api.json.JSONJAXBContext
    2. import com.sun.jersey.api.json.JSONUnmarshaller
    3. public static <T> T unmarshalJson(String jsonTxt, Class<T> clazz) throws JAXBException { JSONJAXBContext jctx = new JSONJAXBContext(clazz)
    4. JSONUnmarshaller unm = jctx.createJSONUnmarshaller()
    5. return (T)unm.unmarshalFromJSON(new StringReader(jsonTxt), clazz)
    6. }

  • Cannot unmarshal a JSON array of objects using Jersey Client

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. import com.sun.jersey.api.json.JSONConfiguration
    2. import com.sun.jersey.api.json.JSONJAXBContext
    3. import java.util.ArrayList
    4. import java.util.List
    5. import javax.ws.rs.ext.ContextResolver
    6. import javax.xml.bind.JAXBContext
    7. @Providerpublic
    8. class JAXBContextResolver implements ContextResolver<JAXBContext> {
    9. private JAXBContext context
    10. private Class<?>[] types = {Badge.class}
    11. private List<Class<?>> classes = new ArrayList<Class<?>>()
    12. public JAXBContextResolver() throws Exception {
    13. this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types)
    14. for (Class<?> clazz : types) {
    15. classes.add(clazz)
    16. }
    17. }
    18. public JAXBContext getContext(Class<?> objectType) {
    19. return classes.contains(objectType) ? context : null
    20. }
    21. }

  • Cannot unmarshal a JSON array of objects using Jersey Client

    Make a JAXB context resolver like this 2. Added the context resolver to your client 3. details

    Reactions - Positive 0, Negative 0, Others 0

    1. ClientConfig config = new DefaultClientConfig()
    2. config.getClasses().add(JAXBContextResolver.class)
    3. Client client = Client.create(config)

  • UnmarshalException when getting json array with Jersey

    Code for retrieve client) Code for the resource on the server) Code for Item . I solved the Problem by using Jackson like in this answer Matt Ball says Jackson's MessageBodyReader implementation appears to be more well-behaved than the Jersey JSON one. details

    Reactions - Positive 0, Negative 0, Others 0

    1. ClientConfig cfg = new DefaultClientConfig()
    2. cfg.getClasses().add(JacksonJsonProvider.class)
    3. Client client = Client.create(cfg)

  • Error when trying to convert JSON to POJO using Jersey

    They need to be enabled on server AND client side. Also the library jersey json is necessary to get this to work I hope this helps you further along even though the question is old. details

    Reactions - Positive 0, Negative 0, Others 0

    1. ClientConfig config = new DefaultClientConfig()
    2. ..config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE)
    3. ..Client client = Client.create(config)

    Other Reactions
    1. The right way to enable this feature on the server is to include org.codehaus.jackson.jaxrs in the list of packages for Jersey servlet, see details [here]( URL_http://stackoverflow.com/questions/12883287/how-to-easily-use - jackson-for-jersey).

  • Getting JSON out put from restful java client

    Thank you. i resolved the same question.if your exception is unexpected element uri:"" local:"id") don't forget add follow code then the code will be ok . details

    Reactions - Positive 2, Negative 0, Others 0

    1. clientConfig = new DefaultClientConfig()
    2. clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE)

    Positive Reactions
    1. Thanks :).
    2. very lovely answer for my casesave my timethanks :).
    Other Reactions
    1. I had to moved to a php client instead of java.
    2. But this might help to somebody.

  • Getting JSON out put from restful java client

    None details

    Reactions - Positive 0, Negative 0, Others 0

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

  • Getting JSON out put from restful java client

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. Exception in thread "main" javax.ws.rs.WebApplicationException: javax.xml.bind.UnmarshalException - with linked exception:[com.sun.istack.internal.SAXParseException2
    2. lineNumber: 0
    3. columnNumber: 0
    4. 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

  • JAX-RS Jersey Client marshaling JSON response with POJO MAPPING & Jackson

    can you also show your JSON. To enable POJO mapping on the client side just do . details

    Reactions - Positive 3, Negative 2, Others 0

    1. ClientConfig clientConfig = new DefaultClientConfig()
    2. clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE)
    3. Client client = Client.create(clientConfig)

    Positive Reactions
    1. That's what the first sentence of my question above, "I'm having a bit of an issue using Jersey client (1.11) with JSONConfiguration.FEATURE_POJO_MAPPING set to true" is referring to.
    2. This exact approach works.
    3. Good answer.
    Negative Reactions
    1. This is essential when configuring JerseyTest too, otherwise only the server part of a JerseyTest will work with POJOs and the client in your test class will fail: URL_https://java.net/projects/jersey/lists/users/archive/2011-07/message/43 .
    2. See my amended comments above for the details of what was wrong.
    Other Reactions
    1. I'm already doing all that.

  • Cannot unmarshal a JSON array of objects using Jersey Client

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. ClientConfig clientConfig = new DefaultClientConfig()
    2. clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE)
    3. Client client = Client.create(clientConfig)
    4. List<Badge> badges = client.resource("/badges").getEntity(new GenericType<List<Badge>>() {})

  • Cannot unmarshal a JSON array of objects using Jersey Client

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. ClientConfig cfg = new DefaultClientConfig()
    2. cfg.getClasses().add(JacksonJsonProvider.class)
    3. Client client = Client.create(cfg)

  • rendering JSON String as JSON Using JAXB within jersey

    You can use a Provider to change default behaviour of JSONJAXBContext. See d4e865 . details

    Reactions - Positive 1, Negative 0, Others 0

    1. import javax.ws.rs.ext.ContextResolver
    2. import javax.ws.rs.ext.Provider
    3. import javax.xml.bind.JAXBContext
    4. import javax.xml.bind.JAXBException
    5. import com.sun.jersey.api.json.JSONConfiguration
    6. import com.sun.jersey.api.json.JSONJAXBContext
    7. @Providerpublic class CustomWoodwingOutputJSONContextProvider implements ContextResolver<JAXBContext> {private JAXBContext context
    8. private Class<?>[] types = { MyClass.class }
    9. public CustomWoodwingOutputJSONContextProvider() throws JAXBException { this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types)
    10. }public JAXBContext getContext(Class<?> objectType) { for (int i = 0
    11. i < this.types.length
    12. i++) if (this.types[i].equals(objectType)) return context
    13. return null
    14. }

    Positive Reactions
    1. I hoped for something more simple.
    Other Reactions
    1. Still maybe it will help someone else.
    2. This is a bit too much for me at the moment.
    3. For my own needs I just left it as a string And I do the json parsing on the client side.

  • Cannot unmarshal a JSON array of objects using Jersey Client

    You can use the JSON Binding extension that is being added to the MOXy component in EclipseLink 2.4 to handle this use case Demo The Jersey client API allows you to leverage the same MessageBodyReader/MessageBodyWriter from the server side on the client side. MOXyJSONProvider Below is a generic MessageBodyReader/MessageBodyWriter that could be used with any server/client to enable MOXy as the JSON binding provider. details

    Reactions - Positive 7, Negative 1, Others 0

    1. package forum9627170
    2. import com.sun.jersey.api.client.*
    3. import com.sun.jersey.api.client.config.*
    4. import java.util.List
    5. public class Demo {
    6. public static void main(String[] args) {
    7. ClientConfig cc = new DefaultClientConfig()
    8. cc.getClasses().add(MOXyJSONProvider.class)
    9. Client client = Client.create(cc)
    10. WebResource apiRoot = client.resource("http://localhost:9000/api")
    11. List<Badge> badges =
    12. apiRoot.path("/badges").accept("application/json").get(new GenericType<List<Badge>>() {})
    13. for (Badge badge : badges) {
    14. System.out.println(badge.getId())
    15. }
    16. }
    17. }

    Positive Reactions
    1. To produce & consume standard JSON into Jersey one have to use Jackson!
    2. This is easy, quick, and was designed as this by the Jersey team.
    3. Oh, interesting.
    4. The stack trace clearly indicated that a JAXB implementation was being used with the JSON and MOXy supports more JAXB annotations than Jackson does.
    5. @BlaiseDoughan Yes, is uses a standard approach to (un)marshall representations but IT IS NOT the standard approach to (un)marshall JSON in Jersey: Jackson is.
    6. This approach uses the standard 'MessageBodyReader/Writer interfaces to interact with the Jersey client API and clearly demonstrates that you do NOT need to use Jackson to produce & consume standard JSON into Jersey.
    7. This approach is NOT the standard one.
    Negative Reactions
    1. I believe it is not working out of the box because your then items in your collection do not have badge as a root element.
    Other Reactions
    1. I'm curious to know _why_ this doesn't work out-of-the-box do you know?
    2. @yvesamsellem by "standard," you mean _de facto_ standard, right?
    3. Thanks, I'll give this a shot.
    4. :).
    5. @MLL - I have updated my answer.
    6. Taking another look at the difference between the JSON I can unmarshall, and the JSON I can't, I see what you mean.
    7. @M LL yes, I mean built in; designed this way by the Jersey developers.
    8. An earlier version of MOXy is already in GlassFish ( URL_http://blog.bdoughan.com/2012/02/glassfish-312-is-full-of - moxy.html), and a version containing the JSON binding will be included in a future GlassFish release.
    9. @yvesamsellem - (-1?)
    10. Also, I knew it was only a matter of time 'til you posted an answer :).
    11. @yvesamsellem - FYI, Tweet from Jersey regarding MOXy: URL_https://twitter.com/gf_jersey/status/218036096758579202 .

  • Cannot unmarshal a JSON array of objects using Jersey Client

    MOXyJSONProvider Below is a generic MessageBodyReader/MessageBodyWriter that could be used with any server/client to enable MOXy as the JSON binding provider. For More Information MOXy-as-Your-JAX-RS-JSON-Provider---Client-Side MOXy-as-Your-JAX-RS-JSON-Provider---Server-Side Specifying-EclipseLink-MOXy-as-Your-JAXB-Provider UPDATE In GlassFish 4 EclipseLink JAXB MOXy is the default JSON-binding provider used by Jersey . details

    Reactions - Positive 7, Negative 1, Others 0

    1. package forum9627170
    2. import java.io.*
    3. import java.lang.annotation.Annotation
    4. import java.lang.reflect.ParameterizedType
    5. import java.lang.reflect.Type
    6. import javax.ws.rs.*
    7. import javax.ws.rs.core.*
    8. import javax.ws.rs.ext.*
    9. import javax.xml.bind.*
    10. import javax.xml.transform.stream.StreamSource
    11. @Provider
    12. @Produces(MediaType.APPLICATION_JSON)
    13. @Consumes(MediaType.APPLICATION_JSON)
    14. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
    15. @Context protected Providers providers
    16. public boolean isReadable(
    17. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    18. return true
    19. }
    20. public Object readFrom(
    21. Class<Object> type,
    22. Type genericType,
    23. Annotation[] annotations,
    24. MediaType mediaType,
    25. MultivaluedMap<String, String> httpHeaders,
    26. InputStream entityStream)
    27. throws IOException, WebApplicationException {
    28. try {
    29. Class domainClass = getDomainClass(genericType)
    30. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
    31. u.setProperty("eclipselink.media-type", mediaType.toString())
    32. u.setProperty("eclipselink.json.include-root", false)
    33. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
    34. } catch (JAXBException jaxbException) {
    35. throw new WebApplicationException(jaxbException)
    36. }
    37. }
    38. public boolean isWriteable(
    39. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    40. return true
    41. }
    42. public void writeTo(
    43. Object object,
    44. Class<?> type,
    45. Type genericType,
    46. Annotation[] annotations,
    47. MediaType mediaType,
    48. MultivaluedMap<String, Object> httpHeaders,
    49. OutputStream entityStream)
    50. throws IOException, WebApplicationException {
    51. try {
    52. Marshaller m = getJAXBContext(getDomainClass(genericType), mediaType).createMarshaller()
    53. m.setProperty("eclipselink.media-type", mediaType.toString())
    54. m.setProperty("eclipselink.json.include-root", false)
    55. m.marshal(object, entityStream)
    56. } catch (JAXBException jaxbException) {
    57. throw new WebApplicationException(jaxbException)
    58. }
    59. }
    60. public long getSize(
    61. Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    62. return -1
    63. }
    64. private JAXBContext getJAXBContext(Class<?> type, MediaType mediaType) throws JAXBException {
    65. ContextResolver<JAXBContext> resolver =
    66. providers.getContextResolver(JAXBContext.class, mediaType)
    67. JAXBContext jaxbContext
    68. if (null == resolver || null == (jaxbContext = resolver.getContext(type))) {
    69. return JAXBContext.newInstance(type)
    70. } else {
    71. return jaxbContext
    72. }
    73. }
    74. private Class<?> getDomainClass(Type genericType) {
    75. if (genericType instanceof Class) {
    76. return (Class) genericType
    77. } else if (genericType instanceof ParameterizedType) {
    78. return (Class) ((ParameterizedType) genericType).getActualTypeArguments()[0]
    79. } else {
    80. return null
    81. }
    82. }
    83. }

    Positive Reactions
    1. To produce & consume standard JSON into Jersey one have to use Jackson!
    2. This is easy, quick, and was designed as this by the Jersey team.
    3. Oh, interesting.
    4. The stack trace clearly indicated that a JAXB implementation was being used with the JSON and MOXy supports more JAXB annotations than Jackson does.
    5. @BlaiseDoughan Yes, is uses a standard approach to (un)marshall representations but IT IS NOT the standard approach to (un)marshall JSON in Jersey: Jackson is.
    6. This approach uses the standard 'MessageBodyReader/Writer interfaces to interact with the Jersey client API and clearly demonstrates that you do NOT need to use Jackson to produce & consume standard JSON into Jersey.
    7. This approach is NOT the standard one.
    Negative Reactions
    1. I believe it is not working out of the box because your then items in your collection do not have badge as a root element.
    Other Reactions
    1. I'm curious to know _why_ this doesn't work out-of-the-box do you know?
    2. @yvesamsellem by "standard," you mean _de facto_ standard, right?
    3. Thanks, I'll give this a shot.
    4. :).
    5. @MLL - I have updated my answer.
    6. Taking another look at the difference between the JSON I can unmarshall, and the JSON I can't, I see what you mean.
    7. @M LL yes, I mean built in; designed this way by the Jersey developers.
    8. An earlier version of MOXy is already in GlassFish ( URL_http://blog.bdoughan.com/2012/02/glassfish-312-is-full-of - moxy.html), and a version containing the JSON binding will be included in a future GlassFish release.
    9. @yvesamsellem - (-1?)
    10. Also, I knew it was only a matter of time 'til you posted an answer :).
    11. @yvesamsellem - FYI, Tweet from Jersey regarding MOXy: URL_https://twitter.com/gf_jersey/status/218036096758579202 .

  • multiple actions (CRUD) in one servlet java

    You can add some extra information in your URL. Like parameters And in your servlet you can use the action parameter for decision making Or you can implement your own dispatcher to route request with URL like Or you can override the service method to support PUT DELETE and make your servlet RESTful. details

    Reactions - Positive 2, Negative 0, Others 0

    1. String action = request.getParameter("action")
    2. if(action.equal(...) { /* Your logic here */ }

    Positive Reactions
    1. @hope_is_grim.Thanks for your reply.
    2. You can start by finding some tutorial about creating and working with RESTful Web service.
    Other Reactions
    1. If it doesn't have to be servlet, I think RESTful Web Service is a better solution.
    2. I am building survey app which may be scale in future.
    3. is this better approach or any other suggestion ?

  • How do I marshal nested lists as JSON using Jersey? I get an array of nulls or an array of one-element dictionaries containing an array

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider
    2. import org.codehaus.jettison.json.JSONArray
    3. import org.codehaus.jettison.json.JSONException
    4. @Provider
    5. @Produces("*/*")
    6. @Consumes("*/*")
    7. public class ListObjectArrayMessagereaderWriterProvider
    8. extends AbstractMessageReaderWriterProvider<ListWrapper> {
    9. public boolean supports(Class type) {
    10. return type == ListWrapper.class
    11. }
    12. @Override
    13. public boolean isReadable(
    14. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    15. return type == ListWrapper.class
    16. }
    17. @Override
    18. public ListWrapper readFrom(
    19. Class<ListWrapper> type,
    20. Type genericType,
    21. Annotation[] annotations,
    22. MediaType mediaType,
    23. MultivaluedMap<String, String> httpHeaders,
    24. InputStream entityStream)
    25. throws IOException, WebApplicationException {
    26. throw new IllegalArgumentException("Not implemented yet.")
    27. }
    28. @Override
    29. public boolean isWriteable(
    30. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    31. return type == ListWrapper.class
    32. }
    33. @SuppressWarnings("unchecked")
    34. @Override
    35. public void writeTo(
    36. ListWrapper t,
    37. Class<?> type,
    38. Type genericType,
    39. Annotation[] annotations,
    40. MediaType mediaType,
    41. MultivaluedMap<String, Object> httpHeaders,
    42. OutputStream entityStream)
    43. throws IOException, WebApplicationException {
    44. final Iterator<Object[]> iterator = t.iterator()
    45. OutputStreamWriter writer = new OutputStreamWriter(entityStream, getCharset(mediaType))
    46. final JSONArray jsonArrayOuter = new JSONArray()
    47. while (iterator.hasNext()) {
    48. final Object[] objs = iterator.next()
    49. JSONArray jsonArrayInner = new JSONArray(Arrays.asList(objs))
    50. jsonArrayOuter.put(jsonArrayInner)
    51. }
    52. try {
    53. jsonArrayOuter.write(writer)
    54. writer.write("\n")
    55. writer.flush()
    56. } catch (JSONException je) {
    57. throw new WebApplicationException(
    58. new Exception(ImplMessages.ERROR_WRITING_JSON_ARRAY(), je), 500)
    59. }
    60. }
    61. }