Mined and Summarized Use Cases For API: javax.ws

  1. JAXB for lists to be returned naturally for JSON or XML

    None .. details

    1. import java.util.*
    2. import javax.ws.rs.core.Application
    3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
    4. public class YourApplication extends Application {
    5. @Override
    6. public Set<Class<?>> getClasses() {
    7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
    8. set.add(YourService.class)
    9. return set
    10. }
    11. @Override
    12. public Set<Object> getSingletons() {
    13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
    14. moxyJsonProvider.setWrapperAsArrayName(true)
    15. HashSet<Object> set = new HashSet<Object>(1)
    16. set.add(moxyJsonProvider)
    17. return set
    18. }
    19. }

    • See Also (4)
    1. MOXy compatible XML and JSON responses

      You can change this by setting a configured instance on a JAX-RS Application class like the one below. For More Information MOXy as the Default JSON-Binding Provider in Jersey/GlassFish If you are using MOXy as the default JSON-binding provider with Jersey/GlassFish you can leverage the MoxyJsonConfig class as follows For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class FooApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(ExampleService.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setIncludeRoot(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

    2. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      9. set.add(ExampleService.class)
      10. return set
      11. }
      12. @Override
      13. public Set<Object> getSingletons() {
      14. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      15. moxyJsonProvider.setAttributePrefix("@")
      16. moxyJsonProvider.setFormattedOutput(true)
      17. moxyJsonProvider.setIncludeRoot(true)
      18. moxyJsonProvider.setMarshalEmptyCollections(false)
      19. moxyJsonProvider.setValueWrapper("$")
      20. Map<String, String> namespacePrefixMapper = new HashMap<String, String>(1)
      21. namespacePrefixMapper.put("http://www.example.org/customer", "cust")
      22. moxyJsonProvider.setNamespacePrefixMapper(namespacePrefixMapper)
      23. moxyJsonProvider.setNamespaceSeparator(':')
      24. HashSet<Object> set = new HashSet<Object>(1)
      25. set.add(moxyJsonProvider)
      26. return set
      27. }
      28. }

    3. JSON deserialisation failing (HTTP 400) with Jersey / MOXy

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class MyApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(SubscriptionResource.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setIncludeRoot(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

    4. How an I get MOXy to just output on one line to save space

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      9. set.add(ExampleService.class)
      10. return set
      11. }
      12. @Override
      13. public Set<Object> getSingletons() {
      14. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      15. moxyJsonProvider.setFormattedOutput(true)
      16. }
      17. }

  2. Why writer for media type application/json missing

    None .. details

    1. @Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)

    • See Also (24)
    1. Using JAXB to parse JSON in Jersey

      Maybe this link is helpful example-with-jersey-jackson or . Try this in your endpoint where Coordinates is a simple POJO mirroring the JSON content you are posting. details

      Reactions - Positive 0, Negative 2, Others 0

      1. @POST@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.TEXT_PLAIN)public String processRequest(Coordinates coordinates) { return "Latitude: " + coordinates.getLatitude() + "\n:Longitude: " + coordinates.getLongitude()
      2. }

      Negative Reactions
      1. I'm getting the exact same error.
      2. I keep getting the same errors: MessageBodyReader not found for media type=application/json, type=class web_service.Request, genericType=class web_service.Request.
      Other Reactions
      1. I added all the Jackson jars, the configuration to the web.xml and turned Request into a POJO.
      2. Try with the configuration I provided.
      3. Nope.
      4. and HTTP Status 415 - Unsupported Media Type.

    2. Parsing String[] Request Parameter through REST with Apache CXF

      I apparently misunderstood how REST works. What I did to finally solve the problem was the following 1 Changed my web service signature 2 Now make sure that the client is sending a request with content-type application/x-www-form-urlencoded and that the client correctly adds form parameters same as those you defined in the FormParam annotations. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/getVersion")@Produces(MediaType.APPLICATION_JSON)@Consumes({"application/xml", "application/json", "application/x-www-form-urlencoded"})public ControllerVersion getVersion(@FormParam("deviceID") String deviceID,@FormParam("macAddresses") String macAddresses)

    3. Parsing String[] Request Parameter through REST with Apache CXF

      What do you think I should do. You're using . details

      Reactions - Positive 1, Negative 1, Others 0

      1. @Consumes(MediaType.APPLICATION_JSON)

      Positive Reactions
      1. Please check the "update" section in my original question.
      Negative Reactions
      1. I tried to add Jackson, but I'm ending up with another exception now.

    4. Why JacksonJsonProvider ignores MediaType's parameters?

      if you have and you would like to add a different implementation of the same endpoint you would add a new piece to the path Where version is whatever version of the api you're choosing. Atlassian's JIRA API does things in this way Also using the built-in constants for media types is good form . details

      Reactions - Positive 1, Negative 1, Others 0

      1. @GET @Path("/rest/api/2/issue") @Produces(MediaType.APPLICATION_JSON)

      Positive Reactions
      1. Hi, thanks for your comment.
      Negative Reactions
      1. I watched [REST+JSON API Design - Best Practices for Developers]( URL_http://www.youtube.com/watch?feature=player_detailpage&v=hdSrT 4yjS1g#t=1947) by Stormpath and they suggest to use the header's metadata to distinguish between the API Versions.I never thought this approach would be so hard to realize...
      Other Reactions
      1. Creating a new endpoint is ok but in my opinion hiding the information what API version to use in the HTTP header as metadata is a neat solution.

    5. Spring 3.2 Test, com.jajway not included as dependency

      You should never need to add them manually to the classpath. In my case Having test code what contained jsonPath usage I was getting and This error was directly caused by lack of such dependencies . details

      Reactions - Positive 0, Negative 0, Others 0

      1. mockMvc.perform(get("/api/userDetails").header("Authorization", base64ForTestUser).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(print()) .andExpect(jsonPath("userName").value("testUser"))

    6. Custom response header Jersey/Java

      Just inject a Context HttpServletResponse response as a method argument. Change the headers on that . details

      Reactions - Positive 3, Negative 0, Others 0

      1. @Produces(MediaType.APPLICATION_JSON)public UserClass getValues(@Context HttpHeaders header, @Context HttpServletResponse response) { response.setHeader("yourheadername", "yourheadervalue")
      2. ...}

      Positive Reactions
      1. :-) you rock!.
      2. Thanks a lot @sotirios.
      3. @Namenoobie You're welcome, good luck!.
      Other Reactions
      1. Yes, your Tomcat installation includes those libraries.
      2. That's where you typically get them from.
      3. @Namenoobie You need the server runtime library.
      4. Does it require me to add additional libraries?
      5. This is basically the servlet api.
      6. If you're on Eclipse, go to your project java buildpath and add library.
      7. When I follow the instruction, I get the Tomcat server which already exists on my local machine.
      8. it says unidentified class "HttpServletResponse".

    7. Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

      This is the solution for my old question I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature. And in the web.xml I registered my package into the servlet definition all the rest is transparently done by jersey/jackson. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.lig.hadas.services.mapper
      2. import javax.ws.rs.Produces
      3. import javax.ws.rs.core.MediaType
      4. import javax.ws.rs.ext.ContextResolver
      5. import org.codehaus.jackson.map.DeserializationConfig
      6. import org.codehaus.jackson.map.ObjectMapper
      7. @Produces(MediaType.APPLICATION_JSON)
      8. @Providerpublic
      9. class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
      10. ObjectMapper mapper
      11. public ObjectMapperProvider() {
      12. mapper = new ObjectMapper()
      13. mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
      14. }
      15. @Override
      16. public ObjectMapper getContext(Class<?> type) {
      17. return mapper
      18. }
      19. }

    8. Jersey, how to POST a list of JSON objects?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/some-path")@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)public String createBatch(Example example){ ... }

    9. RESTeasy, JSON and null fields

      Use Jackson 2. Setup the following provider The Scala module is optional. details

      Reactions - Positive 1, Negative 2, Others 0

      1. package com.recruitinghop.swagger
      2. import com.fasterxml.jackson.annotation.JsonInclude
      3. import com.fasterxml.jackson.databind.DeserializationFeature
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. import com.fasterxml.jackson.databind.SerializationFeature
      6. import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider
      7. import com.fasterxml.jackson.module.scala.DefaultScalaModule
      8. import javax.ws.rs.Produces
      9. import javax.ws.rs.core.MediaType
      10. import javax.ws.rs.ext.Provider
      11. @Provider
      12. @Produces(MediaType.APPLICATION_JSON)
      13. public class JacksonJsonProvider extends JacksonJaxbJsonProvider {
      14. public JacksonJsonProvider() {
      15. ObjectMapper mapper = new ObjectMapper()
      16. mapper.registerModule(new DefaultScalaModule())
      17. mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
      18. mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
      19. mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      20. mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      21. super.setMapper(mapper)
      22. }
      23. }

      Positive Reactions
      1. i would like to using only JAXB(native for JBOSS AS 7) for best performance, avoiding others "jar".
      Negative Reactions
      1. Do a little background googling, signup instead of being anonymous and I'll answer to that.
      2. There are so many things wrong with what you just said.
      Other Reactions
      1. is there solution without Jackson ?

    10. Posting JSON to RESTful through formParam with JAX-RS results in "Unsupported Media Type"

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.ws.rs.Consumes
      2. import javax.ws.rs.FormParam
      3. import javax.ws.rs.POST
      4. import javax.ws.rs.core.MediaType
      5. import org.codehaus.jettison.json.JSONObject
      6. ... @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String postData(@FormParam("textAreaName") JSONObject jsono){..

    11. JSON Formatting with Jersey, Jackson, & json.org/java Parser using Curl Command

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class MyWebService { @GET @Produces(MediaType.APPLICATION_JSON) public Family getFamily() return FamilyUtil.getFamily() }}

    12. Jersey JSON and Date

      Your server code are right. The error is in your client code should be . details

      Reactions - Positive 2, Negative 2, Others 0

      1. resp = r.entity(entity, MediaType.APPLICATION_JSON).post(ClientResponse.class)

      Positive Reactions
      1. I test your code in my environment again, It works well.
      2. Thank you secondflying**.
      Negative Reactions
      1. Sorry for my not careful test.
      2. In updateUser method, the user argument is right.
      Other Reactions
      1. Thanks a lot.Unfortunately, it's not worked for me.What the difference on these methods?After looking API documentation I decided that there are no differences in these two methods.
      2. Can you post your web.xml?

    13. Jersey JSON and Date

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. resp = r.type(MediaType.APPLICATION_JSON).post(ClientResponse.class,entity)

    14. Can not convert attribut "type" in xml string to json string by Restlet StringRepresentation class

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. XMLSerializer serializer = new XMLSerializer()
      2. serializer.setTypeHintsEnabled(false)
      3. result = new StringRepresentation(serializer.read(xml).toString(), MediaType.APPLICATION_JSON, Language.ALL, CharacterSet.UTF_8)

    15. How to add a parameter at the end of a restFul service URL?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON } )public String doGet(@QueryParam("format") String fmt) {//...}

    16. Getting JSON out put from restful java client

      None details

      Reactions - Positive 0, Negative 0, Others 0

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

    17. Please advise the best pattern for serialising JAXB Lists

      Everybody must try what and how platforms serve. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})public List<Item> read() { final List<Item> items = ... // is the variable name relevant return items
      2. }

    18. Jersey object mapping

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/testDifferentClass")
      2. public class TestServlet {
      3. @GET
      4. @Produces(MediaType.APPLICATION_XML)
      5. @Consumes(MediaType.APPLICATION_XML)
      6. public ClassA getClassA() {
      7. ClassA classA = new ClassA()
      8. classA.setOne("Hello")
      9. classA.setTwo(new Date())
      10. classA.setThree(1)
      11. return classA
      12. }
      13. }

    19. REST. Jersey. How to programmatically choose what type to return: JSON or XML?

      If you're picky about URLs like I am you could use a file extension resources/todo.json or resources/todo.xml. No need for seperate classes what you need is seperate methods Then in the client side when you request for the service you indicate in what format you want it . details

      Reactions - Positive 2, Negative 2, Others 0

      1. @GET@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })public Todo getXML() { Todo todo = new Todo()
      2. todo.setSummary("This is my first todo")
      3. todo.setDescription("This is my first todo")
      4. return todo
      5. }

      Positive Reactions
      1. ok ok:) I understand it) But what if I want to return neccesary type depending on some other facts (not on client's accept header)?
      2. thanks, so I understand I need to sent accept header from client to get what type I need.
      Negative Reactions
      1. I fail to see under what situation is that viable?!
      2. In all situation, the client is the one initiating the reequest and the client KNOWS in what format he would like to get the request, what you are suggesting will probably cause the client to hate you :).
      Other Reactions
      1. for example I want to let client to choose type of response in URL: rest/get/cars/xml or rest/get/cars/json.
      2. Then depending on pathParam return right type of response.
      3. Once you add the producess annotation, the framework will do it automatically for you based on the client request.
      4. Or in ither words, how to return xml if client's accept header is JSON?
      5. But how I can return neccesary type from server?
      6. Thats a different question, I'd suggest opening a new discussion.

    20. How do I POST a Pojo with Jersey Client without manually convert to JSON?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(searchQuery, MediaType.APPLICATION_JSON)
      2. ListWrapper listWrapper = response.getEntity(ListWrapper.class)

    21. Passing a DataTable object from JavaScript to Java

      Instead from Java you use the JsonRenderer class api/browse_thread/thread/9098bb0dbe7b9157/153a80b5b22bda3a?pli=1 see-this Google-Groups-email to convert it to a Json-like string that's missing quotes around attributes for modest compression. That string can be parsed in Javascript by surrounding with parentheses not shown in the object literal notation in the examples ad/fe353c56343c552d/9fd6bda579c6ff83?lnk=gst&q=DataTable%20json%20java%20javas cript#9fd6bda579c6ff83 see-this-Google-Group-forum I don't see a method for going the reverse way to the Java Datasource Library DataTable object. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/hello/") @GET @Produces(MediaType.TEXT_PLAIN) public String getDataTable() { DataTable data = new DataTable()
      2. CharSequence charSequence = JsonRenderer.renderDataTable(dataTable, true, true)
      3. return charSequence.toString()
      4. }

    22. Passing a DataTable object from JavaScript to Java

      Am not sure if it can be done the other direction. However the Java DataTable object returned by default serialization is not the same thing as the Google Visualization API javascript DataTable. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @WebService@Path("/tables")public class DataManager extends GenericManager<db, Long> { @Path("/hello/") @GET @Produces(MediaType.APPLICATION_JSON) public DataTable getDataTable() { DataTable data = new DataTable()
      2. ... populate object ... return data
      3. }

    23. Jersey Exception : SEVERE: A message body reader for Java class

      You need to implement your own MessageBodyReader and MessageBodyWriter for your class Lorg.shoppingsite.model.entity.jpa.User. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package javax.ws.rs.ext
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.lang.annotation.Annotation
      5. import java.lang.reflect.Type
      6. import javax.ws.rs.WebApplicationException
      7. import javax.ws.rs.core.MediaType
      8. import javax.ws.rs.core.MultivaluedMap
      9. public interface MessageBodyReader<T extends Object> { public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      10. public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
      11. }package javax.ws.rs.ext
      12. import java.io.IOException
      13. import java.io.OutputStream
      14. import java.lang.annotation.Annotation
      15. import java.lang.reflect.Type
      16. import javax.ws.rs.WebApplicationException
      17. import javax.ws.rs.core.MediaType
      18. import javax.ws.rs.core.MultivaluedMap
      19. public interface MessageBodyWriter<T extends Object> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      20. public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      21. public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
      22. }

      Positive Reactions
      1. Normally mapping of JSON to POJOs works with JAXB without creating an own messageBodyReader, because the message reader for JSON already exists.
      Other Reactions
      1. I think your approach is not the common way.
      2. See answer of VDev.

    24. Spring 3.0 making JSON response using jackson message converter

      This worked for me Note that the method doesn't return anything does the magic. The MessageConverter interface defines a getSupportedMediaTypes method which in case of the MappingJacksonMessageCoverter returns application/json I assume a Accept application/json request header is missing. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public MappingJacksonHttpMessageConverter() { super(new MediaType("application", "json", DEFAULT_CHARSET))
      2. }

  3. Apache Wink Json REST Web Service

    I do not know what exactly you mean with that have a structure similar with the java class'. If you refer to wanting to return a json structure I can add following:To return JSON I used And I parsed the string to JSON-format. .. details

    1. @Produces("application/json")

    • See Also (2)
    1. WebService return a XML/JSON file

      an example using Spring 3 . You could do something like the following with JAX-RS Full Example Part-1---The-Database Part-2---Mapping-the-Database-to-JPA-Entities Part-3---Mapping-JPA-entities-to-XML-(using-JAXB) Part-4---The-RESTful-Service Part-5---The-Client . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import javax.ejb.*
      3. import javax.persistence.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.MediaType
      6. @Stateless
      7. @LocalBean
      8. @Path("/customers")
      9. public class CustomerService {
      10. @PersistenceContext(unitName = "CustomerService", type = PersistenceContextType.TRANSACTION)
      11. EntityManager entityManager
      12. @GET
      13. @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
      14. @Path("{id}")
      15. public Customer read(@PathParam("id") long id) {
      16. return entityManager.find(Customer.class, id)
      17. }
      18. }

    2. Convert JSON query parameters to objects with JAX-RS

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET @Produces("text/plain")public String getIt(@QueryParam("query") JSONParam json) { DataTransferObject dto = json.getDTO()
      2. ...}

  4. How to deserialize dynamic JSON fields with Jackson?

    None .. details

    1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
    2. // import com.fasterxml.jackson.databind.ObjectMapper
    3. import org.codehaus.jackson.annotate.JsonTypeInfo
    4. import org.codehaus.jackson.map.ObjectMapper
    5. import javax.ws.rs.ext.ContextResolver
    6. import javax.ws.rs.ext.Provider
    7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
    8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
    9. this.defaultObjectMapper = new ObjectMapper()
    10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
    11. // .enableDefaultTyping()
    12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
    13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
    14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
    15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
    16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
    17. return this.defaultObjectMapper
    18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

  5. How to deserialize dynamic JSON fields with Jackson?

    None .. details

    1. import javax.inject.Singleton
    2. import javax.ws.rs.GET
    3. import javax.ws.rs.Path
    4. import javax.ws.rs.Produces
    5. import javax.ws.rs.core.MediaType
    6. import javax.ws.rs.core.Response
    7. @Singleton
    8. @Path("test/")
    9. public
    10. class MyResource { // public Thing[] state = {new Thing("asdf"), new Thing("foo"), new Thing("bar")}
    11. public String[] state = {"asdf", "foo", "bar"}
    12. @GET
    13. @Produces(MediaType.APPLICATION_JSON)
    14. public Response test() {
    15. return Response.ok(state).build()
    16. }
    17. }

    • See Also (6)
    1. Please advise the best pattern for serialising JAXB Lists

      This could be an another proper way I think. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})public Response readItems() { final List<Item> items = ...
      2. return Response.ok(new GenericEntity<List<String>>(list) {}).build()
      3. }

    2. what's the correct way to send a file from REST web service to client?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces(MediaType.APPLICATION_OCTECT_STREAM)public Response getFile() { File file = ... // Initialize this to the File path you want to serve. return Response.ok(file, MediaType.APPLICATION_OCTECT_STREAM).build()
      2. }

    3. How to add Content-Length to JAXRS

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String str = OBJECT_MAPPER.writeValueAsString(myObject)
      2. return Response.ok(str , MediaType.APPLICATION_JSON).header(HttpHeaders.CONTENT_LENGTH), str.getBytes("UTF-8").length)).build()

    4. Jersey/JAXB: Use same POJO for HTTP POST and GET, but return only a subset of the properties for GET in JSON response.

      You may even be able to implement this in your retrieveUserFromDB method to avoid the copy step. For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getUser(String Id) { // Pseudo-code for retrieving user User userFromDB = retrieveUserFromDB(user)
      2. User user = new User()
      3. user.setUserName(userFromDB.getUserName())
      4. user.setUserEmail(userFromDB.getUserEmail())
      5. Response.status(200).entity(user)
      6. }

    5. Jersey POST Method is receiving null values as parameters

      As a general rule you should restrict your path parameters to simple values like identifiers or resource endpoints more complex data should be passed to the REST service via request parameters or the request body itself. Here's a mixed approach that passes an entity identifier as a path parameter and the entity data in the request body In the above example the contactId is obtained as a path parameter and the contact is serialized automatically from the request body. details

      Reactions - Positive 8, Negative 3, Others 0

      1. @Path("/contacts/{id}")@PUT@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)public Response updateContact(@PathParam final String contactId, Contact contact) {}

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

    6. Jersey POST Method is receiving null values as parameters

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/contacts")@Consumes(MediaType.APPLICATION_FORM_URLENCODED)public Response createContact(@QueryParam("contact") final Contact contactData, @QueryParam("metadata") final String metaData)

  6. MOXy compatible XML and JSON responses

    None .. details

    1. import javax.ws.rs.ext.*
    2. import org.glassfish.jersey.moxy.json.MoxyJsonConfig
    3. @Providerpublic
    4. class MOXyJsonContextResolver implements ContextResolver<MoxyJsonConfig> {
    5. private final MoxyJsonConfig config
    6. public MOXyJsonContextResolver() {
    7. config = new MoxyJsonConfig().setIncludeRoot(true)
    8. }
    9. @Override
    10. public MoxyJsonConfig getContext(Class<?> objectType) {
    11. return config
    12. }
    13. }

    • See Also (7)
    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. What is the fastest way to stand up a REST service using Java?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package rest
      2. import javax.ws.rs.ApplicationPath
      3. import javax.ws.rs.core.Application
      4. @ApplicationPath("/rest")
      5. public class JaxRsActivator extends Application {}

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

      These are the files I called it simpleRest as seen below. All the archives are exactly as shown pom.xml HelloResource.java JaxRsActivator.java This generates a simpleRest.war through mvn clean package). details

      Reactions - Positive 2, Negative 0, Others 0

      1. package rest
      2. import java.util.Date
      3. import javax.ws.rs.GET
      4. import javax.ws.rs.Path
      5. import javax.ws.rs.Produces
      6. @Path("/hello")
      7. public class HelloResource {
      8. @GET
      9. @Produces("text/plain")
      10. public String helloResource() {
      11. return "Hello! It's " + new Date()
      12. }
      13. }

      Positive Reactions
      1. Thank you, This is a great intro :).
      2. Clean, simple, useful!
      Other Reactions
      1. Did you manage to get it working?
      2. If not, we can help you further.
      3. :).

    4. JSON Jersey JAXB

      I think maybe you just need to escape the s on the command line. When your OrderBean is properly annotated with any XmlXXX you don't have to wrap it with JAXBElement< And you should send exactly the same JSON string Jersey can parse. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Consumes(...)public void addOrder(final OrderBean order) {}

    5. 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.

    6. Java.util.Map to JSON Object with Jersey / JAXB / Jackson

      Thanks but I was specifically interested in a solution integrated with Jersey. Of course you need to have getter/setter for every property in Book. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Consumes("application/json")public void createBook(Book book){ ..... .....}

    7. Implementing a REST api which switches between XML and JSON in Servlets

      You can do simple glob-matching in url-pattern . In Java if you are using JAXRS for your rest services annotate your REST service method like Then add the following to you method argument The the fileExt variable would be your extension. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/statuses/public_timeline{fileExt}")

  7. Why JacksonJsonProvider ignores MediaType&#39;s parameters?

    None .. details

    1. @Path("/rest/api/issue")

    • See Also (2)
    1. Why JacksonJsonProvider ignores MediaType's parameters?

      I.e. if you have and you would like to add a different implementation of the same endpoint you would add a new piece to the path Where version is whatever version of the api you're choosing. details

      Reactions - Positive 1, Negative 1, Others 0

      1. @Path("/rest/api/{version}/issue")

      Positive Reactions
      1. Hi, thanks for your comment.
      Negative Reactions
      1. I watched [REST+JSON API Design - Best Practices for Developers]( URL_http://www.youtube.com/watch?feature=player_detailpage&v=hdSrT 4yjS1g#t=1947) by Stormpath and they suggest to use the header's metadata to distinguish between the API Versions.I never thought this approach would be so hard to realize...
      Other Reactions
      1. Creating a new endpoint is ok but in my opinion hiding the information what API version to use in the HTTP header as metadata is a neat solution.

    2. Passing Object and Integer with JSON

      As the post above mentions you can build your own class that wraps the int and has proper annotations. for this case that you gave in the question I think it would be enough to pass a String and then parse it for the int value . details

      Reactions - Positive 2, Negative 1, Others 0

      1. @POST@Path("/test")@Consumes("application/json")public void test(Person pers, String number){ int x = Integer.parseInt(number)
      2. //rest of code here }

      Positive Reactions
      1. I tried it like Gaby mentioned below but no success.
      2. I changed it to string but its not working yet.
      Negative Reactions
      1. { pers:{"name":"TEST", "surname":"TEST"}, "number":"1000" } Exception: Unexpected character ('p' (code 112)): was expecting double-quote to start field name.
      Other Reactions
      1. I think there is a Problem with JSON-Format.

  8. 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 (4)
    1. Get simple JSON Parameter from a JSON request in JAX-RS

      Then Jersey can decode the JSON object for you transparently and voila. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. @Path("/process-something")@POST@Produces("application/json")@Consumes("application/json")public AResponse processSomething(MyJSONOject json) { log.fine(json.attribute)
      2. }

      Positive Reactions
      1. Although I expected an easier way, such as getting the parameter injected with an annotation (see my answer), I mark this as an answer, as this is still a better solution than decoding it manually with Jackson.

    2. Jersey, how to POST a list of JSON objects?

      Also your MyEntity should have XmlRootElement on it see here section 5.2 for an example). You don't need PathParam in your arguments someParam is available when the request is posted if you leave the in your method signature . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/some-path/{someParam}")

    3. Returning JSON Object from REST Web Service with Complex Objects

      U try to use a xml writer to write json. When the classes are annotated with the json annotations json will be returned . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Produces("application/json")

    4. Jersey POST Method is receiving null values as parameters

      Note that URL parameters are not considered part of the URL. **Example** Given the URL I can define From which I can inject a . details

      Reactions - Positive 8, Negative 3, Others 0

      1. @Path("/contacts/{id}")

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

  9. Returning the JSON representation of a String with Jersey

    is it better to create a DTO for every operation or to create a DTO for each type I want to use. You can also return it as but it's look very strange for me. .. details

    1. @GET@Path("hello/{name}")@Produces( MediaType.APPLICATION_JSON)public String hello(@PathParam("name") String name) { return "\"Hello " + name + ", it is " + new Date()+'"'
    2. }

    • See Also (6)
    1. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    2. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    3. Dynamic JSON passing to REST Web service and using it to insert data into mysql db

      if passing a json paramter is your problem then u can try using the path parameter. but i would recommend you to use post method which would make it simple but you should consider if it is an idempotent operation before u decide to use post. details

      Reactions - Positive 4, Negative 1, Others 0

      1. @GET @Path("{jsonString}") @Produces(MediaType.APPLICATION_JSON) public void getStock(@PathParam("jsonString") String jsonString) { String stackJsonString = jsonString

      Positive Reactions
      1. Thanks a lot for the info.
      2. If you have any insight then it would be great.
      3. crul -X POST -H'Conten- Type:application/json'-d{"stockName":"GOOG"} URL_http://localhost:8080/stock .
      4. Thanks a lot for all your time.
      Negative Reactions
      1. I know how to parse a hard-coded JSON string.
      Other Reactions
      1. URL_http://stackoverflow.com/questions/7172784/how-to-post-json - data-with-curl-from-terminal-commandline-to-test-spring-rest.
      2. does this help?
      3. However,i want to pass the curl command as i just wrote it.
      4. e.g.
      5. However, I dont know how to pass a JSON using a curl command(POST) and use that JSON to populate a db.
      6. Currently I am populating the db using a hrd-coded JSON string as shown above in my original question.

    4. REST. Jersey. How to programmatically choose what type to return: JSON or XML?

      Server Side You can specify that your service offers both XML and JSON messages using the Produces annotation. **For More Information** Client Side You can use the MediaType to indicate the type of message. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

    5. REST/JSON Web Services Java EE Framework

      For an example check out my blog Part-1---The-Database Part-2---JPA-Entities Part-3---JAXB-Bindings Part-4---The-RESTFul-Service Part-5---The-Client The example demonstrates XML messages. If you only want JSON messages change the MediaType To support both JSON and XML messages do the following . details

      Reactions - Positive 5, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

      Positive Reactions
      1. Thanks!
      2. Nice!
      3. your blog is useful!.
      4. @BlaiseDoughan your blog has awesome examples with good explanation.
      5. @rich: Good catch :).
      Other Reactions
      1. Although I assume the second example should have one MediaType for JSON and one for XML?
      2. @rich: I have updated my answer to contain info on how to update my example to work with JSON.
      3. This example seems to be for XML, not JSON?

    6. REST/JSON Web Services Java EE Framework

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces(MediaType.APPLICATION_JSON)@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

  10. Jersey 2.0 equivalent to POJOMappingFeature

    You can configure EclipseLink-MOXy as the JSON-binding provider by configuring the MOXyJsonProvider class through a JAX-RS Application class. Example 1 Example 2 For More Information . .. details

    1. package org.example
    2. import java.util.*
    3. import javax.ws.rs.core.Application
    4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
    5. public class CustomerApplication extends Application {
    6. @Override
    7. public Set<Class<?>> getClasses() {
    8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
    9. set.add(MOXyJsonProvider.class)
    10. set.add(CustomerService.class)
    11. return set
    12. }
    13. }

    Positive Reactions
    1. So it is not possible to enable json support in 2.0 without having to write code?

    • See Also (3)
    1. Registering POJO Support or JSON Providers for JAX-RS programmatically

      Below is an example of registering EclipseLink-MOXy as the JSON provider. For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

    2. How an I get MOXy to just output on one line to save space

      To get formatted output you need to set the following property on the Marshaller Root jaxb.properties Demo The following code demonstrates how to specify formatted output Output Below is the output from running the demo code JAX-RS The same behaviour holds for MOXyJsonProvider see . **One Line** By default when you include MOXyJsonProvider in your JAX-RS application the output will be marshalled on one line **Formatted Output** You can also configure MOXyJsonProvider to produce formatted output . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

      Positive Reactions
      1. Ah should have seen this I was looking at my initialcontext method rather than my marshaller initialization, disabled Marshaller.JAXB_FORMATTED_OUTPUT and it now works.

    3. REST. Jersey. How to programmatically choose what type to return: JSON or XML?

      I believe Jackson provides an implementation in its jar. Below is an example of an Application class that specifies MOXy as the JSON provider Or I need to create separately two classes for JSON and XML. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

  11. PUT method with @FormParam

    Change the Consumes type for your resource to multipart/form-data. Then on your client side set Content-Type multipart/form-data Add form variables for login and password On a side note assuming this isn't for learning you will want to secure your login endpoint with SSL and hash the password before sending it across the wire. .. details

    1. @PUT@Path("/login")@Produces({ "application/json", "text/plain" })@Consumes("multipart/form-data")public String login(@FormParam("login") String login, @FormParam("password") String password) { String response = null
    2. response = new UserManager().login(login, password)
    3. return response
    4. }

    Positive Reactions
    1. You can read [this StackOverflow answer]( URL_http://stackoverflow.com/a/2022938/680925) , which gives a nice summary of what to use when.
    2. But i read that "HTML forms are an easy means of getting information from a user and they are also easy to create.
    3. Something like:HttpPut httpPut new HttpPut(BASE_URI + "/services.users/login");Form f new Form(); f.add("login", "xxxxx"); f.add("password", "xxxxx"); ?
    4. I will try that!.
    5. Thanks, it's working!But I was initially asking how to enter those parameters in the TEST RESTful WEB SERVICES main page.
    Negative Reactions
    1. Sorry, another question about the @FormParam: they can be used with PUTs?
    2. Unfortunately, it doesn't seem like Netbeans could detect the invalid combination of annotations on your resource method.
    3. C:\Users\Ines\Documents\NetBeansProjects\LULServices\build\generated-sources \rest-test\test-resbeans.html.
    4. Is that a problem?
    Other Reactions
    1. That's why I was asking.
    2. ?
    3. let us [continue this discussion in chat]( URL_http://chat.stackoverflow.com/rooms/26660/discussion-between-perception - and-user2144555).
    4. I'm always doing PUTs instead of POSTs.
    5. Actually, each one of the HTTP verbs maps to a specific RESTful operation, and you should try to use them appropriately.
    6. I would guess that to be a Netbeans auto-generated test page for your web service.
    7. You should only do PUT's for operations that will be updating an entity.
    8. But I was thinking that " form variables for login and password** " were send in a different way.
    9. I was using Apache HttpClient too.
    10. It's their main page.
    11. Whats the link of the page you are talking about?
    12. Form data can be used for HTTP GET requests and HTTP POST requests."
    13. Yes, I'm always doing updates.
    14. Do you know what I'm talking about?
    15. @user2144555 - See edits for a viable way to call the server resource, using Apache HttpComponents.

    • See Also (2)
    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.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. }

    2. 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 .

  12. post request with multiple parameters JSON and String on Jackson/Jersey JAVA

    Add the token as a header parameter and access it on the server side as a HeaderParam. Example Option 1 Example Option 2 Client Server Example Option 3 Client Server . .. details

    1. ClientResponse response = webResource .type("application/json") .header("Token", token) .post(ClientResponse.class, request)

    Positive Reactions
    1. Thank you!.
    2. That worked perfect!
    3. I would prefer to avoid option 1 if possible because it will add more complexity then I want.
    4. Thank you!
    Negative Reactions
    1. I tired it like so: JSONObject j new JSONObject(c); ObjectMapper mapper new ObjectMapper(); String request mapper.writeValueAsString(c) + "&token='12345'"; System.out.println("request:" + request); ClientResponse response webResource.type("application/json").
    Other Reactions
    1. I added examples of how to implement options 2 & 3.
    2. I tried option 2 and 3 but token returns null.
    3. Option 3.

    • See Also (1)
    1. Why writer for media type application/json missing

      Jettison is a valid option. You can also use Jackson.If you are using maven it is as simple as including the following dependency in you pom At which point you should have no problem writing code such as . details

      Reactions - Positive 0, Negative 0, Others 0

      1. SomeBean query = new SomeBean("args") request.body("application/json", query)
      2. ClientResponse response = request.post()

  13. Jersey content type customization

    You have to support the preflight in the server code or the CORS request will be rejected. Provide your normal code for getSearchContacts but the preflight will come in on with an OPTIONS method Now the CORS request with the custom headers will be allowed. .. details

    1. @OPTIONSpublic Response preflight( @HeaderParam("Access-Control-Request-Method") String requestMethod, @HeaderParam("Origin") String origin, @HeaderParam("Access-Control-Request-Headers") String requestHeaders) {return Response .ok() .header("Access-Control-Allow-Origin", "*") // TODO replace with specific origin .header("Access-Control-Allow-Headers", "Content-Type") .build()
    2. }

    • See Also (8)
    1. what's the correct way to send a file from REST web service to client?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Response.ok(entity, mediaType)

    2. what's the correct way to send a file from REST web service to client?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Path("/{key}")public Response download(@PathParam("key") String key, @Context HttpServletResponse response) throws IOException { try { //Get your File or Object from wherever you want... //you can use the key parameter to indentify your file //otherwise it can be removed //let's say your file is called "object" response.setContentLength((int) object.getContentLength())
      2. response.setHeader("Content-Disposition", "attachment
      3. filename=" + object.getName())
      4. ServletOutputStream outStream = response.getOutputStream()
      5. byte[] bbuf = new byte[(int) object.getContentLength() + 1024]
      6. DataInputStream in = new DataInputStream( object.getDataInputStream())
      7. int length = 0
      8. while ((in != null) && ((length = in.read(bbuf)) != -1)) { outStream.write(bbuf, 0, length)
      9. } in.close()
      10. outStream.flush()
      11. } catch (S3ServiceException e) { e.printStackTrace()
      12. } catch (ServiceException e) { e.printStackTrace()
      13. } return Response.ok().build()
      14. }

    3. Consuming JSON request and producing different output

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/")public class Test {@Path("/test")@POST @Consumes("application/json")@Produces("text/plain")public Response addOrderJSON(OrderDetails details) {...}}

    4. Jersey POST Method is receiving null values as parameters

      **Example** Given the URL I can define From which I can inject a . This works for any kind of HTTP request GET POST PUT DELETE_). details

      Reactions - Positive 8, Negative 3, Others 0

      1. public Response getContact(@PathParam("id") final String identifier)

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

    5. Jersey POST Method is receiving null values as parameters

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public Response getContactsInGroup(@QueryParam("group") final String groupName)

    6. PlayFramework - Running functional test with json rendering

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Test public void testThatJsonRenderingWorks() { Response response = GET(jsonRequest(newRequest)), "/recipe/1")
      2. assertIsOk(response)
      3. } }

    7. Jersey GenericEntity Not Working

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public Response get() { List<String> list = Arrays.asList("test", "as")
      2. return Response.ok(new GenericEntity<List<String>>(list) {}).build()
      3. }

    8. how to send JSON data with server error response code 500

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Response.status(500)

  14. How correctly produce JSON by RESTful web service?

    None .. details

    1. @GET @Produces("application/json") public MyJaxbBean getMyBean() { return new MyJaxbBean("Agamemnon", 32)
    2. }

    • See Also (1)
    1. java - 400 when posting JSONObject to Restful Web Service

      You specify a PathParam argument in your server signature but do not have a corresponding entry in the Path annotation. I cannot tell from your client signature if you are already adding the device string to the URL but I believe you want something like this This is the key part With this Jersey will know where to look for the String that should be populated into device. details

      Reactions - Positive 1, Negative 0, Others 0

      1. @Path("/add/{device}")

      Positive Reactions
      1. Thanks for the input though.
      Other Reactions
      1. I specify the PathParam device in my class header.

  15. Jersey object mapping

    None .. details

    1. public void test() { Client client = Client.create()
    2. WebResource scResource = client.resource("http://localhost:8080/services/testDifferentClass")
    3. ClassB result = scResource.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML).get(ClassB.class)
    4. System.out.println(result.getOne())
    5. System.out.println(result.getTwo())
    6. }

    • See Also (3)
    1. How do I POST a Pojo with Jersey Client without manually convert to JSON?

      It's still using a Builder but less obviously. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. public void sendExample(Example example) { WebResource webResource = this.client.resource(this.url)
      2. webResource.type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(Example.class, example)
      3. return
      4. }

      Positive Reactions
      1. Thanks, that also worked like charm!.

    2. How do I POST a Pojo with Jersey Client without manually convert to JSON?

      That transition is easily obscured when all the requests are chained together. Here's the same example using chaining. details

      Reactions - Positive 1, Negative 0, Others 0

      1. public void sendExample(Example example) { WebResource webResource = this.client.resource(this.url)
      2. Builder builder = webResource.type(MediaType.APPLICATION_JSON)
      3. builder.accept(MediaType.APPLICATION_JSON)
      4. builder.post(Example.class, example)
      5. return
      6. }

      Positive Reactions
      1. Thanks, that also worked like charm!.

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

      By default the server seems to produces a content-type text/plain. Careful you're negotiating a JSON content-type but you don't pass it to the call First you define the path then Jersey gives you a builder to add content type negotiation headers query parameters etc. details

      Reactions - Positive 6, Negative 2, Others 0

      1. WebResource resource = client.resource(url)
      2. Builder builder = resource.accept(MediaType.APPLICATION_JSON)
      3. GenericType<List<EMailInformations>> genericType = new GenericType<List<EMailInformations>>() {}
      4. List<EMailInformations> response = builder.get(genericType)

      Positive Reactions
      1. Maybe it does not show a good content-type.
      2. A working sample online is even better ;).
      3. Try it, maybe this time it will work well (and Jersey works either with XML and JSON).
      4. Please, give me the HTTP trace (Web Browser can print those, if you don't know how, ask).
      5. Thnx for your responses :) Never minde it's Zimbra ...
      6. The browser is working fine, but not when I want to transform the response using Jersey from json to pojo.
      Negative Reactions
      1. Yes, I get it but the problem is to convert it, this is the title of the topic : Error when trying to convert JSON to POJO using Jersey.
      2. That this services produces JSON by default.
      Other Reactions
      1. And what is the response displayed in your browser?
      2. Seems strange.
      3. Even there SOAP API is ...
      4. Thnx for your answer, but alway got the same error...
      5. They do not ask for JSON.
      6. So you get JSON in the browser?
      7. Getting JSON in the browser means that there is no content-type text/html or application/xml produces by the service.
      8. Yes, but the content is really big, and I need to optimize ... so json is smaller thant xml...
      9. Modern browsers use Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 as you can see.
      10. Maybe the services you ask got specific content-type.
      11. I changed the question, there is a Firebug trace there.
      12. It seems that Zimbra also have an XML content-type (the url call is different).

  16. REST Web Service: Server responding with a JAX-B error to GET

    When using a PathParam annotation you need to add the Path annotation to the method declaration. . .. details

    1. @GET@Path("/{test}")@Produces("application/json")public String getJson(@PathParam("test") String test) { return test
    2. }

    • See Also (4)
    1. Jersey POST Method is receiving null values as parameters

      Now as to the specifics of your case one thing I notice in your code is that you don't actually define any path parameters. Remember that they have to be defined as part of your Path annotation before being consumed in your REST method With the above changes your parameters should no longer show up as being null assuming you have properly encoded the URL on the client side. details

      Reactions - Positive 8, Negative 3, Others 0

      1. @Path("/method/{obj1}/{obj2}")public ResponseObject method(@Context Request request, @PathParam("obj1") Object obj1, @PathParam("obj2") String obj2) {}

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

    2. Jersey POST Method is receiving null values as parameters

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @PathParam("id")

    3. 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. @GET @Path("/{id}/search") @Produces(JSON) public ListWrapper search(@PathParam("id") Integer projectId ) { return DatabaseManager.search(projectId)
      2. }

    4. Why writer for media type application/json missing

      I don't know whether resteasy 1.1 containts jettison provider but version 1.2 does.Also if you are using jdk 1.6 you must exclude javax.xml.stream:stax-api jar file otherwise you will have a problem. Here is the example and JAXB class That's all have a nice day. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.ws.rs.GET
      2. import javax.ws.rs.Path
      3. import javax.ws.rs.PathParam
      4. import javax.ws.rs.Produces
      5. @Path("/account")
      6. public class AccountService {
      7. @GET
      8. @Path("/{accountNo}")
      9. @Produces("application/json")
      10. public Account getAccount(@PathParam("accountNo") String accountNo) {
      11. return new Account(accountNo)
      12. }
      13. }

  17. Including null elements in JSON output of Jersey RESTful API with JAXB

    For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . .. details

    1. import java.io.*
    2. import java.lang.annotation.Annotation
    3. import java.lang.reflect.*
    4. import javax.ws.rs.*
    5. import javax.ws.rs.core.*
    6. import javax.ws.rs.ext.*
    7. import javax.xml.bind.*
    8. import javax.xml.transform.stream.StreamSource
    9. import org.eclipse.persistence.jaxb.JAXBContextFactory
    10. @Provider
    11. @Produces(MediaType.APPLICATION_JSON)
    12. @Consumes(MediaType.APPLICATION_JSON)
    13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
    14. @Context protected Providers providers
    15. public boolean isReadable(
    16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    17. return true
    18. }
    19. public Object readFrom(
    20. Class<Object> type,
    21. Type genericType,
    22. Annotation[] annotations,
    23. MediaType mediaType,
    24. MultivaluedMap<String, String> httpHeaders,
    25. InputStream entityStream)
    26. throws IOException, WebApplicationException {
    27. try {
    28. Class<?> domainClass = getDomainClass(genericType)
    29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
    30. u.setProperty("eclipselink.media-type", mediaType.toString())
    31. u.setProperty("eclipselink.json.include-root", false)
    32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
    33. } catch (JAXBException jaxbException) {
    34. throw new WebApplicationException(jaxbException)
    35. }
    36. }
    37. public boolean isWriteable(
    38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    39. return true
    40. }
    41. public void writeTo(
    42. Object object,
    43. Class<?> type,
    44. Type genericType,
    45. Annotation[] annotations,
    46. MediaType mediaType,
    47. MultivaluedMap<String, Object> httpHeaders,
    48. OutputStream entityStream)
    49. throws IOException, WebApplicationException {
    50. try {
    51. Class<?> domainClass = getDomainClass(genericType)
    52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
    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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
    2. Fixed!
    3. An empty lastName is output lastName : { "nil" : "true" }.
    4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
    5. Thanks a a lot for your help.
    6. I'd prefer to use the most up-to- date stable release (2.3.2).
    Negative Reactions
    1. I think there's some type confusion in getJAXBContext().
    2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
    3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
    4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
    5. Tried the new version, but it still doesn't work (same exception).
    6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
    7. I've also had difficulties downloading the required dependancies for this project.
    Other Reactions
    1. I downloaded and tried it with the JAXBProvider and it didn't work.
    2. I've tried this, but I can't quite get it to work.
    3. Any suggestions?
    4. Or both?
    5. :).
    6. It seems to work now.
    7. I tried looking at this document to no avail.
    8. If so, how do we tell MOXy about it?
    9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
    10. Also, do I need the jaxb.properties file, and if so, then where should it be?
    11. For instance, do I have to change my JAXBContextResolver class?
    12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
    13. @Oleksi - I've updated my answer with a version that may work better for you.
    14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
    15. Does it have to be version 2.4.0-SNAPSHOT?
    16. Do we also need to provide a JAXBContext?
    17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

  18. Java consume JSON list from Rest service GET

    None .. details

    1. ClientConfig clientConfig = new DefaultClientConfig()
    2. clientConfig.getClasses().add(JacksonJsonProvider.class)
    3. Client client = Client.create(clientConfig)
    4. return client .resource(Constants.BASE_URL) .path(Constants.CATEGORIES_ANIMALS) .type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .cookie(cookie) .get(new GenericType<List<AnimalCategoryResponse>>(){})

  19. 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 .

  20. How do I send a json object from my rest service so I can parse in out on the client side javascript

    None .. details

    1. @GET@Produces("application/json")@Consumes("application/json") @Path("/getStatus/")public Mystatus getStatus( @Context HttpServletRequest request, @Context HttpServletResponse response){ response.setContentType("text/javascript")
    2. return new Mystatus("Hello","World")
    3. }

    • See Also (2)
    1. How enable JSONP in RESTEasy?

      This solution takes data via http get parameters and translate to virtual POST request. JQuery Declaration in Service interface Filter class web.xml . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("requestPrice")@Produces("application/json")@Consumes("application/json")PriceResponse requestPrice(PriceRequest request) throws ServiceException

    2. How do I register the Jackson provider with the Wink client?

      Step 1 Create a class that extends javax.ws.rs.core.Application that allows you to set singletons. Step 2 In your action create a org.apache.wink.client.ClientConfig for your org.apache.wink.client.RestClient. details

      Reactions - Positive 0, Negative 1, Others 0

      1. import java.util.Collections
      2. import java.util.Set
      3. import javax.ws.rs.core.Application
      4. public class ClientApplication extends Application {
      5. private Set<Object> singletons = Collections.emptySet()
      6. @Override
      7. public Set<Object> getSingletons() {
      8. return singletons
      9. }
      10. public void setSingletons(final Set<Object> singletons) {
      11. this.singletons = singletons
      12. }
      13. }

      Negative Reactions
      1. My classes have jaxb annotations and the system application provider seems to interfere with the jackson json provider.
      Other Reactions
      1. This didn't work for me.
      2. The solution was to call setLoadWinkApplications(false) on the ClientConfig before setting the applications.

  1. property
      Chart will be rendered here
    1. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
      2. // import com.fasterxml.jackson.databind.ObjectMapper
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. import javax.ws.rs.ext.ContextResolver
      6. import javax.ws.rs.ext.Provider
      7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
      8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
      9. this.defaultObjectMapper = new ObjectMapper()
      10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
      11. // .enableDefaultTyping()
      12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
      13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
      14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
      15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
      16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
      17. return this.defaultObjectMapper
      18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

  2. singleton
      Chart will be rendered here
    1. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.inject.Singleton
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.Produces
      5. import javax.ws.rs.core.MediaType
      6. import javax.ws.rs.core.Response
      7. @Singleton
      8. @Path("test/")
      9. public
      10. class MyResource { // public Thing[] state = {new Thing("asdf"), new Thing("foo"), new Thing("bar")}
      11. public String[] state = {"asdf", "foo", "bar"}
      12. @GET
      13. @Produces(MediaType.APPLICATION_JSON)
      14. public Response test() {
      15. return Response.ok(state).build()
      16. }
      17. }

  3. webapplicationexception
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

    3. Jersey Exception : SEVERE: A message body reader for Java class

      You need to implement your own MessageBodyReader and MessageBodyWriter for your class Lorg.shoppingsite.model.entity.jpa.User. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package javax.ws.rs.ext
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.lang.annotation.Annotation
      5. import java.lang.reflect.Type
      6. import javax.ws.rs.WebApplicationException
      7. import javax.ws.rs.core.MediaType
      8. import javax.ws.rs.core.MultivaluedMap
      9. public interface MessageBodyReader<T extends Object> { public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      10. public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
      11. }package javax.ws.rs.ext
      12. import java.io.IOException
      13. import java.io.OutputStream
      14. import java.lang.annotation.Annotation
      15. import java.lang.reflect.Type
      16. import javax.ws.rs.WebApplicationException
      17. import javax.ws.rs.core.MediaType
      18. import javax.ws.rs.core.MultivaluedMap
      19. public interface MessageBodyWriter<T extends Object> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      20. public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      21. public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
      22. }

      Positive Reactions
      1. Normally mapping of JSON to POJOs works with JAXB without creating an own messageBodyReader, because the message reader for JSON already exists.
      Other Reactions
      1. I think your approach is not the common way.
      2. See answer of VDev.

  4. produces
      Chart will be rendered here
    1. Consuming JSON request and producing different output

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/")public class Test {@Path("/test")@POST @Consumes("application/json")@Produces("text/plain")public Response addOrderJSON(OrderDetails details) {...}}

    2. JSON Formatting with Jersey, Jackson, & json.org/java Parser using Curl Command

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class MyWebService { @GET @Produces(MediaType.APPLICATION_JSON) public Family getFamily() return FamilyUtil.getFamily() }}

    3. Why writer for media type application/json missing

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)

    4. Why writer for media type application/json missing

      I don't know whether resteasy 1.1 containts jettison provider but version 1.2 does.Also if you are using jdk 1.6 you must exclude javax.xml.stream:stax-api jar file otherwise you will have a problem. Here is the example and JAXB class That's all have a nice day. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.ws.rs.GET
      2. import javax.ws.rs.Path
      3. import javax.ws.rs.PathParam
      4. import javax.ws.rs.Produces
      5. @Path("/account")
      6. public class AccountService {
      7. @GET
      8. @Path("/{accountNo}")
      9. @Produces("application/json")
      10. public Account getAccount(@PathParam("accountNo") String accountNo) {
      11. return new Account(accountNo)
      12. }
      13. }

    5. Returning the JSON representation of a String with Jersey

      is it better to create a DTO for every operation or to create a DTO for each type I want to use. You can also return it as but it's look very strange for me. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Path("hello/{name}")@Produces( MediaType.APPLICATION_JSON)public String hello(@PathParam("name") String name) { return "\"Hello " + name + ", it is " + new Date()+'"'
      2. }

    6. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    7. 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. @GET @Path("/{id}/search") @Produces(JSON) public ListWrapper search(@PathParam("id") Integer projectId ) { return DatabaseManager.search(projectId)
      2. }

    8. RESTeasy, JSON and null fields

      Use Jackson 2. Setup the following provider The Scala module is optional. details

      Reactions - Positive 1, Negative 2, Others 0

      1. package com.recruitinghop.swagger
      2. import com.fasterxml.jackson.annotation.JsonInclude
      3. import com.fasterxml.jackson.databind.DeserializationFeature
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. import com.fasterxml.jackson.databind.SerializationFeature
      6. import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider
      7. import com.fasterxml.jackson.module.scala.DefaultScalaModule
      8. import javax.ws.rs.Produces
      9. import javax.ws.rs.core.MediaType
      10. import javax.ws.rs.ext.Provider
      11. @Provider
      12. @Produces(MediaType.APPLICATION_JSON)
      13. public class JacksonJsonProvider extends JacksonJaxbJsonProvider {
      14. public JacksonJsonProvider() {
      15. ObjectMapper mapper = new ObjectMapper()
      16. mapper.registerModule(new DefaultScalaModule())
      17. mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
      18. mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
      19. mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      20. mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      21. super.setMapper(mapper)
      22. }
      23. }

      Positive Reactions
      1. i would like to using only JAXB(native for JBOSS AS 7) for best performance, avoiding others "jar".
      Negative Reactions
      1. Do a little background googling, signup instead of being anonymous and I'll answer to that.
      2. There are so many things wrong with what you just said.
      Other Reactions
      1. is there solution without Jackson ?

    9. Jersey, how to POST a list of JSON objects?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/some-path")@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)public String createBatch(Example example){ ... }

    10. How correctly produce JSON by RESTful web service?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET @Produces("application/json") public MyJaxbBean getMyBean() { return new MyJaxbBean("Agamemnon", 32)
      2. }

    11. 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 .

    12. Apache Wink Json REST Web Service

      I do not know what exactly you mean with that have a structure similar with the java class'. If you refer to wanting to return a json structure I can add following:To return JSON I used And I parsed the string to JSON-format. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Produces("application/json")

    13. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    14. REST/JSON Web Services Java EE Framework

      For an example check out my blog Part-1---The-Database Part-2---JPA-Entities Part-3---JAXB-Bindings Part-4---The-RESTFul-Service Part-5---The-Client The example demonstrates XML messages. If you only want JSON messages change the MediaType To support both JSON and XML messages do the following . details

      Reactions - Positive 5, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

      Positive Reactions
      1. Thanks!
      2. Nice!
      3. your blog is useful!.
      4. @BlaiseDoughan your blog has awesome examples with good explanation.
      5. @rich: Good catch :).
      Other Reactions
      1. Although I assume the second example should have one MediaType for JSON and one for XML?
      2. @rich: I have updated my answer to contain info on how to update my example to work with JSON.
      3. This example seems to be for XML, not JSON?

    15. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    16. Why JacksonJsonProvider ignores MediaType's parameters?

      if you have and you would like to add a different implementation of the same endpoint you would add a new piece to the path Where version is whatever version of the api you're choosing. Atlassian's JIRA API does things in this way Also using the built-in constants for media types is good form . details

      Reactions - Positive 1, Negative 1, Others 0

      1. @GET @Path("/rest/api/2/issue") @Produces(MediaType.APPLICATION_JSON)

      Positive Reactions
      1. Hi, thanks for your comment.
      Negative Reactions
      1. I watched [REST+JSON API Design - Best Practices for Developers]( URL_http://www.youtube.com/watch?feature=player_detailpage&v=hdSrT 4yjS1g#t=1947) by Stormpath and they suggest to use the header's metadata to distinguish between the API Versions.I never thought this approach would be so hard to realize...
      Other Reactions
      1. Creating a new endpoint is ok but in my opinion hiding the information what API version to use in the HTTP header as metadata is a neat solution.

    17. Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

      This is the solution for my old question I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature. And in the web.xml I registered my package into the servlet definition all the rest is transparently done by jersey/jackson. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.lig.hadas.services.mapper
      2. import javax.ws.rs.Produces
      3. import javax.ws.rs.core.MediaType
      4. import javax.ws.rs.ext.ContextResolver
      5. import org.codehaus.jackson.map.DeserializationConfig
      6. import org.codehaus.jackson.map.ObjectMapper
      7. @Produces(MediaType.APPLICATION_JSON)
      8. @Providerpublic
      9. class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
      10. ObjectMapper mapper
      11. public ObjectMapperProvider() {
      12. mapper = new ObjectMapper()
      13. mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
      14. }
      15. @Override
      16. public ObjectMapper getContext(Class<?> type) {
      17. return mapper
      18. }
      19. }

    18. Convert JSON query parameters to objects with JAX-RS

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET @Produces("text/plain")public String getIt(@QueryParam("query") JSONParam json) { DataTransferObject dto = json.getDTO()
      2. ...}

    19. Jersey/JAXB: Use same POJO for HTTP POST and GET, but return only a subset of the properties for GET in JSON response.

      You may even be able to implement this in your retrieveUserFromDB method to avoid the copy step. For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getUser(String Id) { // Pseudo-code for retrieving user User userFromDB = retrieveUserFromDB(user)
      2. User user = new User()
      3. user.setUserName(userFromDB.getUserName())
      4. user.setUserEmail(userFromDB.getUserEmail())
      5. Response.status(200).entity(user)
      6. }

    20. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.inject.Singleton
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.Produces
      5. import javax.ws.rs.core.MediaType
      6. import javax.ws.rs.core.Response
      7. @Singleton
      8. @Path("test/")
      9. public
      10. class MyResource { // public Thing[] state = {new Thing("asdf"), new Thing("foo"), new Thing("bar")}
      11. public String[] state = {"asdf", "foo", "bar"}
      12. @GET
      13. @Produces(MediaType.APPLICATION_JSON)
      14. public Response test() {
      15. return Response.ok(state).build()
      16. }
      17. }

    21. REST/JSON Web Services Java EE Framework

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces(MediaType.APPLICATION_JSON)@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

    22. WebService return a XML/JSON file

      an example using Spring 3 . You could do something like the following with JAX-RS Full Example Part-1---The-Database Part-2---Mapping-the-Database-to-JPA-Entities Part-3---Mapping-JPA-entities-to-XML-(using-JAXB) Part-4---The-RESTful-Service Part-5---The-Client . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import javax.ejb.*
      3. import javax.persistence.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.MediaType
      6. @Stateless
      7. @LocalBean
      8. @Path("/customers")
      9. public class CustomerService {
      10. @PersistenceContext(unitName = "CustomerService", type = PersistenceContextType.TRANSACTION)
      11. EntityManager entityManager
      12. @GET
      13. @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
      14. @Path("{id}")
      15. public Customer read(@PathParam("id") long id) {
      16. return entityManager.find(Customer.class, id)
      17. }
      18. }

    23. Jersey POST Method is receiving null values as parameters

      As a general rule you should restrict your path parameters to simple values like identifiers or resource endpoints more complex data should be passed to the REST service via request parameters or the request body itself. Here's a mixed approach that passes an entity identifier as a path parameter and the entity data in the request body In the above example the contactId is obtained as a path parameter and the contact is serialized automatically from the request body. details

      Reactions - Positive 8, Negative 3, Others 0

      1. @Path("/contacts/{id}")@PUT@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)public Response updateContact(@PathParam final String contactId, Contact contact) {}

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

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

      These are the files I called it simpleRest as seen below. All the archives are exactly as shown pom.xml HelloResource.java JaxRsActivator.java This generates a simpleRest.war through mvn clean package). details

      Reactions - Positive 2, Negative 0, Others 0

      1. package rest
      2. import java.util.Date
      3. import javax.ws.rs.GET
      4. import javax.ws.rs.Path
      5. import javax.ws.rs.Produces
      6. @Path("/hello")
      7. public class HelloResource {
      8. @GET
      9. @Produces("text/plain")
      10. public String helloResource() {
      11. return "Hello! It's " + new Date()
      12. }
      13. }

      Positive Reactions
      1. Thank you, This is a great intro :).
      2. Clean, simple, useful!
      Other Reactions
      1. Did you manage to get it working?
      2. If not, we can help you further.
      3. :).

    25. How do I send a json object from my rest service so I can parse in out on the client side javascript

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces("application/json")@Consumes("application/json") @Path("/getStatus/")public Mystatus getStatus( @Context HttpServletRequest request, @Context HttpServletResponse response){ response.setContentType("text/javascript")
      2. return new Mystatus("Hello","World")
      3. }

    26. REST Web Service: Server responding with a JAX-B error to GET

      When using a PathParam annotation you need to add the Path annotation to the method declaration. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Path("/{test}")@Produces("application/json")public String getJson(@PathParam("test") String test) { return test
      2. }

    27. Dynamic JSON passing to REST Web service and using it to insert data into mysql db

      if passing a json paramter is your problem then u can try using the path parameter. but i would recommend you to use post method which would make it simple but you should consider if it is an idempotent operation before u decide to use post. details

      Reactions - Positive 4, Negative 1, Others 0

      1. @GET @Path("{jsonString}") @Produces(MediaType.APPLICATION_JSON) public void getStock(@PathParam("jsonString") String jsonString) { String stackJsonString = jsonString

      Positive Reactions
      1. Thanks a lot for the info.
      2. If you have any insight then it would be great.
      3. crul -X POST -H'Conten- Type:application/json'-d{"stockName":"GOOG"} URL_http://localhost:8080/stock .
      4. Thanks a lot for all your time.
      Negative Reactions
      1. I know how to parse a hard-coded JSON string.
      Other Reactions
      1. URL_http://stackoverflow.com/questions/7172784/how-to-post-json - data-with-curl-from-terminal-commandline-to-test-spring-rest.
      2. does this help?
      3. However,i want to pass the curl command as i just wrote it.
      4. e.g.
      5. However, I dont know how to pass a JSON using a curl command(POST) and use that JSON to populate a db.
      6. Currently I am populating the db using a hrd-coded JSON string as shown above in my original question.

    28. Parsing String[] Request Parameter through REST with Apache CXF

      I apparently misunderstood how REST works. What I did to finally solve the problem was the following 1 Changed my web service signature 2 Now make sure that the client is sending a request with content-type application/x-www-form-urlencoded and that the client correctly adds form parameters same as those you defined in the FormParam annotations. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/getVersion")@Produces(MediaType.APPLICATION_JSON)@Consumes({"application/xml", "application/json", "application/x-www-form-urlencoded"})public ControllerVersion getVersion(@FormParam("deviceID") String deviceID,@FormParam("macAddresses") String macAddresses)

    29. Please advise the best pattern for serialising JAXB Lists

      Everybody must try what and how platforms serve. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})public List<Item> read() { final List<Item> items = ... // is the variable name relevant return items
      2. }

    30. Passing a DataTable object from JavaScript to Java

      Instead from Java you use the JsonRenderer class api/browse_thread/thread/9098bb0dbe7b9157/153a80b5b22bda3a?pli=1 see-this Google-Groups-email to convert it to a Json-like string that's missing quotes around attributes for modest compression. That string can be parsed in Javascript by surrounding with parentheses not shown in the object literal notation in the examples ad/fe353c56343c552d/9fd6bda579c6ff83?lnk=gst&q=DataTable%20json%20java%20javas cript#9fd6bda579c6ff83 see-this-Google-Group-forum I don't see a method for going the reverse way to the Java Datasource Library DataTable object. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/hello/") @GET @Produces(MediaType.TEXT_PLAIN) public String getDataTable() { DataTable data = new DataTable()
      2. CharSequence charSequence = JsonRenderer.renderDataTable(dataTable, true, true)
      3. return charSequence.toString()
      4. }

    31. Passing a DataTable object from JavaScript to Java

      Am not sure if it can be done the other direction. However the Java DataTable object returned by default serialization is not the same thing as the Google Visualization API javascript DataTable. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @WebService@Path("/tables")public class DataManager extends GenericManager<db, Long> { @Path("/hello/") @GET @Produces(MediaType.APPLICATION_JSON) public DataTable getDataTable() { DataTable data = new DataTable()
      2. ... populate object ... return data
      3. }

    32. PUT method with @FormParam

      Change the Consumes type for your resource to multipart/form-data. Then on your client side set Content-Type multipart/form-data Add form variables for login and password On a side note assuming this isn't for learning you will want to secure your login endpoint with SSL and hash the password before sending it across the wire. details

      Reactions - Positive 5, Negative 4, Others 0

      1. @PUT@Path("/login")@Produces({ "application/json", "text/plain" })@Consumes("multipart/form-data")public String login(@FormParam("login") String login, @FormParam("password") String password) { String response = null
      2. response = new UserManager().login(login, password)
      3. return response
      4. }

      Positive Reactions
      1. You can read [this StackOverflow answer]( URL_http://stackoverflow.com/a/2022938/680925) , which gives a nice summary of what to use when.
      2. But i read that "HTML forms are an easy means of getting information from a user and they are also easy to create.
      3. Something like:HttpPut httpPut new HttpPut(BASE_URI + "/services.users/login");Form f new Form(); f.add("login", "xxxxx"); f.add("password", "xxxxx"); ?
      4. I will try that!.
      5. Thanks, it's working!But I was initially asking how to enter those parameters in the TEST RESTful WEB SERVICES main page.
      Negative Reactions
      1. Sorry, another question about the @FormParam: they can be used with PUTs?
      2. Unfortunately, it doesn't seem like Netbeans could detect the invalid combination of annotations on your resource method.
      3. C:\Users\Ines\Documents\NetBeansProjects\LULServices\build\generated-sources \rest-test\test-resbeans.html.
      4. Is that a problem?
      Other Reactions
      1. That's why I was asking.
      2. ?
      3. let us [continue this discussion in chat]( URL_http://chat.stackoverflow.com/rooms/26660/discussion-between-perception - and-user2144555).
      4. I'm always doing PUTs instead of POSTs.
      5. Actually, each one of the HTTP verbs maps to a specific RESTful operation, and you should try to use them appropriately.
      6. I would guess that to be a Netbeans auto-generated test page for your web service.
      7. You should only do PUT's for operations that will be updating an entity.
      8. But I was thinking that " form variables for login and password** " were send in a different way.
      9. I was using Apache HttpClient too.
      10. It's their main page.
      11. Whats the link of the page you are talking about?
      12. Form data can be used for HTTP GET requests and HTTP POST requests."
      13. Yes, I'm always doing updates.
      14. Do you know what I'm talking about?
      15. @user2144555 - See edits for a viable way to call the server resource, using Apache HttpComponents.

    33. Get simple JSON Parameter from a JSON request in JAX-RS

      Then Jersey can decode the JSON object for you transparently and voila. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. @Path("/process-something")@POST@Produces("application/json")@Consumes("application/json")public AResponse processSomething(MyJSONOject json) { log.fine(json.attribute)
      2. }

      Positive Reactions
      1. Although I expected an easier way, such as getting the parameter injected with an annotation (see my answer), I mark this as an answer, as this is still a better solution than decoding it manually with Jackson.

    34. Please advise the best pattern for serialising JAXB Lists

      This could be an another proper way I think. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})public Response readItems() { final List<Item> items = ...
      2. return Response.ok(new GenericEntity<List<String>>(list) {}).build()
      3. }

    35. Jersey object mapping

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/testDifferentClass")
      2. public class TestServlet {
      3. @GET
      4. @Produces(MediaType.APPLICATION_XML)
      5. @Consumes(MediaType.APPLICATION_XML)
      6. public ClassA getClassA() {
      7. ClassA classA = new ClassA()
      8. classA.setOne("Hello")
      9. classA.setTwo(new Date())
      10. classA.setThree(1)
      11. return classA
      12. }
      13. }

    36. Custom response header Jersey/Java

      Just inject a Context HttpServletResponse response as a method argument. Change the headers on that . details

      Reactions - Positive 3, Negative 0, Others 0

      1. @Produces(MediaType.APPLICATION_JSON)public UserClass getValues(@Context HttpHeaders header, @Context HttpServletResponse response) { response.setHeader("yourheadername", "yourheadervalue")
      2. ...}

      Positive Reactions
      1. :-) you rock!.
      2. Thanks a lot @sotirios.
      3. @Namenoobie You're welcome, good luck!.
      Other Reactions
      1. Yes, your Tomcat installation includes those libraries.
      2. That's where you typically get them from.
      3. @Namenoobie You need the server runtime library.
      4. Does it require me to add additional libraries?
      5. This is basically the servlet api.
      6. If you're on Eclipse, go to your project java buildpath and add library.
      7. When I follow the instruction, I get the Tomcat server which already exists on my local machine.
      8. it says unidentified class "HttpServletResponse".

    37. Returning JSON Object from REST Web Service with Complex Objects

      U try to use a xml writer to write json. When the classes are annotated with the json annotations json will be returned . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Produces("application/json")

    38. REST. Jersey. How to programmatically choose what type to return: JSON or XML?

      Server Side You can specify that your service offers both XML and JSON messages using the Produces annotation. **For More Information** Client Side You can use the MediaType to indicate the type of message. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

    39. REST. Jersey. How to programmatically choose what type to return: JSON or XML?

      If you're picky about URLs like I am you could use a file extension resources/todo.json or resources/todo.xml. No need for seperate classes what you need is seperate methods Then in the client side when you request for the service you indicate in what format you want it . details

      Reactions - Positive 2, Negative 2, Others 0

      1. @GET@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })public Todo getXML() { Todo todo = new Todo()
      2. todo.setSummary("This is my first todo")
      3. todo.setDescription("This is my first todo")
      4. return todo
      5. }

      Positive Reactions
      1. ok ok:) I understand it) But what if I want to return neccesary type depending on some other facts (not on client's accept header)?
      2. thanks, so I understand I need to sent accept header from client to get what type I need.
      Negative Reactions
      1. I fail to see under what situation is that viable?!
      2. In all situation, the client is the one initiating the reequest and the client KNOWS in what format he would like to get the request, what you are suggesting will probably cause the client to hate you :).
      Other Reactions
      1. for example I want to let client to choose type of response in URL: rest/get/cars/xml or rest/get/cars/json.
      2. Then depending on pathParam return right type of response.
      3. Once you add the producess annotation, the framework will do it automatically for you based on the client request.
      4. Or in ither words, how to return xml if client's accept header is JSON?
      5. But how I can return neccesary type from server?
      6. Thats a different question, I'd suggest opening a new discussion.

    40. what's the correct way to send a file from REST web service to client?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces(MediaType.APPLICATION_OCTECT_STREAM)public Response getFile() { File file = ... // Initialize this to the File path you want to serve. return Response.ok(file, MediaType.APPLICATION_OCTECT_STREAM).build()
      2. }

    41. Using JAXB to parse JSON in Jersey

      Maybe this link is helpful example-with-jersey-jackson or . Try this in your endpoint where Coordinates is a simple POJO mirroring the JSON content you are posting. details

      Reactions - Positive 0, Negative 2, Others 0

      1. @POST@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.TEXT_PLAIN)public String processRequest(Coordinates coordinates) { return "Latitude: " + coordinates.getLatitude() + "\n:Longitude: " + coordinates.getLongitude()
      2. }

      Negative Reactions
      1. I'm getting the exact same error.
      2. I keep getting the same errors: MessageBodyReader not found for media type=application/json, type=class web_service.Request, genericType=class web_service.Request.
      Other Reactions
      1. I added all the Jackson jars, the configuration to the web.xml and turned Request into a POJO.
      2. Try with the configuration I provided.
      3. Nope.
      4. and HTTP Status 415 - Unsupported Media Type.

    42. 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. }

    43. How enable JSONP in RESTEasy?

      This solution takes data via http get parameters and translate to virtual POST request. JQuery Declaration in Service interface Filter class web.xml . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("requestPrice")@Produces("application/json")@Consumes("application/json")PriceResponse requestPrice(PriceRequest request) throws ServiceException

  5. clientresponse
      Chart will be rendered here
    1. 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. }

    2. post request with multiple parameters JSON and String on Jackson/Jersey JAVA

      Add the token as a header parameter and access it on the server side as a HeaderParam. Example Option 1 Example Option 2 Client Server Example Option 3 Client Server . details

      Reactions - Positive 4, Negative 1, Others 0

      1. ClientResponse response = webResource .type("application/json") .header("Token", token) .post(ClientResponse.class, request)

      Positive Reactions
      1. Thank you!.
      2. That worked perfect!
      3. I would prefer to avoid option 1 if possible because it will add more complexity then I want.
      4. Thank you!
      Negative Reactions
      1. I tired it like so: JSONObject j new JSONObject(c); ObjectMapper mapper new ObjectMapper(); String request mapper.writeValueAsString(c) + "&token='12345'"; System.out.println("request:" + request); ClientResponse response webResource.type("application/json").
      Other Reactions
      1. I added examples of how to implement options 2 & 3.
      2. I tried option 2 and 3 but token returns null.
      3. Option 3.

    3. Why writer for media type application/json missing

      Jettison is a valid option. You can also use Jackson.If you are using maven it is as simple as including the following dependency in you pom At which point you should have no problem writing code such as . details

      Reactions - Positive 0, Negative 0, Others 0

      1. SomeBean query = new SomeBean("args") request.body("application/json", query)
      2. ClientResponse response = request.post()

  6. feature
      Chart will be rendered here
    1. Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

      This is the solution for my old question I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature. And in the web.xml I registered my package into the servlet definition all the rest is transparently done by jersey/jackson. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.lig.hadas.services.mapper
      2. import javax.ws.rs.Produces
      3. import javax.ws.rs.core.MediaType
      4. import javax.ws.rs.ext.ContextResolver
      5. import org.codehaus.jackson.map.DeserializationConfig
      6. import org.codehaus.jackson.map.ObjectMapper
      7. @Produces(MediaType.APPLICATION_JSON)
      8. @Providerpublic
      9. class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
      10. ObjectMapper mapper
      11. public ObjectMapperProvider() {
      12. mapper = new ObjectMapper()
      13. mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
      14. }
      15. @Override
      16. public ObjectMapper getContext(Class<?> type) {
      17. return mapper
      18. }
      19. }

  7. moxyjsonprovider
      Chart will be rendered here
    1. JSON deserialisation failing (HTTP 400) with Jersey / MOXy

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class MyApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(SubscriptionResource.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setIncludeRoot(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

    2. MOXy compatible XML and JSON responses

      You can change this by setting a configured instance on a JAX-RS Application class like the one below. For More Information MOXy as the Default JSON-Binding Provider in Jersey/GlassFish If you are using MOXy as the default JSON-binding provider with Jersey/GlassFish you can leverage the MoxyJsonConfig class as follows For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class FooApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(ExampleService.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setIncludeRoot(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

    3. REST. Jersey. How to programmatically choose what type to return: JSON or XML?

      I believe Jackson provides an implementation in its jar. Below is an example of an Application class that specifies MOXy as the JSON provider Or I need to create separately two classes for JSON and XML. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

    4. How an I get MOXy to just output on one line to save space

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      9. set.add(ExampleService.class)
      10. return set
      11. }
      12. @Override
      13. public Set<Object> getSingletons() {
      14. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      15. moxyJsonProvider.setFormattedOutput(true)
      16. }
      17. }

    5. Registering POJO Support or JSON Providers for JAX-RS programmatically

      Below is an example of registering EclipseLink-MOXy as the JSON provider. For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

    6. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      9. set.add(ExampleService.class)
      10. return set
      11. }
      12. @Override
      13. public Set<Object> getSingletons() {
      14. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      15. moxyJsonProvider.setAttributePrefix("@")
      16. moxyJsonProvider.setFormattedOutput(true)
      17. moxyJsonProvider.setIncludeRoot(true)
      18. moxyJsonProvider.setMarshalEmptyCollections(false)
      19. moxyJsonProvider.setValueWrapper("$")
      20. Map<String, String> namespacePrefixMapper = new HashMap<String, String>(1)
      21. namespacePrefixMapper.put("http://www.example.org/customer", "cust")
      22. moxyJsonProvider.setNamespacePrefixMapper(namespacePrefixMapper)
      23. moxyJsonProvider.setNamespaceSeparator(':')
      24. HashSet<Object> set = new HashSet<Object>(1)
      25. set.add(moxyJsonProvider)
      26. return set
      27. }
      28. }

    7. Jersey 2.0 equivalent to POJOMappingFeature

      You can configure EclipseLink-MOXy as the JSON-binding provider by configuring the MOXyJsonProvider class through a JAX-RS Application class. Example 1 Example 2 For More Information . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

      Positive Reactions
      1. So it is not possible to enable json support in 2.0 without having to write code?

    8. JAXB for lists to be returned naturally for JSON or XML

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class YourApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(YourService.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setWrapperAsArrayName(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

    9. How an I get MOXy to just output on one line to save space

      To get formatted output you need to set the following property on the Marshaller Root jaxb.properties Demo The following code demonstrates how to specify formatted output Output Below is the output from running the demo code JAX-RS The same behaviour holds for MOXyJsonProvider see . **One Line** By default when you include MOXyJsonProvider in your JAX-RS application the output will be marshalled on one line **Formatted Output** You can also configure MOXyJsonProvider to produce formatted output . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

      Positive Reactions
      1. Ah should have seen this I was looking at my initialcontext method rather than my marshaller initialization, disabled Marshaller.JAXB_FORMATTED_OUTPUT and it now works.

  8. webresource
      Chart will be rendered here
    1. How do I POST a Pojo with Jersey Client without manually convert to JSON?

      It's still using a Builder but less obviously. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. public void sendExample(Example example) { WebResource webResource = this.client.resource(this.url)
      2. webResource.type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(Example.class, example)
      3. return
      4. }

      Positive Reactions
      1. Thanks, that also worked like charm!.

    2. Jersey object mapping

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public void test() { Client client = Client.create()
      2. WebResource scResource = client.resource("http://localhost:8080/services/testDifferentClass")
      3. ClassB result = scResource.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML).get(ClassB.class)
      4. System.out.println(result.getOne())
      5. System.out.println(result.getTwo())
      6. }

    3. How do I POST a Pojo with Jersey Client without manually convert to JSON?

      That transition is easily obscured when all the requests are chained together. Here's the same example using chaining. details

      Reactions - Positive 1, Negative 0, Others 0

      1. public void sendExample(Example example) { WebResource webResource = this.client.resource(this.url)
      2. Builder builder = webResource.type(MediaType.APPLICATION_JSON)
      3. builder.accept(MediaType.APPLICATION_JSON)
      4. builder.post(Example.class, example)
      5. return
      6. }

      Positive Reactions
      1. Thanks, that also worked like charm!.

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

      By default the server seems to produces a content-type text/plain. Careful you're negotiating a JSON content-type but you don't pass it to the call First you define the path then Jersey gives you a builder to add content type negotiation headers query parameters etc. details

      Reactions - Positive 6, Negative 2, Others 0

      1. WebResource resource = client.resource(url)
      2. Builder builder = resource.accept(MediaType.APPLICATION_JSON)
      3. GenericType<List<EMailInformations>> genericType = new GenericType<List<EMailInformations>>() {}
      4. List<EMailInformations> response = builder.get(genericType)

      Positive Reactions
      1. Maybe it does not show a good content-type.
      2. A working sample online is even better ;).
      3. Try it, maybe this time it will work well (and Jersey works either with XML and JSON).
      4. Please, give me the HTTP trace (Web Browser can print those, if you don't know how, ask).
      5. Thnx for your responses :) Never minde it's Zimbra ...
      6. The browser is working fine, but not when I want to transform the response using Jersey from json to pojo.
      Negative Reactions
      1. Yes, I get it but the problem is to convert it, this is the title of the topic : Error when trying to convert JSON to POJO using Jersey.
      2. That this services produces JSON by default.
      Other Reactions
      1. And what is the response displayed in your browser?
      2. Seems strange.
      3. Even there SOAP API is ...
      4. Thnx for your answer, but alway got the same error...
      5. They do not ask for JSON.
      6. So you get JSON in the browser?
      7. Getting JSON in the browser means that there is no content-type text/html or application/xml produces by the service.
      8. Yes, but the content is really big, and I need to optimize ... so json is smaller thant xml...
      9. Modern browsers use Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 as you can see.
      10. Maybe the services you ask got specific content-type.
      11. I changed the question, there is a Firebug trace there.
      12. It seems that Zimbra also have an XML content-type (the url call is different).

  9. outputstream
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

    3. Jersey Exception : SEVERE: A message body reader for Java class

      You need to implement your own MessageBodyReader and MessageBodyWriter for your class Lorg.shoppingsite.model.entity.jpa.User. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package javax.ws.rs.ext
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.lang.annotation.Annotation
      5. import java.lang.reflect.Type
      6. import javax.ws.rs.WebApplicationException
      7. import javax.ws.rs.core.MediaType
      8. import javax.ws.rs.core.MultivaluedMap
      9. public interface MessageBodyReader<T extends Object> { public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      10. public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
      11. }package javax.ws.rs.ext
      12. import java.io.IOException
      13. import java.io.OutputStream
      14. import java.lang.annotation.Annotation
      15. import java.lang.reflect.Type
      16. import javax.ws.rs.WebApplicationException
      17. import javax.ws.rs.core.MediaType
      18. import javax.ws.rs.core.MultivaluedMap
      19. public interface MessageBodyWriter<T extends Object> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      20. public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      21. public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
      22. }

      Positive Reactions
      1. Normally mapping of JSON to POJOs works with JAXB without creating an own messageBodyReader, because the message reader for JSON already exists.
      Other Reactions
      1. I think your approach is not the common way.
      2. See answer of VDev.

  10. formparam
      Chart will be rendered here
    1. PUT method with @FormParam

      Change the Consumes type for your resource to multipart/form-data. Then on your client side set Content-Type multipart/form-data Add form variables for login and password On a side note assuming this isn't for learning you will want to secure your login endpoint with SSL and hash the password before sending it across the wire. details

      Reactions - Positive 5, Negative 4, Others 0

      1. @PUT@Path("/login")@Produces({ "application/json", "text/plain" })@Consumes("multipart/form-data")public String login(@FormParam("login") String login, @FormParam("password") String password) { String response = null
      2. response = new UserManager().login(login, password)
      3. return response
      4. }

      Positive Reactions
      1. You can read [this StackOverflow answer]( URL_http://stackoverflow.com/a/2022938/680925) , which gives a nice summary of what to use when.
      2. But i read that "HTML forms are an easy means of getting information from a user and they are also easy to create.
      3. Something like:HttpPut httpPut new HttpPut(BASE_URI + "/services.users/login");Form f new Form(); f.add("login", "xxxxx"); f.add("password", "xxxxx"); ?
      4. I will try that!.
      5. Thanks, it's working!But I was initially asking how to enter those parameters in the TEST RESTful WEB SERVICES main page.
      Negative Reactions
      1. Sorry, another question about the @FormParam: they can be used with PUTs?
      2. Unfortunately, it doesn't seem like Netbeans could detect the invalid combination of annotations on your resource method.
      3. C:\Users\Ines\Documents\NetBeansProjects\LULServices\build\generated-sources \rest-test\test-resbeans.html.
      4. Is that a problem?
      Other Reactions
      1. That's why I was asking.
      2. ?
      3. let us [continue this discussion in chat]( URL_http://chat.stackoverflow.com/rooms/26660/discussion-between-perception - and-user2144555).
      4. I'm always doing PUTs instead of POSTs.
      5. Actually, each one of the HTTP verbs maps to a specific RESTful operation, and you should try to use them appropriately.
      6. I would guess that to be a Netbeans auto-generated test page for your web service.
      7. You should only do PUT's for operations that will be updating an entity.
      8. But I was thinking that " form variables for login and password** " were send in a different way.
      9. I was using Apache HttpClient too.
      10. It's their main page.
      11. Whats the link of the page you are talking about?
      12. Form data can be used for HTTP GET requests and HTTP POST requests."
      13. Yes, I'm always doing updates.
      14. Do you know what I'm talking about?
      15. @user2144555 - See edits for a viable way to call the server resource, using Apache HttpComponents.

    2. Posting JSON to RESTful through formParam with JAX-RS results in "Unsupported Media Type"

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.ws.rs.Consumes
      2. import javax.ws.rs.FormParam
      3. import javax.ws.rs.POST
      4. import javax.ws.rs.core.MediaType
      5. import org.codehaus.jettison.json.JSONObject
      6. ... @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String postData(@FormParam("textAreaName") JSONObject jsono){..

    3. Parsing String[] Request Parameter through REST with Apache CXF

      I apparently misunderstood how REST works. What I did to finally solve the problem was the following 1 Changed my web service signature 2 Now make sure that the client is sending a request with content-type application/x-www-form-urlencoded and that the client correctly adds form parameters same as those you defined in the FormParam annotations. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/getVersion")@Produces(MediaType.APPLICATION_JSON)@Consumes({"application/xml", "application/json", "application/x-www-form-urlencoded"})public ControllerVersion getVersion(@FormParam("deviceID") String deviceID,@FormParam("macAddresses") String macAddresses)

  11. formdatamultipart
      Chart will be rendered here
    1. 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. }

  12. complexobject
      Chart will be rendered here
    1. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    2. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

  13. jacksonjaxbjsonprovider
      Chart will be rendered here
    1. RESTeasy, JSON and null fields

      Use Jackson 2. Setup the following provider The Scala module is optional. details

      Reactions - Positive 1, Negative 2, Others 0

      1. package com.recruitinghop.swagger
      2. import com.fasterxml.jackson.annotation.JsonInclude
      3. import com.fasterxml.jackson.databind.DeserializationFeature
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. import com.fasterxml.jackson.databind.SerializationFeature
      6. import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider
      7. import com.fasterxml.jackson.module.scala.DefaultScalaModule
      8. import javax.ws.rs.Produces
      9. import javax.ws.rs.core.MediaType
      10. import javax.ws.rs.ext.Provider
      11. @Provider
      12. @Produces(MediaType.APPLICATION_JSON)
      13. public class JacksonJsonProvider extends JacksonJaxbJsonProvider {
      14. public JacksonJsonProvider() {
      15. ObjectMapper mapper = new ObjectMapper()
      16. mapper.registerModule(new DefaultScalaModule())
      17. mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
      18. mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
      19. mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      20. mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      21. super.setMapper(mapper)
      22. }
      23. }

      Positive Reactions
      1. i would like to using only JAXB(native for JBOSS AS 7) for best performance, avoiding others "jar".
      Negative Reactions
      1. Do a little background googling, signup instead of being anonymous and I'll answer to that.
      2. There are so many things wrong with what you just said.
      Other Reactions
      1. is there solution without Jackson ?

  14. providers
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

  15. providerpublic
      Chart will be rendered here
    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.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. }

    2. 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.

    3. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
      2. // import com.fasterxml.jackson.databind.ObjectMapper
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. import javax.ws.rs.ext.ContextResolver
      6. import javax.ws.rs.ext.Provider
      7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
      8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
      9. this.defaultObjectMapper = new ObjectMapper()
      10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
      11. // .enableDefaultTyping()
      12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
      13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
      14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
      15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
      16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
      17. return this.defaultObjectMapper
      18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

    4. MOXy compatible XML and JSON responses

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.ws.rs.ext.*
      2. import org.glassfish.jersey.moxy.json.MoxyJsonConfig
      3. @Providerpublic
      4. class MOXyJsonContextResolver implements ContextResolver<MoxyJsonConfig> {
      5. private final MoxyJsonConfig config
      6. public MOXyJsonContextResolver() {
      7. config = new MoxyJsonConfig().setIncludeRoot(true)
      8. }
      9. @Override
      10. public MoxyJsonConfig getContext(Class<?> objectType) {
      11. return config
      12. }
      13. }

    5. Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

      This is the solution for my old question I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature. And in the web.xml I registered my package into the servlet definition all the rest is transparently done by jersey/jackson. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.lig.hadas.services.mapper
      2. import javax.ws.rs.Produces
      3. import javax.ws.rs.core.MediaType
      4. import javax.ws.rs.ext.ContextResolver
      5. import org.codehaus.jackson.map.DeserializationConfig
      6. import org.codehaus.jackson.map.ObjectMapper
      7. @Produces(MediaType.APPLICATION_JSON)
      8. @Providerpublic
      9. class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
      10. ObjectMapper mapper
      11. public ObjectMapperProvider() {
      12. mapper = new ObjectMapper()
      13. mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
      14. }
      15. @Override
      16. public ObjectMapper getContext(Class<?> type) {
      17. return mapper
      18. }
      19. }

  16. messagebodywriter
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

    3. Jersey Exception : SEVERE: A message body reader for Java class

      You need to implement your own MessageBodyReader and MessageBodyWriter for your class Lorg.shoppingsite.model.entity.jpa.User. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package javax.ws.rs.ext
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.lang.annotation.Annotation
      5. import java.lang.reflect.Type
      6. import javax.ws.rs.WebApplicationException
      7. import javax.ws.rs.core.MediaType
      8. import javax.ws.rs.core.MultivaluedMap
      9. public interface MessageBodyReader<T extends Object> { public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      10. public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
      11. }package javax.ws.rs.ext
      12. import java.io.IOException
      13. import java.io.OutputStream
      14. import java.lang.annotation.Annotation
      15. import java.lang.reflect.Type
      16. import javax.ws.rs.WebApplicationException
      17. import javax.ws.rs.core.MediaType
      18. import javax.ws.rs.core.MultivaluedMap
      19. public interface MessageBodyWriter<T extends Object> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      20. public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      21. public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
      22. }

      Positive Reactions
      1. Normally mapping of JSON to POJOs works with JAXB without creating an own messageBodyReader, because the message reader for JSON already exists.
      Other Reactions
      1. I think your approach is not the common way.
      2. See answer of VDev.

  17. unmarshaller
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

  18. hashset
      Chart will be rendered here
    1. JSON deserialisation failing (HTTP 400) with Jersey / MOXy

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class MyApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(SubscriptionResource.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setIncludeRoot(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

    2. MOXy compatible XML and JSON responses

      You can change this by setting a configured instance on a JAX-RS Application class like the one below. For More Information MOXy as the Default JSON-Binding Provider in Jersey/GlassFish If you are using MOXy as the default JSON-binding provider with Jersey/GlassFish you can leverage the MoxyJsonConfig class as follows For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class FooApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(ExampleService.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setIncludeRoot(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

    3. REST. Jersey. How to programmatically choose what type to return: JSON or XML?

      I believe Jackson provides an implementation in its jar. Below is an example of an Application class that specifies MOXy as the JSON provider Or I need to create separately two classes for JSON and XML. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

    4. How an I get MOXy to just output on one line to save space

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      9. set.add(ExampleService.class)
      10. return set
      11. }
      12. @Override
      13. public Set<Object> getSingletons() {
      14. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      15. moxyJsonProvider.setFormattedOutput(true)
      16. }
      17. }

    5. Registering POJO Support or JSON Providers for JAX-RS programmatically

      Below is an example of registering EclipseLink-MOXy as the JSON provider. For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

    6. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      9. set.add(ExampleService.class)
      10. return set
      11. }
      12. @Override
      13. public Set<Object> getSingletons() {
      14. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      15. moxyJsonProvider.setAttributePrefix("@")
      16. moxyJsonProvider.setFormattedOutput(true)
      17. moxyJsonProvider.setIncludeRoot(true)
      18. moxyJsonProvider.setMarshalEmptyCollections(false)
      19. moxyJsonProvider.setValueWrapper("$")
      20. Map<String, String> namespacePrefixMapper = new HashMap<String, String>(1)
      21. namespacePrefixMapper.put("http://www.example.org/customer", "cust")
      22. moxyJsonProvider.setNamespacePrefixMapper(namespacePrefixMapper)
      23. moxyJsonProvider.setNamespaceSeparator(':')
      24. HashSet<Object> set = new HashSet<Object>(1)
      25. set.add(moxyJsonProvider)
      26. return set
      27. }
      28. }

    7. Jersey 2.0 equivalent to POJOMappingFeature

      You can configure EclipseLink-MOXy as the JSON-binding provider by configuring the MOXyJsonProvider class through a JAX-RS Application class. Example 1 Example 2 For More Information . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

      Positive Reactions
      1. So it is not possible to enable json support in 2.0 without having to write code?

    8. JAXB for lists to be returned naturally for JSON or XML

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class YourApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(YourService.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setWrapperAsArrayName(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

    9. How an I get MOXy to just output on one line to save space

      To get formatted output you need to set the following property on the Marshaller Root jaxb.properties Demo The following code demonstrates how to specify formatted output Output Below is the output from running the demo code JAX-RS The same behaviour holds for MOXyJsonProvider see . **One Line** By default when you include MOXyJsonProvider in your JAX-RS application the output will be marshalled on one line **Formatted Output** You can also configure MOXyJsonProvider to produce formatted output . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

      Positive Reactions
      1. Ah should have seen this I was looking at my initialcontext method rather than my marshaller initialization, disabled Marshaller.JAXB_FORMATTED_OUTPUT and it now works.

  19. system
      Chart will be rendered here
    1. 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. }

    2. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    3. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    4. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
      2. // import com.fasterxml.jackson.databind.ObjectMapper
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. import javax.ws.rs.ext.ContextResolver
      6. import javax.ws.rs.ext.Provider
      7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
      8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
      9. this.defaultObjectMapper = new ObjectMapper()
      10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
      11. // .enableDefaultTyping()
      12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
      13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
      14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
      15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
      16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
      17. return this.defaultObjectMapper
      18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

  20. jsonjaxbcontext
      Chart will be rendered here
    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.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. }

    2. 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.

  21. override
      Chart will be rendered here
    1. JSON deserialisation failing (HTTP 400) with Jersey / MOXy

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class MyApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(SubscriptionResource.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setIncludeRoot(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

    2. Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

      This is the solution for my old question I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature. And in the web.xml I registered my package into the servlet definition all the rest is transparently done by jersey/jackson. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.lig.hadas.services.mapper
      2. import javax.ws.rs.Produces
      3. import javax.ws.rs.core.MediaType
      4. import javax.ws.rs.ext.ContextResolver
      5. import org.codehaus.jackson.map.DeserializationConfig
      6. import org.codehaus.jackson.map.ObjectMapper
      7. @Produces(MediaType.APPLICATION_JSON)
      8. @Providerpublic
      9. class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
      10. ObjectMapper mapper
      11. public ObjectMapperProvider() {
      12. mapper = new ObjectMapper()
      13. mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
      14. }
      15. @Override
      16. public ObjectMapper getContext(Class<?> type) {
      17. return mapper
      18. }
      19. }

    3. MOXy compatible XML and JSON responses

      You can change this by setting a configured instance on a JAX-RS Application class like the one below. For More Information MOXy as the Default JSON-Binding Provider in Jersey/GlassFish If you are using MOXy as the default JSON-binding provider with Jersey/GlassFish you can leverage the MoxyJsonConfig class as follows For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class FooApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(ExampleService.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setIncludeRoot(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

    4. MOXy compatible XML and JSON responses

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.ws.rs.ext.*
      2. import org.glassfish.jersey.moxy.json.MoxyJsonConfig
      3. @Providerpublic
      4. class MOXyJsonContextResolver implements ContextResolver<MoxyJsonConfig> {
      5. private final MoxyJsonConfig config
      6. public MOXyJsonContextResolver() {
      7. config = new MoxyJsonConfig().setIncludeRoot(true)
      8. }
      9. @Override
      10. public MoxyJsonConfig getContext(Class<?> objectType) {
      11. return config
      12. }
      13. }

    5. How do I register the Jackson provider with the Wink client?

      Step 1 Create a class that extends javax.ws.rs.core.Application that allows you to set singletons. Step 2 In your action create a org.apache.wink.client.ClientConfig for your org.apache.wink.client.RestClient. details

      Reactions - Positive 0, Negative 1, Others 0

      1. import java.util.Collections
      2. import java.util.Set
      3. import javax.ws.rs.core.Application
      4. public class ClientApplication extends Application {
      5. private Set<Object> singletons = Collections.emptySet()
      6. @Override
      7. public Set<Object> getSingletons() {
      8. return singletons
      9. }
      10. public void setSingletons(final Set<Object> singletons) {
      11. this.singletons = singletons
      12. }
      13. }

      Negative Reactions
      1. My classes have jaxb annotations and the system application provider seems to interfere with the jackson json provider.
      Other Reactions
      1. This didn't work for me.
      2. The solution was to call setLoadWinkApplications(false) on the ClientConfig before setting the applications.

    6. REST. Jersey. How to programmatically choose what type to return: JSON or XML?

      I believe Jackson provides an implementation in its jar. Below is an example of an Application class that specifies MOXy as the JSON provider Or I need to create separately two classes for JSON and XML. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

    7. How an I get MOXy to just output on one line to save space

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      9. set.add(ExampleService.class)
      10. return set
      11. }
      12. @Override
      13. public Set<Object> getSingletons() {
      14. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      15. moxyJsonProvider.setFormattedOutput(true)
      16. }
      17. }

    8. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
      2. // import com.fasterxml.jackson.databind.ObjectMapper
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. import javax.ws.rs.ext.ContextResolver
      6. import javax.ws.rs.ext.Provider
      7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
      8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
      9. this.defaultObjectMapper = new ObjectMapper()
      10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
      11. // .enableDefaultTyping()
      12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
      13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
      14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
      15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
      16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
      17. return this.defaultObjectMapper
      18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

    9. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      9. set.add(ExampleService.class)
      10. return set
      11. }
      12. @Override
      13. public Set<Object> getSingletons() {
      14. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      15. moxyJsonProvider.setAttributePrefix("@")
      16. moxyJsonProvider.setFormattedOutput(true)
      17. moxyJsonProvider.setIncludeRoot(true)
      18. moxyJsonProvider.setMarshalEmptyCollections(false)
      19. moxyJsonProvider.setValueWrapper("$")
      20. Map<String, String> namespacePrefixMapper = new HashMap<String, String>(1)
      21. namespacePrefixMapper.put("http://www.example.org/customer", "cust")
      22. moxyJsonProvider.setNamespacePrefixMapper(namespacePrefixMapper)
      23. moxyJsonProvider.setNamespaceSeparator(':')
      24. HashSet<Object> set = new HashSet<Object>(1)
      25. set.add(moxyJsonProvider)
      26. return set
      27. }
      28. }

    10. Jersey 2.0 equivalent to POJOMappingFeature

      You can configure EclipseLink-MOXy as the JSON-binding provider by configuring the MOXyJsonProvider class through a JAX-RS Application class. Example 1 Example 2 For More Information . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

      Positive Reactions
      1. So it is not possible to enable json support in 2.0 without having to write code?

    11. JAXB for lists to be returned naturally for JSON or XML

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class YourApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(YourService.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setWrapperAsArrayName(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

    12. How an I get MOXy to just output on one line to save space

      To get formatted output you need to set the following property on the Marshaller Root jaxb.properties Demo The following code demonstrates how to specify formatted output Output Below is the output from running the demo code JAX-RS The same behaviour holds for MOXyJsonProvider see . **One Line** By default when you include MOXyJsonProvider in your JAX-RS application the output will be marshalled on one line **Formatted Output** You can also configure MOXyJsonProvider to produce formatted output . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

      Positive Reactions
      1. Ah should have seen this I was looking at my initialcontext method rather than my marshaller initialization, disabled Marshaller.JAXB_FORMATTED_OUTPUT and it now works.

    13. Registering POJO Support or JSON Providers for JAX-RS programmatically

      Below is an example of registering EclipseLink-MOXy as the JSON provider. For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(2)
      9. set.add(MOXyJsonProvider.class)
      10. set.add(CustomerService.class)
      11. return set
      12. }
      13. }

  22. annotation
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

    3. Jersey Exception : SEVERE: A message body reader for Java class

      You need to implement your own MessageBodyReader and MessageBodyWriter for your class Lorg.shoppingsite.model.entity.jpa.User. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package javax.ws.rs.ext
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.lang.annotation.Annotation
      5. import java.lang.reflect.Type
      6. import javax.ws.rs.WebApplicationException
      7. import javax.ws.rs.core.MediaType
      8. import javax.ws.rs.core.MultivaluedMap
      9. public interface MessageBodyReader<T extends Object> { public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      10. public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
      11. }package javax.ws.rs.ext
      12. import java.io.IOException
      13. import java.io.OutputStream
      14. import java.lang.annotation.Annotation
      15. import java.lang.reflect.Type
      16. import javax.ws.rs.WebApplicationException
      17. import javax.ws.rs.core.MediaType
      18. import javax.ws.rs.core.MultivaluedMap
      19. public interface MessageBodyWriter<T extends Object> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      20. public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      21. public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
      22. }

      Positive Reactions
      1. Normally mapping of JSON to POJOs works with JAXB without creating an own messageBodyReader, because the message reader for JSON already exists.
      Other Reactions
      1. I think your approach is not the common way.
      2. See answer of VDev.

  23. streamsource
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

  24. deserializationconfig
      Chart will be rendered here
    1. Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

      This is the solution for my old question I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature. And in the web.xml I registered my package into the servlet definition all the rest is transparently done by jersey/jackson. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.lig.hadas.services.mapper
      2. import javax.ws.rs.Produces
      3. import javax.ws.rs.core.MediaType
      4. import javax.ws.rs.ext.ContextResolver
      5. import org.codehaus.jackson.map.DeserializationConfig
      6. import org.codehaus.jackson.map.ObjectMapper
      7. @Produces(MediaType.APPLICATION_JSON)
      8. @Providerpublic
      9. class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
      10. ObjectMapper mapper
      11. public ObjectMapperProvider() {
      12. mapper = new ObjectMapper()
      13. mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
      14. }
      15. @Override
      16. public ObjectMapper getContext(Class<?> type) {
      17. return mapper
      18. }
      19. }

  25. clientconfig
      Chart will be rendered here
    1. Java consume JSON list from Rest service GET

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. ClientConfig clientConfig = new DefaultClientConfig()
      2. clientConfig.getClasses().add(JacksonJsonProvider.class)
      3. Client client = Client.create(clientConfig)
      4. return client .resource(Constants.BASE_URL) .path(Constants.CATEGORIES_ANIMALS) .type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .cookie(cookie) .get(new GenericType<List<AnimalCategoryResponse>>(){})

  26. pathparam
      Chart will be rendered here
    1. Jersey POST Method is receiving null values as parameters

      Now as to the specifics of your case one thing I notice in your code is that you don't actually define any path parameters. Remember that they have to be defined as part of your Path annotation before being consumed in your REST method With the above changes your parameters should no longer show up as being null assuming you have properly encoded the URL on the client side. details

      Reactions - Positive 8, Negative 3, Others 0

      1. @Path("/method/{obj1}/{obj2}")public ResponseObject method(@Context Request request, @PathParam("obj1") Object obj1, @PathParam("obj2") String obj2) {}

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

    2. REST/JSON Web Services Java EE Framework

      For an example check out my blog Part-1---The-Database Part-2---JPA-Entities Part-3---JAXB-Bindings Part-4---The-RESTFul-Service Part-5---The-Client The example demonstrates XML messages. If you only want JSON messages change the MediaType To support both JSON and XML messages do the following . details

      Reactions - Positive 5, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

      Positive Reactions
      1. Thanks!
      2. Nice!
      3. your blog is useful!.
      4. @BlaiseDoughan your blog has awesome examples with good explanation.
      5. @rich: Good catch :).
      Other Reactions
      1. Although I assume the second example should have one MediaType for JSON and one for XML?
      2. @rich: I have updated my answer to contain info on how to update my example to work with JSON.
      3. This example seems to be for XML, not JSON?

    3. REST/JSON Web Services Java EE Framework

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces(MediaType.APPLICATION_JSON)@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

    4. WebService return a XML/JSON file

      an example using Spring 3 . You could do something like the following with JAX-RS Full Example Part-1---The-Database Part-2---Mapping-the-Database-to-JPA-Entities Part-3---Mapping-JPA-entities-to-XML-(using-JAXB) Part-4---The-RESTful-Service Part-5---The-Client . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import javax.ejb.*
      3. import javax.persistence.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.MediaType
      6. @Stateless
      7. @LocalBean
      8. @Path("/customers")
      9. public class CustomerService {
      10. @PersistenceContext(unitName = "CustomerService", type = PersistenceContextType.TRANSACTION)
      11. EntityManager entityManager
      12. @GET
      13. @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
      14. @Path("{id}")
      15. public Customer read(@PathParam("id") long id) {
      16. return entityManager.find(Customer.class, id)
      17. }
      18. }

    5. Dynamic JSON passing to REST Web service and using it to insert data into mysql db

      if passing a json paramter is your problem then u can try using the path parameter. but i would recommend you to use post method which would make it simple but you should consider if it is an idempotent operation before u decide to use post. details

      Reactions - Positive 4, Negative 1, Others 0

      1. @GET @Path("{jsonString}") @Produces(MediaType.APPLICATION_JSON) public void getStock(@PathParam("jsonString") String jsonString) { String stackJsonString = jsonString

      Positive Reactions
      1. Thanks a lot for the info.
      2. If you have any insight then it would be great.
      3. crul -X POST -H'Conten- Type:application/json'-d{"stockName":"GOOG"} URL_http://localhost:8080/stock .
      4. Thanks a lot for all your time.
      Negative Reactions
      1. I know how to parse a hard-coded JSON string.
      Other Reactions
      1. URL_http://stackoverflow.com/questions/7172784/how-to-post-json - data-with-curl-from-terminal-commandline-to-test-spring-rest.
      2. does this help?
      3. However,i want to pass the curl command as i just wrote it.
      4. e.g.
      5. However, I dont know how to pass a JSON using a curl command(POST) and use that JSON to populate a db.
      6. Currently I am populating the db using a hrd-coded JSON string as shown above in my original question.

    6. Returning the JSON representation of a String with Jersey

      is it better to create a DTO for every operation or to create a DTO for each type I want to use. You can also return it as but it's look very strange for me. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Path("hello/{name}")@Produces( MediaType.APPLICATION_JSON)public String hello(@PathParam("name") String name) { return "\"Hello " + name + ", it is " + new Date()+'"'
      2. }

    7. Jersey POST Method is receiving null values as parameters

      As a general rule you should restrict your path parameters to simple values like identifiers or resource endpoints more complex data should be passed to the REST service via request parameters or the request body itself. Here's a mixed approach that passes an entity identifier as a path parameter and the entity data in the request body In the above example the contactId is obtained as a path parameter and the contact is serialized automatically from the request body. details

      Reactions - Positive 8, Negative 3, Others 0

      1. @Path("/contacts/{id}")@PUT@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)public Response updateContact(@PathParam final String contactId, Contact contact) {}

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

    8. Jersey POST Method is receiving null values as parameters

      **Example** Given the URL I can define From which I can inject a . This works for any kind of HTTP request GET POST PUT DELETE_). details

      Reactions - Positive 8, Negative 3, Others 0

      1. public Response getContact(@PathParam("id") final String identifier)

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

    9. REST. Jersey. How to programmatically choose what type to return: JSON or XML?

      Server Side You can specify that your service offers both XML and JSON messages using the Produces annotation. **For More Information** Client Side You can use the MediaType to indicate the type of message. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

    10. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    11. 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. @GET @Path("/{id}/search") @Produces(JSON) public ListWrapper search(@PathParam("id") Integer projectId ) { return DatabaseManager.search(projectId)
      2. }

    12. Why writer for media type application/json missing

      I don't know whether resteasy 1.1 containts jettison provider but version 1.2 does.Also if you are using jdk 1.6 you must exclude javax.xml.stream:stax-api jar file otherwise you will have a problem. Here is the example and JAXB class That's all have a nice day. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.ws.rs.GET
      2. import javax.ws.rs.Path
      3. import javax.ws.rs.PathParam
      4. import javax.ws.rs.Produces
      5. @Path("/account")
      6. public class AccountService {
      7. @GET
      8. @Path("/{accountNo}")
      9. @Produces("application/json")
      10. public Account getAccount(@PathParam("accountNo") String accountNo) {
      11. return new Account(accountNo)
      12. }
      13. }

    13. REST Web Service: Server responding with a JAX-B error to GET

      When using a PathParam annotation you need to add the Path annotation to the method declaration. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Path("/{test}")@Produces("application/json")public String getJson(@PathParam("test") String test) { return test
      2. }

    14. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    15. Jersey POST Method is receiving null values as parameters

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @PathParam("id")

    16. what's the correct way to send a file from REST web service to client?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Path("/{key}")public Response download(@PathParam("key") String key, @Context HttpServletResponse response) throws IOException { try { //Get your File or Object from wherever you want... //you can use the key parameter to indentify your file //otherwise it can be removed //let's say your file is called "object" response.setContentLength((int) object.getContentLength())
      2. response.setHeader("Content-Disposition", "attachment
      3. filename=" + object.getName())
      4. ServletOutputStream outStream = response.getOutputStream()
      5. byte[] bbuf = new byte[(int) object.getContentLength() + 1024]
      6. DataInputStream in = new DataInputStream( object.getDataInputStream())
      7. int length = 0
      8. while ((in != null) && ((length = in.read(bbuf)) != -1)) { outStream.write(bbuf, 0, length)
      9. } in.close()
      10. outStream.flush()
      11. } catch (S3ServiceException e) { e.printStackTrace()
      12. } catch (ServiceException e) { e.printStackTrace()
      13. } return Response.ok().build()
      14. }

  27. jsonobject
      Chart will be rendered here
    1. Posting JSON to RESTful through formParam with JAX-RS results in "Unsupported Media Type"

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.ws.rs.Consumes
      2. import javax.ws.rs.FormParam
      3. import javax.ws.rs.POST
      4. import javax.ws.rs.core.MediaType
      5. import org.codehaus.jettison.json.JSONObject
      6. ... @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String postData(@FormParam("textAreaName") JSONObject jsono){..

  28. mediatype
      Chart will be rendered here
    1. Can not convert attribut "type" in xml string to json string by Restlet StringRepresentation class

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. XMLSerializer serializer = new XMLSerializer()
      2. serializer.setTypeHintsEnabled(false)
      3. result = new StringRepresentation(serializer.read(xml).toString(), MediaType.APPLICATION_JSON, Language.ALL, CharacterSet.UTF_8)

    2. JSON Formatting with Jersey, Jackson, & json.org/java Parser using Curl Command

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class MyWebService { @GET @Produces(MediaType.APPLICATION_JSON) public Family getFamily() return FamilyUtil.getFamily() }}

    3. Why writer for media type application/json missing

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)

    4. Spring 3.0 making JSON response using jackson message converter

      This worked for me Note that the method doesn't return anything does the magic. The MessageConverter interface defines a getSupportedMediaTypes method which in case of the MappingJacksonMessageCoverter returns application/json I assume a Accept application/json request header is missing. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public MappingJacksonHttpMessageConverter() { super(new MediaType("application", "json", DEFAULT_CHARSET))
      2. }

    5. Returning the JSON representation of a String with Jersey

      is it better to create a DTO for every operation or to create a DTO for each type I want to use. You can also return it as but it's look very strange for me. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Path("hello/{name}")@Produces( MediaType.APPLICATION_JSON)public String hello(@PathParam("name") String name) { return "\"Hello " + name + ", it is " + new Date()+'"'
      2. }

    6. Jersey Exception : SEVERE: A message body reader for Java class

      You need to implement your own MessageBodyReader and MessageBodyWriter for your class Lorg.shoppingsite.model.entity.jpa.User. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package javax.ws.rs.ext
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.lang.annotation.Annotation
      5. import java.lang.reflect.Type
      6. import javax.ws.rs.WebApplicationException
      7. import javax.ws.rs.core.MediaType
      8. import javax.ws.rs.core.MultivaluedMap
      9. public interface MessageBodyReader<T extends Object> { public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      10. public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
      11. }package javax.ws.rs.ext
      12. import java.io.IOException
      13. import java.io.OutputStream
      14. import java.lang.annotation.Annotation
      15. import java.lang.reflect.Type
      16. import javax.ws.rs.WebApplicationException
      17. import javax.ws.rs.core.MediaType
      18. import javax.ws.rs.core.MultivaluedMap
      19. public interface MessageBodyWriter<T extends Object> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      20. public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      21. public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
      22. }

      Positive Reactions
      1. Normally mapping of JSON to POJOs works with JAXB without creating an own messageBodyReader, because the message reader for JSON already exists.
      Other Reactions
      1. I think your approach is not the common way.
      2. See answer of VDev.

    7. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    8. Getting JSON out put from restful java client

      None details

      Reactions - Positive 0, Negative 0, Others 0

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

    9. RESTeasy, JSON and null fields

      Use Jackson 2. Setup the following provider The Scala module is optional. details

      Reactions - Positive 1, Negative 2, Others 0

      1. package com.recruitinghop.swagger
      2. import com.fasterxml.jackson.annotation.JsonInclude
      3. import com.fasterxml.jackson.databind.DeserializationFeature
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. import com.fasterxml.jackson.databind.SerializationFeature
      6. import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider
      7. import com.fasterxml.jackson.module.scala.DefaultScalaModule
      8. import javax.ws.rs.Produces
      9. import javax.ws.rs.core.MediaType
      10. import javax.ws.rs.ext.Provider
      11. @Provider
      12. @Produces(MediaType.APPLICATION_JSON)
      13. public class JacksonJsonProvider extends JacksonJaxbJsonProvider {
      14. public JacksonJsonProvider() {
      15. ObjectMapper mapper = new ObjectMapper()
      16. mapper.registerModule(new DefaultScalaModule())
      17. mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
      18. mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
      19. mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      20. mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      21. super.setMapper(mapper)
      22. }
      23. }

      Positive Reactions
      1. i would like to using only JAXB(native for JBOSS AS 7) for best performance, avoiding others "jar".
      Negative Reactions
      1. Do a little background googling, signup instead of being anonymous and I'll answer to that.
      2. There are so many things wrong with what you just said.
      Other Reactions
      1. is there solution without Jackson ?

    10. Parsing String[] Request Parameter through REST with Apache CXF

      What do you think I should do. You're using . details

      Reactions - Positive 1, Negative 1, Others 0

      1. @Consumes(MediaType.APPLICATION_JSON)

      Positive Reactions
      1. Please check the "update" section in my original question.
      Negative Reactions
      1. I tried to add Jackson, but I'm ending up with another exception now.

    11. 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 .

    12. Posting JSON to RESTful through formParam with JAX-RS results in "Unsupported Media Type"

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.ws.rs.Consumes
      2. import javax.ws.rs.FormParam
      3. import javax.ws.rs.POST
      4. import javax.ws.rs.core.MediaType
      5. import org.codehaus.jettison.json.JSONObject
      6. ... @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String postData(@FormParam("textAreaName") JSONObject jsono){..

    13. REST/JSON Web Services Java EE Framework

      For an example check out my blog Part-1---The-Database Part-2---JPA-Entities Part-3---JAXB-Bindings Part-4---The-RESTFul-Service Part-5---The-Client The example demonstrates XML messages. If you only want JSON messages change the MediaType To support both JSON and XML messages do the following . details

      Reactions - Positive 5, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

      Positive Reactions
      1. Thanks!
      2. Nice!
      3. your blog is useful!.
      4. @BlaiseDoughan your blog has awesome examples with good explanation.
      5. @rich: Good catch :).
      Other Reactions
      1. Although I assume the second example should have one MediaType for JSON and one for XML?
      2. @rich: I have updated my answer to contain info on how to update my example to work with JSON.
      3. This example seems to be for XML, not JSON?

    14. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    15. Why JacksonJsonProvider ignores MediaType's parameters?

      if you have and you would like to add a different implementation of the same endpoint you would add a new piece to the path Where version is whatever version of the api you're choosing. Atlassian's JIRA API does things in this way Also using the built-in constants for media types is good form . details

      Reactions - Positive 1, Negative 1, Others 0

      1. @GET @Path("/rest/api/2/issue") @Produces(MediaType.APPLICATION_JSON)

      Positive Reactions
      1. Hi, thanks for your comment.
      Negative Reactions
      1. I watched [REST+JSON API Design - Best Practices for Developers]( URL_http://www.youtube.com/watch?feature=player_detailpage&v=hdSrT 4yjS1g#t=1947) by Stormpath and they suggest to use the header's metadata to distinguish between the API Versions.I never thought this approach would be so hard to realize...
      Other Reactions
      1. Creating a new endpoint is ok but in my opinion hiding the information what API version to use in the HTTP header as metadata is a neat solution.

    16. How do I POST a Pojo with Jersey Client without manually convert to JSON?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(searchQuery, MediaType.APPLICATION_JSON)
      2. ListWrapper listWrapper = response.getEntity(ListWrapper.class)

    17. Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

      This is the solution for my old question I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature. And in the web.xml I registered my package into the servlet definition all the rest is transparently done by jersey/jackson. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.lig.hadas.services.mapper
      2. import javax.ws.rs.Produces
      3. import javax.ws.rs.core.MediaType
      4. import javax.ws.rs.ext.ContextResolver
      5. import org.codehaus.jackson.map.DeserializationConfig
      6. import org.codehaus.jackson.map.ObjectMapper
      7. @Produces(MediaType.APPLICATION_JSON)
      8. @Providerpublic
      9. class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
      10. ObjectMapper mapper
      11. public ObjectMapperProvider() {
      12. mapper = new ObjectMapper()
      13. mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
      14. }
      15. @Override
      16. public ObjectMapper getContext(Class<?> type) {
      17. return mapper
      18. }
      19. }

    18. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    19. Jersey/JAXB: Use same POJO for HTTP POST and GET, but return only a subset of the properties for GET in JSON response.

      You may even be able to implement this in your retrieveUserFromDB method to avoid the copy step. For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getUser(String Id) { // Pseudo-code for retrieving user User userFromDB = retrieveUserFromDB(user)
      2. User user = new User()
      3. user.setUserName(userFromDB.getUserName())
      4. user.setUserEmail(userFromDB.getUserEmail())
      5. Response.status(200).entity(user)
      6. }

    20. Java consume JSON list from Rest service GET

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. ClientConfig clientConfig = new DefaultClientConfig()
      2. clientConfig.getClasses().add(JacksonJsonProvider.class)
      3. Client client = Client.create(clientConfig)
      4. return client .resource(Constants.BASE_URL) .path(Constants.CATEGORIES_ANIMALS) .type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .cookie(cookie) .get(new GenericType<List<AnimalCategoryResponse>>(){})

    21. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.inject.Singleton
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.Produces
      5. import javax.ws.rs.core.MediaType
      6. import javax.ws.rs.core.Response
      7. @Singleton
      8. @Path("test/")
      9. public
      10. class MyResource { // public Thing[] state = {new Thing("asdf"), new Thing("foo"), new Thing("bar")}
      11. public String[] state = {"asdf", "foo", "bar"}
      12. @GET
      13. @Produces(MediaType.APPLICATION_JSON)
      14. public Response test() {
      15. return Response.ok(state).build()
      16. }
      17. }

    22. REST/JSON Web Services Java EE Framework

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces(MediaType.APPLICATION_JSON)@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

    23. WebService return a XML/JSON file

      an example using Spring 3 . You could do something like the following with JAX-RS Full Example Part-1---The-Database Part-2---Mapping-the-Database-to-JPA-Entities Part-3---Mapping-JPA-entities-to-XML-(using-JAXB) Part-4---The-RESTful-Service Part-5---The-Client . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import javax.ejb.*
      3. import javax.persistence.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.MediaType
      6. @Stateless
      7. @LocalBean
      8. @Path("/customers")
      9. public class CustomerService {
      10. @PersistenceContext(unitName = "CustomerService", type = PersistenceContextType.TRANSACTION)
      11. EntityManager entityManager
      12. @GET
      13. @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
      14. @Path("{id}")
      15. public Customer read(@PathParam("id") long id) {
      16. return entityManager.find(Customer.class, id)
      17. }
      18. }

    24. Jersey POST Method is receiving null values as parameters

      As a general rule you should restrict your path parameters to simple values like identifiers or resource endpoints more complex data should be passed to the REST service via request parameters or the request body itself. Here's a mixed approach that passes an entity identifier as a path parameter and the entity data in the request body In the above example the contactId is obtained as a path parameter and the contact is serialized automatically from the request body. details

      Reactions - Positive 8, Negative 3, Others 0

      1. @Path("/contacts/{id}")@PUT@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)public Response updateContact(@PathParam final String contactId, Contact contact) {}

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

    25. Spring 3.2 Test, com.jajway not included as dependency

      You should never need to add them manually to the classpath. In my case Having test code what contained jsonPath usage I was getting and This error was directly caused by lack of such dependencies . details

      Reactions - Positive 0, Negative 0, Others 0

      1. mockMvc.perform(get("/api/userDetails").header("Authorization", base64ForTestUser).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(print()) .andExpect(jsonPath("userName").value("testUser"))

    26. Dynamic JSON passing to REST Web service and using it to insert data into mysql db

      if passing a json paramter is your problem then u can try using the path parameter. but i would recommend you to use post method which would make it simple but you should consider if it is an idempotent operation before u decide to use post. details

      Reactions - Positive 4, Negative 1, Others 0

      1. @GET @Path("{jsonString}") @Produces(MediaType.APPLICATION_JSON) public void getStock(@PathParam("jsonString") String jsonString) { String stackJsonString = jsonString

      Positive Reactions
      1. Thanks a lot for the info.
      2. If you have any insight then it would be great.
      3. crul -X POST -H'Conten- Type:application/json'-d{"stockName":"GOOG"} URL_http://localhost:8080/stock .
      4. Thanks a lot for all your time.
      Negative Reactions
      1. I know how to parse a hard-coded JSON string.
      Other Reactions
      1. URL_http://stackoverflow.com/questions/7172784/how-to-post-json - data-with-curl-from-terminal-commandline-to-test-spring-rest.
      2. does this help?
      3. However,i want to pass the curl command as i just wrote it.
      4. e.g.
      5. However, I dont know how to pass a JSON using a curl command(POST) and use that JSON to populate a db.
      6. Currently I am populating the db using a hrd-coded JSON string as shown above in my original question.

    27. what's the correct way to send a file from REST web service to client?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces(MediaType.APPLICATION_OCTECT_STREAM)public Response getFile() { File file = ... // Initialize this to the File path you want to serve. return Response.ok(file, MediaType.APPLICATION_OCTECT_STREAM).build()
      2. }

    28. 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. }

    29. Please advise the best pattern for serialising JAXB Lists

      Everybody must try what and how platforms serve. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})public List<Item> read() { final List<Item> items = ... // is the variable name relevant return items
      2. }

    30. Jersey JSON and Date

      Your server code are right. The error is in your client code should be . details

      Reactions - Positive 2, Negative 2, Others 0

      1. resp = r.entity(entity, MediaType.APPLICATION_JSON).post(ClientResponse.class)

      Positive Reactions
      1. I test your code in my environment again, It works well.
      2. Thank you secondflying**.
      Negative Reactions
      1. Sorry for my not careful test.
      2. In updateUser method, the user argument is right.
      Other Reactions
      1. Thanks a lot.Unfortunately, it's not worked for me.What the difference on these methods?After looking API documentation I decided that there are no differences in these two methods.
      2. Can you post your web.xml?

    31. Jersey JSON and Date

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. resp = r.type(MediaType.APPLICATION_JSON).post(ClientResponse.class,entity)

    32. Passing a DataTable object from JavaScript to Java

      Instead from Java you use the JsonRenderer class api/browse_thread/thread/9098bb0dbe7b9157/153a80b5b22bda3a?pli=1 see-this Google-Groups-email to convert it to a Json-like string that's missing quotes around attributes for modest compression. That string can be parsed in Javascript by surrounding with parentheses not shown in the object literal notation in the examples ad/fe353c56343c552d/9fd6bda579c6ff83?lnk=gst&q=DataTable%20json%20java%20javas cript#9fd6bda579c6ff83 see-this-Google-Group-forum I don't see a method for going the reverse way to the Java Datasource Library DataTable object. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/hello/") @GET @Produces(MediaType.TEXT_PLAIN) public String getDataTable() { DataTable data = new DataTable()
      2. CharSequence charSequence = JsonRenderer.renderDataTable(dataTable, true, true)
      3. return charSequence.toString()
      4. }

    33. Passing a DataTable object from JavaScript to Java

      Am not sure if it can be done the other direction. However the Java DataTable object returned by default serialization is not the same thing as the Google Visualization API javascript DataTable. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @WebService@Path("/tables")public class DataManager extends GenericManager<db, Long> { @Path("/hello/") @GET @Produces(MediaType.APPLICATION_JSON) public DataTable getDataTable() { DataTable data = new DataTable()
      2. ... populate object ... return data
      3. }

    34. How to add a parameter at the end of a restFul service URL?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON } )public String doGet(@QueryParam("format") String fmt) {//...}

    35. How do I POST a Pojo with Jersey Client without manually convert to JSON?

      That transition is easily obscured when all the requests are chained together. Here's the same example using chaining. details

      Reactions - Positive 1, Negative 0, Others 0

      1. public void sendExample(Example example) { WebResource webResource = this.client.resource(this.url)
      2. Builder builder = webResource.type(MediaType.APPLICATION_JSON)
      3. builder.accept(MediaType.APPLICATION_JSON)
      4. builder.post(Example.class, example)
      5. return
      6. }

      Positive Reactions
      1. Thanks, that also worked like charm!.

    36. Jersey, how to POST a list of JSON objects?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/some-path")@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)public String createBatch(Example example){ ... }

    37. Jersey object mapping

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public void test() { Client client = Client.create()
      2. WebResource scResource = client.resource("http://localhost:8080/services/testDifferentClass")
      3. ClassB result = scResource.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML).get(ClassB.class)
      4. System.out.println(result.getOne())
      5. System.out.println(result.getTwo())
      6. }

    38. Please advise the best pattern for serialising JAXB Lists

      This could be an another proper way I think. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})public Response readItems() { final List<Item> items = ...
      2. return Response.ok(new GenericEntity<List<String>>(list) {}).build()
      3. }

    39. How to add Content-Length to JAXRS

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String str = OBJECT_MAPPER.writeValueAsString(myObject)
      2. return Response.ok(str , MediaType.APPLICATION_JSON).header(HttpHeaders.CONTENT_LENGTH), str.getBytes("UTF-8").length)).build()

    40. Jersey object mapping

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/testDifferentClass")
      2. public class TestServlet {
      3. @GET
      4. @Produces(MediaType.APPLICATION_XML)
      5. @Consumes(MediaType.APPLICATION_XML)
      6. public ClassA getClassA() {
      7. ClassA classA = new ClassA()
      8. classA.setOne("Hello")
      9. classA.setTwo(new Date())
      10. classA.setThree(1)
      11. return classA
      12. }
      13. }

    41. Custom response header Jersey/Java

      Just inject a Context HttpServletResponse response as a method argument. Change the headers on that . details

      Reactions - Positive 3, Negative 0, Others 0

      1. @Produces(MediaType.APPLICATION_JSON)public UserClass getValues(@Context HttpHeaders header, @Context HttpServletResponse response) { response.setHeader("yourheadername", "yourheadervalue")
      2. ...}

      Positive Reactions
      1. :-) you rock!.
      2. Thanks a lot @sotirios.
      3. @Namenoobie You're welcome, good luck!.
      Other Reactions
      1. Yes, your Tomcat installation includes those libraries.
      2. That's where you typically get them from.
      3. @Namenoobie You need the server runtime library.
      4. Does it require me to add additional libraries?
      5. This is basically the servlet api.
      6. If you're on Eclipse, go to your project java buildpath and add library.
      7. When I follow the instruction, I get the Tomcat server which already exists on my local machine.
      8. it says unidentified class "HttpServletResponse".

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

      By default the server seems to produces a content-type text/plain. Careful you're negotiating a JSON content-type but you don't pass it to the call First you define the path then Jersey gives you a builder to add content type negotiation headers query parameters etc. details

      Reactions - Positive 6, Negative 2, Others 0

      1. WebResource resource = client.resource(url)
      2. Builder builder = resource.accept(MediaType.APPLICATION_JSON)
      3. GenericType<List<EMailInformations>> genericType = new GenericType<List<EMailInformations>>() {}
      4. List<EMailInformations> response = builder.get(genericType)

      Positive Reactions
      1. Maybe it does not show a good content-type.
      2. A working sample online is even better ;).
      3. Try it, maybe this time it will work well (and Jersey works either with XML and JSON).
      4. Please, give me the HTTP trace (Web Browser can print those, if you don't know how, ask).
      5. Thnx for your responses :) Never minde it's Zimbra ...
      6. The browser is working fine, but not when I want to transform the response using Jersey from json to pojo.
      Negative Reactions
      1. Yes, I get it but the problem is to convert it, this is the title of the topic : Error when trying to convert JSON to POJO using Jersey.
      2. That this services produces JSON by default.
      Other Reactions
      1. And what is the response displayed in your browser?
      2. Seems strange.
      3. Even there SOAP API is ...
      4. Thnx for your answer, but alway got the same error...
      5. They do not ask for JSON.
      6. So you get JSON in the browser?
      7. Getting JSON in the browser means that there is no content-type text/html or application/xml produces by the service.
      8. Yes, but the content is really big, and I need to optimize ... so json is smaller thant xml...
      9. Modern browsers use Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 as you can see.
      10. Maybe the services you ask got specific content-type.
      11. I changed the question, there is a Firebug trace there.
      12. It seems that Zimbra also have an XML content-type (the url call is different).

    43. REST. Jersey. How to programmatically choose what type to return: JSON or XML?

      Server Side You can specify that your service offers both XML and JSON messages using the Produces annotation. **For More Information** Client Side You can use the MediaType to indicate the type of message. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})@Path("{id}")public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id)
      2. }

    44. REST. Jersey. How to programmatically choose what type to return: JSON or XML?

      If you're picky about URLs like I am you could use a file extension resources/todo.json or resources/todo.xml. No need for seperate classes what you need is seperate methods Then in the client side when you request for the service you indicate in what format you want it . details

      Reactions - Positive 2, Negative 2, Others 0

      1. @GET@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })public Todo getXML() { Todo todo = new Todo()
      2. todo.setSummary("This is my first todo")
      3. todo.setDescription("This is my first todo")
      4. return todo
      5. }

      Positive Reactions
      1. ok ok:) I understand it) But what if I want to return neccesary type depending on some other facts (not on client's accept header)?
      2. thanks, so I understand I need to sent accept header from client to get what type I need.
      Negative Reactions
      1. I fail to see under what situation is that viable?!
      2. In all situation, the client is the one initiating the reequest and the client KNOWS in what format he would like to get the request, what you are suggesting will probably cause the client to hate you :).
      Other Reactions
      1. for example I want to let client to choose type of response in URL: rest/get/cars/xml or rest/get/cars/json.
      2. Then depending on pathParam return right type of response.
      3. Once you add the producess annotation, the framework will do it automatically for you based on the client request.
      4. Or in ither words, how to return xml if client's accept header is JSON?
      5. But how I can return neccesary type from server?
      6. Thats a different question, I'd suggest opening a new discussion.

    45. How do I POST a Pojo with Jersey Client without manually convert to JSON?

      It's still using a Builder but less obviously. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. public void sendExample(Example example) { WebResource webResource = this.client.resource(this.url)
      2. webResource.type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(Example.class, example)
      3. return
      4. }

      Positive Reactions
      1. Thanks, that also worked like charm!.

    46. Parsing String[] Request Parameter through REST with Apache CXF

      I apparently misunderstood how REST works. What I did to finally solve the problem was the following 1 Changed my web service signature 2 Now make sure that the client is sending a request with content-type application/x-www-form-urlencoded and that the client correctly adds form parameters same as those you defined in the FormParam annotations. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/getVersion")@Produces(MediaType.APPLICATION_JSON)@Consumes({"application/xml", "application/json", "application/x-www-form-urlencoded"})public ControllerVersion getVersion(@FormParam("deviceID") String deviceID,@FormParam("macAddresses") String macAddresses)

    47. Using JAXB to parse JSON in Jersey

      Maybe this link is helpful example-with-jersey-jackson or . Try this in your endpoint where Coordinates is a simple POJO mirroring the JSON content you are posting. details

      Reactions - Positive 0, Negative 2, Others 0

      1. @POST@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.TEXT_PLAIN)public String processRequest(Coordinates coordinates) { return "Latitude: " + coordinates.getLatitude() + "\n:Longitude: " + coordinates.getLongitude()
      2. }

      Negative Reactions
      1. I'm getting the exact same error.
      2. I keep getting the same errors: MessageBodyReader not found for media type=application/json, type=class web_service.Request, genericType=class web_service.Request.
      Other Reactions
      1. I added all the Jackson jars, the configuration to the web.xml and turned Request into a POJO.
      2. Try with the configuration I provided.
      3. Nope.
      4. and HTTP Status 415 - Unsupported Media Type.

    48. Jersey POST Method is receiving null values as parameters

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/contacts")@Consumes(MediaType.APPLICATION_FORM_URLENCODED)public Response createContact(@QueryParam("contact") final Contact contactData, @QueryParam("metadata") final String metaData)

  29. inputstream
      Chart will be rendered here
    1. 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. }

    2. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    3. 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 .

    4. Jersey Exception : SEVERE: A message body reader for Java class

      You need to implement your own MessageBodyReader and MessageBodyWriter for your class Lorg.shoppingsite.model.entity.jpa.User. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package javax.ws.rs.ext
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.lang.annotation.Annotation
      5. import java.lang.reflect.Type
      6. import javax.ws.rs.WebApplicationException
      7. import javax.ws.rs.core.MediaType
      8. import javax.ws.rs.core.MultivaluedMap
      9. public interface MessageBodyReader<T extends Object> { public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      10. public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
      11. }package javax.ws.rs.ext
      12. import java.io.IOException
      13. import java.io.OutputStream
      14. import java.lang.annotation.Annotation
      15. import java.lang.reflect.Type
      16. import javax.ws.rs.WebApplicationException
      17. import javax.ws.rs.core.MediaType
      18. import javax.ws.rs.core.MultivaluedMap
      19. public interface MessageBodyWriter<T extends Object> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      20. public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      21. public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
      22. }

      Positive Reactions
      1. Normally mapping of JSON to POJOs works with JAXB without creating an own messageBodyReader, because the message reader for JSON already exists.
      Other Reactions
      1. I think your approach is not the common way.
      2. See answer of VDev.

  30. defaultclientconfig
      Chart will be rendered here
    1. Java consume JSON list from Rest service GET

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. ClientConfig clientConfig = new DefaultClientConfig()
      2. clientConfig.getClasses().add(JacksonJsonProvider.class)
      3. Client client = Client.create(clientConfig)
      4. return client .resource(Constants.BASE_URL) .path(Constants.CATEGORIES_ANIMALS) .type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .cookie(cookie) .get(new GenericType<List<AnimalCategoryResponse>>(){})

  31. parameterizedtype
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

  32. xmlrootelement
      Chart will be rendered here
    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. }

  33. response
      Chart will be rendered here
    1. 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. }

    2. PlayFramework - Running functional test with json rendering

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Test public void testThatJsonRenderingWorks() { Response response = GET(jsonRequest(newRequest)), "/recipe/1")
      2. assertIsOk(response)
      3. } }

    3. Jersey GenericEntity Not Working

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public Response get() { List<String> list = Arrays.asList("test", "as")
      2. return Response.ok(new GenericEntity<List<String>>(list) {}).build()
      3. }

    4. Please advise the best pattern for serialising JAXB Lists

      This could be an another proper way I think. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})public Response readItems() { final List<Item> items = ...
      2. return Response.ok(new GenericEntity<List<String>>(list) {}).build()
      3. }

    5. How to add Content-Length to JAXRS

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String str = OBJECT_MAPPER.writeValueAsString(myObject)
      2. return Response.ok(str , MediaType.APPLICATION_JSON).header(HttpHeaders.CONTENT_LENGTH), str.getBytes("UTF-8").length)).build()

    6. Jersey/JAXB: Use same POJO for HTTP POST and GET, but return only a subset of the properties for GET in JSON response.

      You may even be able to implement this in your retrieveUserFromDB method to avoid the copy step. For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getUser(String Id) { // Pseudo-code for retrieving user User userFromDB = retrieveUserFromDB(user)
      2. User user = new User()
      3. user.setUserName(userFromDB.getUserName())
      4. user.setUserEmail(userFromDB.getUserEmail())
      5. Response.status(200).entity(user)
      6. }

    7. how to send JSON data with server error response code 500

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Response.status(500)

    8. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.inject.Singleton
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.Produces
      5. import javax.ws.rs.core.MediaType
      6. import javax.ws.rs.core.Response
      7. @Singleton
      8. @Path("test/")
      9. public
      10. class MyResource { // public Thing[] state = {new Thing("asdf"), new Thing("foo"), new Thing("bar")}
      11. public String[] state = {"asdf", "foo", "bar"}
      12. @GET
      13. @Produces(MediaType.APPLICATION_JSON)
      14. public Response test() {
      15. return Response.ok(state).build()
      16. }
      17. }

    9. Jersey POST Method is receiving null values as parameters

      **Example** Given the URL I can define From which I can inject a . This works for any kind of HTTP request GET POST PUT DELETE_). details

      Reactions - Positive 8, Negative 3, Others 0

      1. public Response getContact(@PathParam("id") final String identifier)

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

    10. Jersey POST Method is receiving null values as parameters

      As a general rule you should restrict your path parameters to simple values like identifiers or resource endpoints more complex data should be passed to the REST service via request parameters or the request body itself. Here's a mixed approach that passes an entity identifier as a path parameter and the entity data in the request body In the above example the contactId is obtained as a path parameter and the contact is serialized automatically from the request body. details

      Reactions - Positive 8, Negative 3, Others 0

      1. @Path("/contacts/{id}")@PUT@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)public Response updateContact(@PathParam final String contactId, Contact contact) {}

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

    11. what's the correct way to send a file from REST web service to client?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Response.ok(entity, mediaType)

    12. what's the correct way to send a file from REST web service to client?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces(MediaType.APPLICATION_OCTECT_STREAM)public Response getFile() { File file = ... // Initialize this to the File path you want to serve. return Response.ok(file, MediaType.APPLICATION_OCTECT_STREAM).build()
      2. }

    13. Consuming JSON request and producing different output

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/")public class Test {@Path("/test")@POST @Consumes("application/json")@Produces("text/plain")public Response addOrderJSON(OrderDetails details) {...}}

    14. 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. }

    15. Jersey POST Method is receiving null values as parameters

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/contacts")@Consumes(MediaType.APPLICATION_FORM_URLENCODED)public Response createContact(@QueryParam("contact") final Contact contactData, @QueryParam("metadata") final String metaData)

    16. Jersey content type customization

      You have to support the preflight in the server code or the CORS request will be rejected. Provide your normal code for getSearchContacts but the preflight will come in on with an OPTIONS method Now the CORS request with the custom headers will be allowed. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @OPTIONSpublic Response preflight( @HeaderParam("Access-Control-Request-Method") String requestMethod, @HeaderParam("Origin") String origin, @HeaderParam("Access-Control-Request-Headers") String requestHeaders) {return Response .ok() .header("Access-Control-Allow-Origin", "*") // TODO replace with specific origin .header("Access-Control-Allow-Headers", "Content-Type") .build()
      2. }

    17. Jersey POST Method is receiving null values as parameters

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public Response getContactsInGroup(@QueryParam("group") final String groupName)

    18. what's the correct way to send a file from REST web service to client?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Path("/{key}")public Response download(@PathParam("key") String key, @Context HttpServletResponse response) throws IOException { try { //Get your File or Object from wherever you want... //you can use the key parameter to indentify your file //otherwise it can be removed //let's say your file is called "object" response.setContentLength((int) object.getContentLength())
      2. response.setHeader("Content-Disposition", "attachment
      3. filename=" + object.getName())
      4. ServletOutputStream outStream = response.getOutputStream()
      5. byte[] bbuf = new byte[(int) object.getContentLength() + 1024]
      6. DataInputStream in = new DataInputStream( object.getDataInputStream())
      7. int length = 0
      8. while ((in != null) && ((length = in.read(bbuf)) != -1)) { outStream.write(bbuf, 0, length)
      9. } in.close()
      10. outStream.flush()
      11. } catch (S3ServiceException e) { e.printStackTrace()
      12. } catch (ServiceException e) { e.printStackTrace()
      13. } return Response.ok().build()
      14. }

  34. objectmapper
      Chart will be rendered here
    1. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
      2. // import com.fasterxml.jackson.databind.ObjectMapper
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. import javax.ws.rs.ext.ContextResolver
      6. import javax.ws.rs.ext.Provider
      7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
      8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
      9. this.defaultObjectMapper = new ObjectMapper()
      10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
      11. // .enableDefaultTyping()
      12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
      13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
      14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
      15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
      16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
      17. return this.defaultObjectMapper
      18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

    2. RESTeasy, JSON and null fields

      Use Jackson 2. Setup the following provider The Scala module is optional. details

      Reactions - Positive 1, Negative 2, Others 0

      1. package com.recruitinghop.swagger
      2. import com.fasterxml.jackson.annotation.JsonInclude
      3. import com.fasterxml.jackson.databind.DeserializationFeature
      4. import com.fasterxml.jackson.databind.ObjectMapper
      5. import com.fasterxml.jackson.databind.SerializationFeature
      6. import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider
      7. import com.fasterxml.jackson.module.scala.DefaultScalaModule
      8. import javax.ws.rs.Produces
      9. import javax.ws.rs.core.MediaType
      10. import javax.ws.rs.ext.Provider
      11. @Provider
      12. @Produces(MediaType.APPLICATION_JSON)
      13. public class JacksonJsonProvider extends JacksonJaxbJsonProvider {
      14. public JacksonJsonProvider() {
      15. ObjectMapper mapper = new ObjectMapper()
      16. mapper.registerModule(new DefaultScalaModule())
      17. mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
      18. mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
      19. mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      20. mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      21. super.setMapper(mapper)
      22. }
      23. }

      Positive Reactions
      1. i would like to using only JAXB(native for JBOSS AS 7) for best performance, avoiding others "jar".
      Negative Reactions
      1. Do a little background googling, signup instead of being anonymous and I'll answer to that.
      2. There are so many things wrong with what you just said.
      Other Reactions
      1. is there solution without Jackson ?

    3. Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

      This is the solution for my old question I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature. And in the web.xml I registered my package into the servlet definition all the rest is transparently done by jersey/jackson. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.lig.hadas.services.mapper
      2. import javax.ws.rs.Produces
      3. import javax.ws.rs.core.MediaType
      4. import javax.ws.rs.ext.ContextResolver
      5. import org.codehaus.jackson.map.DeserializationConfig
      6. import org.codehaus.jackson.map.ObjectMapper
      7. @Produces(MediaType.APPLICATION_JSON)
      8. @Providerpublic
      9. class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
      10. ObjectMapper mapper
      11. public ObjectMapperProvider() {
      12. mapper = new ObjectMapper()
      13. mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
      14. }
      15. @Override
      16. public ObjectMapper getContext(Class<?> type) {
      17. return mapper
      18. }
      19. }

  35. jsonconfiguration
      Chart will be rendered here
    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.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. }

    2. 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.

  36. exception
      Chart will be rendered here
    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.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. }

  37. marshaller
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

  38. messagebodyreader
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

    3. Jersey Exception : SEVERE: A message body reader for Java class

      You need to implement your own MessageBodyReader and MessageBodyWriter for your class Lorg.shoppingsite.model.entity.jpa.User. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package javax.ws.rs.ext
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.lang.annotation.Annotation
      5. import java.lang.reflect.Type
      6. import javax.ws.rs.WebApplicationException
      7. import javax.ws.rs.core.MediaType
      8. import javax.ws.rs.core.MultivaluedMap
      9. public interface MessageBodyReader<T extends Object> { public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      10. public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
      11. }package javax.ws.rs.ext
      12. import java.io.IOException
      13. import java.io.OutputStream
      14. import java.lang.annotation.Annotation
      15. import java.lang.reflect.Type
      16. import javax.ws.rs.WebApplicationException
      17. import javax.ws.rs.core.MediaType
      18. import javax.ws.rs.core.MultivaluedMap
      19. public interface MessageBodyWriter<T extends Object> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      20. public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      21. public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
      22. }

      Positive Reactions
      1. Normally mapping of JSON to POJOs works with JAXB without creating an own messageBodyReader, because the message reader for JSON already exists.
      Other Reactions
      1. I think your approach is not the common way.
      2. See answer of VDev.

  39. applicationpath
      Chart will be rendered here
    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. What is the fastest way to stand up a REST service using Java?

      These are the files I called it simpleRest as seen below. All the archives are exactly as shown pom.xml HelloResource.java JaxRsActivator.java This generates a simpleRest.war through mvn clean package). details

      Reactions - Positive 2, Negative 0, Others 0

      1. package rest
      2. import java.util.Date
      3. import javax.ws.rs.GET
      4. import javax.ws.rs.Path
      5. import javax.ws.rs.Produces
      6. @Path("/hello")
      7. public class HelloResource {
      8. @GET
      9. @Produces("text/plain")
      10. public String helloResource() {
      11. return "Hello! It's " + new Date()
      12. }
      13. }

      Positive Reactions
      1. Thank you, This is a great intro :).
      2. Clean, simple, useful!
      Other Reactions
      1. Did you manage to get it working?
      2. If not, we can help you further.
      3. :).

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

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package rest
      2. import javax.ws.rs.ApplicationPath
      3. import javax.ws.rs.core.Application
      4. @ApplicationPath("/rest")
      5. public class JaxRsActivator extends Application {}

  40. exampleservice
      Chart will be rendered here
    1. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      9. set.add(ExampleService.class)
      10. return set
      11. }
      12. @Override
      13. public Set<Object> getSingletons() {
      14. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      15. moxyJsonProvider.setAttributePrefix("@")
      16. moxyJsonProvider.setFormattedOutput(true)
      17. moxyJsonProvider.setIncludeRoot(true)
      18. moxyJsonProvider.setMarshalEmptyCollections(false)
      19. moxyJsonProvider.setValueWrapper("$")
      20. Map<String, String> namespacePrefixMapper = new HashMap<String, String>(1)
      21. namespacePrefixMapper.put("http://www.example.org/customer", "cust")
      22. moxyJsonProvider.setNamespacePrefixMapper(namespacePrefixMapper)
      23. moxyJsonProvider.setNamespaceSeparator(':')
      24. HashSet<Object> set = new HashSet<Object>(1)
      25. set.add(moxyJsonProvider)
      26. return set
      27. }
      28. }

    2. How an I get MOXy to just output on one line to save space

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.example
      2. import java.util.*
      3. import javax.ws.rs.core.Application
      4. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      5. public class CustomerApplication extends Application {
      6. @Override
      7. public Set<Class<?>> getClasses() {
      8. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      9. set.add(ExampleService.class)
      10. return set
      11. }
      12. @Override
      13. public Set<Object> getSingletons() {
      14. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      15. moxyJsonProvider.setFormattedOutput(true)
      16. }
      17. }

    3. MOXy compatible XML and JSON responses

      You can change this by setting a configured instance on a JAX-RS Application class like the one below. For More Information MOXy as the Default JSON-Binding Provider in Jersey/GlassFish If you are using MOXy as the default JSON-binding provider with Jersey/GlassFish you can leverage the MoxyJsonConfig class as follows For More Information . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import javax.ws.rs.core.Application
      3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
      4. public class FooApplication extends Application {
      5. @Override
      6. public Set<Class<?>> getClasses() {
      7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
      8. set.add(ExampleService.class)
      9. return set
      10. }
      11. @Override
      12. public Set<Object> getSingletons() {
      13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
      14. moxyJsonProvider.setIncludeRoot(true)
      15. HashSet<Object> set = new HashSet<Object>(1)
      16. set.add(moxyJsonProvider)
      17. return set
      18. }
      19. }

  41. arraylist
      Chart will be rendered here
    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.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. }

    2. Why writer for media type application/json missing

      I don't know whether resteasy 1.1 containts jettison provider but version 1.2 does.Also if you are using jdk 1.6 you must exclude javax.xml.stream:stax-api jar file otherwise you will have a problem. Here is the example and JAXB class That's all have a nice day. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.ws.rs.GET
      2. import javax.ws.rs.Path
      3. import javax.ws.rs.PathParam
      4. import javax.ws.rs.Produces
      5. @Path("/account")
      6. public class AccountService {
      7. @GET
      8. @Path("/{accountNo}")
      9. @Produces("application/json")
      10. public Account getAccount(@PathParam("accountNo") String accountNo) {
      11. return new Account(accountNo)
      12. }
      13. }

  42. jaxbexception
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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.

    3. 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 .

  43. method
      Chart will be rendered here
    1. Jersey content type customization

      You have to support the preflight in the server code or the CORS request will be rejected. Provide your normal code for getSearchContacts but the preflight will come in on with an OPTIONS method Now the CORS request with the custom headers will be allowed. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @OPTIONSpublic Response preflight( @HeaderParam("Access-Control-Request-Method") String requestMethod, @HeaderParam("Origin") String origin, @HeaderParam("Access-Control-Request-Headers") String requestHeaders) {return Response .ok() .header("Access-Control-Allow-Origin", "*") // TODO replace with specific origin .header("Access-Control-Allow-Headers", "Content-Type") .build()
      2. }

    2. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

    3. Jersey 2.0 equivalent to POJOMappingFeature

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example
      2. import javax.ws.rs.GET
      3. import javax.ws.rs.Path
      4. import javax.ws.rs.PathParam
      5. import javax.ws.rs.Produces
      6. import javax.ws.rs.core.MediaType
      7. /** * Root resource (exposed at "myresource" path) */
      8. @Path("myresource")
      9. public class MyResource {
      10. /**
      11. * * Method handling HTTP GET requests. The returned object will be sent * to the client as
      12. * "text/plain" media type. * * @return String that will be returned as a text/plain response.
      13. */
      14. @GET
      15. @Produces(MediaType.TEXT_PLAIN)
      16. public String getIt() {
      17. return "Got it!"
      18. }
      19. @Path("complexObject/{name}")
      20. @GET
      21. @Produces({MediaType.APPLICATION_JSON})
      22. public ComplexObject complexObject(@PathParam("name") String name) {
      23. return new ComplexObject(name, System.currentTimeMillis(), 42L)
      24. }
      25. }

  44. contextresolver
      Chart will be rendered here
    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.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. }

    2. 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.

    3. How to deserialize dynamic JSON fields with Jackson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
      2. // import com.fasterxml.jackson.databind.ObjectMapper
      3. import org.codehaus.jackson.annotate.JsonTypeInfo
      4. import org.codehaus.jackson.map.ObjectMapper
      5. import javax.ws.rs.ext.ContextResolver
      6. import javax.ws.rs.ext.Provider
      7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
      8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
      9. this.defaultObjectMapper = new ObjectMapper()
      10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
      11. // .enableDefaultTyping()
      12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
      13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
      14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
      15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
      16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
      17. return this.defaultObjectMapper
      18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

    4. Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

      This is the solution for my old question I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature. And in the web.xml I registered my package into the servlet definition all the rest is transparently done by jersey/jackson. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package org.lig.hadas.services.mapper
      2. import javax.ws.rs.Produces
      3. import javax.ws.rs.core.MediaType
      4. import javax.ws.rs.ext.ContextResolver
      5. import org.codehaus.jackson.map.DeserializationConfig
      6. import org.codehaus.jackson.map.ObjectMapper
      7. @Produces(MediaType.APPLICATION_JSON)
      8. @Providerpublic
      9. class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
      10. ObjectMapper mapper
      11. public ObjectMapperProvider() {
      12. mapper = new ObjectMapper()
      13. mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
      14. }
      15. @Override
      16. public ObjectMapper getContext(Class<?> type) {
      17. return mapper
      18. }
      19. }

  45. multivaluedmap
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

    3. Jersey Exception : SEVERE: A message body reader for Java class

      You need to implement your own MessageBodyReader and MessageBodyWriter for your class Lorg.shoppingsite.model.entity.jpa.User. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package javax.ws.rs.ext
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.lang.annotation.Annotation
      5. import java.lang.reflect.Type
      6. import javax.ws.rs.WebApplicationException
      7. import javax.ws.rs.core.MediaType
      8. import javax.ws.rs.core.MultivaluedMap
      9. public interface MessageBodyReader<T extends Object> { public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      10. public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
      11. }package javax.ws.rs.ext
      12. import java.io.IOException
      13. import java.io.OutputStream
      14. import java.lang.annotation.Annotation
      15. import java.lang.reflect.Type
      16. import javax.ws.rs.WebApplicationException
      17. import javax.ws.rs.core.MediaType
      18. import javax.ws.rs.core.MultivaluedMap
      19. public interface MessageBodyWriter<T extends Object> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      20. public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      21. public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
      22. }

      Positive Reactions
      1. Normally mapping of JSON to POJOs works with JAXB without creating an own messageBodyReader, because the message reader for JSON already exists.
      Other Reactions
      1. I think your approach is not the common way.
      2. See answer of VDev.

  46. ioexception
      Chart will be rendered here
    1. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    2. 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 .

    3. Jersey Exception : SEVERE: A message body reader for Java class

      You need to implement your own MessageBodyReader and MessageBodyWriter for your class Lorg.shoppingsite.model.entity.jpa.User. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package javax.ws.rs.ext
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.lang.annotation.Annotation
      5. import java.lang.reflect.Type
      6. import javax.ws.rs.WebApplicationException
      7. import javax.ws.rs.core.MediaType
      8. import javax.ws.rs.core.MultivaluedMap
      9. public interface MessageBodyReader<T extends Object> { public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      10. public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
      11. }package javax.ws.rs.ext
      12. import java.io.IOException
      13. import java.io.OutputStream
      14. import java.lang.annotation.Annotation
      15. import java.lang.reflect.Type
      16. import javax.ws.rs.WebApplicationException
      17. import javax.ws.rs.core.MediaType
      18. import javax.ws.rs.core.MultivaluedMap
      19. public interface MessageBodyWriter<T extends Object> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      20. public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
      21. public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
      22. }

      Positive Reactions
      1. Normally mapping of JSON to POJOs works with JAXB without creating an own messageBodyReader, because the message reader for JSON already exists.
      Other Reactions
      1. I think your approach is not the common way.
      2. See answer of VDev.

    4. what's the correct way to send a file from REST web service to client?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Path("/{key}")public Response download(@PathParam("key") String key, @Context HttpServletResponse response) throws IOException { try { //Get your File or Object from wherever you want... //you can use the key parameter to indentify your file //otherwise it can be removed //let's say your file is called "object" response.setContentLength((int) object.getContentLength())
      2. response.setHeader("Content-Disposition", "attachment
      3. filename=" + object.getName())
      4. ServletOutputStream outStream = response.getOutputStream()
      5. byte[] bbuf = new byte[(int) object.getContentLength() + 1024]
      6. DataInputStream in = new DataInputStream( object.getDataInputStream())
      7. int length = 0
      8. while ((in != null) && ((length = in.read(bbuf)) != -1)) { outStream.write(bbuf, 0, length)
      9. } in.close()
      10. outStream.flush()
      11. } catch (S3ServiceException e) { e.printStackTrace()
      12. } catch (ServiceException e) { e.printStackTrace()
      13. } return Response.ok().build()
      14. }

  47. context
      Chart will be rendered here
    1. Custom response header Jersey/Java

      Just inject a Context HttpServletResponse response as a method argument. Change the headers on that . details

      Reactions - Positive 3, Negative 0, Others 0

      1. @Produces(MediaType.APPLICATION_JSON)public UserClass getValues(@Context HttpHeaders header, @Context HttpServletResponse response) { response.setHeader("yourheadername", "yourheadervalue")
      2. ...}

      Positive Reactions
      1. :-) you rock!.
      2. Thanks a lot @sotirios.
      3. @Namenoobie You're welcome, good luck!.
      Other Reactions
      1. Yes, your Tomcat installation includes those libraries.
      2. That's where you typically get them from.
      3. @Namenoobie You need the server runtime library.
      4. Does it require me to add additional libraries?
      5. This is basically the servlet api.
      6. If you're on Eclipse, go to your project java buildpath and add library.
      7. When I follow the instruction, I get the Tomcat server which already exists on my local machine.
      8. it says unidentified class "HttpServletResponse".

    2. How do I send a json object from my rest service so I can parse in out on the client side javascript

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces("application/json")@Consumes("application/json") @Path("/getStatus/")public Mystatus getStatus( @Context HttpServletRequest request, @Context HttpServletResponse response){ response.setContentType("text/javascript")
      2. return new Mystatus("Hello","World")
      3. }

    3. Jersey POST Method is receiving null values as parameters

      Now as to the specifics of your case one thing I notice in your code is that you don't actually define any path parameters. Remember that they have to be defined as part of your Path annotation before being consumed in your REST method With the above changes your parameters should no longer show up as being null assuming you have properly encoded the URL on the client side. details

      Reactions - Positive 8, Negative 3, Others 0

      1. @Path("/method/{obj1}/{obj2}")public ResponseObject method(@Context Request request, @PathParam("obj1") Object obj1, @PathParam("obj2") String obj2) {}

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

    4. what's the correct way to send a file from REST web service to client?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Path("/{key}")public Response download(@PathParam("key") String key, @Context HttpServletResponse response) throws IOException { try { //Get your File or Object from wherever you want... //you can use the key parameter to indentify your file //otherwise it can be removed //let's say your file is called "object" response.setContentLength((int) object.getContentLength())
      2. response.setHeader("Content-Disposition", "attachment
      3. filename=" + object.getName())
      4. ServletOutputStream outStream = response.getOutputStream()
      5. byte[] bbuf = new byte[(int) object.getContentLength() + 1024]
      6. DataInputStream in = new DataInputStream( object.getDataInputStream())
      7. int length = 0
      8. while ((in != null) && ((length = in.read(bbuf)) != -1)) { outStream.write(bbuf, 0, length)
      9. } in.close()
      10. outStream.flush()
      11. } catch (S3ServiceException e) { e.printStackTrace()
      12. } catch (ServiceException e) { e.printStackTrace()
      13. } return Response.ok().build()
      14. }

  48. consumes
      Chart will be rendered here
    1. 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. }

    2. Including null elements in JSON output of Jersey RESTful API with JAXB

      For EclipseLink-JAXB-(MOXy) s JSON binding the correct mapping would be the following. You could try it with your provider to see if it would work also For More Information UPDATE 2 EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader/MessageBodyWriter that you can use directly to leverage MOXy's JSON binding UPDATE 1 The following MessageBodyReader/MessageBodyWriter may work better for you . details

      Reactions - Positive 6, Negative 7, Others 0

      1. import java.io.*
      2. import java.lang.annotation.Annotation
      3. import java.lang.reflect.*
      4. import javax.ws.rs.*
      5. import javax.ws.rs.core.*
      6. import javax.ws.rs.ext.*
      7. import javax.xml.bind.*
      8. import javax.xml.transform.stream.StreamSource
      9. import org.eclipse.persistence.jaxb.JAXBContextFactory
      10. @Provider
      11. @Produces(MediaType.APPLICATION_JSON)
      12. @Consumes(MediaType.APPLICATION_JSON)
      13. public class MOXyJSONProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
      14. @Context protected Providers providers
      15. public boolean isReadable(
      16. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      17. return true
      18. }
      19. public Object readFrom(
      20. Class<Object> type,
      21. Type genericType,
      22. Annotation[] annotations,
      23. MediaType mediaType,
      24. MultivaluedMap<String, String> httpHeaders,
      25. InputStream entityStream)
      26. throws IOException, WebApplicationException {
      27. try {
      28. Class<?> domainClass = getDomainClass(genericType)
      29. Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller()
      30. u.setProperty("eclipselink.media-type", mediaType.toString())
      31. u.setProperty("eclipselink.json.include-root", false)
      32. return u.unmarshal(new StreamSource(entityStream), domainClass).getValue()
      33. } catch (JAXBException jaxbException) {
      34. throw new WebApplicationException(jaxbException)
      35. }
      36. }
      37. public boolean isWriteable(
      38. Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
      39. return true
      40. }
      41. public void writeTo(
      42. Object object,
      43. Class<?> type,
      44. Type genericType,
      45. Annotation[] annotations,
      46. MediaType mediaType,
      47. MultivaluedMap<String, Object> httpHeaders,
      48. OutputStream entityStream)
      49. throws IOException, WebApplicationException {
      50. try {
      51. Class<?> domainClass = getDomainClass(genericType)
      52. Marshaller m = getJAXBContext(domainClass, 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 JAXBContextFactory.createContext(new Class[] {type}, null)
      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. Looks like getJAXBContext() in MOXyJSONProvider might not be picking up a context correctly (and thus creating a JAXB context that doesn't know what "eclipselink.media-type" is).
      2. Fixed!
      3. An empty lastName is output lastName : { "nil" : "true" }.
      4. Can you please provide more details on any additional code changes that would be required (other than what's listed above).
      5. Thanks a a lot for your help.
      6. I'd prefer to use the most up-to- date stable release (2.3.2).
      Negative Reactions
      1. I think there's some type confusion in getJAXBContext().
      2. I downloaded and tried it with 2.4.0-M18, but I'm still getting the same exception.
      3. The problem was the we left the old JAXB provider hanging around with it's @Provider annotation.
      4. @Oleksi - The JSON binding is being added to 2.4.0, instead of a snap shot you can use a milestone 2.4.0-M18 URL_http://www.eclipse.org/eclipselink/downloads/milestones.php .
      5. Tried the new version, but it still doesn't work (same exception).
      6. I switched to MOXyJSONProvider given in your example and then I get an exception: javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json at MOXyJSONProvider.writeTo(MOXyJSONProvider.java:58).
      7. I've also had difficulties downloading the required dependancies for this project.
      Other Reactions
      1. I downloaded and tried it with the JAXBProvider and it didn't work.
      2. I've tried this, but I can't quite get it to work.
      3. Any suggestions?
      4. Or both?
      5. :).
      6. It seems to work now.
      7. I tried looking at this document to no avail.
      8. If so, how do we tell MOXy about it?
      9. We will be releasing as part of the Eclipse Juno release this summer and should be entering the release candidate stage very soon.
      10. Also, do I need the jaxb.properties file, and if so, then where should it be?
      11. For instance, do I have to change my JAXBContextResolver class?
      12. Should it be working with avax.xml.bind.JAXBContext or org.eclipse.persistence.jaxb.JAXBContext?
      13. @Oleksi - I've updated my answer with a version that may work better for you.
      14. URL_http://wiki.eclipse.org/EclipseLink/Maven .
      15. Does it have to be version 2.4.0-SNAPSHOT?
      16. Do we also need to provide a JAXBContext?
      17. Here is an example pom.xml: URL_https://github.com/bdoughan/blog20110819/blob/master/pom.xml .

    3. Consuming JSON request and producing different output

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/")public class Test {@Path("/test")@POST @Consumes("application/json")@Produces("text/plain")public Response addOrderJSON(OrderDetails details) {...}}

    4. Jersey object mapping

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Path("/testDifferentClass")
      2. public class TestServlet {
      3. @GET
      4. @Produces(MediaType.APPLICATION_XML)
      5. @Consumes(MediaType.APPLICATION_XML)
      6. public ClassA getClassA() {
      7. ClassA classA = new ClassA()
      8. classA.setOne("Hello")
      9. classA.setTwo(new Date())
      10. classA.setThree(1)
      11. return classA
      12. }
      13. }

    5. 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 .

    6. Why writer for media type application/json missing

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)

    7. 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. }

    8. How enable JSONP in RESTEasy?

      This solution takes data via http get parameters and translate to virtual POST request. JQuery Declaration in Service interface Filter class web.xml . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("requestPrice")@Produces("application/json")@Consumes("application/json")PriceResponse requestPrice(PriceRequest request) throws ServiceException

    9. Java.util.Map to JSON Object with Jersey / JAXB / Jackson

      Thanks but I was specifically interested in a solution integrated with Jersey. Of course you need to have getter/setter for every property in Book. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Consumes("application/json")public void createBook(Book book){ ..... .....}

    10. Jersey POST Method is receiving null values as parameters

      As a general rule you should restrict your path parameters to simple values like identifiers or resource endpoints more complex data should be passed to the REST service via request parameters or the request body itself. Here's a mixed approach that passes an entity identifier as a path parameter and the entity data in the request body In the above example the contactId is obtained as a path parameter and the contact is serialized automatically from the request body. details

      Reactions - Positive 8, Negative 3, Others 0

      1. @Path("/contacts/{id}")@PUT@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)public Response updateContact(@PathParam final String contactId, Contact contact) {}

      Positive Reactions
      1. Thanks for the help @Perception.
      2. After putting all in the same parameter everything worked fine.
      3. Thanks @Perception, I have been reading it and it made me clear some aspects...one of the most important is that you can only treat one request parameter in the request body...so it was imposible to treat two parameters in the way i was doing it.
      4. @Kasas - that was a pretty broad followup question, I linked some documentation in my answer which should be helpful in getting more information.
      5. I hope!
      6. My method now consumes a paramenter like {"obj1":{"id1": "value1", "id2" : "value2"},"obj2":"xxxx"} and everything is fine :).
      7. Thanks so much.
      8. No problem, good luck with the rest of the project!.
      Negative Reactions
      1. However the problem with null parameters is not completely solved... tomorrow i'll find the solution and i'll post it here ;)...
      2. You must use multipart/mixed to do it or make another complex type (that's my solution).
      3. I think it is a problem with the way IOS format the JSON String...
      Other Reactions
      1. If I put the parameters in the path param I didn't receive anything to the server...
      2. Hi Perception, I didn't put the parameters in the Path param because I use a POST method so I thought there was no need to put it (it is not present at the URL).
      3. I thought using PathParam and QueryParam would be used only to know how to pass the parameters to the post request... what is jersey expecting then in the request body??

    11. PUT method with @FormParam

      Change the Consumes type for your resource to multipart/form-data. Then on your client side set Content-Type multipart/form-data Add form variables for login and password On a side note assuming this isn't for learning you will want to secure your login endpoint with SSL and hash the password before sending it across the wire. details

      Reactions - Positive 5, Negative 4, Others 0

      1. @PUT@Path("/login")@Produces({ "application/json", "text/plain" })@Consumes("multipart/form-data")public String login(@FormParam("login") String login, @FormParam("password") String password) { String response = null
      2. response = new UserManager().login(login, password)
      3. return response
      4. }

      Positive Reactions
      1. You can read [this StackOverflow answer]( URL_http://stackoverflow.com/a/2022938/680925) , which gives a nice summary of what to use when.
      2. But i read that "HTML forms are an easy means of getting information from a user and they are also easy to create.
      3. Something like:HttpPut httpPut new HttpPut(BASE_URI + "/services.users/login");Form f new Form(); f.add("login", "xxxxx"); f.add("password", "xxxxx"); ?
      4. I will try that!.
      5. Thanks, it's working!But I was initially asking how to enter those parameters in the TEST RESTful WEB SERVICES main page.
      Negative Reactions
      1. Sorry, another question about the @FormParam: they can be used with PUTs?
      2. Unfortunately, it doesn't seem like Netbeans could detect the invalid combination of annotations on your resource method.
      3. C:\Users\Ines\Documents\NetBeansProjects\LULServices\build\generated-sources \rest-test\test-resbeans.html.
      4. Is that a problem?
      Other Reactions
      1. That's why I was asking.
      2. ?
      3. let us [continue this discussion in chat]( URL_http://chat.stackoverflow.com/rooms/26660/discussion-between-perception - and-user2144555).
      4. I'm always doing PUTs instead of POSTs.
      5. Actually, each one of the HTTP verbs maps to a specific RESTful operation, and you should try to use them appropriately.
      6. I would guess that to be a Netbeans auto-generated test page for your web service.
      7. You should only do PUT's for operations that will be updating an entity.
      8. But I was thinking that " form variables for login and password** " were send in a different way.
      9. I was using Apache HttpClient too.
      10. It's their main page.
      11. Whats the link of the page you are talking about?
      12. Form data can be used for HTTP GET requests and HTTP POST requests."
      13. Yes, I'm always doing updates.
      14. Do you know what I'm talking about?
      15. @user2144555 - See edits for a viable way to call the server resource, using Apache HttpComponents.

    12. Parsing String[] Request Parameter through REST with Apache CXF

      I apparently misunderstood how REST works. What I did to finally solve the problem was the following 1 Changed my web service signature 2 Now make sure that the client is sending a request with content-type application/x-www-form-urlencoded and that the client correctly adds form parameters same as those you defined in the FormParam annotations. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/getVersion")@Produces(MediaType.APPLICATION_JSON)@Consumes({"application/xml", "application/json", "application/x-www-form-urlencoded"})public ControllerVersion getVersion(@FormParam("deviceID") String deviceID,@FormParam("macAddresses") String macAddresses)

    13. Using JAXB to parse JSON in Jersey

      Maybe this link is helpful example-with-jersey-jackson or . Try this in your endpoint where Coordinates is a simple POJO mirroring the JSON content you are posting. details

      Reactions - Positive 0, Negative 2, Others 0

      1. @POST@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.TEXT_PLAIN)public String processRequest(Coordinates coordinates) { return "Latitude: " + coordinates.getLatitude() + "\n:Longitude: " + coordinates.getLongitude()
      2. }

      Negative Reactions
      1. I'm getting the exact same error.
      2. I keep getting the same errors: MessageBodyReader not found for media type=application/json, type=class web_service.Request, genericType=class web_service.Request.
      Other Reactions
      1. I added all the Jackson jars, the configuration to the web.xml and turned Request into a POJO.
      2. Try with the configuration I provided.
      3. Nope.
      4. and HTTP Status 415 - Unsupported Media Type.

    14. Parsing String[] Request Parameter through REST with Apache CXF

      What do you think I should do. You're using . details

      Reactions - Positive 1, Negative 1, Others 0

      1. @Consumes(MediaType.APPLICATION_JSON)

      Positive Reactions
      1. Please check the "update" section in my original question.
      Negative Reactions
      1. I tried to add Jackson, but I'm ending up with another exception now.

    15. How do I send a json object from my rest service so I can parse in out on the client side javascript

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET@Produces("application/json")@Consumes("application/json") @Path("/getStatus/")public Mystatus getStatus( @Context HttpServletRequest request, @Context HttpServletResponse response){ response.setContentType("text/javascript")
      2. return new Mystatus("Hello","World")
      3. }

    16. Get simple JSON Parameter from a JSON request in JAX-RS

      Then Jersey can decode the JSON object for you transparently and voila. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. @Path("/process-something")@POST@Produces("application/json")@Consumes("application/json")public AResponse processSomething(MyJSONOject json) { log.fine(json.attribute)
      2. }

      Positive Reactions
      1. Although I expected an easier way, such as getting the parameter injected with an annotation (see my answer), I mark this as an answer, as this is still a better solution than decoding it manually with Jackson.

    17. Passing Object and Integer with JSON

      As the post above mentions you can build your own class that wraps the int and has proper annotations. for this case that you gave in the question I think it would be enough to pass a String and then parse it for the int value . details

      Reactions - Positive 2, Negative 1, Others 0

      1. @POST@Path("/test")@Consumes("application/json")public void test(Person pers, String number){ int x = Integer.parseInt(number)
      2. //rest of code here }

      Positive Reactions
      1. I tried it like Gaby mentioned below but no success.
      2. I changed it to string but its not working yet.
      Negative Reactions
      1. { pers:{"name":"TEST", "surname":"TEST"}, "number":"1000" } Exception: Unexpected character ('p' (code 112)): was expecting double-quote to start field name.
      Other Reactions
      1. I think there is a Problem with JSON-Format.

    18. Jersey POST Method is receiving null values as parameters

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/contacts")@Consumes(MediaType.APPLICATION_FORM_URLENCODED)public Response createContact(@QueryParam("contact") final Contact contactData, @QueryParam("metadata") final String metaData)

    19. Posting JSON to RESTful through formParam with JAX-RS results in "Unsupported Media Type"

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import javax.ws.rs.Consumes
      2. import javax.ws.rs.FormParam
      3. import javax.ws.rs.POST
      4. import javax.ws.rs.core.MediaType
      5. import org.codehaus.jettison.json.JSONObject
      6. ... @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String postData(@FormParam("textAreaName") JSONObject jsono){..

    20. JSON Jersey JAXB

      I think maybe you just need to escape the s on the command line. When your OrderBean is properly annotated with any XmlXXX you don't have to wrap it with JAXBElement< And you should send exactly the same JSON string Jersey can parse. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Consumes(...)public void addOrder(final OrderBean order) {}

    21. Jersey, how to POST a list of JSON objects?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Path("/some-path")@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)public String createBatch(Example example){ ... }

All usage scenarios for API javax.ws
  • JAXB for lists to be returned naturally for JSON or XML

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. import java.util.*
    2. import javax.ws.rs.core.Application
    3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
    4. public class YourApplication extends Application {
    5. @Override
    6. public Set<Class<?>> getClasses() {
    7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
    8. set.add(YourService.class)
    9. return set
    10. }
    11. @Override
    12. public Set<Object> getSingletons() {
    13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
    14. moxyJsonProvider.setWrapperAsArrayName(true)
    15. HashSet<Object> set = new HashSet<Object>(1)
    16. set.add(moxyJsonProvider)
    17. return set
    18. }
    19. }

  • Why writer for media type application/json missing

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)

  • Apache Wink Json REST Web Service

    I do not know what exactly you mean with that have a structure similar with the java class'. If you refer to wanting to return a json structure I can add following:To return JSON I used And I parsed the string to JSON-format. details

    Reactions - Positive 0, Negative 0, Others 0

    1. @Produces("application/json")

  • How to deserialize dynamic JSON fields with Jackson?

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. import javax.inject.Singleton
    2. import javax.ws.rs.GET
    3. import javax.ws.rs.Path
    4. import javax.ws.rs.Produces
    5. import javax.ws.rs.core.MediaType
    6. import javax.ws.rs.core.Response
    7. @Singleton
    8. @Path("test/")
    9. public
    10. class MyResource { // public Thing[] state = {new Thing("asdf"), new Thing("foo"), new Thing("bar")}
    11. public String[] state = {"asdf", "foo", "bar"}
    12. @GET
    13. @Produces(MediaType.APPLICATION_JSON)
    14. public Response test() {
    15. return Response.ok(state).build()
    16. }
    17. }

  • How to deserialize dynamic JSON fields with Jackson?

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. // import com.fasterxml.jackson.annotation.JsonTypeInfo
    2. // import com.fasterxml.jackson.databind.ObjectMapper
    3. import org.codehaus.jackson.annotate.JsonTypeInfo
    4. import org.codehaus.jackson.map.ObjectMapper
    5. import javax.ws.rs.ext.ContextResolver
    6. import javax.ws.rs.ext.Provider
    7. @Providerpublic class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { final ObjectMapper defaultObjectMapper
    8. public MyObjectMapperProvider() { System.out.println("MyObjectMapperProvider()")
    9. this.defaultObjectMapper = new ObjectMapper()
    10. this.defaultObjectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT )
    11. // .enableDefaultTyping()
    12. // .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE)
    13. // .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT)
    14. // this.defaultObjectMapper.addMixInAnnotations(Bindable.class, MyObjectMapperProvider.MixIn.class)
    15. // this.defaultObjectMapper.addMixInAnnotations(DataModel.WriteOp.class, MyObjectMapperProvider.MixIn.class)
    16. } @Override public ObjectMapper getContext(Class<?> type) { System.out.println("MyObjectMapperProvider.getContext(" + type + ")")
    17. return this.defaultObjectMapper
    18. } // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") // public static class MixIn { // }}

  • Using JAXB to parse JSON in Jersey

    Maybe this link is helpful example-with-jersey-jackson or . Try this in your endpoint where Coordinates is a simple POJO mirroring the JSON content you are posting. details

    Reactions - Positive 0, Negative 2, Others 0

    1. @POST@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.TEXT_PLAIN)public String processRequest(Coordinates coordinates) { return "Latitude: " + coordinates.getLatitude() + "\n:Longitude: " + coordinates.getLongitude()
    2. }

    Negative Reactions
    1. I'm getting the exact same error.
    2. I keep getting the same errors: MessageBodyReader not found for media type=application/json, type=class web_service.Request, genericType=class web_service.Request.
    Other Reactions
    1. I added all the Jackson jars, the configuration to the web.xml and turned Request into a POJO.
    2. Try with the configuration I provided.
    3. Nope.
    4. and HTTP Status 415 - Unsupported Media Type.

  • Parsing String[] Request Parameter through REST with Apache CXF

    I apparently misunderstood how REST works. What I did to finally solve the problem was the following 1 Changed my web service signature 2 Now make sure that the client is sending a request with content-type application/x-www-form-urlencoded and that the client correctly adds form parameters same as those you defined in the FormParam annotations. details

    Reactions - Positive 0, Negative 0, Others 0

    1. @POST@Path("/getVersion")@Produces(MediaType.APPLICATION_JSON)@Consumes({"application/xml", "application/json", "application/x-www-form-urlencoded"})public ControllerVersion getVersion(@FormParam("deviceID") String deviceID,@FormParam("macAddresses") String macAddresses)

  • Parsing String[] Request Parameter through REST with Apache CXF

    What do you think I should do. You're using . details

    Reactions - Positive 1, Negative 1, Others 0

    1. @Consumes(MediaType.APPLICATION_JSON)

    Positive Reactions
    1. Please check the "update" section in my original question.
    Negative Reactions
    1. I tried to add Jackson, but I'm ending up with another exception now.

  • MOXy compatible XML and JSON responses

    You can change this by setting a configured instance on a JAX-RS Application class like the one below. For More Information MOXy as the Default JSON-Binding Provider in Jersey/GlassFish If you are using MOXy as the default JSON-binding provider with Jersey/GlassFish you can leverage the MoxyJsonConfig class as follows For More Information . details

    Reactions - Positive 0, Negative 0, Others 0

    1. import java.util.*
    2. import javax.ws.rs.core.Application
    3. import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider
    4. public class FooApplication extends Application {
    5. @Override
    6. public Set<Class<?>> getClasses() {
    7. HashSet<Class<?>> set = new HashSet<Class<?>>(1)
    8. set.add(ExampleService.class)
    9. return set
    10. }
    11. @Override
    12. public Set<Object> getSingletons() {
    13. MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider()
    14. moxyJsonProvider.setIncludeRoot(true)
    15. HashSet<Object> set = new HashSet<Object>(1)
    16. set.add(moxyJsonProvider)
    17. return set
    18. }
    19. }

  • MOXy compatible XML and JSON responses

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. import javax.ws.rs.ext.*
    2. import org.glassfish.jersey.moxy.json.MoxyJsonConfig
    3. @Providerpublic
    4. class MOXyJsonContextResolver implements ContextResolver<MoxyJsonConfig> {
    5. private final MoxyJsonConfig config
    6. public MOXyJsonContextResolver() {
    7. config = new MoxyJsonConfig().setIncludeRoot(true)
    8. }
    9. @Override
    10. public MoxyJsonConfig getContext(Class<?> objectType) {
    11. return config
    12. }
    13. }

  • Why JacksonJsonProvider ignores MediaType's parameters?

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @Path("/rest/api/issue")

  • Why JacksonJsonProvider ignores MediaType's parameters?

    if you have and you would like to add a different implementation of the same endpoint you would add a new piece to the path Where version is whatever version of the api you're choosing. Atlassian's JIRA API does things in this way Also using the built-in constants for media types is good form . details

    Reactions - Positive 1, Negative 1, Others 0

    1. @GET @Path("/rest/api/2/issue") @Produces(MediaType.APPLICATION_JSON)

    Positive Reactions
    1. Hi, thanks for your comment.
    Negative Reactions
    1. I watched [REST+JSON API Design - Best Practices for Developers]( URL_http://www.youtube.com/watch?feature=player_detailpage&v=hdSrT 4yjS1g#t=1947) by Stormpath and they suggest to use the header's metadata to distinguish between the API Versions.I never thought this approach would be so hard to realize...
    Other Reactions
    1. Creating a new endpoint is ok but in my opinion hiding the information what API version to use in the HTTP header as metadata is a neat solution.

  • Why JacksonJsonProvider ignores MediaType's parameters?

    I.e. if you have and you would like to add a different implementation of the same endpoint you would add a new piece to the path Where version is whatever version of the api you're choosing. details

    Reactions - Positive 1, Negative 1, Others 0

    1. @Path("/rest/api/{version}/issue")

    Positive Reactions
    1. Hi, thanks for your comment.
    Negative Reactions
    1. I watched [REST+JSON API Design - Best Practices for Developers]( URL_http://www.youtube.com/watch?feature=player_detailpage&v=hdSrT 4yjS1g#t=1947) by Stormpath and they suggest to use the header's metadata to distinguish between the API Versions.I never thought this approach would be so hard to realize...
    Other Reactions
    1. Creating a new endpoint is ok but in my opinion hiding the information what API version to use in the HTTP header as metadata is a neat solution.

  • 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. }

  • Returni