One of the things I'm trying to do is output a pojo as json. The class involved looks something like
When I look at a MyClass instance converted to json, I don't see creationThread as a field, unless I also provide a setter. But, for my purposes, it makes no sense to provide a setter. The field is supposed to be read only.
As far as I know, the ability to convert java objects into json is provided somehow by jersey-media-moxy-2.16.jar.
For read-only object members, am I required to provide a do-nothing setter to make pojo -> json work?
Is there some way of experimenting with the pojo -> json capability of that jar, with a simple command line app, without all the added complication of Tomcat & a browser?
An alternative I often use is adding protected setters. That satisfies the needs of the marshalling framework (whatever it may be), but still makes it impossible for classes in a different package to access them.
Stephan van Hulst wrote:You should be using JAX-B to annotate your serializable properties. Jackson understands JAX-B and will serialize the properties as JSON. In the Jersey manual there is a section on which dependencies to add to enable serialization through Jackson. You don't need Moxy.
I'm unclear as to roles played by these various technologies, so please excuse me if these questions don't entirely make sense
What's the advantage of using Jackson over Moxy? The Maven jersey-quickstart-webapp comes with with a jersey-media-moxy dependency already in place, but commented out, in pom.xml. Also,
Jersey User Guide wrote: JSON binding support via MOXy is a default and preferred way of supporting JSON binding in your Jersey applications since Jersey 2.0
I did try adding a dependency in pom.xml,
which if I understood you right, was your suggestion. However I ended up throwing a java.lang.UnsupportedClassVersionError caused by, I think deploying a jar compiled for java 8 to Tomcat running java 7. So, I'd then somehow have to discover what previous version of Jackson used Java 7.
Anyway, you use JAXB annotations to define the serialized format of your data objects. When you have declared a dependency on Moxy in your POM, Jersey will use Moxy to interpret these annotations and serialize your objects to either XML or JSON, depending on the content types that your controller produces.
You can use JAXB annotations without declaring any additional dependencies if you're in a Java EE web application container.
Problem is solved and it was easier than I'd been supposing!
I found that if I explicitly annotate a getter that has no corresponding setter, rather than just rely on the default behavior, I do indeed get read only fields appearing in the resulting json.