/
media.xml
1893 lines (1580 loc) · 89.3 KB
/
media.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" standalone="no"?>
<!--
Copyright (c) 2012, 2023 Oracle and/or its affiliates. All rights reserved.
This program and the accompanying materials are made available under the
terms of the Eclipse Public License v. 2.0, which is available at
http://www.eclipse.org/legal/epl-2.0.
This Source Code may also be made available under the following Secondary
Licenses when the conditions for such availability set forth in the
Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
version 2 with the GNU Classpath Exception, which is available at
https://www.gnu.org/software/classpath/license.html.
SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
-->
<!DOCTYPE chapter [
<!ENTITY link.moxy "<link linkend='json.moxy'>MOXy</link>" >
<!ENTITY link.json-p "<link linkend='json.json-p'>Java API for JSON Processing (JSON-P)</link>" >
<!ENTITY link.jackson "<link linkend='json.jackson'>Jackson</link>" >
<!ENTITY link.jettison "<link linkend='json.jettison'>Jettison</link>" >
<!ENTITY link.json-b "<link linkend='json.json-b'>Java API for JSON Binding (JSON-B)</link>" >
<!ENTITY % ents SYSTEM "jersey.ent" > %ents;
]>
<chapter xmlns="http://docbook.org/ns/docbook"
version="5.0"
xml:lang="en"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xlink="http://www.w3.org/1999/xlink"
xsi:schemaLocation="http://docbook.org/ns/docbook http://docbook.org/xml/5.0/xsd/docbook.xsd
http://www.w3.org/1999/xlink http://www.w3.org/1999/xlink.xsd"
xml:id="media">
<title>Support for Common Media Type Representations</title>
<section xml:id="json">
<title>JSON</title>
<para>
Jersey JSON support comes as a set of extension modules where each of these modules contains an implementation of
a &jaxrs.core.Feature; that needs to be registered into your &jaxrs.core.Configurable; instance (client/server).
There are multiple frameworks that provide support for JSON processing and/or JSON-to-Java binding.
The modules listed below provide support for JSON representations by integrating the individual JSON frameworks into
Jersey. At present, Jersey integrates with the following modules to provide JSON support:
<itemizedlist>
<listitem>
<para>
&link.moxy; - JSON binding support via MOXy is a default and preferred way of supporting JSON binding
in your Jersey applications since Jersey 2.0. When JSON MOXy module is on the class-path, Jersey will
automatically discover the module and seamlessly enable JSON binding support via MOXy in your
applications. (See <xref linkend="deployment.autodiscoverable" />.)
</para>
</listitem>
<listitem>
<para>&link.json-p;</para>
</listitem>
<listitem>
<para>&link.jackson;</para>
</listitem>
<listitem>
<para>&link.jettison;</para>
</listitem>
<listitem>
<para>&link.json-b;</para>
</listitem>
</itemizedlist>
</para>
<section>
<title>Approaches to JSON Support</title>
<para>
Each of the aforementioned extension modules uses one or more of the three basic approaches available when
working with JSON representations:
<itemizedlist>
<listitem>
<para>POJO based JSON binding support</para>
</listitem>
<listitem>
<para>JAXB based JSON binding support</para>
</listitem>
<listitem>
<para>Low-level JSON parsing & processing support</para>
</listitem>
</itemizedlist>
The first method is pretty generic and allows you to map any Java Object to JSON and vice versa.
The other two approaches limit you in Java types your resource methods could produce and/or consume.
JAXB based approach is useful if you plan to utilize certain JAXB features and support both XML and JSON
representations. The last, low-level, approach gives you the best fine-grained control over the out-coming
JSON data format.
</para>
<section xml:id="json-pojo">
<title>POJO support</title>
<para>POJO support represents the easiest way to convert your Java Objects to JSON and back.</para>
<para>Media modules that support this approach are &link.moxy;, &link.jackson;, and &link.json-b;</para>
</section>
<section xml:id="json-jaxb">
<title>JAXB based JSON support</title>
<para>
Taking this approach will save you a lot of time, if you want to easily produce/consume both JSON and XML
data format. With JAXB beans you will be able to use the same Java model to generate JSON as well as XML
representations.
Another advantage is simplicity of working with such a model and availability of the API in Java SE Platform.
JAXB leverages annotated POJOs and these could be handled as simple Java beans.
</para>
<para>
A disadvantage of JAXB based approach could be if you need to work with a very specific JSON format. Then it
might be difficult to find a proper way to get such a format produced and consumed. This is a reason why a
lot of configuration options are provided, so that you can control how JAXB beans get serialized and
de-serialized. The extra configuration options however requires you to learn more details about the framework
you are using.
</para>
<para>
Following is a very simple example of how a JAXB bean could look like.
<example>
<title>Simple JAXB bean implementation</title>
<programlisting language="java" linenumbering="numbered">@XmlRootElement
public class MyJaxbBean {
public String name;
public int age;
public MyJaxbBean() {} // JAXB needs this
public MyJaxbBean(String name, int age) {
this.name = name;
this.age = age;
}
}</programlisting>
</example>
Using the above JAXB bean for producing JSON data format from you resource method, is then as simple as:
<example>
<title>JAXB bean used to generate JSON representation</title>
<programlisting language="java" linenumbering="numbered">@GET
@Produces("application/json")
public MyJaxbBean getMyBean() {
return new MyJaxbBean("Agamemnon", 32);
}</programlisting>
</example>
Notice, that JSON specific mime type is specified in &lit.jaxrs.Produces; annotation, and the method returns
an instance of <literal>MyJaxbBean</literal>, which JAXB is able to process. Resulting JSON in this case
would look like:
<programlisting language="text" linenumbering="unnumbered">{"name":"Agamemnon", "age":"32"}</programlisting>
</para>
<para>
A proper use of JAXB annotations itself enables you to control output JSON format to certain extent.
Specifically, renaming and omitting items is easy to do directly just by using JAXB annotations.
For example, the following example depicts changes in the above mentioned MyJaxbBean that will result in
<literal>{"king":"Agamemnon"}</literal> JSON output.
<example>
<title>Tweaking JSON format using JAXB</title>
<programlisting language="java" linenumbering="numbered">@XmlRootElement
public class MyJaxbBean {
@XmlElement(name="king")
public String name;
@XmlTransient
public int age;
// several lines removed
}</programlisting>
</example>
</para>
<para>Media modules that support this approach are &link.moxy;, &link.jackson;, &link.jettison;</para>
</section>
<section xml:id="json-lowlevel">
<title>Low-level based JSON support</title>
<para>
JSON Processing API is a new standard API for parsing and processing JSON structures in similar way to what
SAX and StAX parsers provide for XML. The API is part of Java EE 7 and later (including Jakarta EE 8).
Another such JSON parsing/processing API is provided by Jettison framework. Both APIs provide a low-level
access to producing and consuming JSON data structures. By adopting this low-level approach you would
be working with
<literal>JsonObject</literal> (or <literal>JSONObject</literal> respectively) and/or
<literal>JsonArray</literal> (or <literal>JSONArray</literal> respectively) classes when processing your
JSON data representations.
</para>
<para>
The biggest advantage of these low-level APIs is that you will gain full control over the JSON format
produced and consumed. You will also be able to produce and consume very large JSON structures using
streaming JSON parser/generator APIs.
On the other hand, dealing with your data model objects will probably be a lot more complex, compared
to the POJO or JAXB based binding approach. Differences are depicted at the following code snippets.
</para>
<para>
Let's start with JAXB-based approach.
<example>
<title>JAXB bean creation</title>
<programlisting language="java" linenumbering="numbered">MyJaxbBean myBean = new MyJaxbBean("Agamemnon", 32);</programlisting>
</example>
Above you construct a simple JAXB bean, which could be written in JSON as
<literal>{"name":"Agamemnon", "age":32}</literal>
</para>
<para>
Now to build an equivalent <literal>JsonObject</literal>/<literal>JSONObject</literal> (in terms of
resulting JSON expression), you would need several more lines of code. The following example illustrates
how to construct the same JSON data using the standard Jakarta EE 8 JSON-Processing API.
<example>
<title>Constructing a <literal>JsonObject</literal> (JSON-Processing)</title>
<programlisting language="java" linenumbering="numbered">JsonObject myObject = Json.createObjectBuilder()
.add("name", "Agamemnon")
.add("age", 32)
.build();</programlisting>
</example>
And at last, here's how the same work can be done with Jettison API.
<example>
<title>Constructing a <literal>JSONObject</literal> (Jettison)</title>
<programlisting language="java" linenumbering="numbered">JSONObject myObject = new JSONObject();
try {
myObject.put("name", "Agamemnon");
myObject.put("age", 32);
} catch (JSONException ex) {
LOGGER.log(Level.SEVERE, "Error ...", ex);
}</programlisting>
</example>
</para>
<para>
Media modules that support the low-level JSON parsing and generating approach are &link.json-p;
and &link.jettison;. Unless you have a strong reason for using the non-standard &link.jettison; API,
we recommend you to use the new standard &link.json-p; API instead.
</para>
</section>
</section>
<section xml:id="json.moxy">
<title>MOXy</title>
<section>
<title>Dependency</title>
<para>
To use MOXy as your JSON provider you need to add &lit.jersey-media-moxy; module to your &lit.pom.xml; file:
<programlisting language="xml" linenumbering="unnumbered"><dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>&version;</version>
</dependency></programlisting>
If you're not using Maven make sure to have all needed dependencies (see &jersey.media.moxy.deps.link;) on the classpath.
</para>
</section>
<section xml:id="moxy-registration">
<title>Configure and register</title>
<para>
As stated in the <xref linkend="deployment.autodiscoverable"/> as well as earlier in this chapter, MOXy media
module is one of the modules where you don't need to explicitly register its &lit.jaxrs.core.Feature;s
(&lit.jersey.media.MoxyJsonFeature;) in your client/server &jaxrs.core.Configurable; as this feature is
automatically discovered and registered when you add &lit.jersey-media-moxy; module to your class-path.
</para>
<para>
The auto-discoverable &lit.jersey-media-moxy; module defines a few properties that can be used to control the
automatic registration of &lit.jersey.media.MoxyJsonFeature; (besides the generic
&jersey.common.CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE; an the its client/server variants):
<itemizedlist>
<listitem>
<para>&jersey.common.CommonProperties.MOXY_JSON_FEATURE_DISABLE;</para>
</listitem>
<listitem>
<para>&jersey.server.ServerProperties.MOXY_JSON_FEATURE_DISABLE;</para>
</listitem>
<listitem>
<para>&jersey.client.ClientProperties.MOXY_JSON_FEATURE_DISABLE;</para>
</listitem>
</itemizedlist>
</para>
<note>
<para>
A manual registration of any other Jersey JSON provider feature (except for &link.json-p;)
disables the automated enabling and configuration of &lit.jersey.media.MoxyJsonFeature;.
</para>
</note>
<para>
To configure &jaxrs.ext.MessageBodyReader;s / &jaxrs.ext.MessageBodyWriter;s provided by MOXy you can simply
create an instance of &jersey.media.MoxyJsonConfig; and set values of needed properties. For most common
properties you can use a particular method to set the value of the property or you can use more generic
methods to set the property:
<itemizedlist>
<listitem>
<para>
&jersey.media.MoxyJsonConfig.property; - sets a property value for both Marshaller and Unmarshaller.
</para>
</listitem>
<listitem>
<para>
&jersey.media.MoxyJsonConfig.marshallerProperty; - sets a property value for Marshaller.
</para>
</listitem>
<listitem>
<para>
&jersey.media.MoxyJsonConfig.unmarshallerProperty; - sets a property value for Unmarshaller.
</para>
</listitem>
</itemizedlist>
<example>
<title>&jersey.media.MoxyJsonConfig; - Setting properties.</title>
<programlisting language="java">final Map<String, String> namespacePrefixMapper = new HashMap<String, String>();
namespacePrefixMapper.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");
final MoxyJsonConfig configuration = new MoxyJsonConfig()
.setNamespacePrefixMapper(namespacePrefixMapper)
.setNamespaceSeparator(':');
</programlisting>
</example>
In order to make &lit.jersey.media.MoxyJsonConfig; visible for MOXy you need to create and register
&lit.jaxrs.ext.ContextResolver; in your client/server code.
<example>
<title>Creating <literal>ContextResolver<MoxyJsonConfig></literal></title>
<programlisting language="java">final Map<String, String> namespacePrefixMapper = new HashMap<String, String>();
namespacePrefixMapper.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");
final MoxyJsonConfig moxyJsonConfig = MoxyJsonConfig()
.setNamespacePrefixMapper(namespacePrefixMapper)
.setNamespaceSeparator(':');
final ContextResolver<MoxyJsonConfig> jsonConfigResolver = moxyJsonConfig.resolver();
</programlisting>
</example>
</para>
<para>
Another way to pass configuration properties to the underlying <literal>MOXyJsonProvider</literal> is to set
them directly into your &jaxrs.core.Configurable; instance (see an example below). These are overwritten by
properties set into the &jersey.media.MoxyJsonConfig;.
<example>
<title>Setting properties for MOXy providers into &jaxrs.core.Configurable;</title>
<programlisting language="java">new ResourceConfig()
.property(MarshallerProperties.JSON_NAMESPACE_SEPARATOR, ".")
// further configuration</programlisting>
</example>
</para>
<para>
There are some properties for which Jersey sets the default value when
&jaxrs.ext.MessageBodyReader; / &jaxrs.ext.MessageBodyWriter; from MOXy is used and they are:
<table frame="all">
<title>Default property values for MOXy &jaxrs.ext.MessageBodyReader; / &jaxrs.ext.MessageBodyWriter;</title>
<tgroup cols="2" align="left">
<tbody>
<row>
<entry><literal>javax.xml.bind.Marshaller#JAXB_FORMATTED_OUTPUT</literal></entry>
<entry><literal>false</literal></entry>
</row>
<row>
<entry>
<literal>org.eclipse.persistence.jaxb.JAXBContextProperties#JSON_INCLUDE_ROOT</literal>
</entry>
<entry><literal>false</literal></entry>
</row>
<row>
<entry>
<literal>org.eclipse.persistence.jaxb.MarshallerProperties#JSON_MARSHAL_EMPTY_COLLECTIONS</literal>
</entry>
<entry><literal>true</literal></entry>
</row>
<row>
<entry>
<literal>org.eclipse.persistence.jaxb.JAXBContextProperties#JSON_NAMESPACE_SEPARATOR</literal>
</entry>
<entry><literal>org.eclipse.persistence.oxm.XMLConstants#DOT</literal></entry>
</row>
</tbody>
</tgroup>
</table>
</para>
<example xml:id="ex-moxy-client">
<title>Building client with MOXy JSON feature enabled.</title>
<programlisting language="java">final Client client = ClientBuilder.newBuilder()
// The line below that registers MOXy feature can be
// omitted if FEATURE_AUTO_DISCOVERY_DISABLE is
// not disabled.
.register(MoxyJsonFeature.class)
.register(jsonConfigResolver)
.build();</programlisting>
</example>
<example xml:id="ex-moxy-server">
<title>Creating JAX-RS application with MOXy JSON feature enabled.</title>
<programlisting language="java">// Create JAX-RS application.
final Application application = new ResourceConfig()
.packages("org.glassfish.jersey.examples.jsonmoxy")
// The line below that registers MOXy feature can be
// omitted if FEATURE_AUTO_DISCOVERY_DISABLE is
// not disabled.
.register(MoxyJsonFeature.class)
.register(jsonConfigResolver);</programlisting>
</example>
</section>
<section>
<title>Examples</title>
<para>
Jersey provides a <link xlink:href='&jersey.github.examples.uri;/json-moxy'>JSON MOXy example</link>
on how to use MOXy to consume/produce JSON.
</para>
</section>
</section>
<section xml:id="json.json-p">
<title>Java API for JSON Processing (JSON-P)</title>
<section>
<title>Dependency</title>
<para>
To use JSON-P as your JSON provider you need to add &lit.jersey-media-json-processing; module to your
&lit.pom.xml; file:
<programlisting language="xml" linenumbering="unnumbered"><dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
<version>&version;</version>
</dependency></programlisting>
If you're not using Maven make sure to have all needed dependencies (see &jersey.media.json-processing.deps.link;)
on the class-path.
</para>
</section>
<section xml:id="jsonp-registration">
<title>Configure and register</title>
<para>
As stated in <xref linkend="deployment.autodiscoverable"/> JSON-Processing media module is one of the
modules where you don't need to explicitly register its
&lit.jaxrs.core.Feature;s (&lit.jersey.media.JsonProcessingFeature;) in your client/server
&jaxrs.core.Configurable; as this feature is automatically discovered and registered when you add
&lit.jersey-media-json-processing; module to your classpath.
</para>
<para>
As for the other modules, &lit.jersey-media-json-processing; has also few properties that can affect the
registration of &lit.jersey.media.JsonProcessingFeature;
(besides &jersey.common.CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE; and the like):
<itemizedlist>
<listitem>
<para>&jersey.common.CommonProperties.JSON_PROCESSING_FEATURE_DISABLE;</para>
</listitem>
<listitem>
<para>&jersey.server.ServerProperties.JSON_PROCESSING_FEATURE_DISABLE;</para>
</listitem>
<listitem>
<para>&jersey.client.ClientProperties.JSON_PROCESSING_FEATURE_DISABLE;</para>
</listitem>
</itemizedlist>
</para>
<para>
To configure &jaxrs.ext.MessageBodyReader;s / &jaxrs.ext.MessageBodyWriter;s provided by JSON-P you can simply
add values for supported properties into the &jaxrs.core.Configuration; instance (client/server). Currently
supported are these properties:
<itemizedlist>
<listitem>
<para>
<literal>JsonGenerator.PRETTY_PRINTING</literal>
("<literal>javax.json.stream.JsonGenerator.prettyPrinting</literal>")
</para>
</listitem>
</itemizedlist>
</para>
<example>
<title>Building client with JSON-Processing JSON feature enabled.</title>
<programlisting language="java">ClientBuilder.newClient(new ClientConfig()
// The line below that registers JSON-Processing feature can be
// omitted if FEATURE_AUTO_DISCOVERY_DISABLE is not disabled.
.register(JsonProcessingFeature.class)
.property(JsonGenerator.PRETTY_PRINTING, true)
);</programlisting>
</example>
<example>
<title>Creating JAX-RS application with JSON-Processing JSON feature enabled.</title>
<programlisting language="java">// Create JAX-RS application.
final Application application = new ResourceConfig()
// The line below that registers JSON-Processing feature can be
// omitted if FEATURE_AUTO_DISCOVERY_DISABLE is not disabled.
.register(JsonProcessingFeature.class)
.packages("org.glassfish.jersey.examples.jsonp")
.property(JsonGenerator.PRETTY_PRINTING, true);</programlisting>
</example>
</section>
<section>
<title>Examples</title>
<para>Jersey provides a
<link xlink:href='&jersey.github.examples.uri;/json-processing-webapp'>JSON Processing example</link>
on how to use JSON-Processing to consume/produce JSON.</para>
</section>
</section>
<section xml:id="json.jackson">
<title>Jackson (1.x and 2.x)</title>
<section>
<title>Dependency</title>
<para>
To use Jackson 2.x as your JSON provider you need to add &lit.jersey-media-json-jackson; module to your
&lit.pom.xml; file:
<programlisting language="xml" linenumbering="unnumbered"><dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>&version;</version>
</dependency></programlisting>
To use Jackson 1.x it'll look like:
<programlisting language="xml" linenumbering="unnumbered"><dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson1</artifactId>
<version>&version;</version>
</dependency></programlisting>
If you're not using Maven make sure to have all needed dependencies (see &jersey.media.json-jackson.deps.link; or
&jersey.media.json-jackson1.deps.link;) on the classpath.
</para>
</section>
<section xml:id="jackson-registration">
<title>Configure and register</title>
<note>
<para>
Note that there is a difference in namespaces between Jackson 1.x (<literal>org.codehaus.jackson</literal>)
and Jackson 2.x (<literal>com.fasterxml.jackson</literal>).
</para>
</note>
<para>
Jackson JSON processor could be controlled via providing a custom Jackson 2 &jersey.media.ObjectMapper; (or
&jersey.media.ObjectMapper1; for Jackson 1) instance.
This could be handy if you need to redefine the default Jackson behaviour and to fine-tune how your JSON data
structures look like. Detailed description of all Jackson features is out of scope of this guide. The example
below gives you a hint on how to wire your &lit.jersey.media.ObjectMapper; (&jersey.media.ObjectMapper1;)
instance into your Jersey application.
</para>
<para>
Since the 2.36 version of Jersey it is possible to filter (include/exclude) Jackson modules by properties
&jersey.common.CommonProperties.JSON_JACKSON_DISABLED_MODULES; and &jersey.common.CommonProperties.JSON_JACKSON_ENABLED_MODULES;
(with their client/server derivatives). If the &jersey.common.CommonProperties.JSON_JACKSON_ENABLED_MODULES; property is used,
only those named modules will be used for JSON processing. On the other hand if the &jersey.common.CommonProperties.JSON_JACKSON_DISABLED_MODULES;
property is used, those listed modules will be explicitly excluded from processing while other (not listed) will remain. Please note that
the <literal>JaxbAnnotationModule</literal> module is always excluded from processing and this is not configurable.
</para>
<para>
In order to use Jackson as your JSON (JAXB/POJO) provider you need to register &jersey.media.JacksonFeature;
(&jersey.media.Jackson1Feature;) and a &lit.jaxrs.ext.ContextResolver; for &lit.jersey.media.ObjectMapper;,
if needed, in your &jaxrs.core.Configurable; (client/server).
<example>
<title><literal>ContextResolver<ObjectMapper></literal></title>
<programlisting language="java" linenumbering="numbered">@Provider
public class MyObjectMapperProvider implements ContextResolver<ObjectMapper> {
final ObjectMapper defaultObjectMapper;
public MyObjectMapperProvider() {
defaultObjectMapper = createDefaultMapper();
}
@Override
public ObjectMapper getContext(Class<?> type) {
return defaultObjectMapper;
}
}
private static ObjectMapper createDefaultMapper() {
final ObjectMapper result = new ObjectMapper();
result.configure(Feature.INDENT_OUTPUT, true);
return result;
}
// ...
}</programlisting>
<para>To view the complete example source code, see
<link xlink:href='&jersey.github.examples.uri;/json-jackson/src/main/java/org/glassfish/jersey/examples/jackson/MyObjectMapperProvider.java'>
MyObjectMapperProvider</link> class from the
<link xlink:href='&jersey.github.examples.uri;/json-jackson'>JSON-Jackson</link> example.</para>
</example>
<example>
<title>Building client with Jackson JSON feature enabled.</title>
<programlisting language="java" linenumbering="numbered">final Client client = ClientBuilder.newBuilder()
.register(MyObjectMapperProvider.class) // No need to register this provider if no special configuration is required.
.register(JacksonFeature.class)
.build();</programlisting>
</example>
<example>
<title>Creating JAX-RS application with Jackson JSON feature enabled.</title>
<programlisting language="java" linenumbering="numbered">// Create JAX-RS application.
final Application application = new ResourceConfig()
.packages("org.glassfish.jersey.examples.jackson")
.register(MyObjectMapperProvider.class) // No need to register this provider if no special configuration is required.
.register(JacksonFeature.class);</programlisting>
</example>
</para>
</section>
<section>
<title>Examples</title>
<para>
Jersey provides <link xlink:href='&jersey.github.examples.uri;/json-jackson'>JSON Jackson (2.x) example</link>
and <link xlink:href='&jersey.github.examples.uri;/json-jackson1'>JSON Jackson (1.x) example</link> showing
how to use Jackson to consume/produce JSON.
</para>
</section>
</section>
<section xml:id="json.jettison">
<title>Jettison</title>
<para>
JAXB approach for (de)serializing JSON in Jettison module provides, in addition to using pure JAXB,
configuration options that could be set on an &jersey.media.JettisonConfig; instance. The instance could be then
further used to create a &jersey.media.JettisonJaxbContext;, which serves as a main configuration point in this
area.
To pass your specialized &lit.jersey.media.JettisonJaxbContext; to Jersey, you will finally need to implement
a JAXBContext &jaxrs.ext.ContextResolver; (see below).
</para>
<section>
<title>Dependency</title>
<para>
To use Jettison as your JSON provider you need to add &lit.jersey-media-json-jettison; module to your
&lit.pom.xml; file:
<programlisting language="xml" linenumbering="unnumbered"><dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jettison</artifactId>
<version>&version;</version>
</dependency></programlisting>
If you're not using Maven make sure to have all needed dependencies (see &jersey.media.json-jettison.deps.link;) on
the classpath.
</para>
</section>
<section>
<title>JSON Notations</title>
<para>
&lit.jersey.media.JettisonConfig; allows you to use two JSON notations. Each of these notations serializes
JSON in a different way. Following is a list of supported notations:
<itemizedlist>
<listitem>
<para>JETTISON_MAPPED (default notation)</para>
</listitem>
<listitem>
<para>BADGERFISH</para>
</listitem>
</itemizedlist>
You might want to use one of these notations, when working with more complex XML documents. Namely when you
deal with multiple XML namespaces in your JAXB beans.
</para>
<para>
Individual notations and their further configuration options are described below. Rather then explaining
rules for mapping XML constructs into JSON, the notations will be described using a simple example. Following
are JAXB beans, which will be used.
<example>
<title>JAXB beans for JSON supported notations description, simple address bean</title>
<programlisting language="java" linenumbering="numbered">@XmlRootElement
public class Address {
public String street;
public String town;
public Address(){}
public Address(String street, String town) {
this.street = street;
this.town = town;
}
}</programlisting>
</example>
<example>
<title>JAXB beans for JSON supported notations description, contact bean</title>
<programlisting language="java" linenumbering="numbered">@XmlRootElement
public class Contact {
public int id;
public String name;
public List<Address> addresses;
public Contact() {};
public Contact(int id, String name, List<Address> addresses) {
this.name = name;
this.id = id;
this.addresses =
(addresses != null) ? new LinkedList<Address>(addresses) : null;
}
}</programlisting>
</example>
</para>
<para>
Following text will be mainly working with a contact bean initialized with:
<example>
<title>JAXB beans for JSON supported notations description, initialization</title>
<programlisting language="java" linenumbering="numbered">Address[] addresses = {new Address("Long Street 1", "Short Village")};
Contact contact = new Contact(2, "Bob", Arrays.asList(addresses));</programlisting>
</example>
I.e. contact bean with <literal>id=2</literal>, <literal>name="Bob"</literal> containing
a single address (<literal>street="Long Street 1"</literal>, <literal>town="Short Village"</literal>).
</para>
<para>
All below described configuration options are documented also in api-docs at &jersey.media.JettisonConfig;.
</para>
<section>
<title>Jettison mapped notation</title>
<para>
If you need to deal with various XML namespaces, you will find Jettison <literal>mapped</literal>
notation pretty useful. Lets define a particular namespace for <code>id</code> item:
<programlisting language="java" linenumbering="numbered">...
@XmlElement(namespace="http://example.com")
public int id;
...</programlisting>
Then you simply configure a mapping from XML namespace into JSON prefix as follows:
<example xml:id="json.jaxb.jettison.mapped.ns.def">
<title>
XML namespace to JSON mapping configuration for Jettison based <literal>mapped</literal> notation
</title>
<programlisting language="java" linenumbering="numbered">Map<String,String> ns2json = new HashMap<String, String>();
ns2json.put("http://example.com", "example");
context = new JettisonJaxbContext(
JettisonConfig.mappedJettison().xml2JsonNs(ns2json).build(),
types);</programlisting>
</example>
Resulting JSON will look like in the example below.
<example>
<title>JSON expression with XML namespaces mapped into JSON</title>
<programlisting language="xml" linenumbering="numbered">{
"contact":{
"example.id":2,
"name":"Bob",
"addresses":{
"street":"Long Street 1",
"town":"Short Village"
}
}
}</programlisting>
</example>
Please note, that <code>id</code> item became <code>example.id</code> based on the XML namespace mapping.
If you have more XML namespaces in your XML, you will need to configure appropriate mapping for all of
them.
</para>
<para>
Another configurable option introduced in Jersey version 2.2 is related to serialization of JSON arrays with Jettison's
mapped notation. When serializing elements representing single item lists/arrays, you might want to utilise
the following Jersey configuration method to explicitly name which elements to treat as arrays no matter what the actual content is.
<example xml:id="json.jaxb.jettison.mapped.array.def">
<title>
JSON Array configuration for Jettison based <literal>mapped</literal> notation
</title>
<programlisting language="java" linenumbering="numbered">context = new JettisonJaxbContext(
JettisonConfig.mappedJettison().serializeAsArray("name").build(),
types);</programlisting>
</example>
Resulting JSON will look like in the example below, unimportant lines removed for sanity.
<example>
<title>JSON expression with JSON arrays explicitly configured via Jersey</title>
<programlisting language="xml" linenumbering="numbered">{
"contact":{
...
"name":["Bob"],
...
}
}</programlisting>
</example>
</para>
</section>
<section>
<title>Badgerfish notation</title>
<para>
From JSON and JavaScript perspective, this notation is definitely the worst readable one.
You will probably not want to use it, unless you need to make sure your JAXB beans could be flawlessly
written and read back to and from JSON, without bothering with any formatting configuration, namespaces,
etc.
</para>
<para>
&lit.jersey.media.JettisonConfig; instance using <literal>badgerfish</literal> notation could be built
with
<programlisting language="java">JettisonConfig.badgerFish().build()</programlisting>
and the JSON output JSON will be as follows.
<example>
<title>JSON expression produced using <literal>badgerfish</literal> notation</title>
<programlisting language="xml" linenumbering="numbered">{
"contact":{
"id":{
"$":"2"
},
"name":{
"$":"Bob"
},
"addresses":{
"street":{
"$":"Long Street 1"
},
"town":{
"$":"Short Village"
}
}
}
}</programlisting>
</example>
</para>
</section>
</section>
<section xml:id="jettison-registration">
<title>Configure and register</title>
<para>
In order to use Jettison as your JSON (JAXB/POJO) provider you need to register &jersey.media.JettisonFeature;
and a &lit.jaxrs.ext.ContextResolver; for &lit.jaxb.JAXBContext; (if needed) in your &jaxrs.core.Configurable;
(client/server).
<example>
<title><literal>ContextResolver<ObjectMapper></literal></title>
<programlisting language="java">@Provider
public class JaxbContextResolver implements ContextResolver<JAXBContext> {
private final JAXBContext context;
private final Set<Class<?>> types;
private final Class<?>[] cTypes = {Flights.class, FlightType.class, AircraftType.class};
public JaxbContextResolver() throws Exception {
this.types = new HashSet<Class<?>>(Arrays.asList(cTypes));
this.context = new JettisonJaxbContext(JettisonConfig.DEFAULT, cTypes);
}
@Override
public JAXBContext getContext(Class<?> objectType) {
return (types.contains(objectType)) ? context : null;
}
}</programlisting>
</example>
<example>
<title>Building client with Jettison JSON feature enabled.</title>
<programlisting language="java">final Client client = ClientBuilder.newBuilder()
.register(JaxbContextResolver.class) // No need to register this provider if no special configuration is required.
.register(JettisonFeature.class)
.build();</programlisting>
</example>
<example>
<title>Creating JAX-RS application with Jettison JSON feature enabled.</title>
<programlisting language="java">// Create JAX-RS application.
final Application application = new ResourceConfig()
.packages("org.glassfish.jersey.examples.jettison")
.register(JaxbContextResolver.class) // No need to register this provider if no special configuration is required.
.register(JettisonFeature.class);</programlisting>
</example>
</para>
</section>
<section>
<title>Examples</title>
<para>
Jersey provides an <link xlink:href='&jersey.github.examples.uri;/json-jettison'>JSON Jettison example</link>
on how to use Jettison to consume/produce JSON.
</para>
</section>
</section>
<section>
<title><literal>@JSONP</literal> - JSON with Padding Support</title>
<para>
Jersey provides out-of-the-box support for <link xlink:href='&wikipedia.uri;JSONP'>JSONP</link>
- JSON with padding. The following conditions has to be met to take advantage of this capability:
<itemizedlist>
<listitem>
<para>
Resource method, which should return wrapped JSON, needs to be annotated with &jersey.server.JSONP;
annotation.
</para>
</listitem>
<listitem>
<para>
&jaxrs.ext.MessageBodyWriter; for <literal>application/json</literal> media type, which also accepts
the return type of the resource method, needs to be registered (see <link linkend="json">JSON</link>
section of this chapter).
</para>
</listitem>
<listitem>
<para>
User's request has to contain &lit.http.header.Accept; header with one of the JavaScript media types
defined (see below).
</para>
</listitem>
</itemizedlist>
Acceptable media types compatible with &lit.jersey.server.JSONP; are: <literal>application/javascript</literal>,
<literal>application/x-javascript</literal>, <literal>application/ecmascript</literal>,
<literal>text/javascript</literal>, <literal>text/x-javascript</literal>, <literal>text/ecmascript</literal>,
<literal>text/jscript</literal>.
<example>
<title>Simplest case of using &lit.jersey.server.JSONP;</title>
<programlisting language="java">@GET
@JSONP
@Produces({"application/json", "application/javascript"})
public JaxbBean getSimpleJSONP() {
return new JaxbBean("jsonp");
}</programlisting>
</example>
Assume that we have registered a JSON providers and that the <literal>JaxbBean</literal> looks like:
<example>
<title>JaxbBean for @JSONP example</title>