├── .gitignore ├── LICENSE ├── README.md ├── pom.xml ├── release.properties └── src ├── main └── java │ └── com │ └── colobu │ └── fastjson │ ├── FastJsonConfig.java │ ├── FastJsonProvider.java │ ├── FastJsonType.java │ └── IOUtils.java └── test └── java └── com └── colobu ├── fastjson ├── ClassDefinitionFastJsonProviderTest.java ├── FastJsonFeature.java ├── FastJsonProviderTest.java └── User.java └── test └── Teacher.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .settings 3 | .classpath 4 | .project 5 | *.iml 6 | *.log* 7 | *.swp 8 | target 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | fastjson-jaxrs-json-provider 2 | ============================ 3 | 4 | A JAX-RS entity provider for [fastjson](https://github.com/alibaba/fastjson) 5 | 6 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.colobu/fastjson-jaxrs-json-provider/badge.svg)](https://github.com/smallnest/fastjson-jaxrs-json-provider) 7 | [![Drone Build Status](https://drone.io/github.com/smallnest/fastjson-jaxrs-json-provider/status.png)](https://github.com/smallnest/fastjson-jaxrs-json-provider) 8 | 9 | 10 | ### What is JAXRS provider? 11 | Entity payload, if present in an received HTTP message, is passed to JAX-RS container as an input stream. The stream may, for example, contain data represented as a plain text, XML or JSON document. 12 | However, in many JAX-RS components that process these inbound data, such as resource methods or client responses, the JAX-RS API user can access the inbound entity as an arbitrary Java object that is created from the content of the input stream based on the representation type information. 13 | For example, an entity created from an input stream that contains data represented as a XML document, can be converted to a custom JAXB bean. 14 | Similar concept is supported for the outbound entities. An entity returned from the resource method in the form of an arbitrary Java object can be serialized by JAX-RS container into a container output stream as a specified representation. 15 | Of course, while JAX-RS implementations do provide default support for most common combinations of Java type and it's respective on-the-wire representation formats, 16 | JAX-RS implementations do not support the conversion described above for any arbitrary Java type and any arbitrary representation format by default. 17 | Instead, a generic extension concept is exposed in JAX-RS API to allow application-level customizations of this JAX-RS runtime to support for entity conversions. 18 | The JAX-RS extension API components that provide the user-level extensibility are typically referred to by several terms with the same meaning, such as entity providers, message body providers, message body workers or message body readers and writers. 19 | You may find all these terms used interchangeably throughout the user guide and they all refer to the same concept. 20 | 21 | In JAX-RS extension API (or SPI - service provider interface, if you like) the concept is captured in 2 interfaces. 22 | One for handling inbound entity representation-to-Java de-serialization - MessageBodyReader and the other one for handling the outbound entity Java-to-representation serialization - MessageBodyWriter. 23 | A MessageBodyReader, as the name suggests, is an extension that supports reading the message body representation from an input stream and converting the data into an instance of a specific Java type. 24 | A MessageBodyWriter is then responsible for converting a message payload from an instance of a specific Java type into a specific representation format that is sent over the wire to the other party as part of an HTTP message exchange. 25 | Both of these providers can be used to provide message payload serialization and de-serialization support on the server as well as the client side. 26 | A message body reader or writer is always used whenever a HTTP request or response contains an entity and the entity is either requested by the application code (e.g. injected as a parameter of JAX-RS resource method or a response entity read on the client from a Response) or has to be serialized and sent to the other party (e.g. an instance returned from a JAX-RS resource method or a request entity sent by a JAX-RS client). 27 | 28 | please read to learn how providers work. 29 | 30 | ### Introduction 31 | 32 | `FastJsonProvider` is a standard entity provider that follows JAX-RS 2.0 spec. 33 | According to different JAX-RS implementations such as CXF, Jersey, maybe you use `FastJsonProvider` in appropriate styles. 34 | `FastJsonProvider` can serialize/deserialize specific types including: 35 | * all types: `public FastJsonProvider()` (default constructor) 36 | * all type annotated with `FastJsonType`: `public FastJsonProvider(boolean annotated)` 37 | * all type annotated in specific packages : `public FastJsonProvider(String[] scanpackages)` 38 | * all type annotated in specific packages with `FastJsonType`: `public FastJsonProvider(String[] scanpackages, boolean annotated)` 39 | * all type in specific classes: `public FastJsonProvider(Class[] clazzes)` 40 | 41 | You can `init` this provider instance with a FastJsonConfig object which is used to configure FastJson features, SerializeConfig, ParserConfig and SerializeFilter. Any parameters can be null and will be default. 42 | 43 | #### Maven 44 | *stable version: 0.3.2* 45 | 46 | ``` 47 | 48 | com.colobu 49 | fastjson-jaxrs-json-provider 50 | 0.3.2 51 | 52 | ``` 53 | 54 | *snapshot version: 0.3.3-SNAPSHOT* 55 | ``` 56 | 57 | com.colobu 58 | fastjson-jaxrs-json-provider 59 | 0.3.3-SNAPSHOT 60 | 61 | ``` 62 | 63 | 64 | ### Jersey configuration 65 | Please check the test and maybe you need to create a FastJsonFeature to override MessageBodyReader and MessageBodyWriter. 66 | 67 | ### CXF confguration 68 | You can use JAXRSServerFactoryBean.setProviders to add a `FastJsonProvider` instance. 69 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | org.sonatype.oss 6 | oss-parent 7 | 7 8 | 9 | com.colobu 10 | fastjson-jaxrs-json-provider 11 | 0.3.3-SNAPSHOT 12 | jar 13 | fastjson-jaxrs-json-provider 14 | a JAX-RS entity provider for https://github.com/alibaba/fastjson 15 | https://github.com/smallnest/fastjson-jaxrs-json-provider/ 16 | 17 | colobu 18 | http://colobu.com 19 | 20 | 21 | 22 | smallnest 23 | smallnest 24 | smallnest@gmail.com 25 | 26 | 27 | 28 | GitHub 29 | http://github.com/smallnest/fastjson-jaxrs-json-provider/issues 30 | 31 | 32 | scm:git:https://smallnest@github.com/smallnest/fastjson-jaxrs-json-provider.git 33 | scm:git:https://smallnest@github.com/smallnest/fastjson-jaxrs-json-provider.git 34 | https://github.com/smallnest/fastjson-jaxrs-json-provider.git 35 | HEAD 36 | 37 | 38 | 39 | sonatype-nexus-snapshots 40 | Sonatype Nexus Snapshots 41 | http://oss.sonatype.org/content/repositories/snapshots 42 | 43 | 44 | sonatype-nexus-staging 45 | Nexus Release Repository 46 | http://oss.sonatype.org/service/local/staging/deploy/maven2/ 47 | 48 | 49 | 50 | 51 | Apache License, Version 2.0 52 | http://www.apache.org/licenses/LICENSE-2.0.txt 53 | repo 54 | 55 | 56 | 57 | UTF-8 58 | 1.7 59 | 1.7 60 | 1.7 61 | 62 | 4.13.1 63 | 1.2.25 64 | 65 | 2.21 66 | 2.21 67 | 68 | [1.1.1,2.1) 69 | 2.3.0 70 | 71 | 72 | 73 | junit 74 | junit 75 | ${junit.version} 76 | test 77 | 78 | 79 | javax.ws.rs 80 | 81 | javax.ws.rs-api 82 | 2.0 83 | 84 | provided 85 | 86 | 87 | com.alibaba 88 | fastjson 89 | ${fastjson.version} 90 | 91 | 92 | org.glassfish.jersey.containers 93 | jersey-container-servlet 94 | ${jersey.version} 95 | test 96 | 97 | 98 | org.glassfish.jersey.core 99 | jersey-client 100 | ${jersey.version} 101 | test 102 | 103 | 104 | org.glassfish.jersey.test-framework.providers 105 | jersey-test-framework-provider-jdk-http 106 | ${jersey.test.version} 107 | test 108 | 109 | 110 | 111 | 112 | 113 | com.google.code.sortpom 114 | maven-sortpom-plugin 115 | ${sortpom.version} 116 | 117 | 118 | com.google.code.maven-replacer-plugin 119 | replacer 120 | 1.5.3 121 | 122 | 123 | process-packageVersion 124 | process-sources 125 | 126 | 127 | 128 | 129 | org.apache.maven.plugins 130 | maven-source-plugin 131 | 2.4 132 | 133 | 134 | attach-sources 135 | 136 | jar 137 | 138 | 139 | 140 | 141 | 142 | org.apache.maven.plugins 143 | maven-javadoc-plugin 144 | 2.10.1 145 | 146 | 147 | attach-javadocs 148 | 149 | jar 150 | 151 | 152 | 153 | 154 | 155 | org.apache.maven.plugins 156 | maven-release-plugin 157 | 2.5.1 158 | 159 | 160 | pom.xml 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | release-sign-artifacts 169 | 170 | 171 | performRelease 172 | true 173 | 174 | 175 | 176 | 177 | 178 | org.apache.maven.plugins 179 | maven-gpg-plugin 180 | 1.6 181 | 182 | 183 | sign-artifacts 184 | verify 185 | 186 | sign 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | -------------------------------------------------------------------------------- /release.properties: -------------------------------------------------------------------------------- 1 | #release configuration 2 | #Fri Nov 04 16:55:54 CST 2016 3 | scm.tagNameFormat=@{project.artifactId}-@{project.version} 4 | pushChanges=true 5 | scm.url=scm\:git\:https\://smallnest@github.com/smallnest/fastjson-jaxrs-json-provider.git 6 | preparationGoals=clean verify 7 | remoteTagging=true 8 | projectVersionPolicyId=default 9 | scm.commentPrefix=[maven-release-plugin] 10 | exec.additionalArguments=-Psonatype-oss-release -P default 11 | exec.snapshotReleasePluginAllowed=false 12 | completedPhase=check-poms 13 | -------------------------------------------------------------------------------- /src/main/java/com/colobu/fastjson/FastJsonConfig.java: -------------------------------------------------------------------------------- 1 | package com.colobu.fastjson; 2 | 3 | import java.util.Map; 4 | 5 | import com.alibaba.fastjson.parser.Feature; 6 | import com.alibaba.fastjson.parser.ParserConfig; 7 | import com.alibaba.fastjson.serializer.SerializeConfig; 8 | import com.alibaba.fastjson.serializer.SerializeFilter; 9 | import com.alibaba.fastjson.serializer.SerializerFeature; 10 | /** 11 | * Config FastJson. 12 | * @author smallnest 13 | * 14 | */ 15 | public class FastJsonConfig { 16 | public SerializeConfig serializeConfig; 17 | public ParserConfig parserConfig; 18 | public SerializerFeature[] serializerFeatures; 19 | public Feature[] features; 20 | public Map, SerializeFilter> serializeFilters; 21 | 22 | public FastJsonConfig(SerializeConfig serializeConfig, SerializerFeature[] serializerFeatures) { 23 | this(serializeConfig, serializerFeatures, null, new ParserConfig(), null); 24 | } 25 | 26 | public FastJsonConfig(SerializeConfig serializeConfig, SerializerFeature[] serializerFeatures, Map, SerializeFilter> serializeFilters) { 27 | this(serializeConfig, serializerFeatures, serializeFilters, new ParserConfig(), null); 28 | } 29 | 30 | public FastJsonConfig(ParserConfig parserConfig, Feature[] features) { 31 | this(new SerializeConfig(), null, null, parserConfig, features); 32 | } 33 | 34 | public FastJsonConfig(SerializeConfig serializeConfig, SerializerFeature[] serializerFeatures, Map, SerializeFilter> serializeFilters, ParserConfig parserConfig, Feature[] features) { 35 | this.serializeConfig = serializeConfig; 36 | this.parserConfig = parserConfig; 37 | this.serializerFeatures = serializerFeatures; 38 | this.features = features; 39 | this.serializeFilters = serializeFilters; 40 | } 41 | 42 | 43 | } -------------------------------------------------------------------------------- /src/main/java/com/colobu/fastjson/FastJsonProvider.java: -------------------------------------------------------------------------------- 1 | package com.colobu.fastjson; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.parser.ParserConfig; 5 | import com.alibaba.fastjson.serializer.*; 6 | 7 | import javax.ws.rs.WebApplicationException; 8 | import javax.ws.rs.core.MediaType; 9 | import javax.ws.rs.core.MultivaluedMap; 10 | import javax.ws.rs.ext.MessageBodyReader; 11 | import javax.ws.rs.ext.MessageBodyWriter; 12 | import javax.ws.rs.ext.Provider; 13 | import java.io.IOException; 14 | import java.io.InputStream; 15 | import java.io.OutputStream; 16 | import java.lang.annotation.Annotation; 17 | import java.lang.reflect.Type; 18 | import java.util.Arrays; 19 | import java.util.List; 20 | 21 | /** 22 | * JAX-RS Provider for fastjson. 23 | * 24 | * @author smallnest 25 | * 26 | */ 27 | @Provider 28 | public class FastJsonProvider implements MessageBodyReader, MessageBodyWriter { 29 | private boolean annotated = false; 30 | private String[] scanpackages = null; 31 | private Class[] clazzes = null; 32 | 33 | protected boolean pretty; 34 | 35 | protected FastJsonConfig fastJsonConfig = new FastJsonConfig(new SerializeConfig(), null, null, new ParserConfig(), null); 36 | 37 | /** 38 | * Can serialize/deserialize all types. 39 | */ 40 | public FastJsonProvider() { 41 | 42 | } 43 | 44 | /** 45 | * Only serialize/deserialize all types annotated with {@link com.colobu.fastjson.FastJsonType}. 46 | */ 47 | public FastJsonProvider(boolean annotated) { 48 | this.annotated = annotated; 49 | } 50 | 51 | /** 52 | * Only serialize/deserialize all types in scanpackages. 53 | */ 54 | public FastJsonProvider(String[] scanpackages) { 55 | this.scanpackages = scanpackages; 56 | } 57 | 58 | /** 59 | * Only serialize/deserialize all types in scanpackages. 60 | */ 61 | public FastJsonProvider(String[] scanpackages, boolean annotated) { 62 | this.scanpackages = scanpackages; 63 | this.annotated = annotated; 64 | } 65 | 66 | /** 67 | * Only serialize/deserialize all types in clazzes. 68 | */ 69 | public FastJsonProvider(Class[] clazzes) { 70 | this.clazzes = clazzes; 71 | } 72 | 73 | /** 74 | * Init this provider with more fastjson configurations. 75 | * @param fastJsonConfig fastjson config 76 | */ 77 | public FastJsonProvider init(FastJsonConfig fastJsonConfig) { 78 | this.fastJsonConfig = fastJsonConfig; 79 | return this; 80 | } 81 | 82 | 83 | // Set pretty format 84 | public FastJsonProvider setPretty(boolean p) { 85 | this.pretty = p; 86 | return this; 87 | } 88 | 89 | /** 90 | * Check whether a class can be serialized or deserialized. It can check 91 | * based on packages, annotations on entities or explicit classes. 92 | * 93 | * @param type class need to check 94 | * @return true if valid 95 | */ 96 | protected boolean isValidType(Class type, Annotation[] classAnnotations) { 97 | if (type == null) 98 | return false; 99 | 100 | if (annotated) { 101 | return checkAnnotation(type); 102 | } else if (scanpackages != null) { 103 | String classPackage = type.getPackage().getName(); 104 | for (String pkg : scanpackages) { 105 | if (classPackage.startsWith(pkg)) { 106 | if (annotated) { 107 | return checkAnnotation(type); 108 | } else 109 | return true; 110 | } 111 | 112 | } 113 | 114 | return false; 115 | } else if (clazzes != null) { 116 | for (Class cls : clazzes) { // must strictly equal. Don't check 117 | // inheritance 118 | if (cls == type) 119 | return true; 120 | } 121 | 122 | return false; 123 | } 124 | 125 | return true; 126 | } 127 | 128 | private boolean checkAnnotation(Class type) { 129 | Annotation[] annotations = type.getAnnotations(); 130 | for (Annotation annotation : annotations) { 131 | if (annotation instanceof FastJsonType) { 132 | return true; 133 | } 134 | } 135 | 136 | return false; 137 | } 138 | 139 | /** 140 | * Check media type like "application/json". 141 | * 142 | * @param mediaType 143 | * media type 144 | * @return true if the media type is valid 145 | */ 146 | protected boolean hasMatchingMediaType(MediaType mediaType) { 147 | if (mediaType != null) { 148 | String subtype = mediaType.getSubtype(); 149 | return "json".equalsIgnoreCase(subtype) || subtype.endsWith("+json") || "javascript".equals(subtype) || "x-javascript".equals(subtype); 150 | } 151 | return true; 152 | } 153 | 154 | public String toJSONString(Object object, SerializeFilter filter, SerializerFeature[] features) { 155 | SerializeWriter out = new SerializeWriter(); 156 | 157 | try { 158 | JSONSerializer serializer = new JSONSerializer(out, fastJsonConfig.serializeConfig); 159 | if (features != null) { 160 | for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) { 161 | serializer.config(feature, true); 162 | } 163 | } 164 | 165 | if (filter != null) { 166 | if (filter instanceof PropertyPreFilter) { 167 | serializer.getPropertyPreFilters().add((PropertyPreFilter) filter); 168 | } 169 | 170 | if (filter instanceof NameFilter) { 171 | serializer.getNameFilters().add((NameFilter) filter); 172 | } 173 | 174 | if (filter instanceof ValueFilter) { 175 | serializer.getValueFilters().add((ValueFilter) filter); 176 | } 177 | 178 | if (filter instanceof PropertyFilter) { 179 | serializer.getPropertyFilters().add((PropertyFilter) filter); 180 | } 181 | 182 | if (filter instanceof BeforeFilter) { 183 | serializer.getBeforeFilters().add((BeforeFilter) filter); 184 | } 185 | 186 | if (filter instanceof AfterFilter) { 187 | serializer.getAfterFilters().add((AfterFilter) filter); 188 | } 189 | } 190 | 191 | serializer.write(object); 192 | 193 | return out.toString(); 194 | } finally { 195 | out.close(); 196 | } 197 | } 198 | 199 | /* 200 | * /********************************************************** /* Partial 201 | * MessageBodyWriter impl 202 | * /********************************************************** 203 | */ 204 | 205 | /** 206 | * Method that JAX-RS container calls to try to check whether given value 207 | * (of specified type) can be serialized by this provider. 208 | */ 209 | public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { 210 | if (!hasMatchingMediaType(mediaType)) { 211 | return false; 212 | } 213 | 214 | return isValidType(type, annotations); 215 | } 216 | 217 | /** 218 | * Method that JAX-RS container calls to try to figure out serialized length 219 | * of given value. always return -1 to denote "not known". 220 | */ 221 | public long getSize(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { 222 | return -1; 223 | } 224 | 225 | /** 226 | * Method that JAX-RS container calls to serialize given value. 227 | */ 228 | public void writeTo(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, 229 | OutputStream entityStream) throws IOException, WebApplicationException { 230 | SerializeFilter filter = null; 231 | 232 | if(pretty) { 233 | if (fastJsonConfig.serializerFeatures == null) 234 | fastJsonConfig.serializerFeatures = new SerializerFeature[]{SerializerFeature.PrettyFormat}; 235 | else { 236 | List serializerFeatures = Arrays.asList(fastJsonConfig.serializerFeatures); 237 | serializerFeatures.add(SerializerFeature.PrettyFormat); 238 | fastJsonConfig.serializerFeatures = serializerFeatures.toArray(new SerializerFeature[]{}); 239 | } 240 | } 241 | 242 | if (fastJsonConfig.serializeFilters != null) 243 | filter = fastJsonConfig.serializeFilters.get(type); 244 | String jsonStr = toJSONString(t, filter, fastJsonConfig.serializerFeatures); 245 | if (jsonStr != null) 246 | entityStream.write(jsonStr.getBytes()); 247 | } 248 | 249 | /* 250 | * /********************************************************** /* 251 | * MessageBodyReader impl 252 | * /********************************************************** 253 | */ 254 | 255 | /** 256 | * Method that JAX-RS container calls to try to check whether values of 257 | * given type (and media type) can be deserialized by this provider. 258 | */ 259 | public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { 260 | if (!hasMatchingMediaType(mediaType)) { 261 | return false; 262 | } 263 | 264 | return isValidType(type, annotations); 265 | } 266 | 267 | /** 268 | * Method that JAX-RS container calls to deserialize given value. 269 | */ 270 | public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, 271 | InputStream entityStream) throws IOException, WebApplicationException { 272 | String input = null; 273 | try { 274 | input = IOUtils.inputStreamToString(entityStream); 275 | } catch (Exception e) { 276 | 277 | } 278 | if (input == null) { 279 | return null; 280 | } 281 | if (fastJsonConfig.features == null) 282 | return JSON.parseObject(input, type, fastJsonConfig.parserConfig, JSON.DEFAULT_PARSER_FEATURE); 283 | else 284 | return JSON.parseObject(input, type, fastJsonConfig.parserConfig, JSON.DEFAULT_PARSER_FEATURE, fastJsonConfig.features); 285 | } 286 | 287 | } 288 | -------------------------------------------------------------------------------- /src/main/java/com/colobu/fastjson/FastJsonType.java: -------------------------------------------------------------------------------- 1 | package com.colobu.fastjson; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | /** 8 | * Annotate a class that can be serialized/deserialized if FastJsonProvider 9 | * is configured with Annotation scan. 10 | * @author smallnest 11 | * 12 | */ 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Target({ ElementType.TYPE }) 15 | public @interface FastJsonType { 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/colobu/fastjson/IOUtils.java: -------------------------------------------------------------------------------- 1 | package com.colobu.fastjson; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStream; 5 | import java.io.InputStreamReader; 6 | 7 | public class IOUtils { 8 | 9 | /** 10 | * read a String from an InputStream object. 11 | * @param in InputStream 12 | * @return String 13 | * @throws Exception 14 | */ 15 | public static String inputStreamToString(InputStream in) throws Exception { 16 | BufferedReader br = new BufferedReader(new InputStreamReader(in)); 17 | StringBuffer buffer = new StringBuffer(); 18 | String line; 19 | while ((line = br.readLine()) != null) { 20 | buffer.append(line); 21 | } 22 | return buffer.toString(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/colobu/fastjson/ClassDefinitionFastJsonProviderTest.java: -------------------------------------------------------------------------------- 1 | package com.colobu.fastjson; 2 | 3 | import com.colobu.test.Teacher; 4 | import org.glassfish.jersey.client.ClientConfig; 5 | import org.glassfish.jersey.server.ResourceConfig; 6 | import org.glassfish.jersey.test.JerseyTest; 7 | import org.glassfish.jersey.test.TestProperties; 8 | import org.junit.Test; 9 | 10 | import javax.ws.rs.GET; 11 | import javax.ws.rs.InternalServerErrorException; 12 | import javax.ws.rs.Path; 13 | import javax.ws.rs.core.Application; 14 | import java.util.Date; 15 | 16 | import static org.junit.Assert.*; 17 | 18 | /* 19 | Only handles specific classes by pass class type array to FastJsonProvider's constructor. 20 | */ 21 | public class ClassDefinitionFastJsonProviderTest extends JerseyTest { 22 | 23 | @Path("teacher") 24 | public static class TeacherResource { 25 | @GET 26 | public Teacher getTeacher() { 27 | Teacher teacher = new Teacher(); 28 | teacher.setId(12345L); 29 | teacher.setName("smallnest"); 30 | teacher.setCreatedOn(new Date()); 31 | return teacher; 32 | } 33 | } 34 | 35 | @Path("user2") 36 | public static class UserResource { 37 | @GET 38 | public User getUser() { 39 | User user = new User(); 40 | user.setId(12345L); 41 | user.setName("smallnest"); 42 | user.setCreatedOn(new Date()); 43 | return user; 44 | } 45 | } 46 | 47 | @Override 48 | protected void configureClient(ClientConfig config) { 49 | Class[] jsonTypes = {User.class}; 50 | config.register(new FastJsonFeature()).register(new FastJsonProvider(jsonTypes)); 51 | } 52 | 53 | @Override 54 | protected Application configure() { 55 | enable(TestProperties.LOG_TRAFFIC); 56 | enable(TestProperties.DUMP_ENTITY); 57 | 58 | ResourceConfig config = new ResourceConfig(); 59 | Class[] jsonTypes = {User.class}; 60 | config.register(new FastJsonFeature()).register(new FastJsonProvider(jsonTypes)); 61 | config.packages("com.colobu.fastjson", "com.colobu.test"); 62 | return config; 63 | } 64 | 65 | @Test 66 | public void testWriteTo() { 67 | final String user = target("user2").request().accept("application/json").get(String.class); 68 | // {"createdOn":1412036891919,"id":12345,"name":"smallnest"}] 69 | assertTrue(user.indexOf("createdOn") > 0); 70 | assertTrue(user.indexOf("\"id\":12345") > 0); 71 | assertTrue(user.indexOf("\"name\":\"smallnest\"") > 0); 72 | } 73 | 74 | @Test 75 | public void testReadFrom() { 76 | final User user = target("user2").request().accept("application/json").get(User.class); 77 | assertNotNull(user); 78 | assertNotNull(user.getCreatedOn()); 79 | assertEquals(user.getId().longValue(), 12345L); 80 | assertEquals(user.getName(), "smallnest"); 81 | } 82 | 83 | @Test(expected=InternalServerErrorException.class) 84 | public void testWriteToForTeacher() { 85 | final String teacher = target("teacher").request().accept("application/json").get(String.class); 86 | assertTrue(teacher.indexOf("createdOn") > 0); 87 | assertTrue(teacher.indexOf("\"id\":12345") > 0); 88 | assertTrue(teacher.indexOf("\"name\":\"smallnest\"") > 0); 89 | } 90 | 91 | @Test(expected=InternalServerErrorException.class) 92 | public void testReadFromForTeacher() { 93 | final Teacher teacher = target("teacher").request().accept("application/json").get(Teacher.class); 94 | assertNotNull(teacher); 95 | assertNotNull(teacher.getCreatedOn()); 96 | assertEquals(teacher.getId().longValue(), 12345L); 97 | assertEquals(teacher.getName(), "smallnest"); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/test/java/com/colobu/fastjson/FastJsonFeature.java: -------------------------------------------------------------------------------- 1 | package com.colobu.fastjson; 2 | 3 | import javax.ws.rs.core.Configuration; 4 | import javax.ws.rs.core.Feature; 5 | import javax.ws.rs.core.FeatureContext; 6 | import javax.ws.rs.ext.MessageBodyReader; 7 | import javax.ws.rs.ext.MessageBodyWriter; 8 | 9 | import org.glassfish.jersey.CommonProperties; 10 | import org.glassfish.jersey.internal.InternalProperties; 11 | import org.glassfish.jersey.internal.util.PropertiesHelper; 12 | 13 | public class FastJsonFeature implements Feature { 14 | 15 | private final static String JSON_FEATURE = FastJsonFeature.class.getSimpleName(); 16 | 17 | public boolean configure(final FeatureContext context) { 18 | final Configuration config = context.getConfiguration(); 19 | final String jsonFeature = CommonProperties.getValue(config.getProperties(), config.getRuntimeType(), InternalProperties.JSON_FEATURE, JSON_FEATURE, 20 | String.class); 21 | // Other JSON providers registered. 22 | if (!JSON_FEATURE.equalsIgnoreCase(jsonFeature)) { 23 | return false; 24 | } 25 | // Disable other JSON providers. 26 | context.property(PropertiesHelper.getPropertyNameForRuntime(InternalProperties.JSON_FEATURE, config.getRuntimeType()), JSON_FEATURE); 27 | // Register FastJson. 28 | if (!config.isRegistered(FastJsonProvider.class)) { 29 | context.register(FastJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class); 30 | } 31 | return true; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/colobu/fastjson/FastJsonProviderTest.java: -------------------------------------------------------------------------------- 1 | package com.colobu.fastjson; 2 | 3 | import org.glassfish.jersey.client.ClientConfig; 4 | import org.glassfish.jersey.server.ResourceConfig; 5 | import org.glassfish.jersey.test.JerseyTest; 6 | import org.glassfish.jersey.test.TestProperties; 7 | import org.junit.Test; 8 | 9 | import javax.ws.rs.GET; 10 | import javax.ws.rs.Path; 11 | import javax.ws.rs.core.Application; 12 | import java.util.Date; 13 | 14 | import static org.junit.Assert.*; 15 | 16 | public class FastJsonProviderTest extends JerseyTest { 17 | 18 | @Path("user") 19 | public static class UserResource { 20 | @GET 21 | public User getUser() { 22 | User user = new User(); 23 | user.setId(12345L); 24 | user.setName("smallnest"); 25 | user.setCreatedOn(new Date()); 26 | return user; 27 | } 28 | } 29 | 30 | @Override 31 | protected void configureClient(ClientConfig config) { 32 | config.register(new FastJsonFeature()).register(FastJsonProvider.class); 33 | } 34 | 35 | @Override 36 | protected Application configure() { 37 | enable(TestProperties.LOG_TRAFFIC); 38 | enable(TestProperties.DUMP_ENTITY); 39 | 40 | ResourceConfig config = new ResourceConfig(); 41 | //config.register(new FastJsonFeature()).register(FastJsonProvider.class); 42 | config.register(new FastJsonFeature()).register(new FastJsonProvider().setPretty(true)); 43 | config.packages("com.colobu.fastjson"); 44 | return config; 45 | } 46 | 47 | @Test 48 | public void testWriteTo() { 49 | final String user = target("user").request().accept("application/json").get(String.class); 50 | // {"createdOn":1412036891919,"id":12345,"name":"smallnest"}] 51 | assertTrue(user.indexOf("createdOn") > 0); 52 | assertTrue(user.indexOf("\"id\":12345") > 0); 53 | assertTrue(user.indexOf("\"name\":\"smallnest\"") > 0); 54 | } 55 | 56 | @Test 57 | public void testWriteToWithPretty() { 58 | System.out.println("@@@@@Test Pretty"); 59 | final String user = target("user").queryParam("pretty", "true").request().accept("application/json").get(String.class); 60 | // {"createdOn":1412036891919,"id":12345,"name":"smallnest"}] 61 | assertTrue(user.indexOf("createdOn") > 0); 62 | assertTrue(user.indexOf("\"id\":12345") > 0); 63 | assertTrue(user.indexOf("\"name\":\"smallnest\"") > 0); 64 | assertTrue(user.indexOf("\n\t") > 0); 65 | 66 | } 67 | 68 | @Test 69 | public void testReadFrom() { 70 | final User user = target("user").request().accept("application/json").get(User.class); 71 | assertNotNull(user); 72 | assertNotNull(user.getCreatedOn()); 73 | assertEquals(user.getId().longValue(), 12345L); 74 | assertEquals(user.getName(), "smallnest"); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/test/java/com/colobu/fastjson/User.java: -------------------------------------------------------------------------------- 1 | package com.colobu.fastjson; 2 | 3 | import java.util.Date; 4 | 5 | import com.alibaba.fastjson.annotation.JSONType; 6 | 7 | @JSONType 8 | public class User { 9 | 10 | private Long id; 11 | private String name; 12 | private Date createdOn; 13 | 14 | public Long getId() { 15 | return id; 16 | } 17 | 18 | public void setId(Long id) { 19 | this.id = id; 20 | } 21 | 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public void setName(String name) { 27 | this.name = name; 28 | } 29 | 30 | public Date getCreatedOn() { 31 | return createdOn; 32 | } 33 | 34 | public void setCreatedOn(Date createdOn) { 35 | this.createdOn = createdOn; 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /src/test/java/com/colobu/test/Teacher.java: -------------------------------------------------------------------------------- 1 | package com.colobu.test; 2 | 3 | import java.util.Date; 4 | 5 | public class Teacher { 6 | 7 | private Long id; 8 | private String name; 9 | private Date createdOn; 10 | 11 | public Long getId() { 12 | return id; 13 | } 14 | 15 | public void setId(Long id) { 16 | this.id = id; 17 | } 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public void setName(String name) { 24 | this.name = name; 25 | } 26 | 27 | public Date getCreatedOn() { 28 | return createdOn; 29 | } 30 | 31 | public void setCreatedOn(Date createdOn) { 32 | this.createdOn = createdOn; 33 | } 34 | 35 | } --------------------------------------------------------------------------------