diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000000..b3fd69dc9d --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +/target +/.project +/.settings +/.classpath +/.idea +/.DS_Store +*.iml + +/bin/ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000..ef2c288661 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,10 @@ +language: java +jdk: + - oraclejdk8 +before_install: + - pip install --user codecov +after_success: + - codecov +branches: + except: + - appveyor diff --git a/README.md b/README.md new file mode 100755 index 0000000000..bd8337fdb2 --- /dev/null +++ b/README.md @@ -0,0 +1,88 @@ +# fastjson + +[![Build Status](https://travis-ci.org/alibaba/fastjson.svg?branch=master)](https://travis-ci.org/alibaba/fastjson) +[![Codecov](https://codecov.io/gh/alibaba/fastjson/branch/master/graph/badge.svg)](https://codecov.io/gh/alibaba/fastjson/branch/master) +[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.alibaba/fastjson/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.alibaba/fastjson/) +[![GitHub release](https://img.shields.io/github/release/alibaba/fastjson.svg)](https://github.com/alibaba/fastjson/releases) +[![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) + +Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Fastjson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. + +### Fastjson Goals + * Provide best performance in server side and android client + * Provide simple toJSONString() and parseObject() methods to convert Java objects to JSON and vice-versa + * Allow pre-existing unmodifiable objects to be converted to and from JSON + * Extensive support of Java Generics + * Allow custom representations for objects + * Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types) + +![fastjson](logo.jpg "fastjson") + +## Documentation + +- [Documentation Home](https://github.com/alibaba/fastjson/wiki) +- [Frequently Asked Questions](https://github.com/alibaba/fastjson/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98) + +## Benchmark + +https://github.com/eishay/jvm-serializers/wiki + +## Download + +- [maven][1] +- [the latest JAR][2] + +[1]: http://repo1.maven.org/maven2/com/alibaba/fastjson/ +[2]: https://search.maven.org/remote_content?g=com.alibaba&a=fastjson&v=LATEST + +## Maven + +```xml + + com.alibaba + fastjson + 1.2.46 + +``` + +```xml + + com.alibaba + fastjson + 1.1.68.android + +``` + +## Gradle via JCenter + +``` groovy +compile 'com.alibaba:fastjson:1.2.46' +``` + +``` groovy +compile 'com.alibaba:fastjson:1.1.68.android' +``` + +Please see this [Wiki Download Page][Wiki] for more repository infos. + +[Wiki]: https://github.com/alibaba/fastjson/wiki#download + +### *License* + +Fastjson is released under the [Apache 2.0 license](license.txt). + +``` +Copyright 1999-2017 Alibaba Group Holding Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at following link. + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` diff --git a/license.txt b/license.txt new file mode 100644 index 0000000000..8deeff6746 --- /dev/null +++ b/license.txt @@ -0,0 +1,13 @@ +Copyright 1999-2016 Alibaba Group Holding Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/logo.jpg b/logo.jpg new file mode 100644 index 0000000000..4686206f2f Binary files /dev/null and b/logo.jpg differ diff --git a/pom.xml b/pom.xml old mode 100644 new mode 100755 index c2a4409664..ac0b23f448 --- a/pom.xml +++ b/pom.xml @@ -1,181 +1,525 @@ - - 4.0.0 - com.alibaba - fastjson - 1.1.2-SNAPSHOT - fastjson - - - UTF-8 - - - - - wenshao - wenshao - szujobs@hotmail.com - - - - - - opensesame - dav:http://code.alibabatech.com/mvn/releases/ - - - opensesame - dav:http://code.alibabatech.com/mvn/snapshots/ - - - - - Alibaba Group - http://code.alibabatech.com/ - - - - - org.apache.maven.wagon - wagon-webdav - 1.0-beta-2 - - - - - org.apache.maven.plugins - maven-compiler-plugin - - UTF-8 - 1.5 - 1.5 - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - - jar-no-fork - - - - - true - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/bvt/**/*.java - - - - - - - - - central - released internal lib - http://repo2.maven.org/maven2/ - - false - - - - gson - gson - http://google-gson.googlecode.com/svn/mavenrepo - - false - - - - jackson - jackson - http://repository.codehaus.org/ - - false - - - - maven2-repository.java.net - Java.net Repository for Maven - http://download.java.net/maven/2/ - default - - - - - - - org.codehaus.jackson - jackson-core-lgpl - 1.8.1 - test - - - org.codehaus.jackson - jackson-mapper-lgpl - 1.8.1 - test - - - org.codehaus.jackson - jackson-jaxrs - 1.8.1 - test - - - org.codehaus.jackson - jackson-smile - 1.8.1 - test - - - commons-io - commons-io - 1.4 - test - - - com.googlecode.json-simple - json-simple - 1.1 - test - - - net.sf.json-lib - json-lib - 2.4 - jdk15 - test - - - junit - junit - 4.5 - test - - - com.google.code.gson - gson - 1.6 - test - - - net.minidev - json-smart - 1.0.6.3 - test - - - \ No newline at end of file + + + 4.0.0 + com.alibaba + fastjson + 1.2.48-SNAPSHOT + + jar + fastjson + Fastjson is a JSON processor (JSON parser + JSON generator) written in Java + + https://github.com/alibaba/fastjson + 2012 + + + 4.12 + true + false + UTF-8 + 1.5 + + + + https://github.com/alibaba/fastjson + scm:git:https://git@github.com/alibaba/fastjson.git + + + + + local-file + file://${basedir}/lib/ + default + + + + + Alibaba Group + https://github.com/alibaba + + + + + wenshao + wenshao + szujobs@hotmail.com + + + axmanwang + axmanwang + iamaxman@hotmail.com + + + kimmking + kimmking + kimmking@163.com + + + Victor Zeng + Victor Zeng + Victor.Zxy@outlook.com + + + Neil Dong + Neil Dong + email_dsl@163.com + + + 李恒名 + https://github.com/lihengming/ + 89921218@qq.com + + + + + + Apache 2 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + A business-friendly OSS license + + + + + + + org.apache.maven.wagon + wagon-webdav + 1.0-beta-2 + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 3.5.1 + + UTF-8 + ${jdk.version} + ${jdk.version} + + + + org.codehaus.plexus + plexus-compiler-javac + 2.7 + + + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar-no-fork + + + + + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/bvt/**/*.java + + + + + + maven-javadoc-plugin + + + attach-javadoc + + jar + + + + + ${javadoc.skip} + public + UTF-8 + UTF-8 + UTF-8 + + http://docs.oracle.com/javase/6/docs/api + + + + + + maven-gpg-plugin + + ${gpg.skip} + + + + sign-artifacts + verify + + sign + + + + + + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + true + + + javax.ws.rs + javax.ws.rs-api + 2.0.1 + provided + true + + + + org.apache.cxf + cxf-rt-transports-http + 3.1.2 + provided + true + + + org.apache.cxf + cxf-rt-frontend-jaxrs + 3.1.2 + provided + true + + + + org.springframework + spring-websocket + 4.3.7.RELEASE + provided + true + + + org.springframework + spring-webmvc + 4.3.7.RELEASE + provided + true + + + + org.springframework + spring-messaging + 4.3.7.RELEASE + provided + true + + + + + org.springframework.data + spring-data-redis + 1.8.6.RELEASE + provided + true + + + + com.squareup.retrofit2 + retrofit + 2.1.0 + provided + + + com.squareup.okhttp3 + okhttp + 3.6.0 + provided + + + + io.springfox + springfox-spring-web + 2.6.1 + provided + true + + + + io.javaslang + javaslang + 2.0.6 + provided + + + + org.glassfish.jersey.core + jersey-common + 2.23.2 + provided + + + + org.eclipse.jetty + jetty-server + 8.1.8.v20121106 + test + true + + + org.eclipse.jetty + jetty-webapp + 8.1.8.v20121106 + test + true + + + + junit + junit + ${junit.version} + test + + + + com.fasterxml.jackson.core + jackson-databind + 2.9.0 + test + + + com.fasterxml.jackson.module + jackson-module-afterburner + 2.9.0 + test + + + com.fasterxml.jackson.module + jackson-module-kotlin + 2.9.0 + test + + + + cglib + cglib-nodep + 2.2.2 + test + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + 2.8.7 + test + + + com.googlecode.json-simple + json-simple + 1.1.1 + test + + + + commons-io + commons-io + 1.4 + test + + + + net.sf.json-lib + json-lib + 2.4 + jdk15 + test + + + + com.google.code.gson + gson + 2.6.2 + test + + + net.minidev + json-smart + 2.2.1 + test + + + + org.clojure + clojure + 1.5.1 + test + + + org.codehaus.groovy + groovy + 2.1.5 + test + + + + org.springframework + spring-test + 4.3.7.RELEASE + test + + + org.javassist + javassist + 3.18.0-GA + test + + + + org.apache.cxf + cxf-rt-rs-client + 3.1.2 + test + + + + org.springframework.data + spring-data-commons-core + 1.4.1.RELEASE + test + + + + org.glassfish.jersey.containers + jersey-container-servlet + 2.23.2 + test + + + org.glassfish.jersey.core + jersey-client + 2.23.2 + test + + + org.glassfish.jersey.test-framework.providers + jersey-test-framework-provider-jdk-http + 2.23.2 + test + + + org.glassfish.jersey.media + jersey-media-json-jackson + 2.23.2 + test + + + com.jsoniter + jsoniter + 0.9.8 + test + + + + org.apache.commons + commons-lang3 + 3.4 + test + + + + org.hibernate + hibernate-core + 5.2.10.Final + test + + + + com.jayway.jsonpath + json-path + 2.3.0 + test + + + + org.jetbrains.kotlin + kotlin-stdlib + 1.1.3-2 + test + + + + org.jetbrains.kotlin + kotlin-reflect + 1.1.3-2 + test + + + + org.springframework.security + spring-security-web + 4.2.3.RELEASE + test + + + + org.apache.commons + commons-collections4 + 4.1 + test + + + + + + + travis + + + env.TRAVIS + true + + + + + + + + + org.jacoco + jacoco-maven-plugin + 0.7.6.201602180812 + + + + prepare-agent + + + + report + test + + report + + + + + + + + + + diff --git a/rfc4627.txt b/rfc4627.txt old mode 100644 new mode 100755 diff --git a/src/main/java/META-INF/MANIFEST.MF b/src/main/java/META-INF/MANIFEST.MF new file mode 100755 index 0000000000..b8c791063b --- /dev/null +++ b/src/main/java/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.1.35 +Class-Path: + diff --git a/src/main/java/com/alibaba/fastjson/JSON.java b/src/main/java/com/alibaba/fastjson/JSON.java old mode 100644 new mode 100755 index ddbb6c3c79..32f57644c4 --- a/src/main/java/com/alibaba/fastjson/JSON.java +++ b/src/main/java/com/alibaba/fastjson/JSON.java @@ -1,463 +1,1063 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson; - -import java.io.IOException; -import java.lang.reflect.Array; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharsetDecoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.DefaultJSONParser; -import com.alibaba.fastjson.parser.Feature; -import com.alibaba.fastjson.parser.ParserConfig; -import com.alibaba.fastjson.serializer.JSONSerializer; -import com.alibaba.fastjson.serializer.JavaBeanSerializer; -import com.alibaba.fastjson.serializer.SerializeConfig; -import com.alibaba.fastjson.serializer.SerializeWriter; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.alibaba.fastjson.util.FieldInfo; -import com.alibaba.fastjson.util.IOUtils; -import com.alibaba.fastjson.util.ThreadLocalCache; -import com.alibaba.fastjson.util.TypeUtils; -import com.alibaba.fastjson.util.UTF8Decoder; - -/** - * @author wenshao - */ -public abstract class JSON implements JSONStreamAware, JSONAware { - - public static final int DEFAULT_PARSER_FEATURE; - static { - int features = 0; - features |= Feature.AutoCloseSource.getMask(); - features |= Feature.InternFieldNames.getMask(); - features |= Feature.UseBigDecimal.getMask(); - features |= Feature.AllowUnQuotedFieldNames.getMask(); - features |= Feature.AllowSingleQuotes.getMask(); - features |= Feature.AllowArbitraryCommas.getMask(); - features |= Feature.SortFeidFastMatch.getMask(); - features |= Feature.IgnoreNotMatch.getMask(); - DEFAULT_PARSER_FEATURE = features; - } - - public static final int DEFAULT_GENERATE_FEATURE; - static { - int features = 0; - features |= com.alibaba.fastjson.serializer.SerializerFeature.QuoteFieldNames.getMask(); - features |= com.alibaba.fastjson.serializer.SerializerFeature.SkipTransientField.getMask(); - features |= com.alibaba.fastjson.serializer.SerializerFeature.SortField.getMask(); - DEFAULT_GENERATE_FEATURE = features; - } - - public static final Object parse(String text) { - return parse(text, DEFAULT_PARSER_FEATURE); - } - - public static final Object parse(String text, int features) { - if (text == null) { - return null; - } - - DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance(), features); - Object value = parser.parse(); - - parser.close(); - - return value; - } - - public static final Object parse(byte[] input, Feature... features) { - return parse(input, 0, input.length, UTF8_CharsetEncoder, features); - } - - public static final Object parse(byte[] input, int off, int len, CharsetDecoder charsetDecoder, Feature... features) { - if (input == null || input.length == 0) { - return null; - } - - int featureValues = DEFAULT_PARSER_FEATURE; - for (Feature featrue : features) { - featureValues = Feature.config(featureValues, featrue, true); - } - - return parse(input, off, len, charsetDecoder, featureValues); - } - - public static final Object parse(byte[] input, int off, int len, CharsetDecoder charsetDecoder, int features) { - charsetDecoder.reset(); - - int scaleLength = (int) (len * (double) charsetDecoder.maxCharsPerByte()); - char[] chars = ThreadLocalCache.getChars(scaleLength); - - ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len); - CharBuffer charBuf = CharBuffer.wrap(chars); - IOUtils.decode(charsetDecoder, byteBuf, charBuf); - - int position = charBuf.position(); - - DefaultJSONParser parser = new DefaultJSONParser(chars, position, ParserConfig.getGlobalInstance(), features); - Object value = parser.parse(); - - parser.close(); - - return value; - } - - public static final Object parse(String text, Feature... features) { - int featureValues = DEFAULT_PARSER_FEATURE; - for (Feature featrue : features) { - featureValues = Feature.config(featureValues, featrue, true); - } - - return parse(text, featureValues); - } - - public static final JSONObject parseObject(String text, Feature... features) { - return (JSONObject) parse(text, features); - } - - public static final JSONObject parseObject(String text) { - return (JSONObject) parse(text); - } - - @SuppressWarnings("unchecked") - public static final T parseObject(String text, TypeReference type, Feature... features) { - return (T) parseObject(text, type.getType(), ParserConfig.getGlobalInstance(), DEFAULT_PARSER_FEATURE, features); - } - - @SuppressWarnings("unchecked") - public static final T parseObject(String text, Class clazz, Feature... features) { - return (T) parseObject(text, (Type) clazz, ParserConfig.getGlobalInstance(), DEFAULT_PARSER_FEATURE, features); - } - - @SuppressWarnings("unchecked") - public static final T parseObject(String input, Type clazz, Feature... features) { - return (T) parseObject(input, clazz, ParserConfig.getGlobalInstance(), DEFAULT_PARSER_FEATURE, features); - } - - @SuppressWarnings("unchecked") - public static final T parseObject(String input, Type clazz, int featureValues, Feature... features) { - if (input == null) { - return null; - } - - for (Feature featrue : features) { - featureValues = Feature.config(featureValues, featrue, true); - } - - DefaultExtJSONParser parser = new DefaultExtJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); - T value = (T) parser.parseObject(clazz); - - parser.close(); - - return (T) value; - } - - @SuppressWarnings("unchecked") - public static final T parseObject(String input, Type clazz, ParserConfig config, int featureValues, - Feature... features) { - if (input == null) { - return null; - } - - for (Feature featrue : features) { - featureValues = Feature.config(featureValues, featrue, true); - } - - DefaultExtJSONParser parser = new DefaultExtJSONParser(input, config, featureValues); - T value = (T) parser.parseObject(clazz); - - if (clazz != JSONArray.class) { - parser.close(); - } - - return (T) value; - } - - @SuppressWarnings("unchecked") - public static final T parseObject(byte[] input, Type clazz, Feature... features) { - return (T) parseObject(input, 0, input.length, UTF8_CharsetEncoder, clazz, features); - } - - public static CharsetDecoder UTF8_CharsetEncoder = new UTF8Decoder(); // = - // Charset.forName("UTF-8").newDecoder(); - - @SuppressWarnings("unchecked") - public static final T parseObject(byte[] input, int off, int len, CharsetDecoder charsetDecoder, Type clazz, - Feature... features) { - charsetDecoder.reset(); - - int scaleLength = (int) (len * (double) charsetDecoder.maxCharsPerByte()); - char[] chars = ThreadLocalCache.getChars(scaleLength); - - ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len); - CharBuffer charByte = CharBuffer.wrap(chars); - IOUtils.decode(charsetDecoder, byteBuf, charByte); - - int position = charByte.position(); - - return (T) parseObject(chars, position, clazz, features); - } - - @SuppressWarnings("unchecked") - public static final T parseObject(char[] input, int length, Type clazz, Feature... features) { - if (input == null || input.length == 0) { - return null; - } - - int featureValues = DEFAULT_PARSER_FEATURE; - for (Feature featrue : features) { - featureValues = Feature.config(featureValues, featrue, true); - } - - DefaultExtJSONParser parser = new DefaultExtJSONParser(input, length, ParserConfig.getGlobalInstance(), - featureValues); - T value = (T) parser.parseObject(clazz); - - parser.close(); - - return (T) value; - } - - public static final T parseObject(String text, Class clazz) { - return parseObject(text, clazz, new Feature[0]); - } - - public static final JSONArray parseArray(String text) { - return (JSONArray) parse(text); - } - - public static final List parseArray(String text, Class clazz) { - if (text == null) { - return null; - } - - List list = new ArrayList(); - - DefaultExtJSONParser parser = new DefaultExtJSONParser(text, ParserConfig.getGlobalInstance()); - parser.parseArray(clazz, list); - - parser.close(); - - return list; - } - - public static final List parseArray(String text, Type[] types) { - if (text == null) { - return null; - } - - List list; - - DefaultExtJSONParser parser = new DefaultExtJSONParser(text, ParserConfig.getGlobalInstance()); - list = Arrays.asList(parser.parseArray(types)); - - parser.close(); - - return list; - } - - // ====================== - - public static final String toJSONString(Object object) { - return toJSONString(object, new SerializerFeature[0]); - } - - public static final String toJSONString(Object object, SerializerFeature... features) { - SerializeWriter out = new SerializeWriter(); - - try { - JSONSerializer serializer = new JSONSerializer(out); - for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) { - serializer.config(feature, true); - } - - serializer.write(object); - - return out.toString(); - } catch (StackOverflowError e) { - throw new JSONException("maybe circular references", e); - } finally { - out.close(); - } - } - - public static final String toJSONString(Object object, SerializeConfig config, SerializerFeature... features) { - SerializeWriter out = new SerializeWriter(); - - try { - JSONSerializer serializer = new JSONSerializer(out, config); - for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) { - serializer.config(feature, true); - } - - serializer.write(object); - - return out.toString(); - } catch (StackOverflowError e) { - throw new JSONException("maybe circular references", e); - } finally { - out.close(); - } - } - - public static final String toJSONStringZ(Object object, SerializeConfig mapping, SerializerFeature... features) { - SerializeWriter out = new SerializeWriter(features); - - try { - JSONSerializer serializer = new JSONSerializer(out, mapping); - - serializer.write(object); - - return out.toString(); - } catch (StackOverflowError e) { - throw new JSONException("maybe circular references", e); - } finally { - out.close(); - } - } - - public static final String toJSONString(Object object, boolean prettyFormat) { - if (!prettyFormat) { - return toJSONString(object); - } - - return toJSONString(object, SerializerFeature.PrettyFormat); - } - - // ====================================== - - @Override - public String toString() { - return toJSONString(); - } - - public String toJSONString() { - SerializeWriter out = new SerializeWriter(); - try { - new JSONSerializer(out).write(this); - return out.toString(); - } finally { - out.close(); - } - } - - public void writeJSONString(Appendable appendable) { - SerializeWriter out = new SerializeWriter(); - try { - new JSONSerializer(out).write(this); - appendable.append(out.toString()); - } catch (IOException e) { - throw new JSONException(e.getMessage(), e); - } finally { - out.close(); - } - } - - // /////// - - public static final Object toJSON(Object javaObject) { - return toJSON(javaObject, ParserConfig.getGlobalInstance()); - } - - @SuppressWarnings("unchecked") - public static final Object toJSON(Object javaObject, ParserConfig mapping) { - if (javaObject == null) { - return null; - } - - if (javaObject instanceof JSON) { - return (JSON) javaObject; - } - - if (javaObject instanceof Map) { - Map map = (Map) javaObject; - - JSONObject json = new JSONObject(map.size()); - - for (Map.Entry entry : map.entrySet()) { - Object jsonValue = toJSON(entry.getValue()); - json.put(entry.getKey(), jsonValue); - } - - return json; - } - - if (javaObject instanceof Collection) { - Collection collection = (Collection) javaObject; - - JSONArray array = new JSONArray(collection.size()); - - for (Object item : collection) { - Object jsonValue = toJSON(item); - array.add(jsonValue); - } - - return array; - } - - Class clazz = javaObject.getClass(); - - if (clazz.isArray()) { - int len = Array.getLength(javaObject); - - JSONArray array = new JSONArray(len); - - for (int i = 0; i < len; ++i) { - Object item = Array.get(javaObject, i); - Object jsonValue = toJSON(item); - array.add(jsonValue); - } - - return array; - } - - if (mapping.isPrimitive(clazz)) { - return javaObject; - } - - try { - List getters = JavaBeanSerializer.computeGetters(clazz, null); - - JSONObject json = new JSONObject(getters.size()); - - for (FieldInfo field : getters) { - Method method = field.getMethod(); - Object value = method.invoke(javaObject, new Object[0]); - Object jsonValue = toJSON(value); - - json.put(field.getName(), jsonValue); - } - - return json; - } catch (Exception e) { - throw new JSONException("toJSON error", e); - } - } - - public static final T toJavaObject(JSON json, Class clazz) { - return TypeUtils.cast(json, clazz, ParserConfig.getGlobalInstance()); - } -} +/* + * Copyright 1999-2017 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Writer; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.util.*; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ExtraProcessor; +import com.alibaba.fastjson.parser.deserializer.ExtraTypeProvider; +import com.alibaba.fastjson.parser.deserializer.FieldTypeResolver; +import com.alibaba.fastjson.parser.deserializer.ParseProcess; +import com.alibaba.fastjson.serializer.*; +import com.alibaba.fastjson.util.IOUtils; +import com.alibaba.fastjson.util.TypeUtils; +import sun.reflect.annotation.AnnotationType; + +/** + * This is the main class for using Fastjson. You usually call these two methods {@link #toJSONString(Object)} and {@link #parseObject(String, Class)}. + * + *

Here is an example of how fastjson is used for a simple Class: + * + *

+ * Model model = new Model();
+ * String json = JSON.toJSONString(model); // serializes model to Json
+ * Model model2 = JSON.parseObject(json, Model.class); // deserializes json into model2
+ * 
+ * +*

If the object that your are serializing/deserializing is a {@code ParameterizedType} + * (i.e. contains at least one type parameter and may be an array) then you must use the + * {@link #toJSONString(Object)} or {@link #parseObject(String, Type, Feature[])} method. Here is an + * example for serializing and deserialing a {@code ParameterizedType}: + * + *

+ * String json = "[{},...]";
+ * Type listType = new TypeReference<List<Model>>() {}.getType();
+ * List<Model> modelList = JSON.parseObject(json, listType);
+ * 
+ * + * @see com.alibaba.fastjson.TypeReference + * + * @author wenshao[szujobs@hotmail.com] + */ +public abstract class JSON implements JSONStreamAware, JSONAware { + public static TimeZone defaultTimeZone = TimeZone.getDefault(); + public static Locale defaultLocale = Locale.getDefault(); + + public static String DEFAULT_TYPE_KEY = "@type"; + + static final SerializeFilter[] emptyFilters = new SerializeFilter[0]; + + public static String DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + //public static String DEFFAULT_LOCAL_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"; + + public static int DEFAULT_PARSER_FEATURE; + static { + int features = 0; + features |= Feature.AutoCloseSource.getMask(); + features |= Feature.InternFieldNames.getMask(); + features |= Feature.UseBigDecimal.getMask(); + features |= Feature.AllowUnQuotedFieldNames.getMask(); + features |= Feature.AllowSingleQuotes.getMask(); + features |= Feature.AllowArbitraryCommas.getMask(); + features |= Feature.SortFeidFastMatch.getMask(); + features |= Feature.IgnoreNotMatch.getMask(); + DEFAULT_PARSER_FEATURE = features; + } + + public static int DEFAULT_GENERATE_FEATURE; + static { + int features = 0; + features |= SerializerFeature.QuoteFieldNames.getMask(); + features |= SerializerFeature.SkipTransientField.getMask(); + features |= SerializerFeature.WriteEnumUsingName.getMask(); + features |= SerializerFeature.SortField.getMask(); + + { + String featuresProperty = IOUtils.getStringProperty("fastjson.serializerFeatures.MapSortField"); + int mask = SerializerFeature.MapSortField.getMask(); + if ("true".equals(featuresProperty)) { + features |= mask; + } else if ("false".equals(featuresProperty)) { + features &= ~mask; + } + } + + DEFAULT_GENERATE_FEATURE = features; + } + + /** + * config default type key + * @since 1.2.14 + */ + public static void setDefaultTypeKey(String typeKey) { + DEFAULT_TYPE_KEY = typeKey; + ParserConfig.global.symbolTable.addSymbol(typeKey, + 0, + typeKey.length(), + typeKey.hashCode(), true); + } + + public static Object parse(String text) { + return parse(text, DEFAULT_PARSER_FEATURE); + } + + /** + * + * @since 1.2.38 + */ + public static Object parse(String text, ParserConfig config) { + return parse(text, config, DEFAULT_PARSER_FEATURE); + } + + /** + * + * @since 1.2.38 + */ + public static Object parse(String text, ParserConfig config, int features) { + if (text == null) { + return null; + } + + DefaultJSONParser parser = new DefaultJSONParser(text, config, features); + Object value = parser.parse(); + + parser.handleResovleTask(value); + + parser.close(); + + return value; + } + + public static Object parse(String text, int features) { + return parse(text, ParserConfig.getGlobalInstance(), features); + } + + public static Object parse(byte[] input, Feature... features) { + char[] chars = allocateChars(input.length); + int len = IOUtils.decodeUTF8(input, 0, input.length, chars); + if (len < 0) { + return null; + } + return parse(new String(chars, 0, len), features); + } + + public static Object parse(byte[] input, int off, int len, CharsetDecoder charsetDecoder, Feature... features) { + if (input == null || input.length == 0) { + return null; + } + + int featureValues = DEFAULT_PARSER_FEATURE; + for (Feature feature : features) { + featureValues = Feature.config(featureValues, feature, true); + } + + return parse(input, off, len, charsetDecoder, featureValues); + } + + public static Object parse(byte[] input, int off, int len, CharsetDecoder charsetDecoder, int features) { + charsetDecoder.reset(); + + int scaleLength = (int) (len * (double) charsetDecoder.maxCharsPerByte()); + char[] chars = allocateChars(scaleLength); + + ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len); + CharBuffer charBuf = CharBuffer.wrap(chars); + IOUtils.decode(charsetDecoder, byteBuf, charBuf); + + int position = charBuf.position(); + + DefaultJSONParser parser = new DefaultJSONParser(chars, position, ParserConfig.getGlobalInstance(), features); + Object value = parser.parse(); + + parser.handleResovleTask(value); + + parser.close(); + + return value; + } + + public static Object parse(String text, Feature... features) { + int featureValues = DEFAULT_PARSER_FEATURE; + for (Feature feature : features) { + featureValues = Feature.config(featureValues, feature, true); + } + + return parse(text, featureValues); + } + + public static JSONObject parseObject(String text, Feature... features) { + return (JSONObject) parse(text, features); + } + + public static JSONObject parseObject(String text) { + Object obj = parse(text); + if (obj instanceof JSONObject) { + return (JSONObject) obj; + } + + try { + return (JSONObject) JSON.toJSON(obj); + } catch (RuntimeException e) { + throw new JSONException("can not cast to JSONObject.", e); + } + } + + /** + *
+     * String jsonStr = "[{\"id\":1001,\"name\":\"Jobs\"}]";
+     * List<Model> models = JSON.parseObject(jsonStr, new TypeReference<List<Model>>() {});
+     * 
+ * @param text json string + * @param type type refernce + * @param features + * @return + */ + @SuppressWarnings("unchecked") + public static T parseObject(String text, TypeReference type, Feature... features) { + return (T) parseObject(text, type.type, ParserConfig.global, DEFAULT_PARSER_FEATURE, features); + } + + /** + * + * This method deserializes the specified Json into an object of the specified class. It is not + * suitable to use if the specified class is a generic type since it will not have the generic + * type information because of the Type Erasure feature of Java. Therefore, this method should not + * be used if the desired type is a generic type. Note that this method works fine if the any of + * the fields of the specified object are generics, just the object itself should not be a + * generic type. For the cases when the object is of generic type, invoke + * {@link #parseObject(String, Type, Feature[])}. If you have the Json in a {@link InputStream} instead of + * a String, use {@link #parseObject(InputStream, Type, Feature[])} instead. + * + * @param json the string from which the object is to be deserialized + * @param clazz the class of T + * @param features parser features + * @return an object of type T from the string + * classOfT + */ + @SuppressWarnings("unchecked") + public static T parseObject(String json, Class clazz, Feature... features) { + return (T) parseObject(json, (Type) clazz, ParserConfig.global, null, DEFAULT_PARSER_FEATURE, features); + } + + @SuppressWarnings("unchecked") + public static T parseObject(String text, Class clazz, ParseProcess processor, Feature... features) { + return (T) parseObject(text, (Type) clazz, ParserConfig.global, processor, DEFAULT_PARSER_FEATURE, + features); + } + + /** + * This method deserializes the specified Json into an object of the specified type. This method + * is useful if the specified object is a generic type. For non-generic objects, use + * {@link #parseObject(String, Class, Feature[])} instead. If you have the Json in a {@link InputStream} instead of + * a String, use {@link #parseObject(InputStream, Type, Feature[])} instead. + * + * @param the type of the desired object + * @param json the string from which the object is to be deserialized + * @param type The specific genericized type of src. You can obtain this type by using the + * {@link com.alibaba.fastjson.TypeReference} class. For example, to get the type for + * {@code Collection}, you should use: + *
+     * Type type = new TypeReference<Collection<Foo>>(){}.getType();
+     * 
+ * @return an object of type T from the string + */ + @SuppressWarnings("unchecked") + public static T parseObject(String json, Type type, Feature... features) { + return (T) parseObject(json, type, ParserConfig.global, DEFAULT_PARSER_FEATURE, features); + } + + @SuppressWarnings("unchecked") + public static T parseObject(String input, Type clazz, ParseProcess processor, Feature... features) { + return (T) parseObject(input, clazz, ParserConfig.global, processor, DEFAULT_PARSER_FEATURE, features); + } + + @SuppressWarnings("unchecked") + public static T parseObject(String input, Type clazz, int featureValues, Feature... features) { + if (input == null) { + return null; + } + + for (Feature feature : features) { + featureValues = Feature.config(featureValues, feature, true); + } + + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); + T value = (T) parser.parseObject(clazz); + + parser.handleResovleTask(value); + + parser.close(); + + return (T) value; + } + + /** + * @since 1.2.11 + */ + public static T parseObject(String input, Type clazz, ParserConfig config, Feature... features) { + return parseObject(input, clazz, config, null, DEFAULT_PARSER_FEATURE, features); + } + + public static T parseObject(String input, Type clazz, ParserConfig config, int featureValues, + Feature... features) { + return parseObject(input, clazz, config, null, featureValues, features); + } + + @SuppressWarnings("unchecked") + public static T parseObject(String input, Type clazz, ParserConfig config, ParseProcess processor, + int featureValues, Feature... features) { + if (input == null) { + return null; + } + + if (features != null) { + for (Feature feature : features) { + featureValues |= feature.mask; + } + } + + DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues); + + if (processor != null) { + if (processor instanceof ExtraTypeProvider) { + parser.getExtraTypeProviders().add((ExtraTypeProvider) processor); + } + + if (processor instanceof ExtraProcessor) { + parser.getExtraProcessors().add((ExtraProcessor) processor); + } + + if (processor instanceof FieldTypeResolver) { + parser.setFieldTypeResolver((FieldTypeResolver) processor); + } + } + + T value = (T) parser.parseObject(clazz, null); + + parser.handleResovleTask(value); + + parser.close(); + + return (T) value; + } + + @SuppressWarnings("unchecked") + public static T parseObject(byte[] bytes, Type clazz, Feature... features) { + return (T) parseObject(bytes, 0, bytes.length, IOUtils.UTF8, clazz, features); + } + + /** + * @since 1.2.11 + */ + @SuppressWarnings("unchecked") + public static T parseObject(byte[] bytes, int offset, int len, Charset charset, Type clazz, Feature... features) { + if (charset == null) { + charset = IOUtils.UTF8; + } + + String strVal; + if (charset == IOUtils.UTF8) { + char[] chars = allocateChars(bytes.length); + int chars_len = IOUtils.decodeUTF8(bytes, offset, len, chars); + if (chars_len < 0) { + return null; + } + strVal = new String(chars, 0, chars_len); + } else { + if (len < 0) { + return null; + } + strVal = new String(bytes, offset, len, charset); + } + return (T) parseObject(strVal, clazz, features); + } + + @SuppressWarnings("unchecked") + public static T parseObject(byte[] input, // + int off, // + int len, // + CharsetDecoder charsetDecoder, // + Type clazz, // + Feature... features) { + charsetDecoder.reset(); + + int scaleLength = (int) (len * (double) charsetDecoder.maxCharsPerByte()); + char[] chars = allocateChars(scaleLength); + + ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len); + CharBuffer charByte = CharBuffer.wrap(chars); + IOUtils.decode(charsetDecoder, byteBuf, charByte); + + int position = charByte.position(); + + return (T) parseObject(chars, position, clazz, features); + } + + @SuppressWarnings("unchecked") + public static T parseObject(char[] input, int length, Type clazz, Feature... features) { + if (input == null || input.length == 0) { + return null; + } + + int featureValues = DEFAULT_PARSER_FEATURE; + for (Feature feature : features) { + featureValues = Feature.config(featureValues, feature, true); + } + + DefaultJSONParser parser = new DefaultJSONParser(input, length, ParserConfig.getGlobalInstance(), featureValues); + T value = (T) parser.parseObject(clazz); + + parser.handleResovleTask(value); + + parser.close(); + + return (T) value; + } + + /** + * @since 1.2.11 + */ + @SuppressWarnings("unchecked") + public static T parseObject(InputStream is, // + Type type, // + Feature... features) throws IOException { + return (T) parseObject(is, IOUtils.UTF8, type, features); + } + + /** + * @since 1.2.11 + */ + @SuppressWarnings("unchecked") + public static T parseObject(InputStream is, // + Charset charset, // + Type type, // + Feature... features) throws IOException { + if (charset == null) { + charset = IOUtils.UTF8; + } + + byte[] bytes = allocateBytes(1024 * 64); + int offset = 0; + for (;;) { + int readCount = is.read(bytes, offset, bytes.length - offset); + if (readCount == -1) { + break; + } + offset += readCount; + if (offset == bytes.length) { + byte[] newBytes = new byte[bytes.length * 3 / 2]; + System.arraycopy(bytes, 0, newBytes, 0, bytes.length); + bytes = newBytes; + } + } + + return (T) parseObject(bytes, 0, offset, charset, type, features); + } + + public static T parseObject(String text, Class clazz) { + return parseObject(text, clazz, new Feature[0]); + } + + public static JSONArray parseArray(String text) { + if (text == null) { + return null; + } + + DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance()); + + JSONArray array; + + JSONLexer lexer = parser.lexer; + if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(); + array = null; + } else if (lexer.token() == JSONToken.EOF) { + array = null; + } else { + array = new JSONArray(); + parser.parseArray(array); + + parser.handleResovleTask(array); + } + + parser.close(); + + return array; + } + + public static List parseArray(String text, Class clazz) { + if (text == null) { + return null; + } + + List list; + + DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance()); + JSONLexer lexer = parser.lexer; + int token = lexer.token(); + if (token == JSONToken.NULL) { + lexer.nextToken(); + list = null; + } else if (token == JSONToken.EOF && lexer.isBlankInput()) { + list = null; + } else { + list = new ArrayList(); + parser.parseArray(clazz, list); + + parser.handleResovleTask(list); + } + + parser.close(); + + return list; + } + + public static List parseArray(String text, Type[] types) { + if (text == null) { + return null; + } + + List list; + + DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance()); + Object[] objectArray = parser.parseArray(types); + if (objectArray == null) { + list = null; + } else { + list = Arrays.asList(objectArray); + } + + parser.handleResovleTask(list); + + parser.close(); + + return list; + } + + /** + * This method serializes the specified object into its equivalent Json representation. Note that this method works fine if the any of the object fields are of generic type, + * just the object itself should not be of a generic type. If you want to write out the object to a + * {@link Writer}, use {@link #writeJSONString(Writer, Object, SerializerFeature[])} instead. + * + * @param object the object for which json representation is to be created setting for fastjson + * @return Json representation of {@code object}. + */ + public static String toJSONString(Object object) { + return toJSONString(object, emptyFilters); + } + + public static String toJSONString(Object object, SerializerFeature... features) { + return toJSONString(object, DEFAULT_GENERATE_FEATURE, features); + } + + /** + * @since 1.2.11 + */ + public static String toJSONString(Object object, int defaultFeatures, SerializerFeature... features) { + SerializeWriter out = new SerializeWriter((Writer) null, defaultFeatures, features); + + try { + JSONSerializer serializer = new JSONSerializer(out); + serializer.write(object); + return out.toString(); + } finally { + out.close(); + } + } + + /** + * @since 1.1.14 + */ + public static String toJSONStringWithDateFormat(Object object, String dateFormat, + SerializerFeature... features) { + return toJSONString(object, SerializeConfig.globalInstance, null, dateFormat, DEFAULT_GENERATE_FEATURE, features); + } + + public static String toJSONString(Object object, SerializeFilter filter, SerializerFeature... features) { + return toJSONString(object, SerializeConfig.globalInstance, new SerializeFilter[] {filter}, null, DEFAULT_GENERATE_FEATURE, features); + } + + public static String toJSONString(Object object, SerializeFilter[] filters, SerializerFeature... features) { + return toJSONString(object, SerializeConfig.globalInstance, filters, null, DEFAULT_GENERATE_FEATURE, features); + } + + public static byte[] toJSONBytes(Object object, SerializerFeature... features) { + return toJSONBytes(object, DEFAULT_GENERATE_FEATURE, features); + } + + public static byte[] toJSONBytes(Object object, SerializeFilter filter, SerializerFeature... features) { + return toJSONBytes(object, SerializeConfig.globalInstance, new SerializeFilter[] {filter}, DEFAULT_GENERATE_FEATURE, features); + } + + /** + * @since 1.2.11 + */ + public static byte[] toJSONBytes(Object object, int defaultFeatures, SerializerFeature... features) { + return toJSONBytes(object, SerializeConfig.globalInstance, defaultFeatures, features); + } + + public static String toJSONString(Object object, SerializeConfig config, SerializerFeature... features) { + return toJSONString(object, config, (SerializeFilter) null, features); + } + + public static String toJSONString(Object object, // + SerializeConfig config, // + SerializeFilter filter, // + SerializerFeature... features) { + return toJSONString(object, config, new SerializeFilter[] {filter}, null, DEFAULT_GENERATE_FEATURE, features); + } + + public static String toJSONString(Object object, // + SerializeConfig config, // + SerializeFilter[] filters, // + SerializerFeature... features) { + return toJSONString(object, config, filters, null, DEFAULT_GENERATE_FEATURE, features); + } + + /** + * @since 1.2.9 + * @return + */ + public static String toJSONString(Object object, // + SerializeConfig config, // + SerializeFilter[] filters, // + String dateFormat, // + int defaultFeatures, // + SerializerFeature... features) { + SerializeWriter out = new SerializeWriter(null, defaultFeatures, features); + + try { + JSONSerializer serializer = new JSONSerializer(out, config); + + if (dateFormat != null && dateFormat.length() != 0) { + serializer.setDateFormat(dateFormat); + serializer.config(SerializerFeature.WriteDateUseDateFormat, true); + } + + if (filters != null) { + for (SerializeFilter filter : filters) { + serializer.addFilter(filter); + } + } + + serializer.write(object); + + return out.toString(); + } finally { + out.close(); + } + } + + /** + * @deprecated + */ + public static String toJSONStringZ(Object object, SerializeConfig mapping, SerializerFeature... features) { + return toJSONString(object, mapping, emptyFilters, null, 0, features); + } + + /** + * @since 1.2.42 + */ + public static byte[] toJSONBytes(Object object, SerializeConfig config, SerializerFeature... features) { + return toJSONBytes(object, config, emptyFilters, DEFAULT_GENERATE_FEATURE, features); + } + + /** + * @since 1.2.11 + */ + public static byte[] toJSONBytes(Object object, SerializeConfig config, int defaultFeatures, SerializerFeature... features) { + return toJSONBytes(object, config, emptyFilters, defaultFeatures, features); + } + + /** + * @since 1.2.42 + */ + public static byte[] toJSONBytes(Object object, SerializeFilter[] filters, SerializerFeature... features) { + return toJSONBytes(object, SerializeConfig.globalInstance, filters, DEFAULT_GENERATE_FEATURE, features); + } + + public static byte[] toJSONBytes(Object object, SerializeConfig config, SerializeFilter filter, SerializerFeature... features) { + return toJSONBytes(object, config, new SerializeFilter[] {filter}, DEFAULT_GENERATE_FEATURE, features); + } + + /** + * @since 1.2.42 + */ + public static byte[] toJSONBytes(Object object, SerializeConfig config, SerializeFilter[] filters, int defaultFeatures, SerializerFeature... features) { + SerializeWriter out = new SerializeWriter(null, defaultFeatures, features); + + try { + JSONSerializer serializer = new JSONSerializer(out, config); + + if (filters != null) { + for (SerializeFilter filter : filters) { + serializer.addFilter(filter); + } + } + + serializer.write(object); + return out.toBytes(IOUtils.UTF8); + } finally { + out.close(); + } + } + + public static String toJSONString(Object object, boolean prettyFormat) { + if (!prettyFormat) { + return toJSONString(object); + } + + return toJSONString(object, SerializerFeature.PrettyFormat); + } + + /** + * @deprecated use writeJSONString + */ + public static void writeJSONStringTo(Object object, Writer writer, SerializerFeature... features) { + writeJSONString(writer, object, features); + } + + /** + * This method serializes the specified object into its equivalent json representation. + * + * @param writer Writer to which the json representation needs to be written + * @param object the object for which json representation is to be created setting for fastjson + * @param features serializer features + * @since 1.2.11 + */ + public static void writeJSONString(Writer writer, Object object, SerializerFeature... features) { + writeJSONString(writer, object, JSON.DEFAULT_GENERATE_FEATURE, features); + } + + /** + * @since 1.2.11 + */ + public static void writeJSONString(Writer writer, Object object, int defaultFeatures, SerializerFeature... features) { + SerializeWriter out = new SerializeWriter(writer, defaultFeatures, features); + + try { + JSONSerializer serializer = new JSONSerializer(out); + serializer.write(object); + } finally { + out.close(); + } + } + + /** + * write object as json to OutputStream + * @param os output stream + * @param object + * @param features serializer features + * @since 1.2.11 + * @throws IOException + */ + public static final int writeJSONString(OutputStream os, // + Object object, // + SerializerFeature... features) throws IOException { + return writeJSONString(os, object, DEFAULT_GENERATE_FEATURE, features); + } + + /** + * @since 1.2.11 + */ + public static final int writeJSONString(OutputStream os, // + Object object, // + int defaultFeatures, // + SerializerFeature... features) throws IOException { + return writeJSONString(os, // + IOUtils.UTF8, // + object, // + SerializeConfig.globalInstance, // + null, // + null, // + defaultFeatures, // + features); + } + + public static final int writeJSONString(OutputStream os, // + Charset charset, // + Object object, // + SerializerFeature... features) throws IOException { + return writeJSONString(os, // + charset, // + object, // + SerializeConfig.globalInstance, // + null, // + null, // + DEFAULT_GENERATE_FEATURE, // + features); + } + + public static final int writeJSONString(OutputStream os, // + Charset charset, // + Object object, // + SerializeConfig config, // + SerializeFilter[] filters, // + String dateFormat, // + int defaultFeatures, // + SerializerFeature... features) throws IOException { + SerializeWriter writer = new SerializeWriter(null, defaultFeatures, features); + + try { + JSONSerializer serializer = new JSONSerializer(writer, config); + + if (dateFormat != null && dateFormat.length() != 0) { + serializer.setDateFormat(dateFormat); + serializer.config(SerializerFeature.WriteDateUseDateFormat, true); + } + + if (filters != null) { + for (SerializeFilter filter : filters) { + serializer.addFilter(filter); + } + } + + serializer.write(object); + + int len = writer.writeToEx(os, charset); + return len; + } finally { + writer.close(); + } + } + + // ====================================== + @Override + public String toString() { + return toJSONString(); + } + + public String toJSONString() { + SerializeWriter out = new SerializeWriter(); + try { + new JSONSerializer(out).write(this); + return out.toString(); + } finally { + out.close(); + } + } + + public void writeJSONString(Appendable appendable) { + SerializeWriter out = new SerializeWriter(); + try { + new JSONSerializer(out).write(this); + appendable.append(out.toString()); + } catch (IOException e) { + throw new JSONException(e.getMessage(), e); + } finally { + out.close(); + } + } + + /** + * This method serializes the specified object into its equivalent representation as a tree of + * {@link JSONObject}s. + * + */ + public static Object toJSON(Object javaObject) { + return toJSON(javaObject, SerializeConfig.globalInstance); + } + + /** + * @deprecated + */ + public static Object toJSON(Object javaObject, ParserConfig parserConfig) { + return toJSON(javaObject, SerializeConfig.globalInstance); + } + + @SuppressWarnings("unchecked") + public static Object toJSON(Object javaObject, SerializeConfig config) { + if (javaObject == null) { + return null; + } + + if (javaObject instanceof JSON) { + return javaObject; + } + + if (javaObject instanceof Map) { + Map map = (Map) javaObject; + + int size = map.size(); + + Map innerMap; + if (map instanceof LinkedHashMap) { + innerMap = new LinkedHashMap(size); + } else if (map instanceof TreeMap) { + innerMap = new TreeMap(); + } else { + innerMap = new HashMap(size); + } + + JSONObject json = new JSONObject(innerMap); + + for (Map.Entry entry : map.entrySet()) { + Object key = entry.getKey(); + String jsonKey = TypeUtils.castToString(key); + Object jsonValue = toJSON(entry.getValue()); + json.put(jsonKey, jsonValue); + } + + return json; + } + + if (javaObject instanceof Collection) { + Collection collection = (Collection) javaObject; + + JSONArray array = new JSONArray(collection.size()); + + for (Object item : collection) { + Object jsonValue = toJSON(item); + array.add(jsonValue); + } + + return array; + } + + if (javaObject instanceof JSONSerializable) { + String json = JSON.toJSONString(javaObject); + return JSON.parse(json); + } + + Class clazz = javaObject.getClass(); + + if (clazz.isEnum()) { + return ((Enum) javaObject).name(); + } + + if (clazz.isArray()) { + int len = Array.getLength(javaObject); + + JSONArray array = new JSONArray(len); + + for (int i = 0; i < len; ++i) { + Object item = Array.get(javaObject, i); + Object jsonValue = toJSON(item); + array.add(jsonValue); + } + + return array; + } + + if (ParserConfig.isPrimitive2(clazz)) { + return javaObject; + } + + ObjectSerializer serializer = config.getObjectWriter(clazz); + if (serializer instanceof JavaBeanSerializer) { + JavaBeanSerializer javaBeanSerializer = (JavaBeanSerializer) serializer; + + JSONObject json = new JSONObject(); + try { + Map values = javaBeanSerializer.getFieldValuesMap(javaObject); + for (Map.Entry entry : values.entrySet()) { + json.put(entry.getKey(), toJSON(entry.getValue())); + } + } catch (Exception e) { + throw new JSONException("toJSON error", e); + } + return json; + } + + String text = JSON.toJSONString(javaObject); + return JSON.parse(text); + } + + public static T toJavaObject(JSON json, Class clazz) { + return TypeUtils.cast(json, clazz, ParserConfig.getGlobalInstance()); + } + + /** + * @since 1.2.9 + */ + public T toJavaObject(Class clazz) { + return TypeUtils.cast(this, clazz, ParserConfig.getGlobalInstance()); + } + + /** + * @since 1.2.33 + */ + public T toJavaObject(Type type) { + return TypeUtils.cast(this, type, ParserConfig.getGlobalInstance()); + } + + /** + * @since 1.2.33 + */ + public T toJavaObject(TypeReference typeReference) { + Type type = typeReference != null ? typeReference.getType() : null; + return TypeUtils.cast(this, type, ParserConfig.getGlobalInstance()); + } + + private final static ThreadLocal bytesLocal = new ThreadLocal(); + private static byte[] allocateBytes(int length) { + byte[] chars = bytesLocal.get(); + + if (chars == null) { + if (length <= 1024 * 64) { + chars = new byte[1024 * 64]; + bytesLocal.set(chars); + } else { + chars = new byte[length]; + } + } else if (chars.length < length) { + chars = new byte[length]; + } + + return chars; + } + + private final static ThreadLocal charsLocal = new ThreadLocal(); + private static char[] allocateChars(int length) { + char[] chars = charsLocal.get(); + + if (chars == null) { + if (length <= 1024 * 64) { + chars = new char[1024 * 64]; + charsLocal.set(chars); + } else { + chars = new char[length]; + } + } else if (chars.length < length) { + chars = new char[length]; + } + + return chars; + } + + public static void handleResovleTask(DefaultJSONParser parser, T value) { + parser.handleResovleTask(value); + } + + public final static String VERSION = "1.2.48"; +} diff --git a/src/main/java/com/alibaba/fastjson/JSONArray.java b/src/main/java/com/alibaba/fastjson/JSONArray.java old mode 100644 new mode 100755 index f80155505c..7e73d773d3 --- a/src/main/java/com/alibaba/fastjson/JSONArray.java +++ b/src/main/java/com/alibaba/fastjson/JSONArray.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ import static com.alibaba.fastjson.util.TypeUtils.castToTimestamp; import java.io.Serializable; +import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; @@ -39,18 +40,22 @@ import java.util.ListIterator; import java.util.RandomAccess; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.alibaba.fastjson.util.TypeUtils; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ -public class JSONArray extends JSON implements List, JSONAware, Cloneable, RandomAccess, Serializable { +public class JSONArray extends JSON implements List, Cloneable, RandomAccess, Serializable { private static final long serialVersionUID = 1L; private final List list; + protected transient Object relatedArray; + protected transient Type componentType; public JSONArray(){ - this.list = new ArrayList(10); + this.list = new ArrayList(); } public JSONArray(List list){ @@ -61,6 +66,26 @@ public JSONArray(int initialCapacity){ this.list = new ArrayList(initialCapacity); } + /** + * @since 1.1.16 + * @return + */ + public Object getRelatedArray() { + return relatedArray; + } + + public void setRelatedArray(Object relatedArray) { + this.relatedArray = relatedArray; + } + + public Type getComponentType() { + return componentType; + } + + public void setComponentType(Type componentType) { + this.componentType = componentType; + } + public int size() { return list.size(); } @@ -89,10 +114,20 @@ public boolean add(Object e) { return list.add(e); } + public JSONArray fluentAdd(Object e) { + list.add(e); + return this; + } + public boolean remove(Object o) { return list.remove(o); } + public JSONArray fluentRemove(Object o) { + list.remove(o); + return this; + } + public boolean containsAll(Collection c) { return list.containsAll(c); } @@ -101,34 +136,87 @@ public boolean addAll(Collection c) { return list.addAll(c); } + public JSONArray fluentAddAll(Collection c) { + list.addAll(c); + return this; + } + public boolean addAll(int index, Collection c) { return list.addAll(index, c); } + public JSONArray fluentAddAll(int index, Collection c) { + list.addAll(index, c); + return this; + } + public boolean removeAll(Collection c) { return list.removeAll(c); } + public JSONArray fluentRemoveAll(Collection c) { + list.removeAll(c); + return this; + } + public boolean retainAll(Collection c) { return list.retainAll(c); } + public JSONArray fluentRetainAll(Collection c) { + list.retainAll(c); + return this; + } + public void clear() { list.clear(); } + public JSONArray fluentClear() { + list.clear(); + return this; + } + public Object set(int index, Object element) { + if (index == -1) { + list.add(element); + return null; + } + + if (list.size() <= index) { + for (int i = list.size(); i < index; ++i) { + list.add(null); + } + list.add(element); + return null; + } + return list.set(index, element); } + public JSONArray fluentSet(int index, Object element) { + set(index, element); + return this; + } + public void add(int index, Object element) { list.add(index, element); } + public JSONArray fluentAdd(int index, Object element) { + list.add(index, element); + return this; + } + public Object remove(int index) { return list.remove(index); } + public JSONArray fluentRemove(int index) { + list.remove(index); + return this; + } + public int indexOf(Object o) { return list.indexOf(o); } @@ -178,6 +266,16 @@ public T getObject(int index, Class clazz) { return TypeUtils.castToJavaBean(obj, clazz); } + public T getObject(int index, Type type) { + Object obj = list.get(index); + if (type instanceof Class) { + return (T) TypeUtils.castToJavaBean(obj, (Class) type); + } else { + String json = JSON.toJSONString(obj); + return (T) JSON.parseObject(json, type); + } + } + public Boolean getBoolean(int index) { Object value = get(index); @@ -291,7 +389,7 @@ public double getDoubleValue(int index) { return 0D; } - return castToDouble(value).floatValue(); + return castToDouble(value); } public BigDecimal getBigDecimal(int index) { @@ -330,15 +428,31 @@ public java.sql.Timestamp getTimestamp(int index) { return castToTimestamp(value); } + /** + * @since 1.2.23 + */ + public List toJavaList(Class clazz) { + List list = new ArrayList(this.size()); + + ParserConfig config = ParserConfig.getGlobalInstance(); + + for (Object item : this) { + T classItem = (T) TypeUtils.cast(item, clazz, config); + list.add(classItem); + } + + return list; + } + @Override public Object clone() { return new JSONArray(new ArrayList(list)); } - + public boolean equals(Object obj) { return this.list.equals(obj); } - + public int hashCode() { return this.list.hashCode(); } diff --git a/src/main/java/com/alibaba/fastjson/JSONAware.java b/src/main/java/com/alibaba/fastjson/JSONAware.java old mode 100644 new mode 100755 index b388a4414d..b552548fbe --- a/src/main/java/com/alibaba/fastjson/JSONAware.java +++ b/src/main/java/com/alibaba/fastjson/JSONAware.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ /** * Beans that support customized output of JSON text shall implement this interface. * - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public interface JSONAware { diff --git a/src/main/java/com/alibaba/fastjson/JSONException.java b/src/main/java/com/alibaba/fastjson/JSONException.java old mode 100644 new mode 100755 index 4a27ee2dec..6dcae3675c --- a/src/main/java/com/alibaba/fastjson/JSONException.java +++ b/src/main/java/com/alibaba/fastjson/JSONException.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,11 @@ package com.alibaba.fastjson; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ +@SuppressWarnings("serial") public class JSONException extends RuntimeException { - private static final long serialVersionUID = 1L; - public JSONException(){ super(); } diff --git a/src/main/java/com/alibaba/fastjson/JSONObject.java b/src/main/java/com/alibaba/fastjson/JSONObject.java old mode 100644 new mode 100755 index b58db975f6..6476c2fac9 --- a/src/main/java/com/alibaba/fastjson/JSONObject.java +++ b/src/main/java/com/alibaba/fastjson/JSONObject.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import static com.alibaba.fastjson.util.TypeUtils.castToBigInteger; import static com.alibaba.fastjson.util.TypeUtils.castToBoolean; import static com.alibaba.fastjson.util.TypeUtils.castToByte; +import static com.alibaba.fastjson.util.TypeUtils.castToBytes; import static com.alibaba.fastjson.util.TypeUtils.castToDate; import static com.alibaba.fastjson.util.TypeUtils.castToDouble; import static com.alibaba.fastjson.util.TypeUtils.castToFloat; @@ -29,6 +30,9 @@ import static com.alibaba.fastjson.util.TypeUtils.castToTimestamp; import java.io.Serializable; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; @@ -38,12 +42,14 @@ import java.util.Map; import java.util.Set; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.util.TypeUtils; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ -public class JSONObject extends JSON implements Map, JSONAware, Cloneable, Serializable { +public class JSONObject extends JSON implements Map, Cloneable, Serializable, InvocationHandler { private static final long serialVersionUID = 1L; private static final int DEFAULT_INITIAL_CAPACITY = 16; @@ -91,7 +97,13 @@ public boolean containsValue(Object value) { } public Object get(Object key) { - return map.get(key); + Object val = map.get(key); + + if (val == null && key instanceof Number) { + val = map.get(key.toString()); + } + + return val; } public JSONObject getJSONObject(String key) { @@ -101,6 +113,10 @@ public JSONObject getJSONObject(String key) { return (JSONObject) value; } + if (value instanceof String) { + return JSON.parseObject((String) value); + } + return (JSONObject) toJSON(value); } @@ -111,6 +127,10 @@ public JSONArray getJSONArray(String key) { return (JSONArray) value; } + if (value instanceof String) { + return (JSONArray) JSON.parse((String) value); + } + return (JSONArray) toJSON(value); } @@ -119,6 +139,19 @@ public T getObject(String key, Class clazz) { return TypeUtils.castToJavaBean(obj, clazz); } + public T getObject(String key, Type type) { + Object obj = map.get(key); + return TypeUtils.cast(obj, type, ParserConfig.getGlobalInstance()); + } + + public T getObject(String key, TypeReference typeReference) { + Object obj = map.get(key); + if (typeReference == null) { + return (T) obj; + } + return TypeUtils.cast(obj, typeReference.getType(), ParserConfig.getGlobalInstance()); + } + public Boolean getBoolean(String key) { Object value = get(key); @@ -129,14 +162,25 @@ public Boolean getBoolean(String key) { return castToBoolean(value); } - public boolean getBooleanValue(String key) { + public byte[] getBytes(String key) { Object value = get(key); if (value == null) { + return null; + } + + return castToBytes(value); + } + + public boolean getBooleanValue(String key) { + Object value = get(key); + + Boolean booleanVal = castToBoolean(value); + if (booleanVal == null) { return false; } - return castToBoolean(value).booleanValue(); + return booleanVal.booleanValue(); } public Byte getByte(String key) { @@ -148,11 +192,12 @@ public Byte getByte(String key) { public byte getByteValue(String key) { Object value = get(key); - if (value == null) { + Byte byteVal = castToByte(value); + if (byteVal == null) { return 0; } - return castToByte(value).byteValue(); + return byteVal.byteValue(); } public Short getShort(String key) { @@ -164,11 +209,12 @@ public Short getShort(String key) { public short getShortValue(String key) { Object value = get(key); - if (value == null) { + Short shortVal = castToShort(value); + if (shortVal == null) { return 0; } - return castToShort(value).shortValue(); + return shortVal.shortValue(); } public Integer getInteger(String key) { @@ -180,11 +226,12 @@ public Integer getInteger(String key) { public int getIntValue(String key) { Object value = get(key); - if (value == null) { + Integer intVal = castToInt(value); + if (intVal == null) { return 0; } - return castToInt(value).intValue(); + return intVal.intValue(); } public Long getLong(String key) { @@ -196,11 +243,12 @@ public Long getLong(String key) { public long getLongValue(String key) { Object value = get(key); - if (value == null) { + Long longVal = castToLong(value); + if (longVal == null) { return 0L; } - return castToLong(value).longValue(); + return longVal.longValue(); } public Float getFloat(String key) { @@ -212,11 +260,12 @@ public Float getFloat(String key) { public float getFloatValue(String key) { Object value = get(key); - if (value == null) { + Float floatValue = castToFloat(value); + if (floatValue == null) { return 0F; } - return castToFloat(value).floatValue(); + return floatValue.floatValue(); } public Double getDouble(String key) { @@ -228,11 +277,12 @@ public Double getDouble(String key) { public double getDoubleValue(String key) { Object value = get(key); - if (value == null) { + Double doubleValue = castToDouble(value); + if (doubleValue == null) { return 0D; } - return castToDouble(value).floatValue(); + return doubleValue.doubleValue(); } public BigDecimal getBigDecimal(String key) { @@ -274,23 +324,43 @@ public java.sql.Timestamp getTimestamp(String key) { return castToTimestamp(value); } - + public Object put(String key, Object value) { return map.put(key, value); } + + public JSONObject fluentPut(String key, Object value) { + map.put(key, value); + return this; + } public void putAll(Map m) { map.putAll(m); } + public JSONObject fluentPutAll(Map m) { + map.putAll(m); + return this; + } + public void clear() { map.clear(); } + public JSONObject fluentClear() { + map.clear(); + return this; + } + public Object remove(Object key) { return map.remove(key); } + public JSONObject fluentRemove(Object key) { + map.remove(key); + return this; + } + public Set keySet() { return map.keySet(); } @@ -305,14 +375,103 @@ public Set> entrySet() { @Override public Object clone() { - return new JSONObject(new HashMap(map)); + return new JSONObject(map instanceof LinkedHashMap // + ? new LinkedHashMap(map) // + : new HashMap(map) + ); } - + public boolean equals(Object obj) { return this.map.equals(obj); } - + public int hashCode() { return this.map.hashCode(); } + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + Class[] parameterTypes = method.getParameterTypes(); + if (parameterTypes.length == 1) { + if (method.getName().equals("equals")) { + return this.equals(args[0]); + } + + Class returnType = method.getReturnType(); + if (returnType != void.class) { + throw new JSONException("illegal setter"); + } + + String name = null; + JSONField annotation = method.getAnnotation(JSONField.class); + if (annotation != null) { + if (annotation.name().length() != 0) { + name = annotation.name(); + } + } + + if (name == null) { + name = method.getName(); + + if (!name.startsWith("set")) { + throw new JSONException("illegal setter"); + } + + name = name.substring(3); + if (name.length() == 0) { + throw new JSONException("illegal setter"); + } + name = Character.toLowerCase(name.charAt(0)) + name.substring(1); + } + + map.put(name, args[0]); + return null; + } + + if (parameterTypes.length == 0) { + Class returnType = method.getReturnType(); + if (returnType == void.class) { + throw new JSONException("illegal getter"); + } + + String name = null; + JSONField annotation = method.getAnnotation(JSONField.class); + if (annotation != null) { + if (annotation.name().length() != 0) { + name = annotation.name(); + } + } + + if (name == null) { + name = method.getName(); + if (name.startsWith("get")) { + name = name.substring(3); + if (name.length() == 0) { + throw new JSONException("illegal getter"); + } + name = Character.toLowerCase(name.charAt(0)) + name.substring(1); + } else if (name.startsWith("is")) { + name = name.substring(2); + if (name.length() == 0) { + throw new JSONException("illegal getter"); + } + name = Character.toLowerCase(name.charAt(0)) + name.substring(1); + } else if (name.startsWith("hashCode")) { + return this.hashCode(); + } else if (name.startsWith("toString")) { + return this.toString(); + } else { + throw new JSONException("illegal getter"); + } + } + + Object value = map.get(name); + return TypeUtils.cast(value, method.getGenericReturnType(), ParserConfig.getGlobalInstance()); + } + + throw new UnsupportedOperationException(method.toGenericString()); + } + + public Map getInnerMap() { + return this.map; + } } diff --git a/src/main/java/com/alibaba/fastjson/JSONPObject.java b/src/main/java/com/alibaba/fastjson/JSONPObject.java new file mode 100644 index 0000000000..65d018ad08 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/JSONPObject.java @@ -0,0 +1,70 @@ +package com.alibaba.fastjson; + +import com.alibaba.fastjson.serializer.JSONSerializable; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +public class JSONPObject implements JSONSerializable { + public static String SECURITY_PREFIX = "/**/"; + private String function; + + private static final int BrowserSecureMask = SerializerFeature.BrowserSecure.mask; + + private final List parameters = new ArrayList(); + + public JSONPObject() { + + } + + public JSONPObject(String function) { + this.function = function; + } + + public String getFunction() { + return function; + } + + public void setFunction(String function) { + this.function = function; + } + + public List getParameters() { + return parameters; + } + + public void addParameter(Object parameter) { + this.parameters.add(parameter); + } + + public String toJSONString() { + return toString(); + } + + public void write(JSONSerializer serializer, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter writer = serializer.out; + + if ((features & BrowserSecureMask) != 0 || (writer.isEnabled(BrowserSecureMask))) { + writer.write(SECURITY_PREFIX); + } + + writer.write(function); + writer.write('('); + for (int i = 0; i < parameters.size(); ++i) { + if (i != 0) { + writer.write(','); + } + serializer.write(parameters.get(i)); + } + writer.write(')'); + } + + public String toString() { + return JSON.toJSONString(this); + } +} diff --git a/src/main/java/com/alibaba/fastjson/JSONPath.java b/src/main/java/com/alibaba/fastjson/JSONPath.java new file mode 100644 index 0000000000..fe299d6006 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/JSONPath.java @@ -0,0 +1,2913 @@ +package com.alibaba.fastjson; + +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.FieldDeserializer; +import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.serializer.FieldSerializer; +import com.alibaba.fastjson.serializer.JavaBeanSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.util.IOUtils; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + * @since 1.2.0 + */ +public class JSONPath implements JSONAware { + private static ConcurrentMap pathCache = new ConcurrentHashMap(128, 0.75f, 1); + + private final String path; + private Segement[] segments; + + private SerializeConfig serializeConfig; + private ParserConfig parserConfig; + + public JSONPath(String path){ + this(path, SerializeConfig.getGlobalInstance(), ParserConfig.getGlobalInstance()); + } + + public JSONPath(String path, SerializeConfig serializeConfig, ParserConfig parserConfig){ + if (path == null || path.length() == 0) { + throw new JSONPathException("json-path can not be null or empty"); + } + + this.path = path; + this.serializeConfig = serializeConfig; + this.parserConfig = parserConfig; + } + + protected void init() { + if (segments != null) { + return; + } + + if ("*".equals(path)) { + this.segments = new Segement[] { WildCardSegement.instance }; + } else { + JSONPathParser parser = new JSONPathParser(path); + this.segments = parser.explain(); + } + } + + public Object eval(Object rootObject) { + if (rootObject == null) { + return null; + } + + init(); + + Object currentObject = rootObject; + for (int i = 0; i < segments.length; ++i) { + Segement segement = segments[i]; + currentObject = segement.eval(this, rootObject, currentObject); + } + return currentObject; + } + + public boolean contains(Object rootObject) { + if (rootObject == null) { + return false; + } + + init(); + + Object currentObject = rootObject; + for (int i = 0; i < segments.length; ++i) { + currentObject = segments[i].eval(this, rootObject, currentObject); + if (currentObject == null) { + return false; + } + } + + return true; + } + + @SuppressWarnings("rawtypes") + public boolean containsValue(Object rootObject, Object value) { + Object currentObject = eval(rootObject); + + if (currentObject == value) { + return true; + } + + if (currentObject == null) { + return false; + } + + if (currentObject instanceof Iterable) { + Iterator it = ((Iterable) currentObject).iterator(); + while (it.hasNext()) { + Object item = it.next(); + if (eq(item, value)) { + return true; + } + } + + return false; + } + + return eq(currentObject, value); + } + + public int size(Object rootObject) { + if (rootObject == null) { + return -1; + } + + init(); + + Object currentObject = rootObject; + for (int i = 0; i < segments.length; ++i) { + currentObject = segments[i].eval(this, rootObject, currentObject); + } + + return evalSize(currentObject); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void arrayAdd(Object rootObject, Object... values) { + if (values == null || values.length == 0) { + return; + } + + if (rootObject == null) { + return; + } + + init(); + + Object currentObject = rootObject; + Object parentObject = null; + for (int i = 0; i < segments.length; ++i) { + if (i == segments.length - 1) { + parentObject = currentObject; + } + currentObject = segments[i].eval(this, rootObject, currentObject); + } + + Object result = currentObject; + + if (result == null) { + throw new JSONPathException("value not found in path " + path); + } + + if (result instanceof Collection) { + Collection collection = (Collection) result; + for (Object value : values) { + collection.add(value); + } + return; + } + + Class resultClass = result.getClass(); + + Object newResult; + if (resultClass.isArray()) { + int length = Array.getLength(result); + Object descArray = Array.newInstance(resultClass.getComponentType(), length + values.length); + + System.arraycopy(result, 0, descArray, 0, length); + for (int i = 0; i < values.length; ++i) { + Array.set(descArray, length + i, values[i]); + + } + newResult = descArray; + } else { + throw new JSONException("unsupported array put operation. " + resultClass); + } + + Segement lastSegement = segments[segments.length - 1]; + if (lastSegement instanceof PropertySegement) { + PropertySegement propertySegement = (PropertySegement) lastSegement; + propertySegement.setValue(this, parentObject, newResult); + return; + } + + if (lastSegement instanceof ArrayAccessSegement) { + ((ArrayAccessSegement) lastSegement).setValue(this, parentObject, newResult); + return; + } + + throw new UnsupportedOperationException(); + } + + public boolean remove(Object rootObject) { + if (rootObject == null) { + return false; + } + + init(); + + Object currentObject = rootObject; + Object parentObject = null; + for (int i = 0; i < segments.length; ++i) { + if (i == segments.length - 1) { + parentObject = currentObject; + break; + } + currentObject = segments[i].eval(this, rootObject, currentObject); + if (currentObject == null) { + break; + } + } + + if (parentObject == null) { + return false; + } + + Segement lastSegement = segments[segments.length - 1]; + if (lastSegement instanceof PropertySegement) { + PropertySegement propertySegement = (PropertySegement) lastSegement; + + if (parentObject instanceof Collection) { + if (segments.length > 1) { + Segement parentSegement = segments[segments.length - 2]; + if (parentSegement instanceof RangeSegement || parentSegement instanceof MultiIndexSegement) { + Collection collection = (Collection) parentObject; + boolean removedOnce = false; + for (Object item : collection) { + boolean removed = propertySegement.remove(this, item); + if (removed) { + removedOnce = true; + } + } + return removedOnce; + } + } + } + return propertySegement.remove(this, parentObject); + } + + if (lastSegement instanceof ArrayAccessSegement) { + return ((ArrayAccessSegement) lastSegement).remove(this, parentObject); + } + + throw new UnsupportedOperationException(); + } + + public boolean set(Object rootObject, Object value) { + return set(rootObject, value, true); + } + + public boolean set(Object rootObject, Object value, boolean p) { + if (rootObject == null) { + return false; + } + + init(); + + Object currentObject = rootObject; + Object parentObject = null; + for (int i = 0; i < segments.length; ++i) { +// if (i == segments.length - 1) { +// parentObject = currentObject; +// break; +// } +// + parentObject = currentObject; + Segement segment = segments[i]; + currentObject = segment.eval(this, rootObject, currentObject); + if (currentObject == null) { + Segement nextSegement = null; + if (i < segments.length - 1) { + nextSegement = segments[i + 1]; + } + + Object newObj = null; + if (nextSegement instanceof PropertySegement) { + JavaBeanDeserializer beanDeserializer = null; + Class fieldClass = null; + if (segment instanceof PropertySegement) { + String propertyName = ((PropertySegement) segment).propertyName; + Class parentClass = parentObject.getClass(); + JavaBeanDeserializer parentBeanDeserializer = getJavaBeanDeserializer(parentClass); + if (parentBeanDeserializer != null) { + FieldDeserializer fieldDeserializer = parentBeanDeserializer.getFieldDeserializer(propertyName); + fieldClass = fieldDeserializer.fieldInfo.fieldClass; + beanDeserializer = getJavaBeanDeserializer(fieldClass); + } + } + + if (beanDeserializer != null) { + + if (beanDeserializer.beanInfo.defaultConstructor != null) { + newObj = beanDeserializer.createInstance(null, fieldClass); + } else { + return false; + } + } else { + newObj = new JSONObject(); + } + } else if (nextSegement instanceof ArrayAccessSegement) { + newObj = new JSONArray(); + } + + if (newObj != null) { + if (segment instanceof PropertySegement) { + PropertySegement propSegement = (PropertySegement) segment; + propSegement.setValue(this, parentObject, newObj); + currentObject = newObj; + continue; + } else if (segment instanceof ArrayAccessSegement) { + ArrayAccessSegement arrayAccessSegement = (ArrayAccessSegement) segment; + arrayAccessSegement.setValue(this, parentObject, newObj); + currentObject = newObj; + continue; + } + } + + break; + } + } + + if (parentObject == null) { + return false; + } + + Segement lastSegement = segments[segments.length - 1]; + if (lastSegement instanceof PropertySegement) { + PropertySegement propertySegement = (PropertySegement) lastSegement; + propertySegement.setValue(this, parentObject, value); + return true; + } + + if (lastSegement instanceof ArrayAccessSegement) { + return ((ArrayAccessSegement) lastSegement).setValue(this, parentObject, value); + } + + throw new UnsupportedOperationException(); + } + + public static Object eval(Object rootObject, String path) { + JSONPath jsonpath = compile(path); + return jsonpath.eval(rootObject); + } + + public static int size(Object rootObject, String path) { + JSONPath jsonpath = compile(path); + Object result = jsonpath.eval(rootObject); + return jsonpath.evalSize(result); + } + + public static boolean contains(Object rootObject, String path) { + if (rootObject == null) { + return false; + } + + JSONPath jsonpath = compile(path); + return jsonpath.contains(rootObject); + } + + public static boolean containsValue(Object rootObject, String path, Object value) { + JSONPath jsonpath = compile(path); + return jsonpath.containsValue(rootObject, value); + } + + public static void arrayAdd(Object rootObject, String path, Object... values) { + JSONPath jsonpath = compile(path); + jsonpath.arrayAdd(rootObject, values); + } + + public static boolean set(Object rootObject, String path, Object value) { + JSONPath jsonpath = compile(path); + return jsonpath.set(rootObject, value); + } + + public static boolean remove(Object root, String path) { + JSONPath jsonpath = compile(path); + return jsonpath.remove(root); + } + + public static JSONPath compile(String path) { + if (path == null) { + throw new JSONPathException("jsonpath can not be null"); + } + + JSONPath jsonpath = pathCache.get(path); + if (jsonpath == null) { + jsonpath = new JSONPath(path); + if (pathCache.size() < 1024) { + pathCache.putIfAbsent(path, jsonpath); + jsonpath = pathCache.get(path); + } + } + return jsonpath; + } + + /** + * @since 1.2.9 + * @param json + * @param path + * @return + */ + public static Object read(String json, String path) { + Object object = JSON.parse(json); + JSONPath jsonpath = compile(path); + return jsonpath.eval(object); + } + + public static Map paths(Object javaObject) { + return paths(javaObject, SerializeConfig.globalInstance); + } + + public static Map paths(Object javaObject, SerializeConfig config) { + Map values = new IdentityHashMap(); + Map paths = new HashMap(); + + paths(values, paths, "/", javaObject, config); + return paths; + } + + private static void paths(Map values, Map paths, String parent, Object javaObject, SerializeConfig config) { + if (javaObject == null) { + return; + } + + String p = values.put(javaObject, parent); + if (p != null) { + boolean basicType = javaObject instanceof String + || javaObject instanceof Number + || javaObject instanceof Date + || javaObject instanceof UUID; + + if (!basicType) { + return; + } + } + + paths.put(parent, javaObject); + + if (javaObject instanceof Map) { + Map map = (Map) javaObject; + + for (Object entryObj : map.entrySet()) { + Map.Entry entry = (Map.Entry) entryObj; + Object key = entry.getKey(); + + if (key instanceof String) { + String path = parent.equals("/") ? "/" + key : parent + "/" + key; + paths(values, paths, path, entry.getValue(), config); + } + } + return; + } + + if (javaObject instanceof Collection) { + Collection collection = (Collection) javaObject; + + int i = 0; + for (Object item : collection) { + String path = parent.equals("/") ? "/" + i : parent + "/" + i; + paths(values, paths, path, item, config); + ++i; + } + + return; + } + + Class clazz = javaObject.getClass(); + + if (clazz.isArray()) { + int len = Array.getLength(javaObject); + + for (int i = 0; i < len; ++i) { + Object item = Array.get(javaObject, i); + + String path = parent.equals("/") ? "/" + i : parent + "/" + i; + paths(values, paths, path, item, config); + } + + return; + } + + if (ParserConfig.isPrimitive2(clazz) || clazz.isEnum()) { + return; + } + + ObjectSerializer serializer = config.getObjectWriter(clazz); + if (serializer instanceof JavaBeanSerializer) { + JavaBeanSerializer javaBeanSerializer = (JavaBeanSerializer) serializer; + + try { + Map fieldValues = javaBeanSerializer.getFieldValuesMap(javaObject); + for (Map.Entry entry : fieldValues.entrySet()) { + String key = entry.getKey(); + + if (key instanceof String) { + String path = parent.equals("/") ? "/" + key : parent + "/" + key; + paths(values, paths, path, entry.getValue(), config); + } + } + } catch (Exception e) { + throw new JSONException("toJSON error", e); + } + return; + } + + return; + } + + @SuppressWarnings("rawtypes") + private static void paths(Map paths, String parent, Object javaObject, SerializeConfig config) { + if (javaObject == null) { + return; + } + + if (paths.containsKey(javaObject)) { + return; + } + + paths.put(javaObject, parent); + + if (javaObject instanceof Map) { + Map map = (Map) javaObject; + + for (Object entryObj : map.entrySet()) { + Map.Entry entry = (Map.Entry) entryObj; + Object key = entry.getKey(); + + if (key instanceof String) { + String path = parent.equals("/") ? "/" + key : parent + "/" + key; + paths(paths, path, entry.getValue(), config); + } + } + return; + } + + if (javaObject instanceof Collection) { + Collection collection = (Collection) javaObject; + + int i = 0; + for (Object item : collection) { + String path = parent.equals("/") ? "/" + i : parent + "/" + i; + paths(paths, path, item, config); + ++i; + } + + return; + } + + Class clazz = javaObject.getClass(); + + if (clazz.isArray()) { + int len = Array.getLength(javaObject); + + for (int i = 0; i < len; ++i) { + Object item = Array.get(javaObject, i); + + String path = parent.equals("/") ? "/" + i : parent + "/" + i; + paths(paths, path, item, config); + } + + return; + } + + if (ParserConfig.isPrimitive2(clazz) || clazz.isEnum()) { + return; + } + + ObjectSerializer serializer = config.getObjectWriter(clazz); + if (serializer instanceof JavaBeanSerializer) { + JavaBeanSerializer javaBeanSerializer = (JavaBeanSerializer) serializer; + + try { + Map fieldValues = javaBeanSerializer.getFieldValuesMap(javaObject); + for (Map.Entry entry : fieldValues.entrySet()) { + String key = entry.getKey(); + + if (key instanceof String) { + String path = parent.equals("/") ? "/" + key : parent + "/" + key; + paths(paths, path, entry.getValue(), config); + } + } + } catch (Exception e) { + throw new JSONException("toJSON error", e); + } + return; + } + + return; + } + + public String getPath() { + return path; + } + + static class JSONPathParser { + + private final String path; + private int pos; + private char ch; + private int level; + + public JSONPathParser(String path){ + this.path = path; + next(); + } + + void next() { + ch = path.charAt(pos++); + } + + char getNextChar() { + return path.charAt(pos); + } + + boolean isEOF() { + return pos >= path.length(); + } + + Segement readSegement() { + if (level == 0 && path.length() == 1) { + if (isDigitFirst(ch)) { + int index = ch - '0'; + return new ArrayAccessSegement(index); + } else if ((ch >= 'a' && ch <= 'z') || ((ch >= 'A' && ch <= 'Z'))) { + return new PropertySegement(Character.toString(ch), false); + } + } + while (!isEOF()) { + skipWhitespace(); + + if (ch == '$') { + next(); + continue; + } + + if (ch == '.' || ch == '/') { + int c0 = ch; + boolean deep = false; + next(); + if (c0 == '.' && ch == '.') { + next(); + deep = true; + if (path.length() > pos + 3 + && ch == '[' + && path.charAt(pos) == '*' + && path.charAt(pos + 1) == ']' + && path.charAt(pos + 2) == '.') { + next(); + next(); + next(); + next(); + } + } + if (ch == '*') { + if (!isEOF()) { + next(); + } + + return WildCardSegement.instance; + } + + if (isDigitFirst(ch)) { + return parseArrayAccess(false); + } + + String propertyName = readName(); + if (ch == '(') { + next(); + if (ch == ')') { + if (!isEOF()) { + next(); + } + + if ("size".equals(propertyName) || "length".equals(propertyName)) { + return SizeSegement.instance; + } + + throw new JSONPathException("not support jsonpath : " + path); + } + + throw new JSONPathException("not support jsonpath : " + path); + } + + return new PropertySegement(propertyName, deep); + } + + if (ch == '[') { + return parseArrayAccess(true); + } + + if (level == 0) { + String propertyName = readName(); + + return new PropertySegement(propertyName, false); + } + + throw new JSONPathException("not support jsonpath : " + path); + } + + return null; + } + + public final void skipWhitespace() { + for (;;) { + if (ch <= ' ' && (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t' || ch == '\f' || ch == '\b')) { + next(); + continue; + } else { + break; + } + } + } + + Segement parseArrayAccess(boolean acceptBracket) { + Object object = parseArrayAccessFilter(acceptBracket); + if (object instanceof Segement) { + return ((Segement) object); + } + return new FilterSegement((Filter) object); + } + + Object parseArrayAccessFilter(boolean acceptBracket) { + if (acceptBracket) { + accept('['); + } + + boolean predicateFlag = false; + + if (ch == '?') { + next(); + accept('('); + if (ch == '@') { + next(); + accept('.'); + } + + predicateFlag = true; + } + + if (predicateFlag || IOUtils.firstIdentifier(ch)) { + String propertyName = readName(); + + skipWhitespace(); + + if (predicateFlag && ch == ')') { + next(); + + Filter filter = new NotNullSegement(propertyName); + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + + if (acceptBracket) { + accept(']'); + } + return filter; + } + + if (acceptBracket && ch == ']') { + next(); + Filter filter = new NotNullSegement(propertyName); + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + + accept(')'); + if (predicateFlag) { + accept(')'); + } + + if (acceptBracket) { + accept(']'); + } + return filter; + } + + Operator op = readOp(); + + skipWhitespace(); + + if (op == Operator.BETWEEN || op == Operator.NOT_BETWEEN) { + final boolean not = (op == Operator.NOT_BETWEEN); + + Object startValue = readValue(); + + String name = readName(); + + if (!"and".equalsIgnoreCase(name)) { + throw new JSONPathException(path); + } + + Object endValue = readValue(); + + if (startValue == null || endValue == null) { + throw new JSONPathException(path); + } + + if (isInt(startValue.getClass()) && isInt(endValue.getClass())) { + Filter filter = new IntBetweenSegement(propertyName, ((Number) startValue).longValue(), + ((Number) endValue).longValue(), not); + return filter; + } + + throw new JSONPathException(path); + } + + if (op == Operator.IN || op == Operator.NOT_IN) { + final boolean not = (op == Operator.NOT_IN); + accept('('); + + List valueList = new JSONArray(); + { + Object value = readValue(); + valueList.add(value); + + for (;;) { + skipWhitespace(); + if (ch != ',') { + break; + } + next(); + + value = readValue(); + valueList.add(value); + } + } + + boolean isInt = true; + boolean isIntObj = true; + boolean isString = true; + for (Object item : valueList) { + if (item == null) { + if (isInt) { + isInt = false; + } + continue; + } + + Class clazz = item.getClass(); + if (isInt && !(clazz == Byte.class || clazz == Short.class || clazz == Integer.class + || clazz == Long.class)) { + isInt = false; + isIntObj = false; + } + + if (isString && clazz != String.class) { + isString = false; + } + } + + if (valueList.size() == 1 && valueList.get(0) == null) { + Filter filter; + if (not) { + filter = new NotNullSegement(propertyName); + } else { + filter = new NullSegement(propertyName); + } + + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + + accept(')'); + if (predicateFlag) { + accept(')'); + } + + if (acceptBracket) { + accept(']'); + } + + return filter; + } + + if (isInt) { + if (valueList.size() == 1) { + long value = ((Number) valueList.get(0)).longValue(); + Operator intOp = not ? Operator.NE : Operator.EQ; + Filter filter = new IntOpSegement(propertyName, value, intOp); + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + + accept(')'); + if (predicateFlag) { + accept(')'); + } + + if (acceptBracket) { + accept(']'); + } + + return filter; + } + + long[] values = new long[valueList.size()]; + for (int i = 0; i < values.length; ++i) { + values[i] = ((Number) valueList.get(i)).longValue(); + } + + Filter filter = new IntInSegement(propertyName, values, not); + + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + + accept(')'); + if (predicateFlag) { + accept(')'); + } + + if (acceptBracket) { + accept(']'); + } + + return filter; + } + + if (isString) { + if (valueList.size() == 1) { + String value = (String) valueList.get(0); + + Operator intOp = not ? Operator.NE : Operator.EQ; + Filter filter = new StringOpSegement(propertyName, value, intOp); + + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + + accept(')'); + if (predicateFlag) { + accept(')'); + } + + if (acceptBracket) { + accept(']'); + } + + return filter; + } + + String[] values = new String[valueList.size()]; + valueList.toArray(values); + + Filter filter = new StringInSegement(propertyName, values, not); + + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + + accept(')'); + if (predicateFlag) { + accept(')'); + } + + if (acceptBracket) { + accept(']'); + } + + return filter; + } + + if (isIntObj) { + Long[] values = new Long[valueList.size()]; + for (int i = 0; i < values.length; ++i) { + Number item = (Number) valueList.get(i); + if (item != null) { + values[i] = item.longValue(); + } + } + + Filter filter = new IntObjInSegement(propertyName, values, not); + + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + + accept(')'); + if (predicateFlag) { + accept(')'); + } + + if (acceptBracket) { + accept(']'); + } + + return filter; + } + + throw new UnsupportedOperationException(); + } + + if (ch == '\'' || ch == '"') { + String strValue = readString(); + + Filter filter = null; + if (op == Operator.RLIKE) { + filter = new RlikeSegement(propertyName, strValue, false); + } else if (op == Operator.NOT_RLIKE) { + filter = new RlikeSegement(propertyName, strValue, true); + } else if (op == Operator.LIKE || op == Operator.NOT_LIKE) { + while (strValue.indexOf("%%") != -1) { + strValue = strValue.replaceAll("%%", "%"); + } + + final boolean not = (op == Operator.NOT_LIKE); + + int p0 = strValue.indexOf('%'); + if (p0 == -1) { + if (op == Operator.LIKE) { + op = Operator.EQ; + } else { + op = Operator.NE; + } + filter = new StringOpSegement(propertyName, strValue, op); + } else { + String[] items = strValue.split("%"); + + String startsWithValue = null; + String endsWithValue = null; + String[] containsValues = null; + if (p0 == 0) { + if (strValue.charAt(strValue.length() - 1) == '%') { + containsValues = new String[items.length - 1]; + System.arraycopy(items, 1, containsValues, 0, containsValues.length); + } else { + endsWithValue = items[items.length - 1]; + if (items.length > 2) { + containsValues = new String[items.length - 2]; + System.arraycopy(items, 1, containsValues, 0, containsValues.length); + } + } + } else if (strValue.charAt(strValue.length() - 1) == '%') { + containsValues = items; + } else { + if (items.length == 1) { + startsWithValue = items[0]; + } else if (items.length == 2) { + startsWithValue = items[0]; + endsWithValue = items[1]; + } else { + startsWithValue = items[0]; + endsWithValue = items[items.length - 1]; + containsValues = new String[items.length - 2]; + System.arraycopy(items, 1, containsValues, 0, containsValues.length); + } + } + + filter = new MatchSegement(propertyName, startsWithValue, endsWithValue, + containsValues, not); + } + } else { + filter = new StringOpSegement(propertyName, strValue, op); + } + + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + + if (predicateFlag) { + accept(')'); + } + + if (acceptBracket) { + accept(']'); + } + + return filter; + } + + if (isDigitFirst(ch)) { + long value = readLongValue(); + double doubleValue = 0D; + if (ch == '.') { + doubleValue = readDoubleValue(value); + + } + + Filter filter; + + if (doubleValue == 0) { + filter = new IntOpSegement(propertyName, value, op); + } else { + filter = new DoubleOpSegement(propertyName, doubleValue, op); + } + + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + + if (predicateFlag) { + accept(')'); + } + + if (acceptBracket) { + accept(']'); + } + + if (doubleValue == 0) { + return filter; + } else { + return filter; + } + } + + if (ch == 'n') { + String name = readName(); + if ("null".equals(name)) { + Filter filter = null; + if (op == Operator.EQ) { + filter = new NullSegement(propertyName); + } else if (op == Operator.NE) { + filter = new NotNullSegement(propertyName); + } + + if (filter != null) { + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + } + + if (predicateFlag) { + accept(')'); + } + accept(']'); + + if (filter != null) { + return filter; + } + + throw new UnsupportedOperationException(); + } + } else if (ch == 't') { + String name = readName(); + + if ("true".equals(name)) { + Filter filter = null; + + if (op == Operator.EQ) { + filter = new ValueSegment(propertyName, Boolean.TRUE, true); + } else if (op == Operator.NE) { + filter = new ValueSegment(propertyName, Boolean.TRUE, false); + } + + if (filter != null) { + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + } + + if (predicateFlag) { + accept(')'); + } + accept(']'); + + if (filter != null) { + return filter; + } + + throw new UnsupportedOperationException(); + } + } else if (ch == 'f') { + String name = readName(); + + if ("false".equals(name)) { + Filter filter = null; + + if (op == Operator.EQ) { + filter = new ValueSegment(propertyName, Boolean.FALSE, true); + } else if (op == Operator.NE) { + filter = new ValueSegment(propertyName, Boolean.FALSE, false); + } + + if (filter != null) { + while (ch == ' ') { + next(); + } + + if (ch == '&' || ch == '|') { + filter = filterRest(filter); + } + } + + if (predicateFlag) { + accept(')'); + } + accept(']'); + + if (filter != null) { + return filter; + } + + throw new UnsupportedOperationException(); + } + } + + throw new UnsupportedOperationException(); + // accept(')'); + } + + int start = pos - 1; + while (ch != ']' && ch != '/' && !isEOF()) { + if (ch == '.' // + && (!predicateFlag) // + && !predicateFlag) { + break; + } + + if (ch == '\\') { + next(); + } + next(); + } + + int end; + if (acceptBracket) { + end = pos - 1; + } else { + if (ch == '/' || ch == '.') { + end = pos - 1; + } else { + end = pos; + } + } + + String text = path.substring(start, end); + + if (text.indexOf("\\.") != -1) { + String propName = text.replaceAll("\\\\\\.","\\."); + if (propName.indexOf("\\-") != -1) { + propName = propName.replaceAll("\\\\-","-"); + } + + if (predicateFlag) { + accept(')'); + } + return new PropertySegement(propName, false); + } + + Segement segment = buildArraySegement(text); + + if (acceptBracket && !isEOF()) { + accept(']'); + } + + return segment; + } + + Filter filterRest(Filter filter) { + boolean and = ch == '&'; + if ((ch == '&' && getNextChar() == '&') || (ch == '|' && getNextChar() == '|')) { + next(); + next(); + + while (ch == ' ') { + next(); + } + + Filter right = (Filter) parseArrayAccessFilter(false); + + filter = new FilterGroup(filter, right, and); + } + return filter; + } + + protected long readLongValue() { + int beginIndex = pos - 1; + if (ch == '+' || ch == '-') { + next(); + } + + while (ch >= '0' && ch <= '9') { + next(); + } + + int endIndex = pos - 1; + String text = path.substring(beginIndex, endIndex); + long value = Long.parseLong(text); + return value; + } + + protected double readDoubleValue(long longValue) { + int beginIndex = pos - 1; + + next(); + while (ch >= '0' && ch <= '9') { + next(); + } + + int endIndex = pos - 1; + String text = path.substring(beginIndex, endIndex); + double value = Double.parseDouble(text); + value += longValue; + return value; + } + + protected Object readValue() { + skipWhitespace(); + + if (isDigitFirst(ch)) { + return readLongValue(); + } + + if (ch == '"' || ch == '\'') { + return readString(); + } + + if (ch == 'n') { + String name = readName(); + + if ("null".equals(name)) { + return null; + } else { + throw new JSONPathException(path); + } + } + + throw new UnsupportedOperationException(); + } + + static boolean isDigitFirst(char ch) { + return ch == '-' || ch == '+' || (ch >= '0' && ch <= '9'); + } + + protected Operator readOp() { + Operator op = null; + if (ch == '=') { + next(); + op = Operator.EQ; + } else if (ch == '!') { + next(); + accept('='); + op = Operator.NE; + } else if (ch == '<') { + next(); + if (ch == '=') { + next(); + op = Operator.LE; + } else { + op = Operator.LT; + } + } else if (ch == '>') { + next(); + if (ch == '=') { + next(); + op = Operator.GE; + } else { + op = Operator.GT; + } + } + + if (op == null) { + String name = readName(); + + if ("not".equalsIgnoreCase(name)) { + skipWhitespace(); + + name = readName(); + + if ("like".equalsIgnoreCase(name)) { + op = Operator.NOT_LIKE; + } else if ("rlike".equalsIgnoreCase(name)) { + op = Operator.NOT_RLIKE; + } else if ("in".equalsIgnoreCase(name)) { + op = Operator.NOT_IN; + } else if ("between".equalsIgnoreCase(name)) { + op = Operator.NOT_BETWEEN; + } else { + throw new UnsupportedOperationException(); + } + } else { + if ("like".equalsIgnoreCase(name)) { + op = Operator.LIKE; + } else if ("rlike".equalsIgnoreCase(name)) { + op = Operator.RLIKE; + } else if ("in".equalsIgnoreCase(name)) { + op = Operator.IN; + } else if ("between".equalsIgnoreCase(name)) { + op = Operator.BETWEEN; + } else { + throw new UnsupportedOperationException(); + } + } + } + return op; + } + + String readName() { + skipWhitespace(); + + if (ch != '\\' && !IOUtils.firstIdentifier(ch)) { + throw new JSONPathException("illeal jsonpath syntax. " + path); + } + + StringBuilder buf = new StringBuilder(); + while (!isEOF()) { + if (ch == '\\') { + next(); + buf.append(ch); + if (isEOF()) { + break; + } + next(); + continue; + } + + boolean identifierFlag = IOUtils.isIdent(ch); + if (!identifierFlag) { + break; + } + buf.append(ch); + next(); + } + + if (isEOF() && IOUtils.isIdent(ch)) { + buf.append(ch); + } + + String propertyName = buf.toString(); + + return propertyName; + } + + String readString() { + char quoate = ch; + next(); + + int beginIndex = pos - 1; + while (ch != quoate && !isEOF()) { + next(); + } + + String strValue = path.substring(beginIndex, isEOF() ? pos : pos - 1); + + accept(quoate); + + return strValue; + } + + void accept(char expect) { + if (ch != expect) { + throw new JSONPathException("expect '" + expect + ", but '" + ch + "'"); + } + + if (!isEOF()) { + next(); + } + } + + public Segement[] explain() { + if (path == null || path.length() == 0) { + throw new IllegalArgumentException(); + } + + Segement[] segements = new Segement[8]; + + for (;;) { + Segement segment = readSegement(); + if (segment == null) { + break; + } + + if (level == segements.length) { + Segement[] t = new Segement[level * 3 / 2]; + System.arraycopy(segements, 0, t, 0, level); + segements = t; + } + segements[level++] = segment; + } + + if (level == segements.length) { + return segements; + } + + Segement[] result = new Segement[level]; + System.arraycopy(segements, 0, result, 0, level); + return result; + } + + Segement buildArraySegement(String indexText) { + final int indexTextLen = indexText.length(); + final char firstChar = indexText.charAt(0); + final char lastChar = indexText.charAt(indexTextLen - 1); + + int commaIndex = indexText.indexOf(','); + + if (indexText.length() > 2 && firstChar == '\'' && lastChar == '\'') { + + if (commaIndex == -1) { + String propertyName = indexText.substring(1, indexTextLen - 1); + return new PropertySegement(propertyName, false); + } + + String[] indexesText = indexText.split(","); + String[] propertyNames = new String[indexesText.length]; + for (int i = 0; i < indexesText.length; ++i) { + String indexesTextItem = indexesText[i]; + propertyNames[i] = indexesTextItem.substring(1, indexesTextItem.length() - 1); + } + + return new MultiPropertySegement(propertyNames); + } + + int colonIndex = indexText.indexOf(':'); + + if (commaIndex == -1 && colonIndex == -1) { + if (TypeUtils.isNumber(indexText)) { + try { + int index = Integer.parseInt(indexText); + return new ArrayAccessSegement(index); + }catch (NumberFormatException ex){ + return new PropertySegement(indexText, false); // fix ISSUE-1208 + } + } else { + return new PropertySegement(indexText, false); + } + } + + if (commaIndex != -1) { + String[] indexesText = indexText.split(","); + int[] indexes = new int[indexesText.length]; + for (int i = 0; i < indexesText.length; ++i) { + indexes[i] = Integer.parseInt(indexesText[i]); + } + return new MultiIndexSegement(indexes); + } + + if (colonIndex != -1) { + String[] indexesText = indexText.split(":"); + int[] indexes = new int[indexesText.length]; + for (int i = 0; i < indexesText.length; ++i) { + String str = indexesText[i]; + if (str.length() == 0) { + if (i == 0) { + indexes[i] = 0; + } else { + throw new UnsupportedOperationException(); + } + } else { + indexes[i] = Integer.parseInt(str); + } + } + + int start = indexes[0]; + int end; + if (indexes.length > 1) { + end = indexes[1]; + } else { + end = -1; + } + int step; + if (indexes.length == 3) { + step = indexes[2]; + } else { + step = 1; + } + + if (end >= 0 && end < start) { + throw new UnsupportedOperationException("end must greater than or equals start. start " + start + + ", end " + end); + } + + if (step <= 0) { + throw new UnsupportedOperationException("step must greater than zero : " + step); + } + return new RangeSegement(start, end, step); + } + + throw new UnsupportedOperationException(); + } + } + + interface Segement { + + Object eval(JSONPath path, Object rootObject, Object currentObject); + } + + + static class SizeSegement implements Segement { + + public final static SizeSegement instance = new SizeSegement(); + + public Integer eval(JSONPath path, Object rootObject, Object currentObject) { + return path.evalSize(currentObject); + } + } + + static class PropertySegement implements Segement { + + private final String propertyName; + private final long propertyNameHash; + private final boolean deep; + + public PropertySegement(String propertyName, boolean deep){ + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + this.deep = deep; + } + + public Object eval(JSONPath path, Object rootObject, Object currentObject) { + if (deep) { + List results = new ArrayList(); + path.deepScan(currentObject, propertyName, results); + return results; + } else { + // return path.getPropertyValue(currentObject, propertyName, true); + return path.getPropertyValue(currentObject, propertyName, propertyNameHash); + } + } + + public void setValue(JSONPath path, Object parent, Object value) { + if (deep) { + path.deepSet(parent, propertyName, propertyNameHash, value); + } else { + path.setPropertyValue(parent, propertyName, propertyNameHash, value); + } + } + + public boolean remove(JSONPath path, Object parent) { + return path.removePropertyValue(parent, propertyName); + } + } + + static class MultiPropertySegement implements Segement { + + private final String[] propertyNames; + private final long[] propertyNamesHash; + + public MultiPropertySegement(String[] propertyNames){ + this.propertyNames = propertyNames; + this.propertyNamesHash = new long[propertyNames.length]; + for (int i = 0; i < propertyNamesHash.length; i++) { + propertyNamesHash[i] = TypeUtils.fnv1a_64(propertyNames[i]); + } + } + + public Object eval(JSONPath path, Object rootObject, Object currentObject) { + List fieldValues = new ArrayList(propertyNames.length); + + for (int i = 0; i < propertyNames.length; i++) { + Object fieldValue = path.getPropertyValue(currentObject, propertyNames[i], propertyNamesHash[i]); + fieldValues.add(fieldValue); + } + + return fieldValues; + } + } + + static class WildCardSegement implements Segement { + + public static WildCardSegement instance = new WildCardSegement(); + + public Object eval(JSONPath path, Object rootObject, Object currentObject) { + return path.getPropertyValues(currentObject); + } + + } + + static class ArrayAccessSegement implements Segement { + + private final int index; + + public ArrayAccessSegement(int index){ + this.index = index; + } + + public Object eval(JSONPath path, Object rootObject, Object currentObject) { + return path.getArrayItem(currentObject, index); + } + + public boolean setValue(JSONPath path, Object currentObject, Object value) { + return path.setArrayItem(path, currentObject, index, value); + } + + public boolean remove(JSONPath path, Object currentObject) { + return path.removeArrayItem(path, currentObject, index); + } + } + + static class MultiIndexSegement implements Segement { + + private final int[] indexes; + + public MultiIndexSegement(int[] indexes){ + this.indexes = indexes; + } + + public Object eval(JSONPath path, Object rootObject, Object currentObject) { + List items = new ArrayList(indexes.length); + for (int i = 0; i < indexes.length; ++i) { + Object item = path.getArrayItem(currentObject, indexes[i]); + items.add(item); + } + return items; + } + } + + static class RangeSegement implements Segement { + + private final int start; + private final int end; + private final int step; + + public RangeSegement(int start, int end, int step){ + this.start = start; + this.end = end; + this.step = step; + } + + public Object eval(JSONPath path, Object rootObject, Object currentObject) { + int size = SizeSegement.instance.eval(path, rootObject, currentObject); + int start = this.start >= 0 ? this.start : this.start + size; + int end = this.end >= 0 ? this.end : this.end + size; + + int array_size = (end - start) / step + 1; + if (array_size == -1) { + return null; + } + + List items = new ArrayList(array_size); + for (int i = start; i <= end && i < size; i += step) { + Object item = path.getArrayItem(currentObject, i); + items.add(item); + } + return items; + } + } + + static class NotNullSegement implements Filter { + + private final String propertyName; + private final long propertyNameHash; + + + public NotNullSegement(String propertyName){ + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + + return propertyValue != null; + } + } + + static class NullSegement implements Filter { + + private final String propertyName; + private final long propertyNameHash; + + public NullSegement(String propertyName){ + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + + return propertyValue == null; + } + } + + static class ValueSegment implements Filter { + private final String propertyName; + private final long propertyNameHash; + private final Object value; + private boolean eq = true; + + public ValueSegment(String propertyName, Object value, boolean eq){ + if (value == null) { + throw new IllegalArgumentException("value is null"); + } + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + this.value = value; + this.eq = eq; + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + boolean result = value.equals(propertyValue); + if (!eq) { + result = !result; + } + return result; + } + + } + + static class IntInSegement implements Filter { + + private final String propertyName; + private final long propertyNameHash; + private final long[] values; + private final boolean not; + + public IntInSegement(String propertyName, long[] values, boolean not){ + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + this.values = values; + this.not = not; + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + + if (propertyValue == null) { + return false; + } + + if (propertyValue instanceof Number) { + long longPropertyValue = ((Number) propertyValue).longValue(); + for (long value : values) { + if (value == longPropertyValue) { + return !not; + } + } + } + + return not; + } + } + + static class IntBetweenSegement implements Filter { + + private final String propertyName; + private final long propertyNameHash; + private final long startValue; + private final long endValue; + private final boolean not; + + public IntBetweenSegement(String propertyName, long startValue, long endValue, boolean not){ + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + this.startValue = startValue; + this.endValue = endValue; + this.not = not; + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + + if (propertyValue == null) { + return false; + } + + if (propertyValue instanceof Number) { + long longPropertyValue = ((Number) propertyValue).longValue(); + if (longPropertyValue >= startValue && longPropertyValue <= endValue) { + return !not; + } + } + + return not; + } + } + + static class IntObjInSegement implements Filter { + + private final String propertyName; + private final long propertyNameHash; + private final Long[] values; + private final boolean not; + + public IntObjInSegement(String propertyName, Long[] values, boolean not){ + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + this.values = values; + this.not = not; + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + + if (propertyValue == null) { + for (Long value : values) { + if (value == null) { + return !not; + } + } + + return not; + } + + if (propertyValue instanceof Number) { + long longPropertyValue = ((Number) propertyValue).longValue(); + for (Long value : values) { + if (value == null) { + continue; + } + + if (value.longValue() == longPropertyValue) { + return !not; + } + } + } + + return not; + } + } + + static class StringInSegement implements Filter { + + private final String propertyName; + private final long propertyNameHash; + private final String[] values; + private final boolean not; + + public StringInSegement(String propertyName, String[] values, boolean not){ + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + this.values = values; + this.not = not; + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + + for (String value : values) { + if (value == propertyValue) { + return !not; + } else if (value != null && value.equals(propertyValue)) { + return !not; + } + } + + return not; + } + } + + static class IntOpSegement implements Filter { + + private final String propertyName; + private final long propertyNameHash; + private final long value; + private final Operator op; + + public IntOpSegement(String propertyName, long value, Operator op){ + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + this.value = value; + this.op = op; + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + + if (propertyValue == null) { + return false; + } + + if (!(propertyValue instanceof Number)) { + return false; + } + + long longValue = ((Number) propertyValue).longValue(); + + if (op == Operator.EQ) { + return longValue == value; + } else if (op == Operator.NE) { + return longValue != value; + } else if (op == Operator.GE) { + return longValue >= value; + } else if (op == Operator.GT) { + return longValue > value; + } else if (op == Operator.LE) { + return longValue <= value; + } else if (op == Operator.LT) { + return longValue < value; + } + + return false; + } + } + + static class DoubleOpSegement implements Filter { + + private final String propertyName; + private final double value; + private final Operator op; + + private final long propertyNameHash; + + public DoubleOpSegement(String propertyName, double value, Operator op){ + this.propertyName = propertyName; + this.value = value; + this.op = op; + propertyNameHash = TypeUtils.fnv1a_64(propertyName); + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + + if (propertyValue == null) { + return false; + } + + if (!(propertyValue instanceof Number)) { + return false; + } + + double doubleValue = ((Number) propertyValue).doubleValue(); + + if (op == Operator.EQ) { + return doubleValue == value; + } else if (op == Operator.NE) { + return doubleValue != value; + } else if (op == Operator.GE) { + return doubleValue >= value; + } else if (op == Operator.GT) { + return doubleValue > value; + } else if (op == Operator.LE) { + return doubleValue <= value; + } else if (op == Operator.LT) { + return doubleValue < value; + } + + return false; + } + } + + static class CombineSegement implements Segement { + public final Segement left; + public final Segement right; + public final Operator operator; + + public CombineSegement(Segement left, Segement right, Operator operator) { + this.left = left; + this.right = right; + this.operator = operator; + } + + public Object eval(JSONPath path, Object rootObject, Object currentObject) { + return null; + } + + + static enum Operator { + And, Or + } + } + + static class MatchSegement implements Filter { + + private final String propertyName; + private final long propertyNameHash; + private final String startsWithValue; + private final String endsWithValue; + private final String[] containsValues; + private final int minLength; + private final boolean not; + + public MatchSegement(String propertyName, String startsWithValue, String endsWithValue, String[] containsValues, + boolean not){ + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + this.startsWithValue = startsWithValue; + this.endsWithValue = endsWithValue; + this.containsValues = containsValues; + this.not = not; + + int len = 0; + if (startsWithValue != null) { + len += startsWithValue.length(); + } + + if (endsWithValue != null) { + len += endsWithValue.length(); + } + + if (containsValues != null) { + for (String item : containsValues) { + len += item.length(); + } + } + + this.minLength = len; + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + + if (propertyValue == null) { + return false; + } + + final String strPropertyValue = propertyValue.toString(); + + if (strPropertyValue.length() < minLength) { + return not; + } + + int start = 0; + if (startsWithValue != null) { + if (!strPropertyValue.startsWith(startsWithValue)) { + return not; + } + start += startsWithValue.length(); + } + + if (containsValues != null) { + for (String containsValue : containsValues) { + int index = strPropertyValue.indexOf(containsValue, start); + if (index == -1) { + return not; + } + start = index + containsValue.length(); + } + } + + if (endsWithValue != null) { + if (!strPropertyValue.endsWith(endsWithValue)) { + return not; + } + } + + return !not; + } + } + + static class RlikeSegement implements Filter { + + private final String propertyName; + private final long propertyNameHash; + private final Pattern pattern; + private final boolean not; + + public RlikeSegement(String propertyName, String pattern, boolean not){ + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + this.pattern = Pattern.compile(pattern); + this.not = not; + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + + if (propertyValue == null) { + return false; + } + + String strPropertyValue = propertyValue.toString(); + Matcher m = pattern.matcher(strPropertyValue); + boolean match = m.matches(); + + if (not) { + match = !match; + } + + return match; + } + } + + static class StringOpSegement implements Filter { + + private final String propertyName; + private final long propertyNameHash; + private final String value; + private final Operator op; + + public StringOpSegement(String propertyName, String value, Operator op){ + this.propertyName = propertyName; + this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); + this.value = value; + this.op = op; + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + Object propertyValue = path.getPropertyValue(item, propertyName, propertyNameHash); + + if (op == Operator.EQ) { + return value.equals(propertyValue); + } else if (op == Operator.NE) { + return !value.equals(propertyValue); + } + + if (propertyValue == null) { + return false; + } + + int compareResult = value.compareTo(propertyValue.toString()); + if (op == Operator.GE) { + return compareResult <= 0; + } else if (op == Operator.GT) { + return compareResult < 0; + } else if (op == Operator.LE) { + return compareResult >= 0; + } else if (op == Operator.LT) { + return compareResult > 0; + } + + return false; + } + } + + enum Operator { + EQ, NE, GT, GE, LT, LE, LIKE, NOT_LIKE, RLIKE, NOT_RLIKE, IN, NOT_IN, BETWEEN, NOT_BETWEEN, And, Or + } + + static public class FilterSegement implements Segement { + + private final Filter filter; + + public FilterSegement(Filter filter){ + super(); + this.filter = filter; + } + + @SuppressWarnings("rawtypes") + public Object eval(JSONPath path, Object rootObject, Object currentObject) { + if (currentObject == null) { + return null; + } + + List items = new JSONArray(); + + if (currentObject instanceof Iterable) { + Iterator it = ((Iterable) currentObject).iterator(); + while (it.hasNext()) { + Object item = it.next(); + + if (filter.apply(path, rootObject, currentObject, item)) { + items.add(item); + } + } + + return items; + } + + if (filter.apply(path, rootObject, currentObject, currentObject)) { + return currentObject; + } + + return null; + } + } + + interface Filter { + + boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item); + } + + static class FilterGroup implements Filter { + private boolean and; + private List fitlers; + + public FilterGroup(Filter left, Filter right, boolean and) { + fitlers = new ArrayList(2); + fitlers.add(left); + fitlers.add(right); + this.and = and; + } + + public FilterGroup(List fitlers, boolean and) { + this.and = and; + this.fitlers = fitlers; + } + + public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { + if (and) { + for (Filter fitler : this.fitlers) { + if (!fitler.apply(path, rootObject, currentObject, item)) { + return false; + } + } + return true; + } else { + for (Filter fitler : this.fitlers) { + if (fitler.apply(path, rootObject, currentObject, item)) { + return true; + } + } + return false; + } + } + } + + @SuppressWarnings("rawtypes") + protected Object getArrayItem(final Object currentObject, int index) { + if (currentObject == null) { + return null; + } + + if (currentObject instanceof List) { + List list = (List) currentObject; + + if (index >= 0) { + if (index < list.size()) { + return list.get(index); + } + return null; + } else { + if (Math.abs(index) <= list.size()) { + return list.get(list.size() + index); + } + return null; + } + } + + if (currentObject.getClass().isArray()) { + int arrayLenth = Array.getLength(currentObject); + + if (index >= 0) { + if (index < arrayLenth) { + return Array.get(currentObject, index); + } + return null; + } else { + if (Math.abs(index) <= arrayLenth) { + return Array.get(currentObject, arrayLenth + index); + } + return null; + } + } + + if (currentObject instanceof Map) { + Map map = (Map) currentObject; + Object value = map.get(index); + if (value == null) { + value = map.get(Integer.toString(index)); + } + return value; + } + + if (currentObject instanceof Collection) { + Collection collection = (Collection) currentObject; + int i = 0; + for (Object item : collection) { + if (i == index) { + return item; + } + i++; + } + return null; + } + + throw new UnsupportedOperationException(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public boolean setArrayItem(JSONPath path, Object currentObject, int index, Object value) { + if (currentObject instanceof List) { + List list = (List) currentObject; + if (index >= 0) { + list.set(index, value); + } else { + list.set(list.size() + index, value); + } + return true; + } + + Class clazz = currentObject.getClass(); + if (clazz.isArray()) { + int arrayLenth = Array.getLength(currentObject); + + if (index >= 0) { + if (index < arrayLenth) { + Array.set(currentObject, index, value); + } + } else { + if (Math.abs(index) <= arrayLenth) { + Array.set(currentObject, arrayLenth + index, value); + } + } + + return true; + } + + throw new JSONPathException("unsupported set operation." + clazz); + } + + @SuppressWarnings("rawtypes") + public boolean removeArrayItem(JSONPath path, Object currentObject, int index) { + if (currentObject instanceof List) { + List list = (List) currentObject; + if (index >= 0) { + if (index >= list.size()) { + return false; + } + list.remove(index); + } else { + int newIndex = list.size() + index; + + if (newIndex < 0) { + return false; + } + + list.remove(newIndex); + } + return true; + } + + Class clazz = currentObject.getClass(); + throw new JSONPathException("unsupported set operation." + clazz); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected Collection getPropertyValues(final Object currentObject) { + final Class currentClass = currentObject.getClass(); + + JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); + + if (beanSerializer != null) { + try { + return beanSerializer.getFieldValues(currentObject); + } catch (Exception e) { + throw new JSONPathException("jsonpath error, path " + path, e); + } + } + + if (currentObject instanceof Map) { + Map map = (Map) currentObject; + return map.values(); + } + + throw new UnsupportedOperationException(); + } + + static boolean eq(Object a, Object b) { + if (a == b) { + return true; + } + + if (a == null || b == null) { + return false; + } + + if (a.getClass() == b.getClass()) { + return a.equals(b); + } + + if (a instanceof Number) { + if (b instanceof Number) { + return eqNotNull((Number) a, (Number) b); + } + + return false; + } + + return a.equals(b); + } + + @SuppressWarnings("rawtypes") + static boolean eqNotNull(Number a, Number b) { + Class clazzA = a.getClass(); + boolean isIntA = isInt(clazzA); + + Class clazzB = b.getClass(); + boolean isIntB = isInt(clazzB); + + if (a instanceof BigDecimal) { + BigDecimal decimalA = (BigDecimal) a; + + if (isIntB) { + return decimalA.equals(BigDecimal.valueOf(b.longValue())); + } + } + + if (isIntA) { + if (isIntB) { + return a.longValue() == b.longValue(); + } + + if (b instanceof BigInteger) { + BigInteger bigIntB = (BigInteger) a; + BigInteger bigIntA = BigInteger.valueOf(a.longValue()); + + return bigIntA.equals(bigIntB); + } + } + + if (isIntB) { + if (a instanceof BigInteger) { + BigInteger bigIntA = (BigInteger) a; + BigInteger bigIntB = BigInteger.valueOf(b.longValue()); + + return bigIntA.equals(bigIntB); + } + } + + + boolean isDoubleA = isDouble(clazzA); + boolean isDoubleB = isDouble(clazzB); + + if ((isDoubleA && isDoubleB) || (isDoubleA && isIntB) || (isDoubleB && isIntA)) { + return a.doubleValue() == b.doubleValue(); + } + + + return false; + } + + protected static boolean isDouble(Class clazzA) { + return clazzA == Float.class || clazzA == Double.class; + } + + protected static boolean isInt(Class clazzA) { + return clazzA == Byte.class || clazzA == Short.class || clazzA == Integer.class || clazzA == Long.class; + } + + final static long SIZE = 0x4dea9618e618ae3cL; // TypeUtils.fnv1a_64("size"); + final static long LENGTH = 0xea11573f1af59eb5L; // TypeUtils.fnv1a_64("length"); + + protected Object getPropertyValue(Object currentObject, String propertyName, long propertyNameHash) { + if (currentObject == null) { + return null; + } + + if (currentObject instanceof Map) { + Map map = (Map) currentObject; + Object val = map.get(propertyName); + + if (val == null && (SIZE == propertyNameHash || LENGTH == propertyNameHash)) { + val = map.size(); + } + + return val; + } + + final Class currentClass = currentObject.getClass(); + + JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); + if (beanSerializer != null) { + try { + return beanSerializer.getFieldValue(currentObject, propertyName, propertyNameHash, false); + } catch (Exception e) { + throw new JSONPathException("jsonpath error, path " + path + ", segement " + propertyName, e); + } + } + + if (currentObject instanceof List) { + List list = (List) currentObject; + + if (SIZE == propertyNameHash || LENGTH == propertyNameHash) { + return list.size(); + } + + List fieldValues = new JSONArray(list.size()); + + for (int i = 0; i < list.size(); ++i) { + Object obj = list.get(i); + + // + if (obj == list) { + fieldValues.add(obj); + continue; + } + + Object itemValue = getPropertyValue(obj, propertyName, propertyNameHash); + if (itemValue instanceof Collection) { + Collection collection = (Collection) itemValue; + fieldValues.addAll(collection); + } else if (itemValue != null) { + fieldValues.add(itemValue); + } + } + + return fieldValues; + } + + if (currentObject instanceof Enum) { + final long NAME = 0xc4bcadba8e631b86L; // TypeUtils.fnv1a_64("name"); + final long ORDINAL = 0xf1ebc7c20322fc22L; //TypeUtils.fnv1a_64("ordinal"); + + Enum e = (Enum) currentObject; + if (NAME == propertyNameHash) { + return e.name(); + } + + if (ORDINAL == propertyNameHash) { + return e.ordinal(); + } + } + + if (currentObject instanceof Calendar) { + final long YEAR = 0x7c64634977425edcL; //TypeUtils.fnv1a_64("year"); + final long MONTH = 0xf4bdc3936faf56a5L; //TypeUtils.fnv1a_64("month"); + final long DAY = 0xca8d3918f4578f1dL; // TypeUtils.fnv1a_64("day"); + final long HOUR = 0x407efecc7eb5764fL; //TypeUtils.fnv1a_64("hour"); + final long MINUTE = 0x5bb2f9bdf2fad1e9L; //TypeUtils.fnv1a_64("minute"); + final long SECOND = 0xa49985ef4cee20bdL; //TypeUtils.fnv1a_64("second"); + + Calendar e = (Calendar) currentObject; + if (YEAR == propertyNameHash) { + return e.get(Calendar.YEAR); + } + if (MONTH == propertyNameHash) { + return e.get(Calendar.MONTH); + } + if (DAY == propertyNameHash) { + return e.get(Calendar.DAY_OF_MONTH); + } + if (HOUR == propertyNameHash) { + return e.get(Calendar.HOUR_OF_DAY); + } + if (MINUTE == propertyNameHash) { + return e.get(Calendar.MINUTE); + } + if (SECOND == propertyNameHash) { + return e.get(Calendar.SECOND); + } + } + + return null; + //throw new JSONPathException("jsonpath error, path " + path + ", segement " + propertyName); + } + + @SuppressWarnings("rawtypes") + protected void deepScan(final Object currentObject, final String propertyName, List results) { + if (currentObject == null) { + return; + } + + if (currentObject instanceof Map) { + Map map = (Map) currentObject; + + if (map.containsKey(propertyName)) { + Object val = map.get(propertyName); + results.add(val); + return; + } + + for (Object val : map.values()) { + deepScan(val, propertyName, results); + } + return; + } + + final Class currentClass = currentObject.getClass(); + + JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); + if (beanSerializer != null) { + try { + FieldSerializer fieldDeser = beanSerializer.getFieldSerializer(propertyName); + if (fieldDeser != null) { + try { + Object val = fieldDeser.getPropertyValueDirect(currentObject); + results.add(val); + } catch (InvocationTargetException ex) { + throw new JSONException("getFieldValue error." + propertyName, ex); + } catch (IllegalAccessException ex) { + throw new JSONException("getFieldValue error." + propertyName, ex); + } + return; + } + List fieldValues = beanSerializer.getFieldValues(currentObject); + for (Object val : fieldValues) { + deepScan(val, propertyName, results); + } + return; + } catch (Exception e) { + throw new JSONPathException("jsonpath error, path " + path + ", segement " + propertyName, e); + } + } + + if (currentObject instanceof List) { + List list = (List) currentObject; + + for (int i = 0; i < list.size(); ++i) { + Object val = list.get(i); + deepScan(val, propertyName, results); + } + return; + } + } + + protected void deepSet(final Object currentObject, final String propertyName, long propertyNameHash, Object value) { + if (currentObject == null) { + return; + } + + if (currentObject instanceof Map) { + Map map = (Map) currentObject; + + if (map.containsKey(propertyName)) { + Object val = map.get(propertyName); + map.put(propertyName, value); + return; + } + + for (Object val : map.values()) { + deepSet(val, propertyName, propertyNameHash, value); + } + return; + } + + final Class currentClass = currentObject.getClass(); + + JavaBeanDeserializer beanDeserializer = getJavaBeanDeserializer(currentClass); + if (beanDeserializer != null) { + try { + FieldDeserializer fieldDeser = beanDeserializer.getFieldDeserializer(propertyName); + if (fieldDeser != null) { + fieldDeser.setValue(currentObject, value); + return; + } + + JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); + List fieldValues = beanSerializer.getObjectFieldValues(currentObject); + for (Object val : fieldValues) { + deepSet(val, propertyName, propertyNameHash, value); + } + return; + } catch (Exception e) { + throw new JSONPathException("jsonpath error, path " + path + ", segement " + propertyName, e); + } + } + + if (currentObject instanceof List) { + List list = (List) currentObject; + + for (int i = 0; i < list.size(); ++i) { + Object val = list.get(i); + deepSet(val, propertyName, propertyNameHash, value); + } + return; + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + protected boolean setPropertyValue(Object parent, String name, long propertyNameHash, Object value) { + if (parent instanceof Map) { + ((Map) parent).put(name, value); + return true; + } + + if (parent instanceof List) { + for (Object element : (List) parent) { + if (element == null) { + continue; + } + setPropertyValue(element, name, propertyNameHash, value); + } + return true; + } + + ObjectDeserializer derializer = parserConfig.getDeserializer(parent.getClass()); + + JavaBeanDeserializer beanDerializer = null; + if (derializer instanceof JavaBeanDeserializer) { + beanDerializer = (JavaBeanDeserializer) derializer; + } + + if (beanDerializer != null) { + FieldDeserializer fieldDeserializer = beanDerializer.getFieldDeserializer(propertyNameHash); + if (fieldDeserializer == null) { + return false; + } + + fieldDeserializer.setValue(parent, value); + return true; + } + + throw new UnsupportedOperationException(); + } + + @SuppressWarnings({"rawtypes" }) + protected boolean removePropertyValue(Object parent, String name) { + if (parent instanceof Map) { + Object origin = ((Map) parent).remove(name); + return origin != null; + } + + ObjectDeserializer derializer = parserConfig.getDeserializer(parent.getClass()); + + JavaBeanDeserializer beanDerializer = null; + if (derializer instanceof JavaBeanDeserializer) { + beanDerializer = (JavaBeanDeserializer) derializer; + } + + if (beanDerializer != null) { + FieldDeserializer fieldDeserializer = beanDerializer.getFieldDeserializer(name); + if (fieldDeserializer == null) { + return false; + } + + fieldDeserializer.setValue(parent, null); + return true; + } + + throw new UnsupportedOperationException(); + } + + protected JavaBeanSerializer getJavaBeanSerializer(final Class currentClass) { + JavaBeanSerializer beanSerializer = null; + { + ObjectSerializer serializer = serializeConfig.getObjectWriter(currentClass); + if (serializer instanceof JavaBeanSerializer) { + beanSerializer = (JavaBeanSerializer) serializer; + } + } + return beanSerializer; + } + + protected JavaBeanDeserializer getJavaBeanDeserializer(final Class currentClass) { + JavaBeanDeserializer beanDeserializer = null; + { + ObjectDeserializer deserializer = parserConfig.getDeserializer(currentClass); + if (deserializer instanceof JavaBeanDeserializer) { + beanDeserializer = (JavaBeanDeserializer) deserializer; + } + } + return beanDeserializer; + } + + @SuppressWarnings("rawtypes") + int evalSize(Object currentObject) { + if (currentObject == null) { + return -1; + } + + if (currentObject instanceof Collection) { + return ((Collection) currentObject).size(); + } + + if (currentObject instanceof Object[]) { + return ((Object[]) currentObject).length; + } + + if (currentObject.getClass().isArray()) { + return Array.getLength(currentObject); + } + + if (currentObject instanceof Map) { + int count = 0; + + for (Object value : ((Map) currentObject).values()) { + if (value != null) { + count++; + } + } + return count; + } + + JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentObject.getClass()); + + if (beanSerializer == null) { + return -1; + } + + try { + return beanSerializer.getSize(currentObject); + } catch (Exception e) { + throw new JSONPathException("evalSize error : " + path, e); + } + } + + public String toJSONString() { + return JSON.toJSONString(path); + } +} diff --git a/src/main/java/com/alibaba/fastjson/JSONPathException.java b/src/main/java/com/alibaba/fastjson/JSONPathException.java new file mode 100644 index 0000000000..a514cf4cb3 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/JSONPathException.java @@ -0,0 +1,13 @@ +package com.alibaba.fastjson; + +@SuppressWarnings("serial") +public class JSONPathException extends JSONException { + + public JSONPathException(String message){ + super(message); + } + + public JSONPathException(String message, Throwable cause){ + super(message, cause); + } +} diff --git a/src/main/java/com/alibaba/fastjson/JSONReader.java b/src/main/java/com/alibaba/fastjson/JSONReader.java new file mode 100644 index 0000000000..ff009b7d2e --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/JSONReader.java @@ -0,0 +1,335 @@ +package com.alibaba.fastjson; + +import static com.alibaba.fastjson.JSONStreamContext.ArrayValue; +import static com.alibaba.fastjson.JSONStreamContext.PropertyKey; +import static com.alibaba.fastjson.JSONStreamContext.PropertyValue; +import static com.alibaba.fastjson.JSONStreamContext.StartArray; +import static com.alibaba.fastjson.JSONStreamContext.StartObject; + +import java.io.Closeable; +import java.io.Reader; +import java.lang.reflect.Type; +import java.util.Locale; +import java.util.Map; +import java.util.TimeZone; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONReaderScanner; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.util.TypeUtils; + +public class JSONReader implements Closeable { + + private final DefaultJSONParser parser; + private JSONStreamContext context; + + public JSONReader(Reader reader){ + this(reader, new Feature[0]); + } + + public JSONReader(Reader reader, Feature... features){ + this(new JSONReaderScanner(reader)); + for (Feature feature : features) { + this.config(feature, true); + } + } + + public JSONReader(JSONLexer lexer){ + this(new DefaultJSONParser(lexer)); + } + + public JSONReader(DefaultJSONParser parser){ + this.parser = parser; + } + + public void setTimzeZone(TimeZone timezone) { + this.parser.lexer.setTimeZone(timezone); + } + + public void setLocale(Locale locale) { + this.parser.lexer.setLocale(locale); + } + + public void config(Feature feature, boolean state) { + this.parser.config(feature, state); + } + + public Locale getLocal() { + return this.parser.lexer.getLocale(); + } + + public TimeZone getTimzeZone() { + return this.parser.lexer.getTimeZone(); + } + + public void startObject() { + if (context == null) { + context = new JSONStreamContext(null, JSONStreamContext.StartObject); + } else { + startStructure(); + context = new JSONStreamContext(context, JSONStreamContext.StartObject); + } + + this.parser.accept(JSONToken.LBRACE, JSONToken.IDENTIFIER); + } + + public void endObject() { + this.parser.accept(JSONToken.RBRACE); + endStructure(); + } + + public void startArray() { + if (context == null) { + context = new JSONStreamContext(null, StartArray); + } else { + startStructure(); + + context = new JSONStreamContext(context, StartArray); + } + this.parser.accept(JSONToken.LBRACKET); + } + + public void endArray() { + this.parser.accept(JSONToken.RBRACKET); + endStructure(); + } + + private void startStructure() { + final int state = context.state; + switch (state) { + case PropertyKey: + parser.accept(JSONToken.COLON); + break; + case PropertyValue: + case ArrayValue: + parser.accept(JSONToken.COMMA); + break; + case StartArray: + case StartObject: + break; + default: + throw new JSONException("illegal state : " + context.state); + } + } + + private void endStructure() { + context = context.parent; + + if (context == null) { + return; + } + + final int state = context.state; + int newState = -1; + switch (state) { + case PropertyKey: + newState = PropertyValue; + break; + case StartArray: + newState = ArrayValue; + break; + case PropertyValue: + case StartObject: + newState = PropertyKey; + break; + default: + break; + } + if (newState != -1) { + context.state = newState; + } + } + + public boolean hasNext() { + if (context == null) { + throw new JSONException("context is null"); + } + + final int token = parser.lexer.token(); + final int state = context.state; + switch (state) { + case StartArray: + case ArrayValue: + return token != JSONToken.RBRACKET; + case StartObject: + case PropertyValue: + return token != JSONToken.RBRACE; + default: + throw new JSONException("illegal state : " + state); + } + } + + public int peek() { + return parser.lexer.token(); + } + + public void close() { + parser.close(); + } + + public Integer readInteger() { + Object object; + if (context == null) { + object = parser.parse(); + } else { + readBefore(); + object = parser.parse(); + readAfter(); + } + + return TypeUtils.castToInt(object); + } + + public Long readLong() { + Object object; + if (context == null) { + object = parser.parse(); + } else { + readBefore(); + object = parser.parse(); + readAfter(); + } + + return TypeUtils.castToLong(object); + } + + public String readString() { + Object object; + if (context == null) { + object = parser.parse(); + } else { + readBefore(); + JSONLexer lexer = parser.lexer; + if (context.state == JSONStreamContext.StartObject && lexer.token() == JSONToken.IDENTIFIER) { + object = lexer.stringVal(); + lexer.nextToken(); + } else { + object = parser.parse(); + } + readAfter(); + } + + return TypeUtils.castToString(object); + } + + public T readObject(TypeReference typeRef) { + return readObject(typeRef.getType()); + } + + public T readObject(Type type) { + if (context == null) { + return parser.parseObject(type); + } + + readBefore(); + T object = parser.parseObject(type); + readAfter(); + return object; + } + + public T readObject(Class type) { + if (context == null) { + return parser.parseObject(type); + } + + readBefore(); + T object = parser.parseObject(type); + readAfter(); + return object; + } + + public void readObject(Object object) { + if (context == null) { + parser.parseObject(object); + return; + } + + readBefore(); + parser.parseObject(object); + readAfter(); + } + + public Object readObject() { + if (context == null) { + return parser.parse(); + } + + readBefore(); + Object object; + switch (context.state) { + case StartObject: + case PropertyValue: + object = parser.parseKey(); + break; + default: + object = parser.parse(); + break; + } + + readAfter(); + return object; + } + + @SuppressWarnings("rawtypes") + public Object readObject(Map object) { + if (context == null) { + return parser.parseObject(object); + } + + readBefore(); + Object value = parser.parseObject(object); + readAfter(); + return value; + } + + private void readBefore() { + int state = context.state; + // before + switch (state) { + case PropertyKey: + parser.accept(JSONToken.COLON); + break; + case PropertyValue: + parser.accept(JSONToken.COMMA, JSONToken.IDENTIFIER); + break; + case ArrayValue: + parser.accept(JSONToken.COMMA); + break; + case StartObject: + break; + case StartArray: + break; + default: + throw new JSONException("illegal state : " + state); + } + } + + private void readAfter() { + int state = context.state; + int newStat = -1; + switch (state) { + case StartObject: + newStat = PropertyKey; + break; + case PropertyKey: + newStat = PropertyValue; + break; + case PropertyValue: + newStat = PropertyKey; + break; + case ArrayValue: + break; + case StartArray: + newStat = ArrayValue; + break; + default: + throw new JSONException("illegal state : " + state); + } + if (newStat != -1) { + context.state = newStat; + } + } + +} diff --git a/src/main/java/com/alibaba/fastjson/JSONStreamAware.java b/src/main/java/com/alibaba/fastjson/JSONStreamAware.java old mode 100644 new mode 100755 index 99ae8f4af9..844579dfcb --- a/src/main/java/com/alibaba/fastjson/JSONStreamAware.java +++ b/src/main/java/com/alibaba/fastjson/JSONStreamAware.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ /** * Beans that support customized output of JSON text to a writer shall implement this interface. * - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public interface JSONStreamAware { diff --git a/src/main/java/com/alibaba/fastjson/JSONStreamContext.java b/src/main/java/com/alibaba/fastjson/JSONStreamContext.java new file mode 100644 index 0000000000..a0309a1376 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/JSONStreamContext.java @@ -0,0 +1,19 @@ +package com.alibaba.fastjson; + +class JSONStreamContext { + + final static int StartObject = 1001; + final static int PropertyKey = 1002; + final static int PropertyValue = 1003; + final static int StartArray = 1004; + final static int ArrayValue = 1005; + + protected final JSONStreamContext parent; + + protected int state; + + public JSONStreamContext(JSONStreamContext parent, int state){ + this.parent = parent; + this.state = state; + } +} diff --git a/src/main/java/com/alibaba/fastjson/JSONWriter.java b/src/main/java/com/alibaba/fastjson/JSONWriter.java new file mode 100755 index 0000000000..7cb288dd8e --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/JSONWriter.java @@ -0,0 +1,204 @@ +package com.alibaba.fastjson; + +import java.io.Closeable; +import java.io.Flushable; +import java.io.IOException; +import java.io.Writer; + +import static com.alibaba.fastjson.JSONStreamContext.*; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class JSONWriter implements Closeable, Flushable { + + private SerializeWriter writer; + + private JSONSerializer serializer; + + private JSONStreamContext context; + + public JSONWriter(Writer out){ + writer = new SerializeWriter(out); + serializer = new JSONSerializer(writer); + } + + public void config(SerializerFeature feature, boolean state) { + this.writer.config(feature, state); + } + + public void startObject() { + if (context != null) { + beginStructure(); + } + context = new JSONStreamContext(context, JSONStreamContext.StartObject); + writer.write('{'); + } + + public void endObject() { + writer.write('}'); + endStructure(); + } + + public void writeKey(String key) { + writeObject(key); + } + + public void writeValue(Object object) { + writeObject(object); + } + + public void writeObject(String object) { + beforeWrite(); + + serializer.write(object); + + afterWriter(); + } + + public void writeObject(Object object) { + beforeWrite(); + serializer.write(object); + afterWriter(); + } + + public void startArray() { + if (context != null) { + beginStructure(); + } + + context = new JSONStreamContext(context, StartArray); + writer.write('['); + } + + private void beginStructure() { + final int state = context.state; + switch (context.state) { + case PropertyKey: + writer.write(':'); + break; + case ArrayValue: + writer.write(','); + break; + case StartObject: + break; + case StartArray: + break; + default: + throw new JSONException("illegal state : " + state); + } + } + + public void endArray() { + writer.write(']'); + endStructure(); + } + + private void endStructure() { + context = context.parent; + + if (context == null) { + return; + } + + int newState = -1; + switch (context.state) { + case PropertyKey: + newState = PropertyValue; + break; + case StartArray: + newState = ArrayValue; + break; + case ArrayValue: + break; + case StartObject: + newState = PropertyKey; + break; + default: + break; + } + if (newState != -1) { + context.state = newState; + } + } + + private void beforeWrite() { + if (context == null) { + return; + } + + switch (context.state) { + case StartObject: + case StartArray: + break; + case PropertyKey: + writer.write(':'); + break; + case PropertyValue: + writer.write(','); + break; + case ArrayValue: + writer.write(','); + break; + default: + break; + } + } + + private void afterWriter() { + if (context == null) { + return; + } + + final int state = context.state; + int newState = -1; + switch (state) { + case PropertyKey: + newState = PropertyValue; + break; + case StartObject: + case PropertyValue: + newState = PropertyKey; + break; + case StartArray: + newState = ArrayValue; + break; + case ArrayValue: + break; + default: + break; + } + + if (newState != -1) { + context.state = newState; + } + } + + public void flush() throws IOException { + writer.flush(); + } + + public void close() throws IOException { + writer.close(); + } + + @Deprecated + public void writeStartObject() { + startObject(); + } + + @Deprecated + public void writeEndObject() { + endObject(); + } + + @Deprecated + public void writeStartArray() { + startArray(); + } + + @Deprecated + public void writeEndArray() { + endArray(); + } +} diff --git a/src/main/java/com/alibaba/fastjson/PropertyNamingStrategy.java b/src/main/java/com/alibaba/fastjson/PropertyNamingStrategy.java new file mode 100644 index 0000000000..adfa285bbe --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/PropertyNamingStrategy.java @@ -0,0 +1,70 @@ +package com.alibaba.fastjson; + +/** + * @since 1.2.15 + */ +public enum PropertyNamingStrategy { + CamelCase, // + PascalCase, // + SnakeCase, // + KebabCase; + + public String translate(String propertyName) { + switch (this) { + case SnakeCase: { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < propertyName.length(); ++i) { + char ch = propertyName.charAt(i); + if (ch >= 'A' && ch <= 'Z') { + char ch_ucase = (char) (ch + 32); + if (i > 0) { + buf.append('_'); + } + buf.append(ch_ucase); + } else { + buf.append(ch); + } + } + return buf.toString(); + } + case KebabCase: { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < propertyName.length(); ++i) { + char ch = propertyName.charAt(i); + if (ch >= 'A' && ch <= 'Z') { + char ch_ucase = (char) (ch + 32); + if (i > 0) { + buf.append('-'); + } + buf.append(ch_ucase); + } else { + buf.append(ch); + } + } + return buf.toString(); + } + case PascalCase: { + char ch = propertyName.charAt(0); + if (ch >= 'a' && ch <= 'z') { + char[] chars = propertyName.toCharArray(); + chars[0] -= 32; + return new String(chars); + } + + return propertyName; + } + case CamelCase: { + char ch = propertyName.charAt(0); + if (ch >= 'A' && ch <= 'Z') { + char[] chars = propertyName.toCharArray(); + chars[0] += 32; + return new String(chars); + } + + return propertyName; + } + default: + return propertyName; + } + } +} diff --git a/src/main/java/com/alibaba/fastjson/TypeReference.java b/src/main/java/com/alibaba/fastjson/TypeReference.java old mode 100644 new mode 100755 index 7cb7085afd..b2c02928bb --- a/src/main/java/com/alibaba/fastjson/TypeReference.java +++ b/src/main/java/com/alibaba/fastjson/TypeReference.java @@ -1,22 +1,132 @@ package com.alibaba.fastjson; +import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import com.alibaba.fastjson.util.ParameterizedTypeImpl; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * Represents a generic type {@code T}. Java doesn't yet provide a way to + * represent generic types, so this class does. Forces clients to create a + * subclass of this class which enables retrieval the type information even at + * runtime. + * + *

For example, to create a type literal for {@code List}, you can + * create an empty anonymous inner class: + * + *

+ * TypeReference<List<String>> list = new TypeReference<List<String>>() {};
+ * 
+ * This syntax cannot be used to create type literals that have wildcard + * parameters, such as {@code Class} or {@code List}. + */ public class TypeReference { + static ConcurrentMap classTypeCache + = new ConcurrentHashMap(16, 0.75f, 1); - private final Type type; + protected final Type type; + /** + * Constructs a new type literal. Derives represented class from type + * parameter. + * + *

Clients create an empty anonymous subclass. Doing so embeds the type + * parameter in the anonymous class's type hierarchy so we can reconstitute it + * at runtime despite erasure. + */ protected TypeReference(){ Type superClass = getClass().getGenericSuperclass(); - type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; + Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; + + Type cachedType = classTypeCache.get(type); + if (cachedType == null) { + classTypeCache.putIfAbsent(type, type); + cachedType = classTypeCache.get(type); + } + + this.type = cachedType; } + /** + * @since 1.2.9 + * @param actualTypeArguments + */ + protected TypeReference(Type... actualTypeArguments){ + Class thisClass = this.getClass(); + Type superClass = thisClass.getGenericSuperclass(); + + ParameterizedType argType = (ParameterizedType) ((ParameterizedType) superClass).getActualTypeArguments()[0]; + Type rawType = argType.getRawType(); + Type[] argTypes = argType.getActualTypeArguments(); + + int actualIndex = 0; + for (int i = 0; i < argTypes.length; ++i) { + if (argTypes[i] instanceof TypeVariable && + actualIndex < actualTypeArguments.length) { + argTypes[i] = actualTypeArguments[actualIndex++]; + } + // fix for openjdk and android env + if (argTypes[i] instanceof GenericArrayType) { + argTypes[i] = TypeUtils.checkPrimitiveArray( + (GenericArrayType) argTypes[i]); + } + + // 如果有多层泛型且该泛型已经注明实现的情况下,判断该泛型下一层是否还有泛型 + if(argTypes[i] instanceof ParameterizedType) { + argTypes[i] = handlerParameterizedType((ParameterizedType) argTypes[i], actualTypeArguments, actualIndex); + } + } + + Type key = new ParameterizedTypeImpl(argTypes, thisClass, rawType); + Type cachedType = classTypeCache.get(key); + if (cachedType == null) { + classTypeCache.putIfAbsent(key, key); + cachedType = classTypeCache.get(key); + } + + type = cachedType; + + } + + private Type handlerParameterizedType(ParameterizedType type, Type[] actualTypeArguments, int actualIndex) { + Class thisClass = this.getClass(); + Type rawType = type.getRawType(); + Type[] argTypes = type.getActualTypeArguments(); + + for(int i = 0; i < argTypes.length; ++i) { + if (argTypes[i] instanceof TypeVariable && actualIndex < actualTypeArguments.length) { + argTypes[i] = actualTypeArguments[actualIndex++]; + } + + // fix for openjdk and android env + if (argTypes[i] instanceof GenericArrayType) { + argTypes[i] = TypeUtils.checkPrimitiveArray( + (GenericArrayType) argTypes[i]); + } + + // 如果有多层泛型且该泛型已经注明实现的情况下,判断该泛型下一层是否还有泛型 + if(argTypes[i] instanceof ParameterizedType) { + return handlerParameterizedType((ParameterizedType) argTypes[i], actualTypeArguments, actualIndex); + } + } + + Type key = new ParameterizedTypeImpl(argTypes, thisClass, rawType); + return key; + } + + /** + * Gets underlying {@code Type} instance. + */ public Type getType() { return type; } - + public final static Type LIST_STRING = new TypeReference>() {}.getType(); } diff --git a/src/main/java/com/alibaba/fastjson/annotation/JSONCreator.java b/src/main/java/com/alibaba/fastjson/annotation/JSONCreator.java new file mode 100755 index 0000000000..10224689d0 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/annotation/JSONCreator.java @@ -0,0 +1,12 @@ +package com.alibaba.fastjson.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.CONSTRUCTOR, ElementType.METHOD }) +public @interface JSONCreator { + +} diff --git a/src/main/java/com/alibaba/fastjson/annotation/JSONField.java b/src/main/java/com/alibaba/fastjson/annotation/JSONField.java old mode 100644 new mode 100755 index 2078031a6c..9907c9ea86 --- a/src/main/java/com/alibaba/fastjson/annotation/JSONField.java +++ b/src/main/java/com/alibaba/fastjson/annotation/JSONField.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,11 +24,17 @@ import com.alibaba.fastjson.serializer.SerializerFeature; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.METHOD, ElementType.FIELD }) +@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) public @interface JSONField { + /** + * config encode/decode ordinal + * @since 1.1.42 + * @return + */ + int ordinal() default 0; String name() default ""; @@ -41,4 +47,36 @@ SerializerFeature[] serialzeFeatures() default {}; Feature[] parseFeatures() default {}; + + String label() default ""; + + /** + * @since 1.2.12 + */ + boolean jsonDirect() default false; + + /** + * Serializer class to use for serializing associated value. + * + * @since 1.2.16 + */ + Class serializeUsing() default Void.class; + + /** + * Deserializer class to use for deserializing associated value. + * + * @since 1.2.16 + */ + Class deserializeUsing() default Void.class; + + /** + * @since 1.2.21 + * @return the alternative names of the field when it is deserialized + */ + String[] alternateNames() default {}; + + /** + * @since 1.2.31 + */ + boolean unwrapped() default false; } diff --git a/src/main/java/com/alibaba/fastjson/annotation/JSONPOJOBuilder.java b/src/main/java/com/alibaba/fastjson/annotation/JSONPOJOBuilder.java new file mode 100644 index 0000000000..648065dbc0 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/annotation/JSONPOJOBuilder.java @@ -0,0 +1,42 @@ +package com.alibaba.fastjson.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * + * @since 1.2.8 + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface JSONPOJOBuilder { + /** + * Property to use for re-defining which zero-argument method + * is considered the actual "build-method": method called after + * all data has been bound, and the actual instance needs to + * be instantiated. + *

+ * Default value is "build". + */ + public String buildMethod() default "build"; + + /** + * Property used for (re)defining name prefix to use for + * auto-detecting "with-methods": methods that are similar to + * "set-methods" (in that they take an argument), but that + * may also return the new builder instance to use + * (which may be 'this', or a new modified builder instance). + * Note that in addition to this prefix, it is also possible + * to use {@link com.alibaba.fastjson.annotation.JSONField} + * annotation to indicate "with-methods". + *

+ * Default value is "with", so that method named "withValue()" + * would be used for binding JSON property "value" (using type + * indicated by the argument; or one defined with annotations. + */ + public String withPrefix() default "with"; + +} diff --git a/src/main/java/com/alibaba/fastjson/annotation/JSONType.java b/src/main/java/com/alibaba/fastjson/annotation/JSONType.java new file mode 100755 index 0000000000..fd179447e0 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/annotation/JSONType.java @@ -0,0 +1,67 @@ +package com.alibaba.fastjson.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import com.alibaba.fastjson.PropertyNamingStrategy; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface JSONType { + + boolean asm() default true; + + String[] orders() default {}; + + /** + * @since 1.2.6 + */ + String[] includes() default {}; + + String[] ignores() default {}; + + SerializerFeature[] serialzeFeatures() default {}; + Feature[] parseFeatures() default {}; + + boolean alphabetic() default true; + + Class mappingTo() default Void.class; + + Class builder() default Void.class; + + /** + * @since 1.2.11 + */ + String typeName() default ""; + + /** + * @since 1.2.32 + */ + String typeKey() default ""; + + /** + * @since 1.2.11 + */ + Class[] seeAlso() default{}; + + /** + * @since 1.2.14 + */ + Class serializer() default Void.class; + + /** + * @since 1.2.14 + */ + Class deserializer() default Void.class; + + boolean serializeEnumAsJavaBean() default false; + + PropertyNamingStrategy naming() default PropertyNamingStrategy.CamelCase; +} diff --git a/src/main/java/com/alibaba/fastjson/asm/ByteVector.java b/src/main/java/com/alibaba/fastjson/asm/ByteVector.java old mode 100644 new mode 100755 diff --git a/src/main/java/com/alibaba/fastjson/asm/ClassReader.java b/src/main/java/com/alibaba/fastjson/asm/ClassReader.java new file mode 100644 index 0000000000..fdab09f1a8 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/asm/ClassReader.java @@ -0,0 +1,299 @@ +package com.alibaba.fastjson.asm; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by wenshao on 05/08/2017. + */ +public class ClassReader { + public final byte[] b; + private final int[] items; + private final String[] strings; + private final int maxStringLength; + public final int header; + + + public ClassReader(final InputStream is) throws IOException { + { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + for (; ; ) { + int len = is.read(buf); + if (len == -1) { + break; + } + + if (len > 0) { + out.write(buf, 0, len); + } + } + is.close(); + this.b = out.toByteArray(); + } + + // parses the constant pool + items = new int[readUnsignedShort(8)]; + int n = items.length; + strings = new String[n]; + int max = 0; + int index = 10; + for (int i = 1; i < n; ++i) { + items[i] = index + 1; + int size; + switch (b[index]) { + case 9: // FIELD: + case 10: // METH: + case 11: //IMETH: + case 3: //INT: + case 4: //FLOAT: + case 18: //INVOKEDYN: + case 12: //NAME_TYPE: + size = 5; + break; + case 5: //LONG: + case 6: //DOUBLE: + size = 9; + ++i; + break; + case 15: //MHANDLE: + size = 4; + break; + case 1: //UTF8: + size = 3 + readUnsignedShort(index + 1); + if (size > max) { + max = size; + } + break; + // case HamConstants.CLASS: + // case HamConstants.STR: + default: + size = 3; + break; + } + index += size; + } + maxStringLength = max; + // the class header information starts just after the constant pool + header = index; + } + + public void accept(final TypeCollector classVisitor) { + char[] c = new char[maxStringLength]; // buffer used to read strings + int i, j, k; // loop variables + int u, v, w; // indexes in b + + String attrName; + int anns = 0; + int ianns = 0; + + // visits the header + u = header; + v = items[readUnsignedShort(u + 4)]; + int len = readUnsignedShort(u + 6); + w = 0; + u += 8; + for (i = 0; i < len; ++i) { + u += 2; + } + v = u; + i = readUnsignedShort(v); + v += 2; + for (; i > 0; --i) { + j = readUnsignedShort(v + 6); + v += 8; + for (; j > 0; --j) { + v += 6 + readInt(v + 2); + } + } + i = readUnsignedShort(v); + v += 2; + for (; i > 0; --i) { + j = readUnsignedShort(v + 6); + v += 8; + for (; j > 0; --j) { + v += 6 + readInt(v + 2); + } + } + + i = readUnsignedShort(v); + v += 2; + for (; i > 0; --i) { + v += 6 + readInt(v + 2); + } + + //annotations not needed. + + // visits the fields + i = readUnsignedShort(u); + u += 2; + for (; i > 0; --i) { + j = readUnsignedShort(u + 6); + u += 8; + for (; j > 0; --j) { + u += 6 + readInt(u + 2); + } + } + + // visits the methods + i = readUnsignedShort(u); + u += 2; + for (; i > 0; --i) { + // inlined in original ASM source, now a method call + u = readMethod(classVisitor, c, u); + } + } + + private int readMethod(TypeCollector classVisitor, char[] c, int u) { + int v; + int w; + int j; + String attrName; + int k; + int access = readUnsignedShort(u); + String name = readUTF8(u + 2, c); + String desc = readUTF8(u + 4, c); + v = 0; + w = 0; + + // looks for Code and Exceptions attributes + j = readUnsignedShort(u + 6); + u += 8; + for (; j > 0; --j) { + attrName = readUTF8(u, c); + int attrSize = readInt(u + 2); + u += 6; + // tests are sorted in decreasing frequency order + // (based on frequencies observed on typical classes) + if (attrName.equals("Code")) { + v = u; + } + u += attrSize; + } + // reads declared exceptions + if (w == 0) { + } else { + w += 2; + for (j = 0; j < readUnsignedShort(w); ++j) { + w += 2; + } + } + + // visits the method's code, if any + MethodCollector mv = classVisitor.visitMethod(access, name, desc); + + if (mv != null && v != 0) { + int codeLength = readInt(v + 4); + v += 8; + + int codeStart = v; + int codeEnd = v + codeLength; + v = codeEnd; + + j = readUnsignedShort(v); + v += 2; + for (; j > 0; --j) { + v += 8; + } + // parses the local variable, line number tables, and code + // attributes + int varTable = 0; + int varTypeTable = 0; + j = readUnsignedShort(v); + v += 2; + for (; j > 0; --j) { + attrName = readUTF8(v, c); + if (attrName.equals("LocalVariableTable")) { + varTable = v + 6; + } else if (attrName.equals("LocalVariableTypeTable")) { + varTypeTable = v + 6; + } + v += 6 + readInt(v + 2); + } + + v = codeStart; + // visits the local variable tables + if (varTable != 0) { + if (varTypeTable != 0) { + k = readUnsignedShort(varTypeTable) * 3; + w = varTypeTable + 2; + int[] typeTable = new int[k]; + while (k > 0) { + typeTable[--k] = w + 6; // signature + typeTable[--k] = readUnsignedShort(w + 8); // index + typeTable[--k] = readUnsignedShort(w); // start + w += 10; + } + } + k = readUnsignedShort(varTable); + w = varTable + 2; + for (; k > 0; --k) { + int index = readUnsignedShort(w + 8); + mv.visitLocalVariable(readUTF8(w + 4, c), index); + w += 10; + } + } + } + return u; + } + + private int readUnsignedShort(final int index) { + byte[] b = this.b; + return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF); + } + + private int readInt(final int index) { + byte[] b = this.b; + return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16) + | ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF); + } + + private String readUTF8(int index, final char[] buf) { + int item = readUnsignedShort(index); + String s = strings[item]; + if (s != null) { + return s; + } + index = items[item]; + return strings[item] = readUTF(index + 2, readUnsignedShort(index), buf); + } + + private String readUTF(int index, final int utfLen, final char[] buf) { + int endIndex = index + utfLen; + byte[] b = this.b; + int strLen = 0; + int c; + int st = 0; + char cc = 0; + while (index < endIndex) { + c = b[index++]; + switch (st) { + case 0: + c = c & 0xFF; + if (c < 0x80) { // 0xxxxxxx + buf[strLen++] = (char) c; + } else if (c < 0xE0 && c > 0xBF) { // 110x xxxx 10xx xxxx + cc = (char) (c & 0x1F); + st = 1; + } else { // 1110 xxxx 10xx xxxx 10xx xxxx + cc = (char) (c & 0x0F); + st = 2; + } + break; + + case 1: // byte 2 of 2-byte char or byte 3 of 3-byte char + buf[strLen++] = (char) ((cc << 6) | (c & 0x3F)); + st = 0; + break; + + case 2: // byte 2 of 3-byte char + cc = (char) ((cc << 6) | (c & 0x3F)); + st = 1; + break; + } + } + return new String(buf, 0, strLen); + } + +} diff --git a/src/main/java/com/alibaba/fastjson/asm/ClassWriter.java b/src/main/java/com/alibaba/fastjson/asm/ClassWriter.java old mode 100644 new mode 100755 index 08edae65fc..7bcf97bd56 --- a/src/main/java/com/alibaba/fastjson/asm/ClassWriter.java +++ b/src/main/java/com/alibaba/fastjson/asm/ClassWriter.java @@ -30,202 +30,10 @@ package com.alibaba.fastjson.asm; /** - * A {@link ClassVisitor} that generates classes in bytecode form. More precisely this visitor generates a byte array - * conforming to the Java class file format. It can be used alone, to generate a Java class "from scratch", or with one - * or more and adapter class visitor to generate a modified class from one or more existing Java classes. * * @author Eric Bruneton */ public class ClassWriter { - - /** - * Flag to automatically compute the maximum stack size and the maximum number of local variables of methods. If - * this flag is set, then the arguments of the {@link MethodVisitor#visitMaxs visitMaxs} method of the - * {@link MethodVisitor} returned by the {@link #visitMethod visitMethod} method will be ignored, and computed - * automatically from the signature and the bytecode of each method. - * - * @see #ClassWriter(int) - */ - public static final int COMPUTE_MAXS = 1; - - /** - * Flag to automatically compute the stack map frames of methods from scratch. If this flag is set, then the calls - * to the {@link MethodVisitor#visitFrame} method are ignored, and the stack map frames are recomputed from the - * methods bytecode. The arguments of the {@link MethodVisitor#visitMaxs visitMaxs} method are also ignored and - * recomputed from the bytecode. In other words, computeFrames implies computeMaxs. - * - * @see #ClassWriter(int) - */ - public static final int COMPUTE_FRAMES = 2; - - /** - * Pseudo access flag to distinguish between the synthetic attribute and the synthetic access flag. - */ - static final int ACC_SYNTHETIC_ATTRIBUTE = 0x40000; - - /** - * The type of instructions without any argument. - */ - static final int NOARG_INSN = 0; - - /** - * The type of instructions with an signed byte argument. - */ - static final int SBYTE_INSN = 1; - - /** - * The type of instructions with an signed short argument. - */ - static final int SHORT_INSN = 2; - - /** - * The type of instructions with a local variable index argument. - */ - static final int VAR_INSN = 3; - - /** - * The type of instructions with an implicit local variable index argument. - */ - static final int IMPLVAR_INSN = 4; - - /** - * The type of instructions with a type descriptor argument. - */ - static final int TYPE_INSN = 5; - - /** - * The type of field and method invocations instructions. - */ - static final int FIELDORMETH_INSN = 6; - - /** - * The type of the INVOKEINTERFACE/INVOKEDYNAMIC instruction. - */ - static final int ITFDYNMETH_INSN = 7; - - /** - * The type of instructions with a 2 bytes bytecode offset label. - */ - static final int LABEL_INSN = 8; - - /** - * The type of instructions with a 4 bytes bytecode offset label. - */ - static final int LABELW_INSN = 9; - - /** - * The type of the LDC instruction. - */ - static final int LDC_INSN = 10; - - /** - * The type of the LDC_W and LDC2_W instructions. - */ - static final int LDCW_INSN = 11; - - /** - * The type of the IINC instruction. - */ - static final int IINC_INSN = 12; - - /** - * The type of the TABLESWITCH instruction. - */ - static final int TABL_INSN = 13; - - /** - * The type of the LOOKUPSWITCH instruction. - */ - static final int LOOK_INSN = 14; - - /** - * The type of the MULTIANEWARRAY instruction. - */ - static final int MANA_INSN = 15; - - /** - * The type of the WIDE instruction. - */ - static final int WIDE_INSN = 16; - - /** - * The instruction types of all JVM opcodes. - */ - static final byte[] TYPE; - - /** - * The type of CONSTANT_Class constant pool items. - */ - static final int CLASS = 7; - - /** - * The type of CONSTANT_Fieldref constant pool items. - */ - static final int FIELD = 9; - - /** - * The type of CONSTANT_Methodref constant pool items. - */ - static final int METH = 10; - - /** - * The type of CONSTANT_InterfaceMethodref constant pool items. - */ - static final int IMETH = 11; - - /** - * The type of CONSTANT_String constant pool items. - */ - static final int STR = 8; - - /** - * The type of CONSTANT_Integer constant pool items. - */ - static final int INT = 3; - - /** - * The type of CONSTANT_Float constant pool items. - */ - static final int FLOAT = 4; - - /** - * The type of CONSTANT_Long constant pool items. - */ - static final int LONG = 5; - - /** - * The type of CONSTANT_Double constant pool items. - */ - static final int DOUBLE = 6; - - /** - * The type of CONSTANT_NameAndType constant pool items. - */ - static final int NAME_TYPE = 12; - - /** - * The type of CONSTANT_Utf8 constant pool items. - */ - static final int UTF8 = 1; - - /** - * Normal type Item stored in the ClassWriter {@link ClassWriter#typeTable}, instead of the constant pool, in order - * to avoid clashes with normal constant pool items in the ClassWriter constant pool's hash table. - */ - static final int TYPE_NORMAL = 13; - - /** - * Uninitialized type Item stored in the ClassWriter {@link ClassWriter#typeTable}, instead of the constant pool, in - * order to avoid clashes with normal constant pool items in the ClassWriter constant pool's hash table. - */ - static final int TYPE_UNINIT = 14; - - /** - * Merged type Item stored in the ClassWriter {@link ClassWriter#typeTable}, instead of the constant pool, in order - * to avoid clashes with normal constant pool items in the ClassWriter constant pool's hash table. - */ - static final int TYPE_MERGED = 15; - /** * Minor and major version numbers of the class to be generated. */ @@ -331,91 +139,6 @@ public class ClassWriter { */ MethodWriter lastMethod; - // ------------------------------------------------------------------------ - // Static initializer - // ------------------------------------------------------------------------ - - /** - * Computes the instruction types of JVM opcodes. - */ - static { - int i; - byte[] b = new byte[220]; - String s = "AAAAAAAAAAAAAAAABCKLLDDDDDEEEEEEEEEEEEEEEEEEEEAAAAAAAADD" + "DDDEEEEEEEEEEEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAIIIIIIIIIIIIIIIIDNOAA" + "AAAAGGGGGGGHHFBFAAFFAAQPIIJJIIIIIIIIIIIIIIIIII"; - for (i = 0; i < b.length; ++i) { - b[i] = (byte) (s.charAt(i) - 'A'); - } - TYPE = b; - - // code to generate the above string - // - // // SBYTE_INSN instructions - // b[Constants.NEWARRAY] = SBYTE_INSN; - // b[Constants.BIPUSH] = SBYTE_INSN; - // - // // SHORT_INSN instructions - // b[Constants.SIPUSH] = SHORT_INSN; - // - // // (IMPL)VAR_INSN instructions - // b[Constants.RET] = VAR_INSN; - // for (i = Constants.ILOAD; i <= Constants.ALOAD; ++i) { - // b[i] = VAR_INSN; - // } - // for (i = Constants.ISTORE; i <= Constants.ASTORE; ++i) { - // b[i] = VAR_INSN; - // } - // for (i = 26; i <= 45; ++i) { // ILOAD_0 to ALOAD_3 - // b[i] = IMPLVAR_INSN; - // } - // for (i = 59; i <= 78; ++i) { // ISTORE_0 to ASTORE_3 - // b[i] = IMPLVAR_INSN; - // } - // - // // TYPE_INSN instructions - // b[Constants.NEW] = TYPE_INSN; - // b[Constants.ANEWARRAY] = TYPE_INSN; - // b[Constants.CHECKCAST] = TYPE_INSN; - // b[Constants.INSTANCEOF] = TYPE_INSN; - // - // // (Set)FIELDORMETH_INSN instructions - // for (i = Constants.GETSTATIC; i <= Constants.INVOKESTATIC; ++i) { - // b[i] = FIELDORMETH_INSN; - // } - // b[Constants.INVOKEINTERFACE] = ITFDYNMETH_INSN; - // b[Constants.INVOKEDYNAMIC] = ITFDYNMETH_INSN; - // - // // LABEL(W)_INSN instructions - // for (i = Constants.IFEQ; i <= Constants.JSR; ++i) { - // b[i] = LABEL_INSN; - // } - // b[Constants.IFNULL] = LABEL_INSN; - // b[Constants.IFNONNULL] = LABEL_INSN; - // b[200] = LABELW_INSN; // GOTO_W - // b[201] = LABELW_INSN; // JSR_W - // // temporary opcodes used internally by ASM - see Label and - // MethodWriter - // for (i = 202; i < 220; ++i) { - // b[i] = LABEL_INSN; - // } - // - // // LDC(_W) instructions - // b[Constants.LDC] = LDC_INSN; - // b[19] = LDCW_INSN; // LDC_W - // b[20] = LDCW_INSN; // LDC2_W - // - // // special instructions - // b[Constants.IINC] = IINC_INSN; - // b[Constants.TABLESWITCH] = TABL_INSN; - // b[Constants.LOOKUPSWITCH] = LOOK_INSN; - // b[Constants.MULTIANEWARRAY] = MANA_INSN; - // b[196] = WIDE_INSN; // WIDE - // - // for (i = 0; i < b.length; ++i) { - // System.err.print((char)('A' + b[i])); - // } - // System.err.println(); - } - // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ @@ -424,12 +147,6 @@ public ClassWriter(){ this(0); } - /** - * Constructs a new {@link ClassWriter} object. - * - * @param flags option flags that can be used to modify the default behavior of this class. See - * {@link #COMPUTE_MAXS}, {@link #COMPUTE_FRAMES}. - */ private ClassWriter(final int flags){ index = 1; pool = new ByteVector(); @@ -447,29 +164,18 @@ private ClassWriter(final int flags){ public void visit(final int version, final int access, final String name, final String superName, final String[] interfaces) { this.version = version; this.access = access; - this.name = newClass(name); + this.name = newClassItem(name).index; thisName = name; - this.superName = superName == null ? 0 : newClass(superName); + this.superName = superName == null ? 0 : newClassItem(superName).index; if (interfaces != null && interfaces.length > 0) { interfaceCount = interfaces.length; this.interfaces = new int[interfaceCount]; for (int i = 0; i < interfaceCount; ++i) { - this.interfaces[i] = newClass(interfaces[i]); + this.interfaces[i] = newClassItem(interfaces[i]).index; } } } - public FieldVisitor visitField(final int access, final String name, final String desc) { - return new FieldWriter(this, access, name, desc); - } - - public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { - return new MethodWriter(this, access, name, desc, signature, exceptions); - } - - public void visitEnd() { - } - // ------------------------------------------------------------------------ // Other public methods // ------------------------------------------------------------------------ @@ -503,7 +209,7 @@ public byte[] toByteArray() { ByteVector out = new ByteVector(size); out.putInt(0xCAFEBABE).putInt(version); out.putShort(index).putByteArray(pool.data, 0, pool.length); - int mask = Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC)); + int mask = 393216; // Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC)); out.putShort(access & ~mask).putShort(name).putShort(superName); out.putShort(interfaceCount); for (int i = 0; i < interfaceCount; ++i) { @@ -538,42 +244,49 @@ public byte[] toByteArray() { * @return a new or already existing constant item with the given value. */ Item newConstItem(final Object cst) { - if (cst instanceof String) { + if (cst instanceof Integer) { + int val = ((Integer) cst).intValue(); + // return newInteger(val); + key.set(val); + Item result = get(key); + if (result == null) { + pool.putByte(3 /* INT */ ).putInt(val); + result = new Item(index++, key); + put(result); + } + return result; + } else if (cst instanceof String) { return newString((String) cst); } else if (cst instanceof Type) { Type t = (Type) cst; - return newClassItem(t.getSort() == Type.OBJECT ? t.getInternalName() : t.getDescriptor()); + return newClassItem(t.sort == 10 /*Type.OBJECT*/ ? t.getInternalName() : t.getDescriptor()); } else { throw new IllegalArgumentException("value " + cst); } } public int newUTF8(final String value) { - key.set(UTF8, value, null, null); + key.set(1 /* UTF8 */, value, null, null); Item result = get(key); if (result == null) { - pool.putByte(UTF8).putUTF8(value); + pool.putByte(1 /* UTF8 */).putUTF8(value); result = new Item(index++, key); put(result); } return result.index; } - Item newClassItem(final String value) { - key2.set(CLASS, value, null, null); + public Item newClassItem(final String value) { + key2.set(7 /* CLASS */, value, null, null); Item result = get(key2); if (result == null) { - pool.put12(CLASS, newUTF8(value)); + pool.put12(7 /* CLASS */, newUTF8(value)); result = new Item(index++, key2); put(result); } return result; } - public int newClass(final String value) { - return newClassItem(value).index; - } - /** * Adds a field reference to the constant pool of the class being build. Does nothing if the constant pool already * contains a similar item. @@ -584,10 +297,12 @@ public int newClass(final String value) { * @return a new or already existing field reference item. */ Item newFieldItem(final String owner, final String name, final String desc) { - key3.set(FIELD, owner, name, desc); + key3.set(9 /* FIELD */, owner, name, desc); Item result = get(key3); if (result == null) { - put122(FIELD, newClass(owner), newNameType(name, desc)); + // put122(9 /* FIELD */, newClassItem(owner).index, newNameTypeItem(name, desc).index); + int s1 = newClassItem(owner).index, s2 = newNameTypeItem(name, desc).index; + pool.put12(9 /* FIELD */, s1).putShort(s2); result = new Item(index++, key3); put(result); } @@ -605,65 +320,44 @@ Item newFieldItem(final String owner, final String name, final String desc) { * @return a new or already existing method reference item. */ Item newMethodItem(final String owner, final String name, final String desc, final boolean itf) { - int type = itf ? IMETH : METH; + int type = itf ? 11 /* IMETH */ : 10 /* METH */; key3.set(type, owner, name, desc); Item result = get(key3); if (result == null) { - put122(type, newClass(owner), newNameType(name, desc)); + // put122(type, newClassItem(owner).index, newNameTypeItem(name, desc).index); + int s1 = newClassItem(owner).index, s2 = newNameTypeItem(name, desc).index; + pool.put12(type, s1).putShort(s2); result = new Item(index++, key3); put(result); } return result; } - /** - * Adds a string to the constant pool of the class being build. Does nothing if the constant pool already contains a - * similar item. - * - * @param value the String value. - * @return a new or already existing string item. - */ private Item newString(final String value) { - key2.set(STR, value, null, null); + key2.set(8 /* STR */, value, null, null); Item result = get(key2); if (result == null) { - pool.put12(STR, newUTF8(value)); + pool.put12(8 /*STR*/, newUTF8(value)); result = new Item(index++, key2); put(result); } return result; } - public int newNameType(final String name, final String desc) { - return newNameTypeItem(name, desc).index; - } - - /** - * Adds a name and type to the constant pool of the class being build. Does nothing if the constant pool already - * contains a similar item. - * - * @param name a name. - * @param desc a type descriptor. - * @return a new or already existing name and type item. - */ - Item newNameTypeItem(final String name, final String desc) { - key2.set(NAME_TYPE, name, desc, null); + public Item newNameTypeItem(final String name, final String desc) { + key2.set(12 /* NAME_TYPE */, name, desc, null); Item result = get(key2); if (result == null) { - put122(NAME_TYPE, newUTF8(name), newUTF8(desc)); + //put122(12 /* NAME_TYPE */, newUTF8(name), newUTF8(desc)); + int s1 = newUTF8(name), s2 = newUTF8(desc); + pool.put12(12 /* NAME_TYPE */, s1).putShort(s2); result = new Item(index++, key2); put(result); } return result; } - /** - * Returns the constant pool's hash table item which is equal to the given item. - * - * @param key a constant pool item. - * @return the constant pool's hash table item which is equal to the given item, or null if there is no - * such item. - */ + private Item get(final Item key) { Item i = items[key.hashCode % items.length]; while (i != null && (i.type != key.type || !key.isEqualTo(i))) { @@ -672,11 +366,6 @@ private Item get(final Item key) { return i; } - /** - * Puts the given item in the constant pool's hash table. The hash table must not already contains this item. - * - * @param i the item to be added to the constant pool's hash table. - */ private void put(final Item i) { if (index > threshold) { int ll = items.length; @@ -699,15 +388,4 @@ private void put(final Item i) { i.next = items[index]; items[index] = i; } - - /** - * Puts one byte and two shorts into the constant pool. - * - * @param b a byte. - * @param s1 a short. - * @param s2 another short. - */ - private void put122(final int b, final int s1, final int s2) { - pool.put12(b, s1).putShort(s2); - } } diff --git a/src/main/java/com/alibaba/fastjson/asm/FieldVisitor.java b/src/main/java/com/alibaba/fastjson/asm/FieldVisitor.java deleted file mode 100644 index e14ff77c17..0000000000 --- a/src/main/java/com/alibaba/fastjson/asm/FieldVisitor.java +++ /dev/null @@ -1,45 +0,0 @@ -/*** - * ASM: a very small and fast Java bytecode manipulation framework - * Copyright (c) 2000-2007 INRIA, France Telecom - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.alibaba.fastjson.asm; - -/** - * A visitor to visit a Java field. The methods of this interface must be called in the following order: ( - * visitAnnotation | visitAttribute )* visitEnd. - * - * @author Eric Bruneton - */ -public interface FieldVisitor { - - /** - * Visits the end of the field. This method, which is the last one to be called, is used to inform the visitor that - * all the annotations and attributes of the field have been visited. - */ - void visitEnd(); -} diff --git a/src/main/java/com/alibaba/fastjson/asm/FieldWriter.java b/src/main/java/com/alibaba/fastjson/asm/FieldWriter.java old mode 100644 new mode 100755 index 2a75dbf683..4a93009e4a --- a/src/main/java/com/alibaba/fastjson/asm/FieldWriter.java +++ b/src/main/java/com/alibaba/fastjson/asm/FieldWriter.java @@ -30,15 +30,12 @@ package com.alibaba.fastjson.asm; /** - * An {@link FieldVisitor} that generates Java fields in bytecode form. + * An FieldWriter that generates Java fields in bytecode form. * * @author Eric Bruneton */ -final class FieldWriter implements FieldVisitor { +public final class FieldWriter { - /** - * Next field writer (see {@link ClassWriter#firstField firstField}). - */ FieldWriter next; /** @@ -60,17 +57,7 @@ final class FieldWriter implements FieldVisitor { // Constructor // ------------------------------------------------------------------------ - /** - * Constructs a new {@link FieldWriter}. - * - * @param cw the class writer to which this field must be added. - * @param access the field's access flags (see {@link Opcodes}). - * @param name the field's name. - * @param desc the field's descriptor (see {@link Type}). - * @param signature the field's signature. May be null. - * @param value the field's constant value. May be null. - */ - FieldWriter(final ClassWriter cw, final int access, final String name, final String desc){ + public FieldWriter(final ClassWriter cw, final int access, final String name, final String desc){ if (cw.firstField == null) { cw.firstField = this; } else { @@ -108,7 +95,7 @@ int getSize() { * @param out where the content of this field must be put. */ void put(final ByteVector out) { - int mask = Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC)); + final int mask = 393216; // Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC)); out.putShort(access & ~mask).putShort(name).putShort(desc); int attributeCount = 0; out.putShort(attributeCount); diff --git a/src/main/java/com/alibaba/fastjson/asm/Item.java b/src/main/java/com/alibaba/fastjson/asm/Item.java old mode 100644 new mode 100755 index 1b1a559892..d941c41b47 --- a/src/main/java/com/alibaba/fastjson/asm/Item.java +++ b/src/main/java/com/alibaba/fastjson/asm/Item.java @@ -41,16 +41,6 @@ final class Item { */ int index; - /** - * Type of this constant pool item. A single class is used to represent all constant pool item types, in order to - * minimize the bytecode size of this package. The value of this field is one of {@link ClassWriter#INT}, - * {@link ClassWriter#LONG}, {@link ClassWriter#FLOAT}, {@link ClassWriter#DOUBLE}, {@link ClassWriter#UTF8}, - * {@link ClassWriter#STR}, {@link ClassWriter#CLASS}, {@link ClassWriter#NAME_TYPE}, {@link ClassWriter#FIELD}, - * {@link ClassWriter#METH}, {@link ClassWriter#IMETH}. Special Item types are used for Items that are stored in the - * ClassWriter {@link ClassWriter#typeTable}, instead of the constant pool, in order to avoid clashes with normal - * constant pool items in the ClassWriter constant pool's hash table. These special item types are - * {@link ClassWriter#TYPE_NORMAL}, {@link ClassWriter#TYPE_UNINIT} and {@link ClassWriter#TYPE_MERGED}. - */ int type; /** @@ -125,13 +115,13 @@ void set(final int type, final String strVal1, final String strVal2, final Strin this.strVal2 = strVal2; this.strVal3 = strVal3; switch (type) { - case ClassWriter.UTF8: - case ClassWriter.STR: - case ClassWriter.CLASS: - case ClassWriter.TYPE_NORMAL: + case 1 /* ClassWriter.UTF8 */: + case 8 /* ClassWriter.STR */: + case 7 /* ClassWriter.CLASS */: + case 13 /* ClassWriter.TYPE_NORMAL */: hashCode = 0x7FFFFFFF & (type + strVal1.hashCode()); return; - case ClassWriter.NAME_TYPE: + case 12 /* ClassWriter.NAME_TYPE */: hashCode = 0x7FFFFFFF & (type + strVal1.hashCode() * strVal2.hashCode()); return; // ClassWriter.FIELD: @@ -141,6 +131,17 @@ void set(final int type, final String strVal1, final String strVal2, final Strin hashCode = 0x7FFFFFFF & (type + strVal1.hashCode() * strVal2.hashCode() * strVal3.hashCode()); } } + + /** + * Sets this item to an integer item. + * + * @param intVal the value of this item. + */ + void set(final int intVal) { + this.type = 3 /* ClassWriter.INT */; + this.intVal = intVal; + this.hashCode = 0x7FFFFFFF & (type + intVal); + } /** * Indicates if the given item is equal to this one. This method assumes that the two items have the same @@ -151,21 +152,19 @@ void set(final int type, final String strVal1, final String strVal2, final Strin */ boolean isEqualTo(final Item i) { switch (type) { - case ClassWriter.UTF8: - case ClassWriter.STR: - case ClassWriter.CLASS: - case ClassWriter.TYPE_NORMAL: + case 1 /* ClassWriter.UTF8 */: + case 8 /* ClassWriter.STR */: + case 7 /* ClassWriter.CLASS */ : + case 13 /* ClassWriter.TYPE_NORMAL */ : return i.strVal1.equals(strVal1); - case ClassWriter.TYPE_MERGED: - case ClassWriter.LONG: - case ClassWriter.DOUBLE: + case 15 /* ClassWriter.TYPE_MERGED */ : + case 5 /* ClassWriter.LONG */ : + case 6 /* ClassWriter.DOUBLE */: return i.longVal == longVal; - case ClassWriter.INT: - case ClassWriter.FLOAT: + case 3 /* ClassWriter.INT */ : + case 4 /* ClassWriter.FLOAT */: return i.intVal == intVal; - case ClassWriter.TYPE_UNINIT: - return i.intVal == intVal && i.strVal1.equals(strVal1); - case ClassWriter.NAME_TYPE: + case 12 /* ClassWriter.NAME_TYPE */: return i.strVal1.equals(strVal1) && i.strVal2.equals(strVal2); // case ClassWriter.FIELD: // case ClassWriter.METH: diff --git a/src/main/java/com/alibaba/fastjson/asm/Label.java b/src/main/java/com/alibaba/fastjson/asm/Label.java old mode 100644 new mode 100755 index 5adbd03e1c..f37786b623 --- a/src/main/java/com/alibaba/fastjson/asm/Label.java +++ b/src/main/java/com/alibaba/fastjson/asm/Label.java @@ -38,26 +38,8 @@ * @author Eric Bruneton */ public class Label { - - /** - * Indicates if the position of this label is known. - */ - static final int RESOLVED = 2; - - /** - * Field used to associate user information to a label. Warning: this field is used by the ASM tree package. In - * order to use it with the ASM tree package you must override the - * {@link com.alibaba.fastjson.asm.tree.MethodNode#getLabelNode} method. - */ - public Object info; - int status; - /** - * The line number corresponding to this label, if known. - */ - int line; - /** * The position of this label in the code, if known. */ @@ -74,7 +56,7 @@ public class Label { * reference, while the second is the position of the first byte of the forward reference itself. In fact the sign * of the first integer indicates if this reference uses 2 or 4 bytes, and its absolute value gives the position of * the bytecode instruction. This array is also used as a bitset to store the subroutines to which a basic block - * belongs. This information is needed in {@linked MethodWriter#visitMaxs}, after all forward references have been + * belongs. This information is needed in MethodWriter#visitMaxs, after all forward references have been * resolved. Hence the same array can be used for both purposes without problems. */ private int[] srcAndRefPositions; @@ -90,7 +72,7 @@ public class Label { * stack map frames are similar and use two steps. The first step, during the visit of each instruction, builds * information about the state of the local variables and the operand stack at the end of each basic block, called * the "output frame", relatively to the frame state at the beginning of the basic block, which is called the - * "input frame", and which is unknown during this step. The second step, in {@link MethodWriter#visitMaxs}, + * "input frame", and which is unknown during this step. The second step, in link MethodWriter#visitMaxs, * is a fix point algorithm that computes information about the input frame of each basic block, from the input * state of the first basic block (known from the method signature), and by the using the previously computed * relative output frames. The algorithm used to compute the maximum stack size only computes the relative output @@ -117,7 +99,7 @@ public class Label { /** * The successor of this label, in the order they are visited. This linked list does not include labels used for - * debug info only. If {@link ClassWriter#COMPUTE_FRAMES} option is used then, in addition, it does not contain + * debug info only. If ClassWriter#COMPUTE_FRAMES option is used then, in addition, it does not contain * successive labels that denote the same bytecode position (in this case only the first label appears in this * list). */ @@ -159,7 +141,7 @@ public Label(){ * @throws IllegalArgumentException if this label has not been created by the given code writer. */ void put(final MethodWriter owner, final ByteVector out, final int source) { - if ((status & RESOLVED) == 0) { + if ((status & 2 /* RESOLVED */ ) == 0) { addReference(source, out.length); out.putShort(-1); } else { @@ -204,45 +186,18 @@ private void addReference(final int sourcePosition, final int referencePosition) * @throws IllegalArgumentException if this label has already been resolved, or if it has not been created by the * given code writer. */ - boolean resolve(final MethodWriter owner, final int position, final byte[] data) { - boolean needUpdate = false; - this.status |= RESOLVED; + void resolve(final MethodWriter owner, final int position, final byte[] data) { + this.status |= 2 /* RESOLVED */ ; this.position = position; int i = 0; while (i < referenceCount) { int source = srcAndRefPositions[i++]; int reference = srcAndRefPositions[i++]; - int offset; - if (source >= 0) { - offset = position - source; - if (offset < Short.MIN_VALUE || offset > Short.MAX_VALUE) { - /* - * changes the opcode of the jump instruction, in order to be able to find it later (see - * resizeInstructions in MethodWriter). These temporary opcodes are similar to jump instruction - * opcodes, except that the 2 bytes offset is unsigned (and can therefore represent values from 0 to - * 65535, which is sufficient since the size of a method is limited to 65535 bytes). - */ - int opcode = data[reference - 1] & 0xFF; - if (opcode <= Opcodes.JSR) { - // changes IFEQ ... JSR to opcodes 202 to 217 - data[reference - 1] = (byte) (opcode + 49); - } else { - // changes IFNULL and IFNONNULL to opcodes 218 and 219 - data[reference - 1] = (byte) (opcode + 20); - } - needUpdate = true; - } - data[reference++] = (byte) (offset >>> 8); - data[reference] = (byte) offset; - } else { - offset = position + source + 1; - data[reference++] = (byte) (offset >>> 24); - data[reference++] = (byte) (offset >>> 16); - data[reference++] = (byte) (offset >>> 8); - data[reference] = (byte) offset; - } + int offset = position - source; + data[reference++] = (byte) (offset >>> 8); + data[reference] = (byte) offset; + } - return needUpdate; } } diff --git a/src/main/java/com/alibaba/fastjson/asm/MethodCollector.java b/src/main/java/com/alibaba/fastjson/asm/MethodCollector.java new file mode 100644 index 0000000000..4af294edf0 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/asm/MethodCollector.java @@ -0,0 +1,41 @@ +package com.alibaba.fastjson.asm; + +/** + * Created by wenshao on 05/08/2017. + */ +public class MethodCollector { + + private final int paramCount; + + private final int ignoreCount; + + private int currentParameter; + + private final StringBuffer result; + + protected boolean debugInfoPresent; + + protected MethodCollector(int ignoreCount, int paramCount) { + this.ignoreCount = ignoreCount; + this.paramCount = paramCount; + this.result = new StringBuffer(); + this.currentParameter = 0; + // if there are 0 parameters, there is no need for debug info + this.debugInfoPresent = paramCount == 0; + } + + protected void visitLocalVariable(String name, int index) { + if (index >= ignoreCount && index < ignoreCount + paramCount) { + if (!name.equals("arg" + currentParameter)) { + debugInfoPresent = true; + } + result.append(','); + result.append(name); + currentParameter++; + } + } + + protected String getResult() { + return result.length() != 0 ? result.substring(1) : ""; + } +} \ No newline at end of file diff --git a/src/main/java/com/alibaba/fastjson/asm/MethodVisitor.java b/src/main/java/com/alibaba/fastjson/asm/MethodVisitor.java old mode 100644 new mode 100755 index 1c916ddd16..e32a216de6 --- a/src/main/java/com/alibaba/fastjson/asm/MethodVisitor.java +++ b/src/main/java/com/alibaba/fastjson/asm/MethodVisitor.java @@ -30,15 +30,6 @@ package com.alibaba.fastjson.asm; /** - * A visitor to visit a Java method. The methods of this interface must be called in the following order: [ - * visitAnnotationDefault ] ( visitAnnotation | visitParameterAnnotation | - * visitAttribute )* [ visitCode ( visitFrame | visitXInsn | - * visitLabel | visitTryCatchBlock | visitLocalVariable | visitLineNumber)* - * visitMaxs ] visitEnd. In addition, the visitXInsn and visitLabel - * methods must be called in the sequential order of the bytecode instructions of the visited code, - * visitTryCatchBlock must be called before the labels passed as arguments have been visited, and the - * visitLocalVariable and visitLineNumber methods must be called after the labels passed as - * arguments have been visited. * * @author Eric Bruneton */ @@ -66,17 +57,6 @@ public interface MethodVisitor { */ void visitInsn(int opcode); - /** - * Visits an instruction with a single int operand. - * - * @param opcode the opcode of the instruction to be visited. This opcode is either BIPUSH, SIPUSH or NEWARRAY. - * @param operand the operand of the instruction to be visited.
- * When opcode is BIPUSH, operand value should be between Byte.MIN_VALUE and Byte.MAX_VALUE.
- * When opcode is SIPUSH, operand value should be between Short.MIN_VALUE and Short.MAX_VALUE.
- * When opcode is NEWARRAY, operand value should be one of {@link Opcodes#T_BOOLEAN}, {@link Opcodes#T_CHAR}, - * {@link Opcodes#T_FLOAT}, {@link Opcodes#T_DOUBLE}, {@link Opcodes#T_BYTE}, {@link Opcodes#T_SHORT}, - * {@link Opcodes#T_INT} or {@link Opcodes#T_LONG}. - */ void visitIntInsn(int opcode, int operand); /** @@ -112,16 +92,6 @@ public interface MethodVisitor { */ void visitFieldInsn(int opcode, String owner, String name, String desc); - /** - * Visits a method instruction. A method instruction is an instruction that invokes a method. - * - * @param opcode the opcode of the type instruction to be visited. This opcode is either INVOKEVIRTUAL, - * INVOKESPECIAL, INVOKESTATIC, INVOKEINTERFACE or INVOKEDYNAMIC. - * @param owner the internal name of the method's owner class (see {@link Type#getInternalName() getInternalName}) - * or {@link com.alibaba.fastjson.asm.Opcodes#INVOKEDYNAMIC_OWNER}. - * @param name the method's name. - * @param desc the method's descriptor (see {@link Type Type}). - */ void visitMethodInsn(int opcode, String owner, String name, String desc); /** diff --git a/src/main/java/com/alibaba/fastjson/asm/MethodWriter.java b/src/main/java/com/alibaba/fastjson/asm/MethodWriter.java old mode 100644 new mode 100755 index 4ec9776ce0..1cd633d2e0 --- a/src/main/java/com/alibaba/fastjson/asm/MethodWriter.java +++ b/src/main/java/com/alibaba/fastjson/asm/MethodWriter.java @@ -30,62 +30,10 @@ package com.alibaba.fastjson.asm; /** - * A {@link MethodVisitor} that generates methods in bytecode form. Each visit method of this class appends the bytecode - * corresponding to the visited instruction to a byte vector, in the order these methods are called. - * * @author Eric Bruneton * @author Eugene Kuleshov */ -class MethodWriter implements MethodVisitor { - - /** - * Pseudo access flag used to denote constructors. - */ - static final int ACC_CONSTRUCTOR = 262144; - - /** - * Frame has exactly the same locals as the previous stack map frame and number of stack items is zero. - */ - static final int SAME_FRAME = 0; // to 63 (0-3f) - - /** - * Frame has exactly the same locals as the previous stack map frame and number of stack items is 1 - */ - static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64; // to 127 (40-7f) - - /** - * Reserved for future use - */ - static final int RESERVED = 128; - - /** - * Frame has exactly the same locals as the previous stack map frame and number of stack items is 1. Offset is - * bigger then 63; - */ - static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247; // f7 - - /** - * Frame where current locals are the same as the locals in the previous frame, except that the k last locals are - * absent. The value of k is given by the formula 251-frame_type. - */ - static final int CHOP_FRAME = 248; // to 250 (f8-fA) - - /** - * Frame has exactly the same locals as the previous stack map frame and number of stack items is zero. Offset is - * bigger then 63; - */ - static final int SAME_FRAME_EXTENDED = 251; // fb - - /** - * Frame where current locals are the same as the locals in the previous frame, except that k additional locals are - * defined. The value of k is given by the formula frame_type-251. - */ - static final int APPEND_FRAME = 252; // to 254 // fc-fe - - /** - * Full frame - */ - static final int FULL_FRAME = 255; // ff +public class MethodWriter implements MethodVisitor { /** * Next method writer (see {@link ClassWriter#firstMethod firstMethod}). @@ -112,12 +60,6 @@ class MethodWriter implements MethodVisitor { */ private final int desc; - /** - * If not zero, indicates that the code of this method must be copied from the ClassReader associated to this writer - * in cw.cr. More precisely, this field gives the number of bytes to copied from cw.cr.b. - */ - int classReaderLength; - /** * Number of exceptions that can be thrown by this method. */ @@ -144,11 +86,6 @@ class MethodWriter implements MethodVisitor { */ private int maxLocals; - /** - * Indicates if some jump instructions are too small and need to be resized. - */ - private boolean resize; - // ------------------------------------------------------------------------ /* @@ -162,20 +99,7 @@ class MethodWriter implements MethodVisitor { // Constructor // ------------------------------------------------------------------------ - /** - * Constructs a new {@link MethodWriter}. - * - * @param cw the class writer in which the method must be added. - * @param access the method's access flags (see {@link Opcodes}). - * @param name the method's name. - * @param desc the method's descriptor (see {@link Type}). - * @param signature the method's signature. May be null. - * @param exceptions the internal names of the method's exceptions. May be null. - * @param computeMaxs true if the maximum stack size and number of local variables must be automatically - * computed. - * @param computeFrames true if the stack map tables must be recomputed from scratch. - */ - MethodWriter(final ClassWriter cw, final int access, final String name, final String desc, final String signature, final String[] exceptions){ + public MethodWriter(final ClassWriter cw, final int access, final String name, final String desc, final String signature, final String[] exceptions){ if (cw.firstMethod == null) { cw.firstMethod = this; } else { @@ -191,7 +115,7 @@ class MethodWriter implements MethodVisitor { exceptionCount = exceptions.length; this.exceptions = new int[exceptionCount]; for (int i = 0; i < exceptionCount; ++i) { - this.exceptions[i] = cw.newClass(exceptions[i]); + this.exceptions[i] = cw.newClassItem(exceptions[i]).index; } } } @@ -271,7 +195,7 @@ public void visitMethodInsn(final int opcode, final String owner, final String n public void visitJumpInsn(final int opcode, final Label label) { // Label currentBlock = this.currentBlock; // adds the instruction to the bytecode of the method - if ((label.status & Label.RESOLVED) != 0 && label.position - code.length < Short.MIN_VALUE) { + if ((label.status & 2 /* Label.RESOLVED */ ) != 0 && label.position - code.length < Short.MIN_VALUE) { throw new UnsupportedOperationException(); } else { /* @@ -286,7 +210,7 @@ public void visitJumpInsn(final int opcode, final Label label) { public void visitLabel(final Label label) { // resolves previous forward references to label, if any - resize |= label.resolve(this, code.length, code.data); + label.resolve(this, code.length, code.data); } public void visitLdcInsn(final Object cst) { @@ -294,22 +218,22 @@ public void visitLdcInsn(final Object cst) { // Label currentBlock = this.currentBlock; // adds the instruction to the bytecode of the method int index = i.index; - if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) { + if (i.type == 5 /* ClassWriter.LONG */ || i.type == 6 /* ClassWriter.DOUBLE */) { code.put12(20 /* LDC2_W */, index); } else if (index >= 256) { code.put12(19 /* LDC_W */, index); } else { - code.put11(Opcodes.LDC, index); + code.put11(18 /*Opcodes.LDC*/, index); } } public void visitIincInsn(final int var, final int increment) { // adds the instruction to the bytecode of the method - if ((var > 255) || (increment > 127) || (increment < -128)) { - code.putByte(196 /* WIDE */).put12(Opcodes.IINC, var).putShort(increment); - } else { - code.putByte(Opcodes.IINC).put11(var, increment); - } +// if ((var > 255) || (increment > 127) || (increment < -128)) { +// code.putByte(196 /* WIDE */).put12(Opcodes.IINC, var).putShort(increment); +// } else { + code.putByte(132 /* Opcodes.IINC*/ ).put11(var, increment); +// } } public void visitMaxs(final int maxStack, final int maxLocals) { @@ -338,10 +262,6 @@ public void visitEnd() { * @return the size of the bytecode of this method. */ final int getSize() { - if (resize) { - // replaces the temporary jump opcodes introduced by Label.resolve. - throw new UnsupportedOperationException(); - } int size = 8; if (code.length > 0) { cw.newUTF8("Code"); @@ -360,7 +280,7 @@ final int getSize() { * @param out the byte vector into which the bytecode of this method must be copied. */ final void put(final ByteVector out) { - int mask = Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC)); + final int mask = 393216; //Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC)); out.putShort(access & ~mask).putShort(name).putShort(desc); int attributeCount = 0; if (code.length > 0) { diff --git a/src/main/java/com/alibaba/fastjson/asm/Opcodes.java b/src/main/java/com/alibaba/fastjson/asm/Opcodes.java old mode 100644 new mode 100755 index cc9e9b6ac5..3440da9804 --- a/src/main/java/com/alibaba/fastjson/asm/Opcodes.java +++ b/src/main/java/com/alibaba/fastjson/asm/Opcodes.java @@ -39,6 +39,7 @@ * @author Eugene Kuleshov */ public interface Opcodes { + int T_INT = 10; // versions @@ -53,59 +54,20 @@ public interface Opcodes { // access flags int ACC_PUBLIC = 0x0001; // class, field, method - int ACC_PRIVATE = 0x0002; // class, field, method int ACC_SUPER = 0x0020; // class - int ACC_SYNTHETIC = 0x1000; // class, field, method - - // ASM specific pseudo access flags - - int ACC_DEPRECATED = 0x20000; // class, field, method - - // types for NEWARRAY - - int T_BOOLEAN = 4; - int T_CHAR = 5; - int T_FLOAT = 6; - int T_DOUBLE = 7; - int T_BYTE = 8; - int T_SHORT = 9; - int T_INT = 10; - int T_LONG = 11; - - // Integer TOP = new Integer(0); - // Integer INTEGER = new Integer(1); - // Integer FLOAT = new Integer(2); - // Integer DOUBLE = new Integer(3); - // Integer LONG = new Integer(4); - // Integer NULL = new Integer(5); - // Integer UNINITIALIZED_THIS = new Integer(6); - - /** - * Represents a owner of an invokedynamic call. - */ - String INVOKEDYNAMIC_OWNER = "java/lang/dyn/Dynamic"; // opcodes // visit method (- = idem) - int NOP = 0; // visitInsn int ACONST_NULL = 1; // - - int ICONST_M1 = 2; // - int ICONST_0 = 3; // - int ICONST_1 = 4; // - - int ICONST_2 = 5; // - - int ICONST_3 = 6; // - - int ICONST_4 = 7; // - - int ICONST_5 = 8; // - int LCONST_0 = 9; // - int LCONST_1 = 10; // - int FCONST_0 = 11; // - - int FCONST_1 = 12; // - - int FCONST_2 = 13; // - int DCONST_0 = 14; // - - int DCONST_1 = 15; // - int BIPUSH = 16; // visitIntInsn -// int SIPUSH = 17; // - - int LDC = 18; // visitLdcInsn + // int SIPUSH = 17; // - +// int LDC = 18; // visitLdcInsn // int LDC_W = 19; // - // int LDC2_W = 20; // - int ILOAD = 21; // visitVarInsn @@ -113,160 +75,48 @@ public interface Opcodes { int FLOAD = 23; // - int DLOAD = 24; // - int ALOAD = 25; // - - // int ILOAD_0 = 26; // - - // int ILOAD_1 = 27; // - - // int ILOAD_2 = 28; // - - // int ILOAD_3 = 29; // - - // int LLOAD_0 = 30; // - - // int LLOAD_1 = 31; // - - // int LLOAD_2 = 32; // - - // int LLOAD_3 = 33; // - - // int FLOAD_0 = 34; // - - // int FLOAD_1 = 35; // - - // int FLOAD_2 = 36; // - - // int FLOAD_3 = 37; // - - // int DLOAD_0 = 38; // - - // int DLOAD_1 = 39; // - - // int DLOAD_2 = 40; // - - // int DLOAD_3 = 41; // - - // int ALOAD_0 = 42; // - - // int ALOAD_1 = 43; // - - // int ALOAD_2 = 44; // - - // int ALOAD_3 = 45; // - - int IALOAD = 46; // visitInsn - int LALOAD = 47; // - - int FALOAD = 48; // - - int DALOAD = 49; // - - int AALOAD = 50; // - - int BALOAD = 51; // - - int CALOAD = 52; // - - int SALOAD = 53; // - + int ISTORE = 54; // visitVarInsn int LSTORE = 55; // - int FSTORE = 56; // - int DSTORE = 57; // - int ASTORE = 58; // - - // int ISTORE_0 = 59; // - - // int ISTORE_1 = 60; // - - // int ISTORE_2 = 61; // - - // int ISTORE_3 = 62; // - - // int LSTORE_0 = 63; // - - // int LSTORE_1 = 64; // - - // int LSTORE_2 = 65; // - - // int LSTORE_3 = 66; // - - // int FSTORE_0 = 67; // - - // int FSTORE_1 = 68; // - - // int FSTORE_2 = 69; // - - // int FSTORE_3 = 70; // - - // int DSTORE_0 = 71; // - - // int DSTORE_1 = 72; // - - // int DSTORE_2 = 73; // - - // int DSTORE_3 = 74; // - - // int ASTORE_0 = 75; // - - // int ASTORE_1 = 76; // - - // int ASTORE_2 = 77; // - - // int ASTORE_3 = 78; // - - // int IASTORE = 79; // visitInsn - // int LASTORE = 80; // - - // int FASTORE = 81; // - - // int DASTORE = 82; // - - // int AASTORE = 83; // - - // int BASTORE = 84; // - - // int CASTORE = 85; // - - // int SASTORE = 86; // - + int IASTORE = 79; // visitInsn + int POP = 87; // - - int POP2 = 88; // - +// int POP2 = 88; // - int DUP = 89; // - -// int DUP_X1 = 90; // - -// int DUP_X2 = 91; // - -// int DUP2 = 92; // - -// int DUP2_X1 = 93; // - -// int DUP2_X2 = 94; // - -// int SWAP = 95; // - + int IADD = 96; // - - int LADD = 97; // - -// int FADD = 98; // - -// int DADD = 99; // - - int ISUB = 100; // - -// int LSUB = 101; // - -// int FSUB = 102; // - -// int DSUB = 103; // - -// int IMUL = 104; // - -// int LMUL = 105; // - -// int FMUL = 106; // - -// int DMUL = 107; // - -// int IDIV = 108; // - -// int LDIV = 109; // - -// int FDIV = 110; // - -// int DDIV = 111; // - -// int IREM = 112; // - -// int LREM = 113; // - -// int FREM = 114; // - -// int DREM = 115; // - -// int INEG = 116; // - -// int LNEG = 117; // - -// int FNEG = 118; // - -// int DNEG = 119; // - -// int ISHL = 120; // - -// int LSHL = 121; // - -// int ISHR = 122; // - -// int LSHR = 123; // - -// int IUSHR = 124; // - -// int LUSHR = 125; // - -// int IAND = 126; // - -// int LAND = 127; // - -// int IOR = 128; // - -// int LOR = 129; // - -// int IXOR = 130; // - -// int LXOR = 131; // - - int IINC = 132; // visitIincInsn -// int I2L = 133; // visitInsn -// int I2F = 134; // - -// int I2D = 135; // - -// int L2I = 136; // - -// int L2F = 137; // - -// int L2D = 138; // - -// int F2I = 139; // - -// int F2L = 140; // - -// int F2D = 141; // - -// int D2I = 142; // - -// int D2L = 143; // - -// int D2F = 144; // - - int I2B = 145; // - - int I2C = 146; // - - int I2S = 147; // - + +// int ISUB = 100; // - + + int IAND = 126; // - + // int LAND = 127; // - + int IOR = 128; // - + // int LOR = 129; // - + // int IXOR = 130; // - + // int LXOR = 131; // - + // int IINC = 132; // visitIincInsn + int LCMP = 148; // - int FCMPL = 149; // - - int FCMPG = 150; // - int DCMPL = 151; // - - int DCMPG = 152; // - int IFEQ = 153; // visitJumpInsn int IFNE = 154; // - - int IFLT = 155; // - - int IFGE = 156; // - - int IFGT = 157; // - int IFLE = 158; // - int IF_ICMPEQ = 159; // - int IF_ICMPNE = 160; // - int IF_ICMPLT = 161; // - int IF_ICMPGE = 162; // - int IF_ICMPGT = 163; // - - int IF_ICMPLE = 164; // - int IF_ACMPEQ = 165; // - int IF_ACMPNE = 166; // - int GOTO = 167; // - - int JSR = 168; // - int RET = 169; // visitVarInsn -// int TABLESWITCH = 170; // visiTableSwitchInsn -// int LOOKUPSWITCH = 171; // visitLookupSwitch - int IRETURN = 172; // visitInsn -// int LRETURN = 173; // - -// int FRETURN = 174; // - -// int DRETURN = 175; // - int ARETURN = 176; // - int RETURN = 177; // - int GETSTATIC = 178; // visitFieldInsn - int PUTSTATIC = 179; // - int GETFIELD = 180; // - int PUTFIELD = 181; // - int INVOKEVIRTUAL = 182; // visitMethodInsn @@ -275,16 +125,13 @@ public interface Opcodes { int INVOKEINTERFACE = 185; // - // int INVOKEDYNAMIC = 186; // - int NEW = 187; // visitTypeInsn -// int NEWARRAY = 188; // visitIntInsn -// int ANEWARRAY = 189; // visitTypeInsn -// int ARRAYLENGTH = 190; // visitInsn -// int ATHROW = 191; // - + int NEWARRAY = 188; // visitIntInsn + // int ANEWARRAY = 189; // visitTypeInsn + // int ARRAYLENGTH = 190; // visitInsn + // int ATHROW = 191; // - int CHECKCAST = 192; // visitTypeInsn - int INSTANCEOF = 193; // - -// int MONITORENTER = 194; // visitInsn -// int MONITOREXIT = 195; // - - // int WIDE = 196; // NOT VISITED -// int MULTIANEWARRAY = 197; // visitMultiANewArrayInsn + int INSTANCEOF = 193; + int IFNULL = 198; // visitJumpInsn int IFNONNULL = 199; // - // int GOTO_W = 200; // - diff --git a/src/main/java/com/alibaba/fastjson/asm/Type.java b/src/main/java/com/alibaba/fastjson/asm/Type.java old mode 100644 new mode 100755 index cfc0751724..4a5da99996 --- a/src/main/java/com/alibaba/fastjson/asm/Type.java +++ b/src/main/java/com/alibaba/fastjson/asm/Type.java @@ -36,106 +36,50 @@ * @author Chris Nokleberg */ public class Type { - - /** - * The sort of the void type. See {@link #getSort getSort}. - */ - public static final int VOID = 0; - - /** - * The sort of the boolean type. See {@link #getSort getSort}. - */ - public static final int BOOLEAN = 1; - - /** - * The sort of the char type. See {@link #getSort getSort}. - */ - public static final int CHAR = 2; - - /** - * The sort of the byte type. See {@link #getSort getSort}. - */ - public static final int BYTE = 3; - - /** - * The sort of the short type. See {@link #getSort getSort}. - */ - public static final int SHORT = 4; - - /** - * The sort of the int type. See {@link #getSort getSort}. - */ - public static final int INT = 5; - - /** - * The sort of the float type. See {@link #getSort getSort}. - */ - public static final int FLOAT = 6; - - /** - * The sort of the long type. See {@link #getSort getSort}. - */ - public static final int LONG = 7; - - /** - * The sort of the double type. See {@link #getSort getSort}. - */ - public static final int DOUBLE = 8; - - /** - * The sort of array reference types. See {@link #getSort getSort}. - */ - public static final int ARRAY = 9; - - /** - * The sort of object reference type. See {@link #getSort getSort}. - */ - public static final int OBJECT = 10; - /** * The void type. */ - public static final Type VOID_TYPE = new Type(VOID, null, ('V' << 24) | (5 << 16) | (0 << 8) | 0, 1); + public static final Type VOID_TYPE = new Type(0, null, ('V' << 24) | (5 << 16) | (0 << 8) | 0, 1); /** * The boolean type. */ - public static final Type BOOLEAN_TYPE = new Type(BOOLEAN, null, ('Z' << 24) | (0 << 16) | (5 << 8) | 1, 1); + public static final Type BOOLEAN_TYPE = new Type(1, null, ('Z' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The char type. */ - public static final Type CHAR_TYPE = new Type(CHAR, null, ('C' << 24) | (0 << 16) | (6 << 8) | 1, 1); + public static final Type CHAR_TYPE = new Type(2, null, ('C' << 24) | (0 << 16) | (6 << 8) | 1, 1); /** * The byte type. */ - public static final Type BYTE_TYPE = new Type(BYTE, null, ('B' << 24) | (0 << 16) | (5 << 8) | 1, 1); + public static final Type BYTE_TYPE = new Type(3, null, ('B' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The short type. */ - public static final Type SHORT_TYPE = new Type(SHORT, null, ('S' << 24) | (0 << 16) | (7 << 8) | 1, 1); + public static final Type SHORT_TYPE = new Type(4, null, ('S' << 24) | (0 << 16) | (7 << 8) | 1, 1); /** * The int type. */ - public static final Type INT_TYPE = new Type(INT, null, ('I' << 24) | (0 << 16) | (0 << 8) | 1, 1); + public static final Type INT_TYPE = new Type(5, null, ('I' << 24) | (0 << 16) | (0 << 8) | 1, 1); /** * The float type. */ - public static final Type FLOAT_TYPE = new Type(FLOAT, null, ('F' << 24) | (2 << 16) | (2 << 8) | 1, 1); + public static final Type FLOAT_TYPE = new Type(6, null, ('F' << 24) | (2 << 16) | (2 << 8) | 1, 1); /** * The long type. */ - public static final Type LONG_TYPE = new Type(LONG, null, ('J' << 24) | (1 << 16) | (1 << 8) | 2, 1); + public static final Type LONG_TYPE = new Type(7, null, ('J' << 24) | (1 << 16) | (1 << 8) | 2, 1); /** * The double type. */ - public static final Type DOUBLE_TYPE = new Type(DOUBLE, null, ('D' << 24) | (3 << 16) | (3 << 8) | 2, 1); + public static final Type DOUBLE_TYPE = new Type(8, null, ('D' << 24) | (3 << 16) | (3 << 8) | 2, 1); // ------------------------------------------------------------------------ // Fields @@ -144,7 +88,7 @@ public class Type { /** * The sort of this Java type. */ - private final int sort; + protected final int sort; /** * A buffer containing the internal name of this Java type. This field is only used for reference types. @@ -167,14 +111,6 @@ public class Type { // Constructors // ------------------------------------------------------------------------ - /** - * Constructs a reference type. - * - * @param sort the sort of the reference type to be constructed. - * @param buf a buffer containing the descriptor of the previous type. - * @param off the offset of this descriptor in the previous buffer. - * @param len the length of this descriptor. - */ private Type(final int sort, final char[] buf, final int off, final int len){ this.sort = sort; this.buf = buf; @@ -192,14 +128,6 @@ public static Type getType(final String typeDescriptor) { return getType(typeDescriptor.toCharArray(), 0); } - /** - * Computes the size of the arguments and of the return value of a method. - * - * @param desc the descriptor of a method. - * @return the size of the arguments of the method (plus one for the implicit this argument), argSize, and the size - * of its return value, retSize, packed into a single int i = (argSize << 2) | retSize (argSize is - * therefore equal to i >> 2, and retSize to i & 0x03). - */ public static int getArgumentsAndReturnSizes(final String desc) { int n = 1; int c = 1; @@ -212,13 +140,13 @@ public static int getArgumentsAndReturnSizes(final String desc) { while (desc.charAt(c++) != ';') { } n += 1; - } else if (car == '[') { - while ((car = desc.charAt(c)) == '[') { - ++c; - } - if (car == 'D' || car == 'J') { - n -= 1; - } +// } else if (car == '[') { +// while ((car = desc.charAt(c)) == '[') { +// ++c; +// } +// if (car == 'D' || car == 'J') { +// n -= 1; +// } } else if (car == 'D' || car == 'J') { n += 2; } else { @@ -266,39 +194,17 @@ private static Type getType(final char[] buf, final int off) { ++len; } } - return new Type(ARRAY, buf, off, len + 1); + return new Type(9 /*ARRAY*/, buf, off, len + 1); // case 'L': default: len = 1; while (buf[off + len] != ';') { ++len; } - return new Type(OBJECT, buf, off + 1, len - 1); + return new Type(10/*OBJECT*/, buf, off + 1, len - 1); } } - // ------------------------------------------------------------------------ - // Accessors - // ------------------------------------------------------------------------ - - /** - * Returns the sort of this Java type. - * - * @return {@link #VOID VOID}, {@link #BOOLEAN BOOLEAN}, {@link #CHAR CHAR}, {@link #BYTE BYTE}, {@link #SHORT - * SHORT}, {@link #INT INT}, {@link #FLOAT FLOAT}, {@link #LONG LONG}, {@link #DOUBLE DOUBLE}, {@link #ARRAY ARRAY} - * or {@link #OBJECT OBJECT}. - */ - public int getSort() { - return sort; - } - - /** - * Returns the internal name of the class corresponding to this object or array type. The internal name of a class - * is its fully qualified name (as returned by Class.getName(), where '.' are replaced by '/'. This method should - * only be used for an object or array type. - * - * @return the internal name of the class corresponding to this object type. - */ public String getInternalName() { return new String(buf, off, len); } @@ -309,23 +215,79 @@ public String getInternalName() { /** * Returns the descriptor corresponding to this Java type. - * + * * @return the descriptor corresponding to this Java type. */ - public String getDescriptor() { - StringBuffer buf = new StringBuffer(); + String getDescriptor() { + return new String(this.buf, off, len); + } - if (this.buf == null) { - // descriptor is in byte 3 of 'off' for primitive types (buf == null) - buf.append((char) ((off & 0xFF000000) >>> 24)); - } else if (sort == ARRAY) { - buf.append(this.buf, off, len); - } else { // sort == OBJECT - buf.append('L'); - buf.append(this.buf, off, len); - buf.append(';'); + private int getDimensions() { + int i = 1; + while (buf[off + i] == '[') { + ++i; } + return i; + } - return buf.toString(); + static Type[] getArgumentTypes(final String methodDescriptor) { + char[] buf = methodDescriptor.toCharArray(); + int off = 1; + int size = 0; + for (;;) { + char car = buf[off++]; + if (car == ')') { + break; + } else if (car == 'L') { + while (buf[off++] != ';') { + } + ++size; + } else if (car != '[') { + ++size; + } + } + + Type[] args = new Type[size]; + off = 1; + size = 0; + while (buf[off] != ')') { + args[size] = getType(buf, off); + off += args[size].len + (args[size].sort == 10 /*OBJECT*/ ? 2 : 0); + size += 1; + } + return args; + } + + protected String getClassName() { + switch (sort) { + case 0: //VOID: + return "void"; + case 1: //BOOLEAN: + return "boolean"; + case 2: //CHAR: + return "char"; + case 3: //BYTE: + return "byte"; + case 4: //SHORT: + return "short"; + case 5: //INT: + return "int"; + case 6: //FLOAT: + return "float"; + case 7: //LONG: + return "long"; + case 8: //DOUBLE: + return "double"; + case 9: //ARRAY: + Type elementType = getType(buf, off + getDimensions()); + StringBuffer b = new StringBuffer(elementType.getClassName()); + for (int i = getDimensions(); i > 0; --i) { + b.append("[]"); + } + return b.toString(); + // case OBJECT: + default: + return new String(buf, off, len).replace('/', '.'); + } } } diff --git a/src/main/java/com/alibaba/fastjson/asm/TypeCollector.java b/src/main/java/com/alibaba/fastjson/asm/TypeCollector.java new file mode 100644 index 0000000000..32f82b94d4 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/asm/TypeCollector.java @@ -0,0 +1,89 @@ +package com.alibaba.fastjson.asm; + +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; + +public class TypeCollector { + private static final Map primitives = new HashMap() { + { + put("int","I"); + put("boolean","Z"); + put("byte", "B"); + put("char","C"); + put("short","S"); + put("float","F"); + put("long","J"); + put("double","D"); + } + }; + + private final String methodName; + + private final Class[] parameterTypes; + + protected MethodCollector collector; + + public TypeCollector(String methodName, Class[] parameterTypes) { + this.methodName = methodName; + this.parameterTypes = parameterTypes; + this.collector = null; + } + + protected MethodCollector visitMethod(int access, String name, String desc) { + if (collector != null) { + return null; + } + + if (!name.equals(methodName)) { + return null; + } + + Type[] argTypes = Type.getArgumentTypes(desc); + int longOrDoubleQuantity = 0; + for (Type t : argTypes) { + String className = t.getClassName(); + if (className.equals("long") || className.equals("double")) { + longOrDoubleQuantity++; + } + } + + if (argTypes.length != this.parameterTypes.length) { + return null; + } + for (int i = 0; i < argTypes.length; i++) { + if (!correctTypeName(argTypes[i], this.parameterTypes[i].getName())) { + return null; + } + } + + return collector = new MethodCollector( + Modifier.isStatic(access) ? 0 : 1, + argTypes.length + longOrDoubleQuantity); + } + + private boolean correctTypeName(Type type, String paramTypeName) { + String s = type.getClassName(); + // array notation needs cleanup. + String braces = ""; + while (s.endsWith("[]")) { + braces = braces + "["; + s = s.substring(0, s.length() - 2); + } + if (!braces.equals("")) { + if (primitives.containsKey(s)) { + s = braces + primitives.get(s); + } else { + s = braces + "L" + s + ";"; + } + } + return s.equals(paramTypeName); + } + + public String[] getParameterNamesForMethod() { + if (collector == null || !collector.debugInfoPresent) { + return new String[0]; + } + return collector.getResult().split(","); + } +} \ No newline at end of file diff --git a/src/main/java/com/alibaba/fastjson/asm/package.html b/src/main/java/com/alibaba/fastjson/asm/package.html deleted file mode 100644 index fd6caf73f6..0000000000 --- a/src/main/java/com/alibaba/fastjson/asm/package.html +++ /dev/null @@ -1,83 +0,0 @@ - - - - Provides a small and fast bytecode manipulation framework. - -

- The ASM framework is - organized around the {@link org.objectweb.asm.ClassVisitor - ClassVisitor}, {@link org.objectweb.asm.FieldVisitor FieldVisitor} and - {@link org.objectweb.asm.MethodVisitor MethodVisitor} interfaces, - which allow one to visit the fields and methods of a class, including - the bytecode instructions of each method. -

In addition to these main interfaces, ASM provides a {@link - org.objectweb.asm.ClassReader ClassReader} class, that can parse an - existing class and make a given visitor visit it. ASM also provides a - {@link org.objectweb.asm.ClassWriter ClassWriter} class, which is a - visitor that generates Java class files. -

- In order to generate a class from scratch, only the {@link - org.objectweb.asm.ClassWriter ClassWriter} class is necessary. Indeed, - in order to generate a class, one must just call its visitXXX - methods with the appropriate arguments to generate the desired fields - and methods. See the "helloworld" example in the ASM distribution for - more details about class generation. -

In order to modify existing classes, one must use a {@link - org.objectweb.asm.ClassReader ClassReader} class to analyze the - original class, a class modifier, and a {@link - org.objectweb.asm.ClassWriter ClassWriter} to construct the modified - class. The class modifier is just a {@link - org.objectweb.asm.ClassVisitor ClassVisitor} that delegates most of - the work to another {@link org.objectweb.asm.ClassVisitor - ClassVisitor}, but that sometimes changes some parameter values, or - call additional methods, in order to implement the desired - modification process. In order to make it easier to implement such - class modifiers, ASM provides the {@link - org.objectweb.asm.ClassAdapter ClassAdapter} and {@link - org.objectweb.asm.MethodAdapter MethodAdapter} classes, which - implement the {@link org.objectweb.asm.ClassVisitor ClassVisitor} and - {@link org.objectweb.asm.MethodVisitor MethodVisitor} interfaces by - delegating all work to other visitors. See the "adapt" example in the - ASM distribution for more details about class modification. -

- The size of the core ASM library, - asm.jar - , is only 42KB, which is much smaller than the size of the BCEL library (504KB), and - than the size of the SERP - library (150KB). ASM is also much faster than these tools. Indeed the - overhead of a load time class transformation process is of the order - of 60% with ASM, 700% or more with BCEL, and 1100% or more with SERP - (see the - test/perf - directory in the ASM distribution)! @since ASM 1.3 - - diff --git a/src/main/java/com/alibaba/fastjson/parser/AbstractJSONParser.java b/src/main/java/com/alibaba/fastjson/parser/AbstractJSONParser.java deleted file mode 100644 index e6e084653a..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/AbstractJSONParser.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.alibaba.fastjson.parser; - -import static com.alibaba.fastjson.parser.JSONToken.EOF; -import static com.alibaba.fastjson.parser.JSONToken.FALSE; -import static com.alibaba.fastjson.parser.JSONToken.LBRACE; -import static com.alibaba.fastjson.parser.JSONToken.LBRACKET; -import static com.alibaba.fastjson.parser.JSONToken.LITERAL_FLOAT; -import static com.alibaba.fastjson.parser.JSONToken.LITERAL_INT; -import static com.alibaba.fastjson.parser.JSONToken.LITERAL_STRING; -import static com.alibaba.fastjson.parser.JSONToken.NEW; -import static com.alibaba.fastjson.parser.JSONToken.NULL; -import static com.alibaba.fastjson.parser.JSONToken.RBRACKET; -import static com.alibaba.fastjson.parser.JSONToken.TRUE; - -import java.util.Collection; -import java.util.Date; -import java.util.Map; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.JSONObject; - -public abstract class AbstractJSONParser { - - @SuppressWarnings("rawtypes") - public abstract void parseObject(final Map object); - - public JSONObject parseObject() { - JSONObject object = new JSONObject(); - parseObject(object); - return object; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public final void parseArray(final Collection array) { - final JSONLexer lexer = getLexer(); - - if (lexer.token() != JSONToken.LBRACKET) { - throw new JSONException("syntax error, expect [, actual " - + JSONToken.name(lexer.token())); - } - - lexer.nextToken(JSONToken.LITERAL_STRING); - - for (;;) { - if (isEnabled(Feature.AllowArbitraryCommas)) { - while (lexer.token() == JSONToken.COMMA) { - lexer.nextToken(); - continue; - } - } - - Object value; - switch (lexer.token()) { - case LITERAL_INT: - value = lexer.integerValue(); - lexer.nextToken(JSONToken.COMMA); - break; - case LITERAL_FLOAT: - if (lexer.isEnabled(Feature.UseBigDecimal)) { - value = lexer.decimalValue(); - } else { - value = lexer.doubleValue(); - } - lexer.nextToken(JSONToken.COMMA); - break; - case LITERAL_STRING: - String stringLiteral = lexer.stringVal(); - lexer.nextToken(JSONToken.COMMA); - - if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) { - JSONScanner iso8601Lexer = new JSONScanner(stringLiteral); - if (iso8601Lexer.scanISO8601DateIfMatch()) { - value = iso8601Lexer.getCalendar().getTime(); - } else { - value = stringLiteral; - } - } else { - value = stringLiteral; - } - - break; - case TRUE: - value = Boolean.TRUE; - lexer.nextToken(JSONToken.COMMA); - break; - case FALSE: - value = Boolean.FALSE; - lexer.nextToken(JSONToken.COMMA); - break; - case LBRACE: - JSONObject object = new JSONObject(); - parseObject(object); - value = object; - break; - case LBRACKET: - Collection items = new JSONArray(); - parseArray(items); - value = items; - break; - case NULL: - value = null; - lexer.nextToken(JSONToken.LITERAL_STRING); - break; - case RBRACKET: - lexer.nextToken(JSONToken.COMMA); - return; - default: - value = parse(); - break; - } - - array.add(value); - - if (lexer.token() == JSONToken.COMMA) { - lexer.nextToken(JSONToken.LITERAL_STRING); - continue; - } - } - } - - public Object parse() { - final JSONLexer lexer = getLexer(); - switch (lexer.token()) { - case LBRACKET: - JSONArray array = new JSONArray(); - parseArray(array); - return array; - case LBRACE: - JSONObject object = new JSONObject(); - parseObject(object); - return object; - case LITERAL_INT: - Number intValue = lexer.integerValue(); - lexer.nextToken(); - return intValue; - case LITERAL_FLOAT: - - Object value; - if (isEnabled(Feature.UseBigDecimal)) { - value = lexer.decimalValue(); - } else { - value = lexer.doubleValue(); - } - lexer.nextToken(); - return value; - case LITERAL_STRING: - String stringLiteral = lexer.stringVal(); - lexer.nextToken(JSONToken.COMMA); - - if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) { - JSONScanner iso8601Lexer = new JSONScanner(stringLiteral); - if (iso8601Lexer.scanISO8601DateIfMatch()) { - return iso8601Lexer.getCalendar().getTime(); - } - } - - return stringLiteral; - case NULL: - lexer.nextToken(); - return null; - case TRUE: - lexer.nextToken(); - return Boolean.TRUE; - case FALSE: - lexer.nextToken(); - return Boolean.FALSE; - case NEW: - lexer.nextToken(JSONToken.IDENTIFIER); - - if (lexer.token() != JSONToken.IDENTIFIER) { - throw new JSONException("syntax error"); - } - lexer.nextToken(JSONToken.LPAREN); - - accept(JSONToken.LPAREN); - long time = ((Number) lexer.integerValue()).longValue(); - accept(JSONToken.LITERAL_INT); - - accept(JSONToken.RPAREN); - - return new Date(time); - case EOF: - if (lexer.isBlankInput()) { - return null; - } - default: - throw new JSONException("TODO " + JSONToken.name(lexer.token()) - + " " + lexer.stringVal()); - } - } - - public void config(Feature feature, boolean state) { - getLexer().config(feature, state); - } - - public boolean isEnabled(Feature feature) { - return getLexer().isEnabled(feature); - } - - public abstract JSONLexer getLexer(); - - public final void accept(final int token) { - final JSONLexer lexer = getLexer(); - if (lexer.token() == token) { - lexer.nextToken(); - } else { - throw new JSONException("syntax error, expect " - + JSONToken.name(token) + ", actual " - + JSONToken.name(lexer.token())); - } - } - - public void close() { - final JSONLexer lexer = getLexer(); - - if (isEnabled(Feature.AutoCloseSource)) { - if (!lexer.isEOF()) { - throw new JSONException("not close json text, token : " - + JSONToken.name(lexer.token())); - } - } - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/CharTypes.java b/src/main/java/com/alibaba/fastjson/parser/CharTypes.java deleted file mode 100644 index c3ab3df2b2..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/CharTypes.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.parser; - -/** - * @author wenshao - */ -public final class CharTypes { - - public final static boolean[] firstIdentifierFlags = new boolean[256]; - static { - for (char c = 0; c < firstIdentifierFlags.length; ++c) { - if (c >= 'A' && c <= 'Z') { - firstIdentifierFlags[c] = true; - } else if (c >= 'a' && c <= 'z') { - firstIdentifierFlags[c] = true; - } else if (c == '_') { - firstIdentifierFlags[c] = true; - } - } - } - - public final static boolean[] identifierFlags = new boolean[256]; - - static { - for (char c = 0; c < identifierFlags.length; ++c) { - if (c >= 'A' && c <= 'Z') { - identifierFlags[c] = true; - } else if (c >= 'a' && c <= 'z') { - identifierFlags[c] = true; - } else if (c == '_') { - identifierFlags[c] = true; - } else if (c >= '0' && c <= '9') { - identifierFlags[c] = true; - } - } - } - - public final static boolean[] specicalFlags_doubleQuotes = new boolean[((int) '\\' + 1)]; - public final static boolean[] specicalFlags_singleQuotes = new boolean[((int) '\\' + 1)]; - - public static boolean isSpecial_doubleQuotes(char ch) { - return ch < specicalFlags_doubleQuotes.length && specicalFlags_doubleQuotes[ch]; - } - - public final static char[] replaceChars = new char[((int) '\\' + 1)]; - static { - specicalFlags_doubleQuotes['\b'] = true; - specicalFlags_doubleQuotes['\n'] = true; - specicalFlags_doubleQuotes['\f'] = true; - specicalFlags_doubleQuotes['\r'] = true; - specicalFlags_doubleQuotes['\"'] = true; - specicalFlags_doubleQuotes['\\'] = true; - - specicalFlags_singleQuotes['\b'] = true; - specicalFlags_singleQuotes['\n'] = true; - specicalFlags_singleQuotes['\f'] = true; - specicalFlags_singleQuotes['\r'] = true; - specicalFlags_singleQuotes['\''] = true; - specicalFlags_singleQuotes['\\'] = true; - - replaceChars['\b'] = 'b'; - replaceChars['\n'] = 'n'; - replaceChars['\f'] = 'f'; - replaceChars['\r'] = 'r'; - replaceChars['\"'] = '"'; - replaceChars['\''] = '\''; - replaceChars['\\'] = '\\'; - replaceChars['\t'] = 't'; - } - -} diff --git a/src/main/java/com/alibaba/fastjson/parser/DefaultExtJSONParser.java b/src/main/java/com/alibaba/fastjson/parser/DefaultExtJSONParser.java index 35dc417784..cbfcac7508 100644 --- a/src/main/java/com/alibaba/fastjson/parser/DefaultExtJSONParser.java +++ b/src/main/java/com/alibaba/fastjson/parser/DefaultExtJSONParser.java @@ -1,372 +1,42 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.parser; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.deserializer.DefaultObjectDeserializer; -import com.alibaba.fastjson.parser.deserializer.IntegerDeserializer; -import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; -import com.alibaba.fastjson.parser.deserializer.StringDeserializer; -import com.alibaba.fastjson.util.TypeUtils; - -/** - * @author wenshao - */ -@SuppressWarnings("rawtypes") -public class DefaultExtJSONParser extends DefaultJSONParser { - - private DefaultObjectDeserializer derializer = new DefaultObjectDeserializer(); - - private final static Set> primitiveClasses = new HashSet>(); - static { - primitiveClasses.add(boolean.class); - primitiveClasses.add(byte.class); - primitiveClasses.add(short.class); - primitiveClasses.add(int.class); - primitiveClasses.add(long.class); - primitiveClasses.add(float.class); - primitiveClasses.add(double.class); - - primitiveClasses.add(Boolean.class); - primitiveClasses.add(Byte.class); - primitiveClasses.add(Short.class); - primitiveClasses.add(Integer.class); - primitiveClasses.add(Long.class); - primitiveClasses.add(Float.class); - primitiveClasses.add(Double.class); - - primitiveClasses.add(BigInteger.class); - primitiveClasses.add(BigDecimal.class); - primitiveClasses.add(String.class); - } - - public DefaultExtJSONParser(String input){ - this(input, ParserConfig.getGlobalInstance()); - } - - public DefaultExtJSONParser(String input, ParserConfig mapping){ - super(input, mapping); - } - - public DefaultExtJSONParser(String input, ParserConfig mapping, int features){ - super(input, mapping, features); - } - - public DefaultExtJSONParser(char[] input, int length, ParserConfig mapping, int features){ - super(input, length, mapping, features); - } - - public ParserConfig getConfig() { - return config; - } - - public void setConfig(ParserConfig config) { - this.config = config; - } - - // compatible - @SuppressWarnings("unchecked") - public T parseObject(Class clazz) { - return (T) parseObject((Type) clazz); - } - - @SuppressWarnings("unchecked") - public T parseObject(Type type) { - if (lexer.token() == JSONToken.NULL) { - lexer.nextToken(); - return null; - } - - ObjectDeserializer derializer = config.getDeserializer(type); - - try { - return (T) derializer.deserialze(this, type); - } catch (JSONException e) { - throw e; - } catch (Throwable e) { - throw new JSONException(e.getMessage(), e); - } - } - - public List parseArray(Class clazz) { - List array = new ArrayList(); - parseArray(clazz, array); - return array; - } - - public void parseArray(Class clazz, Collection array) { - parseArray((Type) clazz, array); - } - - @SuppressWarnings({ "unchecked" }) - public void parseArray(Type type, Collection array) { - if (lexer.token() != JSONToken.LBRACKET) { - throw new JSONException("exepct '[', but " + JSONToken.name(lexer.token())); - } - - ObjectDeserializer deserializer = null; - if (int.class == type) { - deserializer = IntegerDeserializer.instance; - lexer.nextToken(JSONToken.LITERAL_INT); - } else if (String.class == type) { - deserializer = StringDeserializer.instance; - lexer.nextToken(JSONToken.LITERAL_STRING); - } else { - deserializer = config.getDeserializer(type); - lexer.nextToken(deserializer.getFastMatchToken()); - } - - for (;;) { - if (isEnabled(Feature.AllowArbitraryCommas)) { - while (lexer.token() == JSONToken.COMMA) { - lexer.nextToken(); - continue; - } - } - - if (lexer.token() == JSONToken.RBRACKET) { - break; - } - - if (int.class == type) { - Object val = IntegerDeserializer.deserialze(this); - array.add(val); - } else if (String.class == type) { - String value; - if (lexer.token() == JSONToken.LITERAL_STRING) { - value = lexer.stringVal(); - lexer.nextToken(JSONToken.COMMA); - } else { - Object obj = this.parse(); - if (obj == null) { - value = null; - } else { - value = obj.toString(); - } - } - - array.add(value); - } else { - Object val = deserializer.deserialze(this, type); - array.add(val); - } - - if (lexer.token() == JSONToken.COMMA) { - lexer.nextToken(deserializer.getFastMatchToken()); - continue; - } - } - - lexer.nextToken(JSONToken.COMMA); - } - - public Object[] parseArray(Type[] types) { - - if (lexer.token() != JSONToken.LBRACKET) { - throw new JSONException("syntax error"); - } - - Object[] list = new Object[types.length]; - if (types.length == 0) { - lexer.nextToken(JSONToken.RBRACKET); - - if (lexer.token() != JSONToken.RBRACKET) { - throw new JSONException("syntax error"); - } - - lexer.nextToken(JSONToken.COMMA); - return new Object[0]; - } - - lexer.nextToken(JSONToken.LITERAL_INT); - - for (int i = 0; i < types.length; ++i) { - Object value; - - if (lexer.token() == JSONToken.NULL) { - value = null; - lexer.nextToken(JSONToken.COMMA); - } else { - Type type = types[i]; - if (type == int.class || type == Integer.class) { - if (lexer.token() == JSONToken.LITERAL_INT) { - value = Integer.valueOf(lexer.intValue()); - lexer.nextToken(JSONToken.COMMA); - } else { - value = this.parse(); - value = TypeUtils.cast(value, type, config); - } - } else if (type == String.class) { - if (lexer.token() == JSONToken.LITERAL_STRING) { - value = lexer.stringVal(); - lexer.nextToken(JSONToken.COMMA); - } else { - value = this.parse(); - value = TypeUtils.cast(value, type, config); - } - } else { - boolean isArray = false; - Class componentType = null; - if (i == types.length - 1) { - if (type instanceof Class) { - Class clazz = (Class) type; - isArray = clazz.isArray(); - componentType = clazz.getComponentType(); - } - } - - // support varArgs - if (isArray && lexer.token() != JSONToken.LBRACKET) { - List varList = new ArrayList(); - - ObjectDeserializer derializer = config.getDeserializer(componentType); - int fastMatch = derializer.getFastMatchToken(); - - if (lexer.token() != JSONToken.RBRACKET) { - for (;;) { - Object item = derializer.deserialze(this, type); - varList.add(item); - - if (lexer.token() == JSONToken.COMMA) { - lexer.nextToken(fastMatch); - } else if (lexer.token() == JSONToken.RBRACKET) { - break; - } else { - throw new JSONException("syntax error :" + JSONToken.name(lexer.token())); - } - } - } - - value = TypeUtils.cast(varList, type, config); - } else { - ObjectDeserializer derializer = config.getDeserializer(type); - value = derializer.deserialze(this, type); - } - } - } - list[i] = value; - - if (lexer.token() == JSONToken.RBRACKET) { - break; - } - - if (lexer.token() != JSONToken.COMMA) { - throw new JSONException("syntax error :" + JSONToken.name(lexer.token())); - } - - if (i == types.length - 1) { - lexer.nextToken(JSONToken.RBRACKET); - } else { - lexer.nextToken(JSONToken.LITERAL_INT); - } - } - - if (lexer.token() != JSONToken.RBRACKET) { - throw new JSONException("syntax error"); - } - - lexer.nextToken(JSONToken.COMMA); - - return list; - } - - public void parseObject(Object object) { - derializer.parseObject(this, object); - } - - public Object parseArrayWithType(Type collectionType) { - if (lexer.token() == JSONToken.NULL) { - lexer.nextToken(); - return null; - } - - Type[] actualTypes = ((ParameterizedType) collectionType).getActualTypeArguments(); - - if (actualTypes.length != 1) { - throw new JSONException("not support type " + collectionType); - } - - Type actualTypeArgument = actualTypes[0]; - - if (actualTypeArgument instanceof Class) { - List array = new ArrayList(); - this.parseArray((Class) actualTypeArgument, array); - return array; - } - - if (actualTypeArgument instanceof WildcardType) { - WildcardType wildcardType = (WildcardType) actualTypeArgument; - - // assert wildcardType.getUpperBounds().length == 1; - Type upperBoundType = wildcardType.getUpperBounds()[0]; - - // assert upperBoundType instanceof Class; - if (Object.class.equals(upperBoundType)) { - if (wildcardType.getLowerBounds().length == 0) { - // Collection - return parse(); - } else { - throw new JSONException("not support type : " + collectionType); - } - } - - List array = new ArrayList(); - this.parseArray((Class) upperBoundType, array); - return array; - - // throw new JSONException("not support type : " + - // collectionType);return parse(); - } - - if (actualTypeArgument instanceof TypeVariable) { - TypeVariable typeVariable = (TypeVariable) actualTypeArgument; - Type[] bounds = typeVariable.getBounds(); - - if (bounds.length != 1) { - throw new JSONException("not support : " + typeVariable); - } - - Type boundType = bounds[0]; - if (boundType instanceof Class) { - List array = new ArrayList(); - this.parseArray((Class) boundType, array); - return array; - } - } - - if (actualTypeArgument instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) actualTypeArgument; - - List array = new ArrayList(); - this.parseArray(parameterizedType, array); - return array; - } - - throw new JSONException("TODO : " + collectionType); - } -} +/* + * Copyright 1999-2017 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.parser; + + +/** + * @author wenshao[szujobs@hotmail.com] + */ +@Deprecated +public class DefaultExtJSONParser extends DefaultJSONParser { + + public DefaultExtJSONParser(String input){ + this(input, ParserConfig.getGlobalInstance()); + } + + public DefaultExtJSONParser(String input, ParserConfig mapping){ + super(input, mapping); + } + + public DefaultExtJSONParser(String input, ParserConfig mapping, int features){ + super(input, mapping, features); + } + + public DefaultExtJSONParser(char[] input, int length, ParserConfig mapping, int features){ + super(input, length, mapping, features); + } + + +} diff --git a/src/main/java/com/alibaba/fastjson/parser/DefaultJSONParser.java b/src/main/java/com/alibaba/fastjson/parser/DefaultJSONParser.java old mode 100644 new mode 100755 index cfd587fa3b..fd7aaee252 --- a/src/main/java/com/alibaba/fastjson/parser/DefaultJSONParser.java +++ b/src/main/java/com/alibaba/fastjson/parser/DefaultJSONParser.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,24 +15,111 @@ */ package com.alibaba.fastjson.parser; -import static com.alibaba.fastjson.parser.JSONScanner.EOI; +import static com.alibaba.fastjson.parser.JSONLexer.EOI; +import static com.alibaba.fastjson.parser.JSONToken.*; -import java.util.Map; +import java.io.Closeable; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.*; +import com.alibaba.fastjson.parser.deserializer.*; +import com.alibaba.fastjson.serializer.*; +import com.alibaba.fastjson.util.TypeUtils; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ -public class DefaultJSONParser extends AbstractJSONParser { +public class DefaultJSONParser implements Closeable { - protected final JSONLexer lexer; - protected final Object input; - protected final SymbolTable symbolTable; - protected ParserConfig config; + public final Object input; + public final SymbolTable symbolTable; + protected ParserConfig config; + + private final static Set> primitiveClasses = new HashSet>(); + + private String dateFormatPattern = JSON.DEFFAULT_DATE_FORMAT; + private DateFormat dateFormat; + + public final JSONLexer lexer; + + protected ParseContext context; + + private ParseContext[] contextArray; + private int contextArrayIndex = 0; + + private List resolveTaskList; + + public final static int NONE = 0; + public final static int NeedToResolve = 1; + public final static int TypeNameRedirect = 2; + + public int resolveStatus = NONE; + + private List extraTypeProviders = null; + private List extraProcessors = null; + protected FieldTypeResolver fieldTypeResolver = null; + + private boolean autoTypeEnable; + private String[] autoTypeAccept = null; + + protected transient BeanContext lastBeanContext; + + static { + Class[] classes = new Class[] { + boolean.class, + byte.class, + short.class, + int.class, + long.class, + float.class, + double.class, + + Boolean.class, + Byte.class, + Short.class, + Integer.class, + Long.class, + Float.class, + Double.class, + + BigInteger.class, + BigDecimal.class, + String.class + }; + + for (Class clazz : classes) { + primitiveClasses.add(clazz); + } + } + + public String getDateFomartPattern() { + return dateFormatPattern; + } + + public DateFormat getDateFormat() { + if (dateFormat == null) { + dateFormat = new SimpleDateFormat(dateFormatPattern, lexer.getLocale()); + dateFormat.setTimeZone(lexer.getTimeZone()); + } + return dateFormat; + } + + public void setDateFormat(String dateFormat) { + this.dateFormatPattern = dateFormat; + this.dateFormat = null; + } + + public void setDateFomrat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } public DefaultJSONParser(String input){ this(input, ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); @@ -50,23 +137,36 @@ public DefaultJSONParser(final char[] input, int length, final ParserConfig conf this(input, new JSONScanner(input, length, features), config); } + public DefaultJSONParser(final JSONLexer lexer){ + this(lexer, ParserConfig.getGlobalInstance()); + } + + public DefaultJSONParser(final JSONLexer lexer, final ParserConfig config){ + this(null, lexer, config); + } + public DefaultJSONParser(final Object input, final JSONLexer lexer, final ParserConfig config){ - this.input = input; this.lexer = lexer; + this.input = input; this.config = config; - this.symbolTable = config.getSymbolTable(); + this.symbolTable = config.symbolTable; - lexer.nextToken(JSONToken.LBRACE); // prime the pump + int ch = lexer.getCurrent(); + if (ch == '{') { + lexer.next(); + ((JSONLexerBase) lexer).token = JSONToken.LBRACE; + } else if (ch == '[') { + lexer.next(); + ((JSONLexerBase) lexer).token = JSONToken.LBRACKET; + } else { + lexer.nextToken(); // prime the pump + } } public SymbolTable getSymbolTable() { return symbolTable; } - public JSONLexer getLexer() { - return lexer; - } - public String getInput() { if (input instanceof char[]) { return new String((char[]) input); @@ -74,250 +174,1560 @@ public String getInput() { return input.toString(); } - // public final void parseObject2(final Map map) { - // JSONScanner lexer = (JSONScanner) this.lexer; - // - // if (lexer.token() != JSONToken.LBRACE) { - // throw new JSONException("syntax error, expect {, actual " + lexer.token()); - // } - // - // for (;;) { - // // lexer.scanSymbol - // String key = lexer.scanSymbol(getSymbolTable()); - // - // if (key == null) { - // if (lexer.token() == JSONToken.RBRACE) { - // lexer.nextToken(JSONToken.COMMA); - // return; - // } - // if (lexer.token() == JSONToken.COMMA) { - // if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { - // continue; - // } - // } - // } - // - // Object value; - // - // lexer.nextTokenWithColon(JSONToken.LITERAL_STRING); - // switch (lexer.token()) { - // case LITERAL_INT: - // value = lexer.integerValue(); - // lexer.nextToken(JSONToken.COMMA); - // break; - // case LITERAL_FLOAT: - // if (lexer.isEnabled(Feature.UseBigDecimal)) { - // value = lexer.decimalValue(); - // } else { - // value = Double.parseDouble(lexer.numberString()); - // } - // lexer.nextToken(JSONToken.COMMA); - // break; - // case LITERAL_STRING: - // String stringLiteral = lexer.stringVal(); - // lexer.nextToken(JSONToken.COMMA); - // - // if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) { - // JSONScanner iso8601Lexer = new JSONScanner(stringLiteral); - // if (iso8601Lexer.scanISO8601DateIfMatch()) { - // value = iso8601Lexer.getCalendar().getTime(); - // } else { - // value = stringLiteral; - // } - // } else { - // value = stringLiteral; - // } - // - // break; - // case TRUE: - // value = Boolean.TRUE; - // lexer.nextToken(JSONToken.COMMA); - // break; - // case FALSE: - // value = Boolean.FALSE; - // lexer.nextToken(JSONToken.COMMA); - // break; - // case LBRACE: - // JSONObject object = new JSONObject(); - // parseObject(object); - // value = object; - // break; - // case LBRACKET: - // Collection array = new ArrayList(); - // parseArray(array); - // value = array; - // break; - // case NULL: - // value = null; - // lexer.nextToken(); - // break; - // default: - // value = parse(); - // break; - // } - // - // map.put(key, value); - // - // if (lexer.token() == JSONToken.COMMA) { - // continue; - // } - // - // if (lexer.token() == JSONToken.RBRACE) { - // lexer.nextToken(JSONToken.COMMA); - // return; - // } - // } - // - // } - @SuppressWarnings({ "unchecked", "rawtypes" }) - public final void parseObject(final Map object) { - JSONScanner lexer = (JSONScanner) this.lexer; - if (lexer.token() != JSONToken.LBRACE) { - throw new JSONException("syntax error, expect {, actual " + lexer.token()); + public final Object parseObject(final Map object, Object fieldName) { + final JSONLexer lexer = this.lexer; + + if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(); + return null; + } + + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + return object; } - for (;;) { - lexer.skipWhitespace(); - char ch = lexer.getCurrent(); - if (isEnabled(Feature.AllowArbitraryCommas)) { - while (ch == ',') { - lexer.incrementBufferPosition(); + if (lexer.token() == JSONToken.LITERAL_STRING && lexer.stringVal().length() == 0) { + lexer.nextToken(); + return object; + } + + if (lexer.token() != JSONToken.LBRACE && lexer.token() != JSONToken.COMMA) { + throw new JSONException("syntax error, expect {, actual " + lexer.tokenName() + ", " + lexer.info()); + } + + ParseContext context = this.context; + try { + Map map = object instanceof JSONObject ? ((JSONObject) object).getInnerMap() : object; + + boolean setContextFlag = false; + for (;;) { + lexer.skipWhitespace(); + char ch = lexer.getCurrent(); + if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { + while (ch == ',') { + lexer.next(); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + } + } + + boolean isObjectKey = false; + Object key; + if (ch == '"') { + key = lexer.scanSymbol(symbolTable, '"'); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + if (ch != ':') { + throw new JSONException("expect ':' at " + lexer.pos() + ", name " + key); + } + } else if (ch == '}') { + lexer.next(); + lexer.resetStringPosition(); + lexer.nextToken(); + + if (!setContextFlag) { + if (this.context != null && fieldName == this.context.fieldName && object == this.context.object) { + context = this.context; + } else { + ParseContext contextR = setContext(object, fieldName); + if (context == null) { + context = contextR; + } + setContextFlag = true; + } + } + + return object; + } else if (ch == '\'') { + if (!lexer.isEnabled(Feature.AllowSingleQuotes)) { + throw new JSONException("syntax error"); + } + + key = lexer.scanSymbol(symbolTable, '\''); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + if (ch != ':') { + throw new JSONException("expect ':' at " + lexer.pos()); + } + } else if (ch == EOI) { + throw new JSONException("syntax error"); + } else if (ch == ',') { + throw new JSONException("syntax error"); + } else if ((ch >= '0' && ch <= '9') || ch == '-') { + lexer.resetStringPosition(); + lexer.scanNumber(); + try { + if (lexer.token() == JSONToken.LITERAL_INT) { + key = lexer.integerValue(); + } else { + key = lexer.decimalValue(true); + } + if (lexer.isEnabled(Feature.NonStringKeyAsString)) { + key = key.toString(); + } + } catch (NumberFormatException e) { + throw new JSONException("parse number key error" + lexer.info()); + } + ch = lexer.getCurrent(); + if (ch != ':') { + throw new JSONException("parse number key error" + lexer.info()); + } + } else if (ch == '{' || ch == '[') { + lexer.nextToken(); + key = parse(); + isObjectKey = true; + } else { + if (!lexer.isEnabled(Feature.AllowUnQuotedFieldNames)) { + throw new JSONException("syntax error"); + } + + key = lexer.scanSymbolUnQuoted(symbolTable); lexer.skipWhitespace(); ch = lexer.getCurrent(); + if (ch != ':') { + throw new JSONException("expect ':' at " + lexer.pos() + ", actual " + ch); + } } - } - String key; - if (ch == '"') { - key = lexer.scanSymbol(symbolTable, '"'); - lexer.skipWhitespace(); - ch = lexer.getCurrent(); - if (ch != ':') { - throw new JSONException("expect ':' at " + lexer.pos() + ", name " + key); + if (!isObjectKey) { + lexer.next(); + lexer.skipWhitespace(); } - } else if (ch == '}') { - lexer.incrementBufferPosition(); + + ch = lexer.getCurrent(); + lexer.resetStringPosition(); - lexer.nextToken(); - return; - } else if (ch == '\'') { - if (!isEnabled(Feature.AllowSingleQuotes)) { - throw new JSONException("syntax error"); + + if (key == JSON.DEFAULT_TYPE_KEY + && !lexer.isEnabled(Feature.DisableSpecialKeyDetect)) { + String typeName = lexer.scanSymbol(symbolTable, '"'); + + if (lexer.isEnabled(Feature.IgnoreAutoType)) { + continue; + } + + Class clazz = null; + if (object != null + && object.getClass().getName().equals(typeName)) { + clazz = object.getClass(); + } else { + clazz = config.checkAutoType(typeName, null, lexer.getFeatures()); + } + + if (clazz == null) { + map.put(JSON.DEFAULT_TYPE_KEY, typeName); + continue; + } + + lexer.nextToken(JSONToken.COMMA); + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + try { + Object instance = null; + ObjectDeserializer deserializer = this.config.getDeserializer(clazz); + if (deserializer instanceof JavaBeanDeserializer) { + JavaBeanDeserializer javaBeanDeserializer = (JavaBeanDeserializer) deserializer; + instance = javaBeanDeserializer.createInstance(this, clazz); + + for (Object o : map.entrySet()) { + Map.Entry entry = (Map.Entry) o; + Object entryKey = entry.getKey(); + if (entryKey instanceof String) { + FieldDeserializer fieldDeserializer = javaBeanDeserializer.getFieldDeserializer((String) entryKey); + if (fieldDeserializer != null) { + fieldDeserializer.setValue(instance, entry.getValue()); + } + } + } + } + + if (instance == null) { + if (clazz == Cloneable.class) { + instance = new HashMap(); + } else if ("java.util.Collections$EmptyMap".equals(typeName)) { + instance = Collections.emptyMap(); + } else { + instance = clazz.newInstance(); + } + } + + return instance; + } catch (Exception e) { + throw new JSONException("create instance error", e); + } + } + + this.setResolveStatus(TypeNameRedirect); + + if (this.context != null + && fieldName != null + && !(fieldName instanceof Integer) + && !(this.context.fieldName instanceof Integer)) { + this.popContext(); + } + + if (object.size() > 0) { + Object newObj = TypeUtils.cast(object, clazz, this.config); + this.parseObject(newObj); + return newObj; + } + + ObjectDeserializer deserializer = config.getDeserializer(clazz); + Class deserClass = deserializer.getClass(); + if (JavaBeanDeserializer.class.isAssignableFrom(deserClass) + && deserClass != JavaBeanDeserializer.class + && deserClass != ThrowableDeserializer.class) { + this.setResolveStatus(NONE); + } + Object obj = deserializer.deserialze(this, clazz, fieldName); + return obj; } - key = lexer.scanSymbol(symbolTable, '\''); - lexer.skipWhitespace(); - ch = lexer.getCurrent(); - if (ch != ':') { - throw new JSONException("expect ':' at " + lexer.pos()); + if (key == "$ref" + && context != null + && !lexer.isEnabled(Feature.DisableSpecialKeyDetect)) { + lexer.nextToken(JSONToken.LITERAL_STRING); + if (lexer.token() == JSONToken.LITERAL_STRING) { + String ref = lexer.stringVal(); + lexer.nextToken(JSONToken.RBRACE); + + Object refValue = null; + if ("@".equals(ref)) { + if (this.context != null) { + ParseContext thisContext = this.context; + Object thisObj = thisContext.object; + if (thisObj instanceof Object[] || thisObj instanceof Collection) { + refValue = thisObj; + } else if (thisContext.parent != null) { + refValue = thisContext.parent.object; + } + } + } else if ("..".equals(ref)) { + if (context.object != null) { + refValue = context.object; + } else { + addResolveTask(new ResolveTask(context, ref)); + setResolveStatus(DefaultJSONParser.NeedToResolve); + } + } else if ("$".equals(ref)) { + ParseContext rootContext = context; + while (rootContext.parent != null) { + rootContext = rootContext.parent; + } + + if (rootContext.object != null) { + refValue = rootContext.object; + } else { + addResolveTask(new ResolveTask(rootContext, ref)); + setResolveStatus(DefaultJSONParser.NeedToResolve); + } + } else { + addResolveTask(new ResolveTask(context, ref)); + setResolveStatus(DefaultJSONParser.NeedToResolve); + } + + if (lexer.token() != JSONToken.RBRACE) { + throw new JSONException("syntax error"); + } + lexer.nextToken(JSONToken.COMMA); + + return refValue; + } else { + throw new JSONException("illegal ref, " + JSONToken.name(lexer.token())); + } } - } else if (ch == EOI) { - throw new JSONException("syntax error"); - } else if (ch == ',') { - throw new JSONException("syntax error"); - } else { - if (!isEnabled(Feature.AllowUnQuotedFieldNames)) { - throw new JSONException("syntax error"); + + if (!setContextFlag) { + if (this.context != null && fieldName == this.context.fieldName && object == this.context.object) { + context = this.context; + } else { + ParseContext contextR = setContext(object, fieldName); + if (context == null) { + context = contextR; + } + setContextFlag = true; + } + } + + if (object.getClass() == JSONObject.class) { + if (key == null) { + key = "null"; + } + } + + Object value; + if (ch == '"') { + lexer.scanString(); + String strValue = lexer.stringVal(); + value = strValue; + + if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) { + JSONScanner iso8601Lexer = new JSONScanner(strValue); + if (iso8601Lexer.scanISO8601DateIfMatch()) { + value = iso8601Lexer.getCalendar().getTime(); + } + iso8601Lexer.close(); + } + + map.put(key, value); + } else if (ch >= '0' && ch <= '9' || ch == '-') { + lexer.scanNumber(); + if (lexer.token() == JSONToken.LITERAL_INT) { + value = lexer.integerValue(); + } else { + value = lexer.decimalValue(lexer.isEnabled(Feature.UseBigDecimal)); + } + + map.put(key, value); + } else if (ch == '[') { // 减少嵌套,兼容android + lexer.nextToken(); + + JSONArray list = new JSONArray(); + + final boolean parentIsArray = fieldName != null && fieldName.getClass() == Integer.class; +// if (!parentIsArray) { +// this.setContext(context); +// } + if (fieldName == null) { + this.setContext(context); + } + + this.parseArray(list, key); + + if (lexer.isEnabled(Feature.UseObjectArray)) { + value = list.toArray(); + } else { + value = list; + } + map.put(key, value); + + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + return object; + } else if (lexer.token() == JSONToken.COMMA) { + continue; + } else { + throw new JSONException("syntax error"); + } + } else if (ch == '{') { // 减少嵌套,兼容android + lexer.nextToken(); + + final boolean parentIsArray = fieldName != null && fieldName.getClass() == Integer.class; + + Map input; + if (lexer.isEnabled(Feature.CustomMapDeserializer)) { + MapDeserializer mapDeserializer = (MapDeserializer) config.getDeserializer(Map.class); + input = mapDeserializer.createMap(Map.class); + } else { + input = new JSONObject(lexer.isEnabled(Feature.OrderedField)); + } + ParseContext ctxLocal = null; + + if (!parentIsArray) { + ctxLocal = setContext(context, input, key); + } + + Object obj = null; + boolean objParsed = false; + if (fieldTypeResolver != null) { + String resolveFieldName = key != null ? key.toString() : null; + Type fieldType = fieldTypeResolver.resolve(object, resolveFieldName); + if (fieldType != null) { + ObjectDeserializer fieldDeser = config.getDeserializer(fieldType); + obj = fieldDeser.deserialze(this, fieldType, key); + objParsed = true; + } + } + if (!objParsed) { + obj = this.parseObject(input, key); + } + + if (ctxLocal != null && input != obj) { + ctxLocal.object = object; + } + + if (key != null) { + checkMapResolve(object, key.toString()); + } + + map.put(key, obj); + + if (parentIsArray) { + //setContext(context, obj, key); + setContext(obj, key); + } + + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + + setContext(context); + return object; + } else if (lexer.token() == JSONToken.COMMA) { + if (parentIsArray) { + this.popContext(); + } else { + this.setContext(context); + } + continue; + } else { + throw new JSONException("syntax error, " + lexer.tokenName()); + } + } else { + lexer.nextToken(); + value = parse(); + + map.put(key, value); + + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + return object; + } else if (lexer.token() == JSONToken.COMMA) { + continue; + } else { + throw new JSONException("syntax error, position at " + lexer.pos() + ", name " + key); + } } - key = lexer.scanSymbolUnQuoted(symbolTable); lexer.skipWhitespace(); ch = lexer.getCurrent(); - if (ch != ':') { - throw new JSONException("expect ':' at " + lexer.pos() + ", actual " + ch); + if (ch == ',') { + lexer.next(); + continue; + } else if (ch == '}') { + lexer.next(); + lexer.resetStringPosition(); + lexer.nextToken(); + + // this.setContext(object, fieldName); + this.setContext(value, key); + + return object; + } else { + throw new JSONException("syntax error, position at " + lexer.pos() + ", name " + key); } + + } + } finally { + this.setContext(context); + } + + } + + public ParserConfig getConfig() { + return config; + } + + public void setConfig(ParserConfig config) { + this.config = config; + } + + // compatible + @SuppressWarnings("unchecked") + public T parseObject(Class clazz) { + return (T) parseObject(clazz, null); + } + + public T parseObject(Type type) { + return parseObject(type, null); + } + + @SuppressWarnings("unchecked") + public T parseObject(Type type, Object fieldName) { + int token = lexer.token(); + if (token == JSONToken.NULL) { + lexer.nextToken(); + return null; + } + + if (token == JSONToken.LITERAL_STRING) { + if (type == byte[].class) { + byte[] bytes = lexer.bytesValue(); + lexer.nextToken(); + return (T) bytes; + } + + if (type == char[].class) { + String strVal = lexer.stringVal(); + lexer.nextToken(); + return (T) strVal.toCharArray(); } + } - lexer.incrementBufferPosition(); - lexer.skipWhitespace(); - ch = lexer.getCurrent(); + ObjectDeserializer derializer = config.getDeserializer(type); - lexer.resetStringPosition(); + try { + return (T) derializer.deserialze(this, type, fieldName); + } catch (JSONException e) { + throw e; + } catch (Throwable e) { + throw new JSONException(e.getMessage(), e); + } + } - Object value; - if (ch == '"') { - lexer.scanString(); - String strValue = lexer.stringVal(); - value = strValue; + public List parseArray(Class clazz) { + List array = new ArrayList(); + parseArray(clazz, array); + return array; + } - if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) { - JSONScanner iso8601Lexer = new JSONScanner(strValue); - if (iso8601Lexer.scanISO8601DateIfMatch()) { - value = iso8601Lexer.getCalendar().getTime(); + public void parseArray(Class clazz, @SuppressWarnings("rawtypes") Collection array) { + parseArray((Type) clazz, array); + } + + @SuppressWarnings("rawtypes") + public void parseArray(Type type, Collection array) { + parseArray(type, array, null); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void parseArray(Type type, Collection array, Object fieldName) { + int token = lexer.token(); + if (token == JSONToken.SET || token == JSONToken.TREE_SET) { + lexer.nextToken(); + token = lexer.token(); + } + + if (token != JSONToken.LBRACKET) { + throw new JSONException("exepct '[', but " + JSONToken.name(token) + ", " + lexer.info()); + } + + ObjectDeserializer deserializer = null; + if (int.class == type) { + deserializer = IntegerCodec.instance; + lexer.nextToken(JSONToken.LITERAL_INT); + } else if (String.class == type) { + deserializer = StringCodec.instance; + lexer.nextToken(JSONToken.LITERAL_STRING); + } else { + deserializer = config.getDeserializer(type); + lexer.nextToken(deserializer.getFastMatchToken()); + } + + ParseContext context = this.context; + this.setContext(array, fieldName); + try { + for (int i = 0;; ++i) { + if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { + while (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(); + continue; } } - object.put(key, value); - } else if (ch >= '0' && ch <= '9' || ch == '-') { - lexer.scanNumber(); - if (lexer.token() == JSONToken.LITERAL_INT) { - value = lexer.integerValue(); - } else { - value = lexer.decimalValue(); + if (lexer.token() == JSONToken.RBRACKET) { + break; } - object.put(key, value); - } else if (ch == '[') { // 减少潜套,兼容android - lexer.nextToken(); - JSONArray list = new JSONArray(); - this.parseArray(list); - value = list; - object.put(key, value); + if (int.class == type) { + Object val = IntegerCodec.instance.deserialze(this, null, null); + array.add(val); + } else if (String.class == type) { + String value; + if (lexer.token() == JSONToken.LITERAL_STRING) { + value = lexer.stringVal(); + lexer.nextToken(JSONToken.COMMA); + } else { + Object obj = this.parse(); + if (obj == null) { + value = null; + } else { + value = obj.toString(); + } + } - if (lexer.token() == JSONToken.RBRACE) { - lexer.nextToken(); - return; - } else if (lexer.token() == JSONToken.COMMA) { - continue; + array.add(value); } else { - throw new JSONException("syntax error"); + Object val; + if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(); + val = null; + } else { + val = deserializer.deserialze(this, type, i); + } + array.add(val); + checkListResolve(array); } - } else if (ch == '{') { // 减少潜套,兼容android - lexer.nextToken(); - JSONObject obj = new JSONObject(); - this.parseObject(obj); - object.put(key, obj); - if (lexer.token() == JSONToken.RBRACE) { - lexer.nextToken(); - return; - } else if (lexer.token() == JSONToken.COMMA) { + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(deserializer.getFastMatchToken()); continue; - } else { - throw new JSONException("syntax error"); } - } else { - lexer.nextToken(); - value = parse(); - object.put(key, value); + } + } finally { + this.setContext(context); + } - if (lexer.token() == JSONToken.RBRACE) { - lexer.nextToken(); - return; - } else if (lexer.token() == JSONToken.COMMA) { - continue; + lexer.nextToken(JSONToken.COMMA); + } + + public Object[] parseArray(Type[] types) { + if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(JSONToken.COMMA); + return null; + } + + if (lexer.token() != JSONToken.LBRACKET) { + throw new JSONException("syntax error : " + lexer.tokenName()); + } + + Object[] list = new Object[types.length]; + if (types.length == 0) { + lexer.nextToken(JSONToken.RBRACKET); + + if (lexer.token() != JSONToken.RBRACKET) { + throw new JSONException("syntax error"); + } + + lexer.nextToken(JSONToken.COMMA); + return new Object[0]; + } + + lexer.nextToken(JSONToken.LITERAL_INT); + + for (int i = 0; i < types.length; ++i) { + Object value; + + if (lexer.token() == JSONToken.NULL) { + value = null; + lexer.nextToken(JSONToken.COMMA); + } else { + Type type = types[i]; + if (type == int.class || type == Integer.class) { + if (lexer.token() == JSONToken.LITERAL_INT) { + value = Integer.valueOf(lexer.intValue()); + lexer.nextToken(JSONToken.COMMA); + } else { + value = this.parse(); + value = TypeUtils.cast(value, type, config); + } + } else if (type == String.class) { + if (lexer.token() == JSONToken.LITERAL_STRING) { + value = lexer.stringVal(); + lexer.nextToken(JSONToken.COMMA); + } else { + value = this.parse(); + value = TypeUtils.cast(value, type, config); + } } else { - throw new JSONException("syntax error, position at " + lexer.pos() + ", name " + key); + boolean isArray = false; + Class componentType = null; + if (i == types.length - 1) { + if (type instanceof Class) { + Class clazz = (Class) type; + isArray = clazz.isArray(); + componentType = clazz.getComponentType(); + } + } + + // support varArgs + if (isArray && lexer.token() != JSONToken.LBRACKET) { + List varList = new ArrayList(); + + ObjectDeserializer derializer = config.getDeserializer(componentType); + int fastMatch = derializer.getFastMatchToken(); + + if (lexer.token() != JSONToken.RBRACKET) { + for (;;) { + Object item = derializer.deserialze(this, type, null); + varList.add(item); + + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(fastMatch); + } else if (lexer.token() == JSONToken.RBRACKET) { + break; + } else { + throw new JSONException("syntax error :" + JSONToken.name(lexer.token())); + } + } + } + + value = TypeUtils.cast(varList, type, config); + } else { + ObjectDeserializer derializer = config.getDeserializer(type); + value = derializer.deserialze(this, type, i); + } } } + list[i] = value; - lexer.skipWhitespace(); - ch = lexer.getCurrent(); - if (ch == ',') { - lexer.incrementBufferPosition(); - continue; - } else if (ch == '}') { - lexer.incrementBufferPosition(); - lexer.resetStringPosition(); - lexer.nextToken(); - return; + if (lexer.token() == JSONToken.RBRACKET) { + break; + } + + if (lexer.token() != JSONToken.COMMA) { + throw new JSONException("syntax error :" + JSONToken.name(lexer.token())); + } + + if (i == types.length - 1) { + lexer.nextToken(JSONToken.RBRACKET); } else { - throw new JSONException("syntax error, position at " + lexer.pos() + ", name " + key); + lexer.nextToken(JSONToken.LITERAL_INT); } + } + if (lexer.token() != JSONToken.RBRACKET) { + throw new JSONException("syntax error"); } + + lexer.nextToken(JSONToken.COMMA); + + return list; } + public void parseObject(Object object) { + Class clazz = object.getClass(); + JavaBeanDeserializer beanDeser = null; + ObjectDeserializer deserizer = config.getDeserializer(clazz); + if (deserizer instanceof JavaBeanDeserializer) { + beanDeser = (JavaBeanDeserializer) deserizer; + } + if (lexer.token() != JSONToken.LBRACE && lexer.token() != JSONToken.COMMA) { + throw new JSONException("syntax error, expect {, actual " + lexer.tokenName()); + } + + for (;;) { + // lexer.scanSymbol + String key = lexer.scanSymbol(symbolTable); + + if (key == null) { + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + break; + } + if (lexer.token() == JSONToken.COMMA) { + if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { + continue; + } + } + } + + FieldDeserializer fieldDeser = null; + if (beanDeser != null) { + fieldDeser = beanDeser.getFieldDeserializer(key); + } + + if (fieldDeser == null) { + if (!lexer.isEnabled(Feature.IgnoreNotMatch)) { + throw new JSONException("setter not found, class " + clazz.getName() + ", property " + key); + } + + lexer.nextTokenWithColon(); + parse(); // skip + + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + return; + } + + continue; + } else { + Class fieldClass = fieldDeser.fieldInfo.fieldClass; + Type fieldType = fieldDeser.fieldInfo.fieldType; + Object fieldValue; + if (fieldClass == int.class) { + lexer.nextTokenWithColon(JSONToken.LITERAL_INT); + fieldValue = IntegerCodec.instance.deserialze(this, fieldType, null); + } else if (fieldClass == String.class) { + lexer.nextTokenWithColon(JSONToken.LITERAL_STRING); + fieldValue = StringCodec.deserialze(this); + } else if (fieldClass == long.class) { + lexer.nextTokenWithColon(JSONToken.LITERAL_INT); + fieldValue = LongCodec.instance.deserialze(this, fieldType, null); + } else { + ObjectDeserializer fieldValueDeserializer = config.getDeserializer(fieldClass, fieldType); + + lexer.nextTokenWithColon(fieldValueDeserializer.getFastMatchToken()); + fieldValue = fieldValueDeserializer.deserialze(this, fieldType, null); + } + + fieldDeser.setValue(object, fieldValue); + } + + if (lexer.token() == JSONToken.COMMA) { + continue; + } + + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + return; + } + } + } + + public Object parseArrayWithType(Type collectionType) { + if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(); + return null; + } + + Type[] actualTypes = ((ParameterizedType) collectionType).getActualTypeArguments(); + + if (actualTypes.length != 1) { + throw new JSONException("not support type " + collectionType); + } + + Type actualTypeArgument = actualTypes[0]; + + if (actualTypeArgument instanceof Class) { + List array = new ArrayList(); + this.parseArray((Class) actualTypeArgument, array); + return array; + } + + if (actualTypeArgument instanceof WildcardType) { + WildcardType wildcardType = (WildcardType) actualTypeArgument; + + // assert wildcardType.getUpperBounds().length == 1; + Type upperBoundType = wildcardType.getUpperBounds()[0]; + + // assert upperBoundType instanceof Class; + if (Object.class.equals(upperBoundType)) { + if (wildcardType.getLowerBounds().length == 0) { + // Collection + return parse(); + } else { + throw new JSONException("not support type : " + collectionType); + } + } + + List array = new ArrayList(); + this.parseArray((Class) upperBoundType, array); + return array; + + // throw new JSONException("not support type : " + + // collectionType);return parse(); + } + + if (actualTypeArgument instanceof TypeVariable) { + TypeVariable typeVariable = (TypeVariable) actualTypeArgument; + Type[] bounds = typeVariable.getBounds(); + + if (bounds.length != 1) { + throw new JSONException("not support : " + typeVariable); + } + + Type boundType = bounds[0]; + if (boundType instanceof Class) { + List array = new ArrayList(); + this.parseArray((Class) boundType, array); + return array; + } + } + + if (actualTypeArgument instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) actualTypeArgument; + + List array = new ArrayList(); + this.parseArray(parameterizedType, array); + return array; + } + + throw new JSONException("TODO : " + collectionType); + } + + public void acceptType(String typeName) { + JSONLexer lexer = this.lexer; + + lexer.nextTokenWithColon(); + + if (lexer.token() != JSONToken.LITERAL_STRING) { + throw new JSONException("type not match error"); + } + + if (typeName.equals(lexer.stringVal())) { + lexer.nextToken(); + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(); + } + } else { + throw new JSONException("type not match error"); + } + } + + public int getResolveStatus() { + return resolveStatus; + } + + public void setResolveStatus(int resolveStatus) { + this.resolveStatus = resolveStatus; + } + + public Object getObject(String path) { + for (int i = 0; i < contextArrayIndex; ++i) { + if (path.equals(contextArray[i].toString())) { + return contextArray[i].object; + } + } + + return null; + } + + @SuppressWarnings("rawtypes") + public void checkListResolve(Collection array) { + if (resolveStatus == NeedToResolve) { + if (array instanceof List) { + final int index = array.size() - 1; + final List list = (List) array; + ResolveTask task = getLastResolveTask(); + task.fieldDeserializer = new ResolveFieldDeserializer(this, list, index); + task.ownerContext = context; + setResolveStatus(DefaultJSONParser.NONE); + } else { + ResolveTask task = getLastResolveTask(); + task.fieldDeserializer = new ResolveFieldDeserializer(array); + task.ownerContext = context; + setResolveStatus(DefaultJSONParser.NONE); + } + } + } + + @SuppressWarnings("rawtypes") + public void checkMapResolve(Map object, Object fieldName) { + if (resolveStatus == NeedToResolve) { + ResolveFieldDeserializer fieldResolver = new ResolveFieldDeserializer(object, fieldName); + ResolveTask task = getLastResolveTask(); + task.fieldDeserializer = fieldResolver; + task.ownerContext = context; + setResolveStatus(DefaultJSONParser.NONE); + } + } + + @SuppressWarnings("rawtypes") + public Object parseObject(final Map object) { + return parseObject(object, null); + } + + public JSONObject parseObject() { + JSONObject object = new JSONObject(lexer.isEnabled(Feature.OrderedField)); + object = (JSONObject) parseObject(object); + return object; + } + + @SuppressWarnings("rawtypes") + public final void parseArray(final Collection array) { + parseArray(array, null); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public final void parseArray(final Collection array, Object fieldName) { + final JSONLexer lexer = this.lexer; + + if (lexer.token() == JSONToken.SET || lexer.token() == JSONToken.TREE_SET) { + lexer.nextToken(); + } + + if (lexer.token() != JSONToken.LBRACKET) { + throw new JSONException("syntax error, expect [, actual " + JSONToken.name(lexer.token()) + ", pos " + + lexer.pos() + ", fieldName " + fieldName); + } + + lexer.nextToken(JSONToken.LITERAL_STRING); + + ParseContext context = this.context; + this.setContext(array, fieldName); + try { + for (int i = 0;; ++i) { + if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { + while (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(); + continue; + } + } + + Object value; + switch (lexer.token()) { + case LITERAL_INT: + value = lexer.integerValue(); + lexer.nextToken(JSONToken.COMMA); + break; + case LITERAL_FLOAT: + if (lexer.isEnabled(Feature.UseBigDecimal)) { + value = lexer.decimalValue(true); + } else { + value = lexer.decimalValue(false); + } + lexer.nextToken(JSONToken.COMMA); + break; + case LITERAL_STRING: + String stringLiteral = lexer.stringVal(); + lexer.nextToken(JSONToken.COMMA); + + if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) { + JSONScanner iso8601Lexer = new JSONScanner(stringLiteral); + if (iso8601Lexer.scanISO8601DateIfMatch()) { + value = iso8601Lexer.getCalendar().getTime(); + } else { + value = stringLiteral; + } + iso8601Lexer.close(); + } else { + value = stringLiteral; + } + + break; + case TRUE: + value = Boolean.TRUE; + lexer.nextToken(JSONToken.COMMA); + break; + case FALSE: + value = Boolean.FALSE; + lexer.nextToken(JSONToken.COMMA); + break; + case LBRACE: + JSONObject object = new JSONObject(lexer.isEnabled(Feature.OrderedField)); + value = parseObject(object, i); + break; + case LBRACKET: + Collection items = new JSONArray(); + parseArray(items, i); + if (lexer.isEnabled(Feature.UseObjectArray)) { + value = items.toArray(); + } else { + value = items; + } + break; + case NULL: + value = null; + lexer.nextToken(JSONToken.LITERAL_STRING); + break; + case UNDEFINED: + value = null; + lexer.nextToken(JSONToken.LITERAL_STRING); + break; + case RBRACKET: + lexer.nextToken(JSONToken.COMMA); + return; + case EOF: + throw new JSONException("unclosed jsonArray"); + default: + value = parse(); + break; + } + + array.add(value); + checkListResolve(array); + + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(JSONToken.LITERAL_STRING); + continue; + } + } + } finally { + this.setContext(context); + } + } + + public ParseContext getContext() { + return context; + } + + public List getResolveTaskList() { + if (resolveTaskList == null) { + resolveTaskList = new ArrayList(2); + } + return resolveTaskList; + } + + public void addResolveTask(ResolveTask task) { + if (resolveTaskList == null) { + resolveTaskList = new ArrayList(2); + } + resolveTaskList.add(task); + } + + public ResolveTask getLastResolveTask() { + return resolveTaskList.get(resolveTaskList.size() - 1); + } + + public List getExtraProcessors() { + if (extraProcessors == null) { + extraProcessors = new ArrayList(2); + } + return extraProcessors; + } + + public List getExtraTypeProviders() { + if (extraTypeProviders == null) { + extraTypeProviders = new ArrayList(2); + } + return extraTypeProviders; + } + + public FieldTypeResolver getFieldTypeResolver() { + return fieldTypeResolver; + } + + public void setFieldTypeResolver(FieldTypeResolver fieldTypeResolver) { + this.fieldTypeResolver = fieldTypeResolver; + } + + public void setContext(ParseContext context) { + if (lexer.isEnabled(Feature.DisableCircularReferenceDetect)) { + return; + } + this.context = context; + } + + public void popContext() { + if (lexer.isEnabled(Feature.DisableCircularReferenceDetect)) { + return; + } + + this.context = this.context.parent; + + if (contextArrayIndex <= 0) { + return; + } + + contextArrayIndex--; + contextArray[contextArrayIndex] = null; + } + + public ParseContext setContext(Object object, Object fieldName) { + if (lexer.isEnabled(Feature.DisableCircularReferenceDetect)) { + return null; + } + + return setContext(this.context, object, fieldName); + } + + public ParseContext setContext(ParseContext parent, Object object, Object fieldName) { + if (lexer.isEnabled(Feature.DisableCircularReferenceDetect)) { + return null; + } + + this.context = new ParseContext(parent, object, fieldName); + addContext(this.context); + + return this.context; + } + + private void addContext(ParseContext context) { + int i = contextArrayIndex++; + if (contextArray == null) { + contextArray = new ParseContext[8]; + } else if (i >= contextArray.length) { + int newLen = (contextArray.length * 3) / 2; + ParseContext[] newArray = new ParseContext[newLen]; + System.arraycopy(contextArray, 0, newArray, 0, contextArray.length); + contextArray = newArray; + } + contextArray[i] = context; + } + + public Object parse() { + return parse(null); + } + + public Object parseKey() { + if (lexer.token() == JSONToken.IDENTIFIER) { + String value = lexer.stringVal(); + lexer.nextToken(JSONToken.COMMA); + return value; + } + return parse(null); + } + + public Object parse(Object fieldName) { + final JSONLexer lexer = this.lexer; + switch (lexer.token()) { + case SET: + lexer.nextToken(); + HashSet set = new HashSet(); + parseArray(set, fieldName); + return set; + case TREE_SET: + lexer.nextToken(); + TreeSet treeSet = new TreeSet(); + parseArray(treeSet, fieldName); + return treeSet; + case LBRACKET: + JSONArray array = new JSONArray(); + parseArray(array, fieldName); + if (lexer.isEnabled(Feature.UseObjectArray)) { + return array.toArray(); + } + return array; + case LBRACE: + JSONObject object = new JSONObject(lexer.isEnabled(Feature.OrderedField)); + return parseObject(object, fieldName); +// case LBRACE: { +// Map map = lexer.isEnabled(Feature.OrderedField) +// ? new LinkedHashMap() +// : new HashMap(); +// Object obj = parseObject(map, fieldName); +// if (obj != map) { +// return obj; +// } +// return new JSONObject(map); +// } + case LITERAL_INT: + Number intValue = lexer.integerValue(); + lexer.nextToken(); + return intValue; + case LITERAL_FLOAT: + Object value = lexer.decimalValue(lexer.isEnabled(Feature.UseBigDecimal)); + lexer.nextToken(); + return value; + case LITERAL_STRING: + String stringLiteral = lexer.stringVal(); + lexer.nextToken(JSONToken.COMMA); + + if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) { + JSONScanner iso8601Lexer = new JSONScanner(stringLiteral); + try { + if (iso8601Lexer.scanISO8601DateIfMatch()) { + return iso8601Lexer.getCalendar().getTime(); + } + } finally { + iso8601Lexer.close(); + } + } + + return stringLiteral; + case NULL: + lexer.nextToken(); + return null; + case UNDEFINED: + lexer.nextToken(); + return null; + case TRUE: + lexer.nextToken(); + return Boolean.TRUE; + case FALSE: + lexer.nextToken(); + return Boolean.FALSE; + case NEW: + lexer.nextToken(JSONToken.IDENTIFIER); + + if (lexer.token() != JSONToken.IDENTIFIER) { + throw new JSONException("syntax error"); + } + lexer.nextToken(JSONToken.LPAREN); + + accept(JSONToken.LPAREN); + long time = ((Number) lexer.integerValue()).longValue(); + accept(JSONToken.LITERAL_INT); + + accept(JSONToken.RPAREN); + + return new Date(time); + case EOF: + if (lexer.isBlankInput()) { + return null; + } + throw new JSONException("unterminated json string, " + lexer.info()); + case HEX: + byte[] bytes = lexer.bytesValue(); + lexer.nextToken(); + return bytes; + case IDENTIFIER: + String identifier = lexer.stringVal(); + if ("NaN".equals(identifier)) { + lexer.nextToken(); + return null; + } + throw new JSONException("syntax error, " + lexer.info()); + case ERROR: + default: + throw new JSONException("syntax error, " + lexer.info()); + } + } + + public void config(Feature feature, boolean state) { + this.lexer.config(feature, state); + } + + public boolean isEnabled(Feature feature) { + return lexer.isEnabled(feature); + } + + public JSONLexer getLexer() { + return lexer; + } + + public final void accept(final int token) { + final JSONLexer lexer = this.lexer; + if (lexer.token() == token) { + lexer.nextToken(); + } else { + throw new JSONException("syntax error, expect " + JSONToken.name(token) + ", actual " + + JSONToken.name(lexer.token())); + } + } + + public final void accept(final int token, int nextExpectToken) { + final JSONLexer lexer = this.lexer; + if (lexer.token() == token) { + lexer.nextToken(nextExpectToken); + } else { + throwException(token); + } + } + + public void throwException(int token) { + throw new JSONException("syntax error, expect " + JSONToken.name(token) + ", actual " + + JSONToken.name(lexer.token())); + } + + public void close() { + final JSONLexer lexer = this.lexer; + + try { + if (lexer.isEnabled(Feature.AutoCloseSource)) { + if (lexer.token() != JSONToken.EOF) { + throw new JSONException("not close json text, token : " + JSONToken.name(lexer.token())); + } + } + } finally { + lexer.close(); + } + } + + public Object resolveReference(String ref) { + if(contextArray == null) { + return null; + } + for (int i = 0; i < contextArray.length && i < contextArrayIndex; i++) { + ParseContext context = contextArray[i]; + if (context.toString().equals(ref)) { + return context.object; + } + } + return null; + } + + public void handleResovleTask(Object value) { + if (resolveTaskList == null) { + return; + } + + for (int i = 0, size = resolveTaskList.size(); i < size; ++i) { + ResolveTask task = resolveTaskList.get(i); + String ref = task.referenceValue; + + Object object = null; + if (task.ownerContext != null) { + object = task.ownerContext.object; + } + + Object refValue; + + if (ref.startsWith("$")) { + refValue = getObject(ref); + if (refValue == null) { + try { + refValue = JSONPath.eval(value, ref); + } catch (JSONPathException ex) { + // skip + } + } + } else { + refValue = task.context.object; + } + + FieldDeserializer fieldDeser = task.fieldDeserializer; + + if (fieldDeser != null) { + if (refValue != null + && refValue.getClass() == JSONObject.class + && fieldDeser.fieldInfo != null + && !Map.class.isAssignableFrom(fieldDeser.fieldInfo.fieldClass)) { + Object root = this.contextArray[0].object; + refValue = JSONPath.eval(root, ref); + } + + fieldDeser.setValue(object, refValue); + } + } + } + + public static class ResolveTask { + + public final ParseContext context; + public final String referenceValue; + public FieldDeserializer fieldDeserializer; + public ParseContext ownerContext; + + public ResolveTask(ParseContext context, String referenceValue){ + this.context = context; + this.referenceValue = referenceValue; + } + } + + public void parseExtra(Object object, String key) { + final JSONLexer lexer = this.lexer; // xxx + lexer.nextTokenWithColon(); + Type type = null; + + if (extraTypeProviders != null) { + for (ExtraTypeProvider extraProvider : extraTypeProviders) { + type = extraProvider.getExtraType(object, key); + } + } + Object value = type == null // + ? parse() // skip + : parseObject(type); + + if (object instanceof ExtraProcessable) { + ExtraProcessable extraProcessable = ((ExtraProcessable) object); + extraProcessable.processExtra(key, value); + return; + } + + if (extraProcessors != null) { + for (ExtraProcessor process : extraProcessors) { + process.processExtra(object, key, value); + } + } + + if (resolveStatus == NeedToResolve) { + resolveStatus = NONE; + } + } + + public Object parse(PropertyProcessable object, Object fieldName) { + if (lexer.token() != JSONToken.LBRACE) { + String msg = "syntax error, expect {, actual " + lexer.tokenName(); + if (fieldName instanceof String) { + msg += ", fieldName "; + msg += fieldName; + } + msg += ", "; + msg += lexer.info(); + + JSONArray array = new JSONArray(); + parseArray(array, fieldName); + + if (array.size() == 1) { + Object first = array.get(0); + if (first instanceof JSONObject) { + return (JSONObject) first; + } + } + + throw new JSONException(msg); + } + + ParseContext context = this.context; + try { + for (int i = 0;;++i) { + lexer.skipWhitespace(); + char ch = lexer.getCurrent(); + if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { + while (ch == ',') { + lexer.next(); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + } + } + + String key; + if (ch == '"') { + key = lexer.scanSymbol(symbolTable, '"'); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + if (ch != ':') { + throw new JSONException("expect ':' at " + lexer.pos()); + } + } else if (ch == '}') { + lexer.next(); + lexer.resetStringPosition(); + lexer.nextToken(JSONToken.COMMA); + return object; + } else if (ch == '\'') { + if (!lexer.isEnabled(Feature.AllowSingleQuotes)) { + throw new JSONException("syntax error"); + } + + key = lexer.scanSymbol(symbolTable, '\''); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + if (ch != ':') { + throw new JSONException("expect ':' at " + lexer.pos()); + } + } else { + if (!lexer.isEnabled(Feature.AllowUnQuotedFieldNames)) { + throw new JSONException("syntax error"); + } + + key = lexer.scanSymbolUnQuoted(symbolTable); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + if (ch != ':') { + throw new JSONException("expect ':' at " + lexer.pos() + ", actual " + ch); + } + } + + lexer.next(); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + + lexer.resetStringPosition(); + + if (key == JSON.DEFAULT_TYPE_KEY && !lexer.isEnabled(Feature.DisableSpecialKeyDetect)) { + String typeName = lexer.scanSymbol(symbolTable, '"'); + + Class clazz = config.checkAutoType(typeName, null, lexer.getFeatures()); + + if (Map.class.isAssignableFrom(clazz) ) { + lexer.nextToken(JSONToken.COMMA); + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + return object; + } + continue; + } + + ObjectDeserializer deserializer = config.getDeserializer(clazz); + + lexer.nextToken(JSONToken.COMMA); + + setResolveStatus(DefaultJSONParser.TypeNameRedirect); + + if (context != null && !(fieldName instanceof Integer)) { + popContext(); + } + + return (Map) deserializer.deserialze(this, clazz, fieldName); + } + + Object value; + lexer.nextToken(); + + if (i != 0) { + setContext(context); + } + + Type valueType = object.getType(key); + + if (lexer.token() == JSONToken.NULL) { + value = null; + lexer.nextToken(); + } else { + value = parseObject(valueType, key); + } + + object.apply(key, value); + + setContext(context, value, key); + setContext(context); + + final int tok = lexer.token(); + if (tok == JSONToken.EOF || tok == JSONToken.RBRACKET) { + return object; + } + + if (tok == JSONToken.RBRACE) { + lexer.nextToken(); + return object; + } + } + } finally { + setContext(context); + } + } } diff --git a/src/main/java/com/alibaba/fastjson/parser/Feature.java b/src/main/java/com/alibaba/fastjson/parser/Feature.java old mode 100644 new mode 100755 index 19585e2241..86e3212a5e --- a/src/main/java/com/alibaba/fastjson/parser/Feature.java +++ b/src/main/java/com/alibaba/fastjson/parser/Feature.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,9 @@ */ package com.alibaba.fastjson.parser; + /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public enum Feature { /** @@ -60,37 +61,118 @@ public enum Feature { IgnoreNotMatch, /** - * + * @since 1.1.3 */ SortFeidFastMatch, /** + * @since 1.1.3 + */ + DisableASM, + + /** + * @since 1.1.7 + */ + DisableCircularReferenceDetect, + + /** + * @since 1.1.10 + */ + InitStringFieldAsEmpty, + + /** + * @since 1.1.35 * */ - DisableASM + SupportArrayToBean, + + /** + * @since 1.2.3 + * + */ + OrderedField, + + /** + * @since 1.2.5 + * + */ + DisableSpecialKeyDetect, + + /** + * @since 1.2.9 + */ + UseObjectArray, + + /** + * @since 1.2.22, 1.1.54.android + */ + SupportNonPublicField, + + /** + * @since 1.2.29 + * + * disable autotype key '@type' + */ + IgnoreAutoType, + + /** + * @since 1.2.30 + * + * disable field smart match, improve performance in some scenarios. + */ + DisableFieldSmartMatch, + + /** + * @since 1.2.41, backport to 1.1.66.android + */ + SupportAutoType, + + /** + * @since 1.2.42 + */ + NonStringKeyAsString, + + /** + * @since 1.2.45 + */ + CustomMapDeserializer ; - private Feature(){ + Feature(){ mask = (1 << ordinal()); } - private final int mask; + public final int mask; public final int getMask() { return mask; } public static boolean isEnabled(int features, Feature feature) { - return (features & feature.getMask()) != 0; + return (features & feature.mask) != 0; } public static int config(int features, Feature feature, boolean state) { if (state) { - features |= feature.getMask(); + features |= feature.mask; } else { - features &= ~feature.getMask(); + features &= ~feature.mask; } return features; } + + public static int of(Feature[] features) { + if (features == null) { + return 0; + } + + int value = 0; + + for (Feature feature: features) { + value |= feature.mask; + } + + return value; + } } diff --git a/src/main/java/com/alibaba/fastjson/parser/JSONLexer.java b/src/main/java/com/alibaba/fastjson/parser/JSONLexer.java index d4f19874b8..248eac66ec 100644 --- a/src/main/java/com/alibaba/fastjson/parser/JSONLexer.java +++ b/src/main/java/com/alibaba/fastjson/parser/JSONLexer.java @@ -1,83 +1,108 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.parser; - -import java.math.BigDecimal; -import java.util.Calendar; - -/** - * @author wenshao - */ -public interface JSONLexer { - - void nextToken(); - - void nextToken(int expect); - - int token(); - - int pos(); - - String stringVal(); - - Number integerValue(); - - void nextTokenWithColon(int expect); - - BigDecimal decimalValue(); - - double doubleValue(); - - float floatValue(); - - void config(Feature feature, boolean state); - - boolean isEnabled(Feature feature); - - String numberString(); - - boolean isEOF(); - - String symbol(SymbolTable symbolTable); - - boolean isBlankInput(); - - char getCurrent(); - - void skipWhitespace(); - - void incrementBufferPosition(); - - String scanSymbol(final SymbolTable symbolTable); - - String scanSymbol(final SymbolTable symbolTable, final char quote); - - void resetStringPosition(); - - String scanSymbolUnQuoted(final SymbolTable symbolTable); - - void scanString(); - - void scanNumber(); - - boolean scanISO8601DateIfMatch(); - - Calendar getCalendar(); - - int intValue() throws NumberFormatException; - - long longValue() throws NumberFormatException; -} +package com.alibaba.fastjson.parser; + +import java.math.BigDecimal; +import java.util.Collection; +import java.util.Locale; +import java.util.TimeZone; + +public interface JSONLexer { + + char EOI = 0x1A; + int NOT_MATCH = -1; + int NOT_MATCH_NAME = -2; + int UNKNOWN = 0; + int OBJECT = 1; + int ARRAY = 2; + int VALUE = 3; + int END = 4; + int VALUE_NULL = 5; + + int token(); + + String tokenName(); + + void skipWhitespace(); + + void nextToken(); + + void nextToken(int expect); + + char getCurrent(); + + char next(); + + String scanSymbol(final SymbolTable symbolTable); + + String scanSymbol(final SymbolTable symbolTable, final char quote); + + void resetStringPosition(); + + void scanNumber(); + + int pos(); + + Number integerValue(); + + BigDecimal decimalValue(); + + Number decimalValue(boolean decimal); + + String scanSymbolUnQuoted(final SymbolTable symbolTable); + + String stringVal(); + + boolean isEnabled(int feature); + + boolean isEnabled(Feature feature); + + void config(Feature feature, boolean state); + + void scanString(); + + int intValue(); + + void nextTokenWithColon(); + + void nextTokenWithColon(int expect); + + boolean isBlankInput(); + + void close(); + + long longValue(); + + boolean isRef(); + + String numberString(); + + byte[] bytesValue(); + + float floatValue(); + + int scanInt(char expectNext); + long scanLong(char expectNextChar); + float scanFloat(char seperator); + double scanDouble(char seperator); + boolean scanBoolean(char expectNext); + BigDecimal scanDecimal(char seperator); + + String scanString(char expectNextChar); + + Enum scanEnum(Class enumClass, final SymbolTable symbolTable, char serperator); + + String scanSymbolWithSeperator(final SymbolTable symbolTable, char serperator); + + void scanStringArray(Collection collection, char seperator); + + TimeZone getTimeZone(); + + void setTimeZone(TimeZone timeZone); + + Locale getLocale(); + + void setLocale(Locale locale); + + String info(); + + int getFeatures(); +} diff --git a/src/main/java/com/alibaba/fastjson/parser/JSONLexerBase.java b/src/main/java/com/alibaba/fastjson/parser/JSONLexerBase.java new file mode 100755 index 0000000000..3402110474 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/JSONLexerBase.java @@ -0,0 +1,5113 @@ +/* + * Copyright 1999-2017 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.parser; + +import java.io.Closeable; +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.util.*; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.util.IOUtils; +import com.alibaba.fastjson.util.TypeUtils; + +import static com.alibaba.fastjson.parser.JSONToken.*; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public abstract class JSONLexerBase implements JSONLexer, Closeable { + + protected void lexError(String key, Object... args) { + token = ERROR; + } + + protected int token; + protected int pos; + protected int features; + + protected char ch; + protected int bp; + + protected int eofPos; + + /** + * A character buffer for literals. + */ + protected char[] sbuf; + protected int sp; + + /** + * number start position + */ + protected int np; + + protected boolean hasSpecial; + + protected Calendar calendar = null; + protected TimeZone timeZone = JSON.defaultTimeZone; + protected Locale locale = JSON.defaultLocale; + + public int matchStat = UNKNOWN; + + private final static ThreadLocal SBUF_LOCAL = new ThreadLocal(); + + protected String stringDefaultValue = null; + + public JSONLexerBase(int features){ + this.features = features; + + if ((features & Feature.InitStringFieldAsEmpty.mask) != 0) { + stringDefaultValue = ""; + } + + sbuf = SBUF_LOCAL.get(); + + if (sbuf == null) { + sbuf = new char[512]; + } + } + + public final int matchStat() { + return matchStat; + } + + /** + * internal method, don't invoke + * @param token + */ + public void setToken(int token) { + this.token = token; + } + + public final void nextToken() { + sp = 0; + + for (;;) { + pos = bp; + + if (ch == '/') { + skipComment(); + continue; + } + + if (ch == '"') { + scanString(); + return; + } + + if (ch == ',') { + next(); + token = COMMA; + return; + } + + if (ch >= '0' && ch <= '9') { + scanNumber(); + return; + } + + if (ch == '-') { + scanNumber(); + return; + } + + switch (ch) { + case '\'': + if (!isEnabled(Feature.AllowSingleQuotes)) { + throw new JSONException("Feature.AllowSingleQuotes is false"); + } + scanStringSingleQuote(); + return; + case ' ': + case '\t': + case '\b': + case '\f': + case '\n': + case '\r': + next(); + break; + case 't': // true + scanTrue(); + return; + case 'f': // false + scanFalse(); + return; + case 'n': // new,null + scanNullOrNew(); + return; + case 'T': + case 'N': // NULL + case 'S': + case 'u': // undefined + scanIdent(); + return; + case '(': + next(); + token = LPAREN; + return; + case ')': + next(); + token = RPAREN; + return; + case '[': + next(); + token = LBRACKET; + return; + case ']': + next(); + token = RBRACKET; + return; + case '{': + next(); + token = LBRACE; + return; + case '}': + next(); + token = RBRACE; + return; + case ':': + next(); + token = COLON; + return; + case ';': + next(); + token = SEMI; + return; + case '.': + next(); + token = DOT; + return; + case '+': + next(); + scanNumber(); + return; + case 'x': + scanHex(); + return; + default: + if (isEOF()) { // JLS + if (token == EOF) { + throw new JSONException("EOF error"); + } + + token = EOF; + pos = bp = eofPos; + } else { + if (ch <= 31 || ch == 127) { + next(); + break; + } + + lexError("illegal.char", String.valueOf((int) ch)); + next(); + } + + return; + } + } + + } + + public final void nextToken(int expect) { + sp = 0; + + for (;;) { + switch (expect) { + case JSONToken.LBRACE: + if (ch == '{') { + token = JSONToken.LBRACE; + next(); + return; + } + if (ch == '[') { + token = JSONToken.LBRACKET; + next(); + return; + } + break; + case JSONToken.COMMA: + if (ch == ',') { + token = JSONToken.COMMA; + next(); + return; + } + + if (ch == '}') { + token = JSONToken.RBRACE; + next(); + return; + } + + if (ch == ']') { + token = JSONToken.RBRACKET; + next(); + return; + } + + if (ch == EOI) { + token = JSONToken.EOF; + return; + } + break; + case JSONToken.LITERAL_INT: + if (ch >= '0' && ch <= '9') { + pos = bp; + scanNumber(); + return; + } + + if (ch == '"') { + pos = bp; + scanString(); + return; + } + + if (ch == '[') { + token = JSONToken.LBRACKET; + next(); + return; + } + + if (ch == '{') { + token = JSONToken.LBRACE; + next(); + return; + } + + break; + case JSONToken.LITERAL_STRING: + if (ch == '"') { + pos = bp; + scanString(); + return; + } + + if (ch >= '0' && ch <= '9') { + pos = bp; + scanNumber(); + return; + } + + if (ch == '[') { + token = JSONToken.LBRACKET; + next(); + return; + } + + if (ch == '{') { + token = JSONToken.LBRACE; + next(); + return; + } + break; + case JSONToken.LBRACKET: + if (ch == '[') { + token = JSONToken.LBRACKET; + next(); + return; + } + + if (ch == '{') { + token = JSONToken.LBRACE; + next(); + return; + } + break; + case JSONToken.RBRACKET: + if (ch == ']') { + token = JSONToken.RBRACKET; + next(); + return; + } + case JSONToken.EOF: + if (ch == EOI) { + token = JSONToken.EOF; + return; + } + break; + case JSONToken.IDENTIFIER: + nextIdent(); + return; + default: + break; + } + + if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b') { + next(); + continue; + } + + nextToken(); + break; + } + } + + public final void nextIdent() { + while (isWhitespace(ch)) { + next(); + } + if (ch == '_' || ch == '$' || Character.isLetter(ch)) { + scanIdent(); + } else { + nextToken(); + } + } + + public final void nextTokenWithColon() { + nextTokenWithChar(':'); + } + + public final void nextTokenWithChar(char expect) { + sp = 0; + + for (;;) { + if (ch == expect) { + next(); + nextToken(); + return; + } + + if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b') { + next(); + continue; + } + + throw new JSONException("not match " + expect + " - " + ch + ", info : " + this.info()); + } + } + + public final int token() { + return token; + } + + public final String tokenName() { + return JSONToken.name(token); + } + + public final int pos() { + return pos; + } + + public final String stringDefaultValue() { + return stringDefaultValue; + } + + public final Number integerValue() throws NumberFormatException { + long result = 0; + boolean negative = false; + if (np == -1) { + np = 0; + } + int i = np, max = np + sp; + long limit; + long multmin; + int digit; + + char type = ' '; + + switch (charAt(max - 1)) { + case 'L': + max--; + type = 'L'; + break; + case 'S': + max--; + type = 'S'; + break; + case 'B': + max--; + type = 'B'; + break; + default: + break; + } + + if (charAt(np) == '-') { + negative = true; + limit = Long.MIN_VALUE; + i++; + } else { + limit = -Long.MAX_VALUE; + } + multmin = MULTMIN_RADIX_TEN; + if (i < max) { + digit = charAt(i++) - '0'; + result = -digit; + } + while (i < max) { + // Accumulating negatively avoids surprises near MAX_VALUE + digit = charAt(i++) - '0'; + if (result < multmin) { + return new BigInteger(numberString()); + } + result *= 10; + if (result < limit + digit) { + return new BigInteger(numberString()); + } + result -= digit; + } + + if (negative) { + if (i > np + 1) { + if (result >= Integer.MIN_VALUE && type != 'L') { + if (type == 'S') { + return (short) result; + } + + if (type == 'B') { + return (byte) result; + } + + return (int) result; + } + return result; + } else { /* Only got "-" */ + throw new NumberFormatException(numberString()); + } + } else { + result = -result; + if (result <= Integer.MAX_VALUE && type != 'L') { + if (type == 'S') { + return (short) result; + } + + if (type == 'B') { + return (byte) result; + } + + return (int) result; + } + return result; + } + } + + public final void nextTokenWithColon(int expect) { + nextTokenWithChar(':'); + } + + public float floatValue() { + String strVal = numberString(); + float floatValue = Float.parseFloat(strVal); + if (floatValue == 0 || floatValue == Float.POSITIVE_INFINITY) { + char c0 = strVal.charAt(0); + if (c0 > '0' && c0 <= '9') { + throw new JSONException("float overflow : " + strVal); + } + } + return floatValue; + } + + public double doubleValue() { + return Double.parseDouble(numberString()); + } + + public void config(Feature feature, boolean state) { + features = Feature.config(features, feature, state); + + if ((features & Feature.InitStringFieldAsEmpty.mask) != 0) { + stringDefaultValue = ""; + } + } + + public final boolean isEnabled(Feature feature) { + return isEnabled(feature.mask); + } + + public final boolean isEnabled(int feature) { + return (this.features & feature) != 0; + } + + public final boolean isEnabled(int features, int feature) { + return (this.features & feature) != 0 || (features & feature) != 0; + } + + public abstract String numberString(); + + public abstract boolean isEOF(); + + public final char getCurrent() { + return ch; + } + + public abstract char charAt(int index); + + // public final char next() { + // ch = doNext(); + //// if (ch == '/' && (this.features & Feature.AllowComment.mask) != 0) { + //// skipComment(); + //// } + // return ch; + // } + + public abstract char next(); + + protected void skipComment() { + next(); + if (ch == '/') { + for (;;) { + next(); + if (ch == '\n') { + next(); + return; + } else if (ch == EOI) { + return; + } + } + } else if (ch == '*') { + next(); + + for (; ch != EOI;) { + if (ch == '*') { + next(); + if (ch == '/') { + next(); + return; + } else { + continue; + } + } + next(); + } + } else { + throw new JSONException("invalid comment"); + } + } + + public final String scanSymbol(final SymbolTable symbolTable) { + skipWhitespace(); + + if (ch == '"') { + return scanSymbol(symbolTable, '"'); + } + + if (ch == '\'') { + if (!isEnabled(Feature.AllowSingleQuotes)) { + throw new JSONException("syntax error"); + } + + return scanSymbol(symbolTable, '\''); + } + + if (ch == '}') { + next(); + token = JSONToken.RBRACE; + return null; + } + + if (ch == ',') { + next(); + token = JSONToken.COMMA; + return null; + } + + if (ch == EOI) { + token = JSONToken.EOF; + return null; + } + + if (!isEnabled(Feature.AllowUnQuotedFieldNames)) { + throw new JSONException("syntax error"); + } + + return scanSymbolUnQuoted(symbolTable); + } + + // public abstract String scanSymbol(final SymbolTable symbolTable, final char quote); + + protected abstract void arrayCopy(int srcPos, char[] dest, int destPos, int length); + + public final String scanSymbol(final SymbolTable symbolTable, final char quote) { + int hash = 0; + + np = bp; + sp = 0; + boolean hasSpecial = false; + char chLocal; + for (;;) { + chLocal = next(); + + if (chLocal == quote) { + break; + } + + if (chLocal == EOI) { + throw new JSONException("unclosed.str"); + } + + if (chLocal == '\\') { + if (!hasSpecial) { + hasSpecial = true; + + if (sp >= sbuf.length) { + int newCapcity = sbuf.length * 2; + if (sp > newCapcity) { + newCapcity = sp; + } + char[] newsbuf = new char[newCapcity]; + System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length); + sbuf = newsbuf; + } + + // text.getChars(np + 1, np + 1 + sp, sbuf, 0); + // System.arraycopy(this.buf, np + 1, sbuf, 0, sp); + arrayCopy(np + 1, sbuf, 0, sp); + } + + chLocal = next(); + + switch (chLocal) { + case '0': + hash = 31 * hash + (int) chLocal; + putChar('\0'); + break; + case '1': + hash = 31 * hash + (int) chLocal; + putChar('\1'); + break; + case '2': + hash = 31 * hash + (int) chLocal; + putChar('\2'); + break; + case '3': + hash = 31 * hash + (int) chLocal; + putChar('\3'); + break; + case '4': + hash = 31 * hash + (int) chLocal; + putChar('\4'); + break; + case '5': + hash = 31 * hash + (int) chLocal; + putChar('\5'); + break; + case '6': + hash = 31 * hash + (int) chLocal; + putChar('\6'); + break; + case '7': + hash = 31 * hash + (int) chLocal; + putChar('\7'); + break; + case 'b': // 8 + hash = 31 * hash + (int) '\b'; + putChar('\b'); + break; + case 't': // 9 + hash = 31 * hash + (int) '\t'; + putChar('\t'); + break; + case 'n': // 10 + hash = 31 * hash + (int) '\n'; + putChar('\n'); + break; + case 'v': // 11 + hash = 31 * hash + (int) '\u000B'; + putChar('\u000B'); + break; + case 'f': // 12 + case 'F': + hash = 31 * hash + (int) '\f'; + putChar('\f'); + break; + case 'r': // 13 + hash = 31 * hash + (int) '\r'; + putChar('\r'); + break; + case '"': // 34 + hash = 31 * hash + (int) '"'; + putChar('"'); + break; + case '\'': // 39 + hash = 31 * hash + (int) '\''; + putChar('\''); + break; + case '/': // 47 + hash = 31 * hash + (int) '/'; + putChar('/'); + break; + case '\\': // 92 + hash = 31 * hash + (int) '\\'; + putChar('\\'); + break; + case 'x': + char x1 = ch = next(); + char x2 = ch = next(); + + int x_val = digits[x1] * 16 + digits[x2]; + char x_char = (char) x_val; + hash = 31 * hash + (int) x_char; + putChar(x_char); + break; + case 'u': + char c1 = chLocal = next(); + char c2 = chLocal = next(); + char c3 = chLocal = next(); + char c4 = chLocal = next(); + int val = Integer.parseInt(new String(new char[] { c1, c2, c3, c4 }), 16); + hash = 31 * hash + val; + putChar((char) val); + break; + default: + this.ch = chLocal; + throw new JSONException("unclosed.str.lit"); + } + continue; + } + + hash = 31 * hash + chLocal; + + if (!hasSpecial) { + sp++; + continue; + } + + if (sp == sbuf.length) { + putChar(chLocal); + } else { + sbuf[sp++] = chLocal; + } + } + + token = LITERAL_STRING; + + String value; + if (!hasSpecial) { + // return this.text.substring(np + 1, np + 1 + sp).intern(); + int offset; + if (np == -1) { + offset = 0; + } else { + offset = np + 1; + } + value = addSymbol(offset, sp, hash, symbolTable); + } else { + value = symbolTable.addSymbol(sbuf, 0, sp, hash); + } + + sp = 0; + this.next(); + + return value; + } + + public final void resetStringPosition() { + this.sp = 0; + } + + public String info() { + return ""; + } + + public final String scanSymbolUnQuoted(final SymbolTable symbolTable) { + if (token == JSONToken.ERROR && pos == 0 && bp == 1) { + bp = 0; // adjust + } + final boolean[] firstIdentifierFlags = IOUtils.firstIdentifierFlags; + final char first = ch; + + final boolean firstFlag = ch >= firstIdentifierFlags.length || firstIdentifierFlags[first]; + if (!firstFlag) { + throw new JSONException("illegal identifier : " + ch // + + info()); + } + + final boolean[] identifierFlags = IOUtils.identifierFlags; + + int hash = first; + + np = bp; + sp = 1; + char chLocal; + for (;;) { + chLocal = next(); + + if (chLocal < identifierFlags.length) { + if (!identifierFlags[chLocal]) { + break; + } + } + + hash = 31 * hash + chLocal; + + sp++; + continue; + } + + this.ch = charAt(bp); + token = JSONToken.IDENTIFIER; + + final int NULL_HASH = 3392903; + if (sp == 4 && hash == NULL_HASH && charAt(np) == 'n' && charAt(np + 1) == 'u' && charAt(np + 2) == 'l' + && charAt(np + 3) == 'l') { + return null; + } + + // return text.substring(np, np + sp).intern(); + + if (symbolTable == null) { + return subString(np, sp); + } + + return this.addSymbol(np, sp, hash, symbolTable); + // return symbolTable.addSymbol(buf, np, sp, hash); + } + + protected abstract void copyTo(int offset, int count, char[] dest); + + public final void scanString() { + np = bp; + hasSpecial = false; + char ch; + for (;;) { + ch = next(); + + if (ch == '\"') { + break; + } + + if (ch == EOI) { + if (!isEOF()) { + putChar((char) EOI); + continue; + } + throw new JSONException("unclosed string : " + ch); + } + + if (ch == '\\') { + if (!hasSpecial) { + hasSpecial = true; + + if (sp >= sbuf.length) { + int newCapcity = sbuf.length * 2; + if (sp > newCapcity) { + newCapcity = sp; + } + char[] newsbuf = new char[newCapcity]; + System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length); + sbuf = newsbuf; + } + + copyTo(np + 1, sp, sbuf); + // text.getChars(np + 1, np + 1 + sp, sbuf, 0); + // System.arraycopy(buf, np + 1, sbuf, 0, sp); + } + + ch = next(); + + switch (ch) { + case '0': + putChar('\0'); + break; + case '1': + putChar('\1'); + break; + case '2': + putChar('\2'); + break; + case '3': + putChar('\3'); + break; + case '4': + putChar('\4'); + break; + case '5': + putChar('\5'); + break; + case '6': + putChar('\6'); + break; + case '7': + putChar('\7'); + break; + case 'b': // 8 + putChar('\b'); + break; + case 't': // 9 + putChar('\t'); + break; + case 'n': // 10 + putChar('\n'); + break; + case 'v': // 11 + putChar('\u000B'); + break; + case 'f': // 12 + case 'F': + putChar('\f'); + break; + case 'r': // 13 + putChar('\r'); + break; + case '"': // 34 + putChar('"'); + break; + case '\'': // 39 + putChar('\''); + break; + case '/': // 47 + putChar('/'); + break; + case '\\': // 92 + putChar('\\'); + break; + case 'x': + char x1 = ch = next(); + char x2 = ch = next(); + + int x_val = digits[x1] * 16 + digits[x2]; + char x_char = (char) x_val; + putChar(x_char); + break; + case 'u': + char u1 = ch = next(); + char u2 = ch = next(); + char u3 = ch = next(); + char u4 = ch = next(); + int val = Integer.parseInt(new String(new char[] { u1, u2, u3, u4 }), 16); + putChar((char) val); + break; + default: + this.ch = ch; + throw new JSONException("unclosed string : " + ch); + } + continue; + } + + if (!hasSpecial) { + sp++; + continue; + } + + if (sp == sbuf.length) { + putChar(ch); + } else { + sbuf[sp++] = ch; + } + } + + token = JSONToken.LITERAL_STRING; + this.ch = next(); + } + + public Calendar getCalendar() { + return this.calendar; + } + + public TimeZone getTimeZone() { + return timeZone; + } + + public void setTimeZone(TimeZone timeZone) { + this.timeZone = timeZone; + } + + public Locale getLocale() { + return locale; + } + + public void setLocale(Locale locale) { + this.locale = locale; + } + + public final int intValue() { + if (np == -1) { + np = 0; + } + + int result = 0; + boolean negative = false; + int i = np, max = np + sp; + int limit; + int digit; + + if (charAt(np) == '-') { + negative = true; + limit = Integer.MIN_VALUE; + i++; + } else { + limit = -Integer.MAX_VALUE; + } + long multmin = INT_MULTMIN_RADIX_TEN; + if (i < max) { + digit = charAt(i++) - '0'; + result = -digit; + } + while (i < max) { + // Accumulating negatively avoids surprises near MAX_VALUE + char chLocal = charAt(i++); + + if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B') { + break; + } + + digit = chLocal - '0'; + + if (result < multmin) { + throw new NumberFormatException(numberString()); + } + result *= 10; + if (result < limit + digit) { + throw new NumberFormatException(numberString()); + } + result -= digit; + } + + if (negative) { + if (i > np + 1) { + return result; + } else { /* Only got "-" */ + throw new NumberFormatException(numberString()); + } + } else { + return -result; + } + } + + public abstract byte[] bytesValue(); + + public void close() { + if (sbuf.length <= 1024 * 8) { + SBUF_LOCAL.set(sbuf); + } + this.sbuf = null; + } + + public final boolean isRef() { + if (sp != 4) { + return false; + } + + return charAt(np + 1) == '$' // + && charAt(np + 2) == 'r' // + && charAt(np + 3) == 'e' // + && charAt(np + 4) == 'f'; + } + + protected final static char[] typeFieldName = ("\"" + JSON.DEFAULT_TYPE_KEY + "\":\"").toCharArray(); + + public final int scanType(String type) { + matchStat = UNKNOWN; + + if (!charArrayCompare(typeFieldName)) { + return NOT_MATCH_NAME; + } + + int bpLocal = this.bp + typeFieldName.length; + + final int typeLength = type.length(); + for (int i = 0; i < typeLength; ++i) { + if (type.charAt(i) != charAt(bpLocal + i)) { + return NOT_MATCH; + } + } + bpLocal += typeLength; + if (charAt(bpLocal) != '"') { + return NOT_MATCH; + } + + this.ch = charAt(++bpLocal); + + if (ch == ',') { + this.ch = charAt(++bpLocal); + this.bp = bpLocal; + token = JSONToken.COMMA; + return VALUE; + } else if (ch == '}') { + ch = charAt(++bpLocal); + if (ch == ',') { + token = JSONToken.COMMA; + this.ch = charAt(++bpLocal); + } else if (ch == ']') { + token = JSONToken.RBRACKET; + this.ch = charAt(++bpLocal); + } else if (ch == '}') { + token = JSONToken.RBRACE; + this.ch = charAt(++bpLocal); + } else if (ch == EOI) { + token = JSONToken.EOF; + } else { + return NOT_MATCH; + } + matchStat = END; + } + + this.bp = bpLocal; + return matchStat; + } + + public final boolean matchField(char[] fieldName) { + for (;;) { + if (!charArrayCompare(fieldName)) { + if (isWhitespace(ch)) { + next(); + continue; + } + return false; + } else { + break; + } + } + + bp = bp + fieldName.length; + ch = charAt(bp); + + if (ch == '{') { + next(); + token = JSONToken.LBRACE; + } else if (ch == '[') { + next(); + token = JSONToken.LBRACKET; + } else if (ch == 'S' && charAt(bp + 1) == 'e' && charAt(bp + 2) == 't' && charAt(bp + 3) == '[') { + bp += 3; + ch = charAt(bp); + token = JSONToken.SET; + } else { + nextToken(); + } + + return true; + } + + public abstract int indexOf(char ch, int startIndex); + + public abstract String addSymbol(int offset, int len, int hash, final SymbolTable symbolTable); + + public String scanFieldString(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return stringDefaultValue(); + } + + // int index = bp + fieldName.length; + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + + if (chLocal != '"') { + matchStat = NOT_MATCH; + + return stringDefaultValue(); + } + + final String strVal; + { + int startIndex = bp + fieldName.length + 1; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); + } + + int startIndex2 = bp + fieldName.length + 1; // must re compute + String stringVal = subString(startIndex2, endIndex - startIndex2); + if (stringVal.indexOf('\\') != -1) { + for (;;) { + int slashCount = 0; + for (int i = endIndex - 1; i >= 0; --i) { + if (charAt(i) == '\\') { + slashCount++; + } else { + break; + } + } + if (slashCount % 2 == 0) { + break; + } + endIndex = indexOf('"', endIndex + 1); + } + + int chars_len = endIndex - (bp + fieldName.length + 1); + char[] chars = sub_chars( bp + fieldName.length + 1, chars_len); + + stringVal = readString(chars, chars_len); + } + + offset += (endIndex - (bp + fieldName.length + 1) + 1); + chLocal = charAt(bp + (offset++)); + strVal = stringVal; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + return strVal; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return stringDefaultValue(); + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return stringDefaultValue(); + } + + return strVal; + } + + public String scanString(char expectNextChar) { + matchStat = UNKNOWN; + + int offset = 0; + char chLocal = charAt(bp + (offset++)); + + if (chLocal == 'n') { + if (charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + offset += 3; + chLocal = charAt(bp + (offset++)); + } else { + matchStat = NOT_MATCH; + return null; + } + + if (chLocal == expectNextChar) { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + return null; + } else { + matchStat = NOT_MATCH; + return null; + } + } + + + + final String strVal; + for (;;) { + if (chLocal == '"') { + int startIndex = bp + offset; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); + } + + String stringVal = subString(bp + offset, endIndex - startIndex); + if (stringVal.indexOf('\\') != -1) { + for (; ; ) { + int slashCount = 0; + for (int i = endIndex - 1; i >= 0; --i) { + if (charAt(i) == '\\') { + slashCount++; + } else { + break; + } + } + if (slashCount % 2 == 0) { + break; + } + endIndex = indexOf('"', endIndex + 1); + } + + int chars_len = endIndex - startIndex; + char[] chars = sub_chars(bp + 1, chars_len); + + stringVal = readString(chars, chars_len); + } + + offset += (endIndex - startIndex + 1); + chLocal = charAt(bp + (offset++)); + strVal = stringVal; + break; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(bp + (offset++)); + continue; + } else { + matchStat = NOT_MATCH; + + return stringDefaultValue(); + } + } + + for (;;) { + if (chLocal == expectNextChar) { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE; + return strVal; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(bp + (offset++)); + continue; + } else { + matchStat = NOT_MATCH; + return strVal; + } + } + } + + public long scanFieldSymbol(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return 0; + } + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + + if (chLocal != '"') { + matchStat = NOT_MATCH; + return 0; + } + + long hash = 0xcbf29ce484222325L; + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal == '\"') { + chLocal = charAt(bp + (offset++)); + break; + } + + hash ^= chLocal; + hash *= 0x100000001b3L; + + if (chLocal == '\\') { + matchStat = NOT_MATCH; + return 0; + } + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + return hash; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return 0; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return 0; + } + + return hash; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public Enum scanEnum(Class enumClass, final SymbolTable symbolTable, char serperator) { + String name = scanSymbolWithSeperator(symbolTable, serperator); + if (name == null) { + return null; + } + return Enum.valueOf((Class) enumClass, name); + } + + public String scanSymbolWithSeperator(final SymbolTable symbolTable, char serperator) { + matchStat = UNKNOWN; + + int offset = 0; + char chLocal = charAt(bp + (offset++)); + + if (chLocal == 'n') { + if (charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + offset += 3; + chLocal = charAt(bp + (offset++)); + } else { + matchStat = NOT_MATCH; + return null; + } + + if (chLocal == serperator) { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + return null; + } else { + matchStat = NOT_MATCH; + return null; + } + } + + if (chLocal != '"') { + matchStat = NOT_MATCH; + return null; + } + + String strVal; + // int start = index; + int hash = 0; + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal == '\"') { + // bp = index; + // this.ch = chLocal = charAt(bp); + int start = bp + 0 + 1; + int len = bp + offset - start - 1; + strVal = addSymbol(start, len, hash, symbolTable); + chLocal = charAt(bp + (offset++)); + break; + } + + hash = 31 * hash + chLocal; + + if (chLocal == '\\') { + matchStat = NOT_MATCH; + return null; + } + } + + for (;;) { + if (chLocal == serperator) { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + return strVal; + } else { + if (isWhitespace(chLocal)) { + chLocal = charAt(bp + (offset++)); + continue; + } + + matchStat = NOT_MATCH; + return strVal; + } + } + } + + public Collection newCollectionByType(Class type){ + if (type.isAssignableFrom(HashSet.class)) { + HashSet list = new HashSet(); + return list; + } else if (type.isAssignableFrom(ArrayList.class)) { + ArrayList list2 = new ArrayList(); + return list2; + } else { + try { + Collection list = (Collection) type.newInstance(); + return list; + } catch (Exception e) { + throw new JSONException(e.getMessage(), e); + } + } + } + + @SuppressWarnings("unchecked") + public Collection scanFieldStringArray(char[] fieldName, Class type) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return null; + } + + Collection list = newCollectionByType(type); + +// if (type.isAssignableFrom(HashSet.class)) { +// list = new HashSet(); +// } else if (type.isAssignableFrom(ArrayList.class)) { +// list = new ArrayList(); +// } else { +// try { +// list = (Collection) type.newInstance(); +// } catch (Exception e) { +// throw new JSONException(e.getMessage(), e); +// } +// } + + // int index = bp + fieldName.length; + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + + if (chLocal != '[') { + matchStat = NOT_MATCH; + return null; + } + + chLocal = charAt(bp + (offset++)); + + for (;;) { + // int start = index; + if (chLocal == '"') { + int startIndex = bp + offset; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); + } + + int startIndex2 = bp + offset; // must re compute + String stringVal = subString(startIndex2, endIndex - startIndex2); + if (stringVal.indexOf('\\') != -1) { + for (;;) { + int slashCount = 0; + for (int i = endIndex - 1; i >= 0; --i) { + if (charAt(i) == '\\') { + slashCount++; + } else { + break; + } + } + if (slashCount % 2 == 0) { + break; + } + endIndex = indexOf('"', endIndex + 1); + } + + int chars_len = endIndex - (bp + offset); + char[] chars = sub_chars(bp + offset, chars_len); + + stringVal = readString(chars, chars_len); + } + + offset += (endIndex - (bp + offset) + 1); + chLocal = charAt(bp + (offset++)); + + list.add(stringVal); + } else if (chLocal == 'n' // + && charAt(bp + offset) == 'u' // + && charAt(bp + offset + 1) == 'l' // + && charAt(bp + offset + 2) == 'l') { + offset += 3; + chLocal = charAt(bp + (offset++)); + list.add(null); + } else if (chLocal == ']' && list.size() == 0) { + chLocal = charAt(bp + (offset++)); + break; + } else { + throw new JSONException("illega str"); + } + + if (chLocal == ',') { + chLocal = charAt(bp + (offset++)); + continue; + } + + if (chLocal == ']') { + chLocal = charAt(bp + (offset++)); + break; + } + + matchStat = NOT_MATCH; + return null; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + return list; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + bp += (offset - 1); + token = JSONToken.EOF; + this.ch = EOI; + } else { + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return null; + } + + return list; + } + + public void scanStringArray(Collection list, char seperator) { + matchStat = UNKNOWN; + + int offset = 0; + char chLocal = charAt(bp + (offset++)); + + if (chLocal == 'n' + && charAt(bp + offset) == 'u' + && charAt(bp + offset + 1) == 'l' + && charAt(bp + offset + 2) == 'l' + && charAt(bp + offset + 3) == seperator + ) { + bp += 5; + ch = charAt(bp); + matchStat = VALUE_NULL; + return; + } + + if (chLocal != '[') { + matchStat = NOT_MATCH; + return; + } + + chLocal = charAt(bp + (offset++)); + + for (;;) { + if (chLocal == 'n' // + && charAt(bp + offset) == 'u' // + && charAt(bp + offset + 1) == 'l' // + && charAt(bp + offset + 2) == 'l') { + offset += 3; + chLocal = charAt(bp + (offset++)); + list.add(null); + } else if (chLocal == ']' && list.size() == 0) { + chLocal = charAt(bp + (offset++)); + break; + } else if (chLocal != '"') { + matchStat = NOT_MATCH; + return; + } else { + int startIndex = bp + offset; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); + } + + String stringVal = subString(bp + offset, endIndex - startIndex); + if (stringVal.indexOf('\\') != -1) { + for (;;) { + int slashCount = 0; + for (int i = endIndex - 1; i >= 0; --i) { + if (charAt(i) == '\\') { + slashCount++; + } else { + break; + } + } + if (slashCount % 2 == 0) { + break; + } + endIndex = indexOf('"', endIndex + 1); + } + + int chars_len = endIndex - startIndex; + char[] chars = sub_chars(bp + offset, chars_len); + + stringVal = readString(chars, chars_len); + } + + offset += (endIndex - (bp + offset) + 1); + chLocal = charAt(bp + (offset++)); + list.add(stringVal); + } + + if (chLocal == ',') { + chLocal = charAt(bp + (offset++)); + continue; + } + + if (chLocal == ']') { + chLocal = charAt(bp + (offset++)); + break; + } + + matchStat = NOT_MATCH; + return; + } + + if (chLocal == seperator) { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + return; + } else { + matchStat = NOT_MATCH; + return; + } + } + + public int scanFieldInt(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return 0; + } + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + + final boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + int value; + if (chLocal >= '0' && chLocal <= '9') { + value = chLocal - '0'; + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + value = value * 10 + (chLocal - '0'); + } else if (chLocal == '.') { + matchStat = NOT_MATCH; + return 0; + } else { + break; + } + } + if (value < 0 // + || offset > 11 + 3 + fieldName.length) { + if (value != Integer.MIN_VALUE // + || offset != 17 // + || !negative) { + matchStat = NOT_MATCH; + return 0; + } + } + } else { + matchStat = NOT_MATCH; + return 0; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return negative ? -value : value; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return 0; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return 0; + } + + return negative ? -value : value; + } + + public final int[] scanFieldIntArray(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return null; + } + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + + if (chLocal != '[') { + matchStat = NOT_MATCH_NAME; + return null; + } + chLocal = charAt(bp + (offset++)); + + int[] array = new int[16]; + int arrayIndex = 0; + + if (chLocal == ']') { + chLocal = charAt(bp + (offset++)); + } else { + for (;;) { + boolean nagative = false; + if (chLocal == '-') { + chLocal = charAt(bp + (offset++)); + nagative = true; + } + if (chLocal >= '0' && chLocal <= '9') { + int value = chLocal - '0'; + for (; ; ) { + chLocal = charAt(bp + (offset++)); + + if (chLocal >= '0' && chLocal <= '9') { + value = value * 10 + (chLocal - '0'); + } else { + break; + } + } + + if (arrayIndex >= array.length) { + int[] tmp = new int[array.length * 3 / 2]; + System.arraycopy(array, 0, tmp, 0, arrayIndex); + array = tmp; + } + array[arrayIndex++] = nagative ? -value : value; + + if (chLocal == ',') { + chLocal = charAt(bp + (offset++)); + } else if (chLocal == ']') { + chLocal = charAt(bp + (offset++)); + break; + } + } else { + matchStat = NOT_MATCH; + return null; + } + } + } + + + if (arrayIndex != array.length) { + int[] tmp = new int[arrayIndex]; + System.arraycopy(array, 0, tmp, 0, arrayIndex); + array = tmp; + } + + if (chLocal == ',') { + bp += (offset - 1); + this.next(); + matchStat = VALUE; + token = JSONToken.COMMA; + return array; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += (offset - 1); + this.next(); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += (offset - 1); + this.next(); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += (offset - 1); + this.next(); + } else if (chLocal == EOI) { + bp += (offset - 1); + token = JSONToken.EOF; + ch = EOI; + } else { + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return null; + } + + return array; + } + + public boolean scanBoolean(char expectNext) { + matchStat = UNKNOWN; + + int offset = 0; + char chLocal = charAt(bp + (offset++)); + + boolean value = false; + if (chLocal == 't') { + if (charAt(bp + offset) == 'r' // + && charAt(bp + offset + 1) == 'u' // + && charAt(bp + offset + 2) == 'e') { + offset += 3; + chLocal = charAt(bp + (offset++)); + value = true; + } else { + matchStat = NOT_MATCH; + return false; + } + } else if (chLocal == 'f') { + if (charAt(bp + offset) == 'a' // + && charAt(bp + offset + 1) == 'l' // + && charAt(bp + offset + 2) == 's' // + && charAt(bp + offset + 3) == 'e') { + offset += 4; + chLocal = charAt(bp + (offset++)); + value = false; + } else { + matchStat = NOT_MATCH; + return false; + } + } else if (chLocal == '1') { + chLocal = charAt(bp + (offset++)); + value = true; + } else if (chLocal == '0') { + chLocal = charAt(bp + (offset++)); + value = false; + } + + for (;;) { + if (chLocal == expectNext) { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + return value; + } else { + if (isWhitespace(chLocal)) { + chLocal = charAt(bp + (offset++)); + continue; + } + matchStat = NOT_MATCH; + return value; + } + } + } + + public int scanInt(char expectNext) { + matchStat = UNKNOWN; + + int offset = 0; + char chLocal = charAt(bp + (offset++)); + + final boolean quote = chLocal == '"'; + if (quote) { + chLocal = charAt(bp + (offset++)); + } + + final boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + int value; + if (chLocal >= '0' && chLocal <= '9') { + value = chLocal - '0'; + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + value = value * 10 + (chLocal - '0'); + } else if (chLocal == '.') { + matchStat = NOT_MATCH; + return 0; + } else { + break; + } + } + if (value < 0) { + matchStat = NOT_MATCH; + return 0; + } + } else if (chLocal == 'n' && charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + matchStat = VALUE_NULL; + value = 0; + offset += 3; + chLocal = charAt(bp + offset++); + + if (quote && chLocal == '"') { + chLocal = charAt(bp + offset++); + } + + for (;;) { + if (chLocal == ',') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == ']') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACKET; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(bp + offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return 0; + } else { + matchStat = NOT_MATCH; + return 0; + } + + for (;;) { + if (chLocal == expectNext) { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return negative ? -value : value; + } else { + if (isWhitespace(chLocal)) { + chLocal = charAt(bp + (offset++)); + continue; + } + matchStat = NOT_MATCH; + return negative ? -value : value; + } + } + } + + public boolean scanFieldBoolean(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return false; + } + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + + boolean value; + if (chLocal == 't') { + if (charAt(bp + (offset++)) != 'r') { + matchStat = NOT_MATCH; + return false; + } + if (charAt(bp + (offset++)) != 'u') { + matchStat = NOT_MATCH; + return false; + } + if (charAt(bp + (offset++)) != 'e') { + matchStat = NOT_MATCH; + return false; + } + + value = true; + } else if (chLocal == 'f') { + if (charAt(bp + (offset++)) != 'a') { + matchStat = NOT_MATCH; + return false; + } + if (charAt(bp + (offset++)) != 'l') { + matchStat = NOT_MATCH; + return false; + } + if (charAt(bp + (offset++)) != 's') { + matchStat = NOT_MATCH; + return false; + } + if (charAt(bp + (offset++)) != 'e') { + matchStat = NOT_MATCH; + return false; + } + + value = false; + } else { + matchStat = NOT_MATCH; + return false; + } + + chLocal = charAt(bp + offset++); + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + + return value; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return false; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return false; + } + + return value; + } + + public long scanFieldLong(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return 0; + } + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + + boolean negative = false; + if (chLocal == '-') { + chLocal = charAt(bp + (offset++)); + negative = true; + } + + long value; + if (chLocal >= '0' && chLocal <= '9') { + value = chLocal - '0'; + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + value = value * 10 + (chLocal - '0'); + } else if (chLocal == '.') { + matchStat = NOT_MATCH; + return 0; + } else { + break; + } + } + + boolean valid = offset - fieldName.length < 21 + && (value >= 0 || (value == -9223372036854775808L && negative)); + if (!valid) { + matchStat = NOT_MATCH; + return 0; + } + } else { + matchStat = NOT_MATCH; + return 0; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return negative ? -value : value; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return 0; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return 0; + } + + return negative ? -value : value; + } + + public long scanLong(char expectNextChar) { + matchStat = UNKNOWN; + + int offset = 0; + char chLocal = charAt(bp + (offset++)); + final boolean quote = chLocal == '"'; + if (quote) { + chLocal = charAt(bp + (offset++)); + } + + final boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + long value; + if (chLocal >= '0' && chLocal <= '9') { + value = chLocal - '0'; + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + value = value * 10 + (chLocal - '0'); + } else if (chLocal == '.') { + matchStat = NOT_MATCH; + return 0; + } else { + break; + } + } + boolean valid = value >= 0 || (value == -9223372036854775808L && negative); + if (!valid) { + String val = subString(bp, offset - 1); + throw new NumberFormatException(val); + } + } else if (chLocal == 'n' && charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + matchStat = VALUE_NULL; + value = 0; + offset += 3; + chLocal = charAt(bp + offset++); + + if (quote && chLocal == '"') { + chLocal = charAt(bp + offset++); + } + + for (;;) { + if (chLocal == ',') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == ']') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACKET; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(bp + offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return 0; + } else { + matchStat = NOT_MATCH; + return 0; + } + + if (quote) { + if (chLocal != '"') { + matchStat = NOT_MATCH; + return 0; + } else { + chLocal = charAt(bp + (offset++)); + } + } + + for (;;) { + if (chLocal == expectNextChar) { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return negative ? -value : value; + } else { + if (isWhitespace(chLocal)) { + chLocal = charAt(bp + (offset++)); + continue; + } + + matchStat = NOT_MATCH; + return value; + } + } + } + + public final float scanFieldFloat(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return 0; + } + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + + final boolean quote = chLocal == '"'; + if (quote) { + chLocal = charAt(bp + (offset++)); + } + + boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + float value; + if (chLocal >= '0' && chLocal <= '9') { + int intVal = chLocal - '0'; + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + continue; + } else { + break; + } + } + + int power = 1; + boolean small = (chLocal == '.'); + if (small) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power = 10; + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power *= 10; + continue; + } else { + break; + } + } + } else { + matchStat = NOT_MATCH; + return 0; + } + } + + boolean exp = chLocal == 'e' || chLocal == 'E'; + if (exp) { + chLocal = charAt(bp + (offset++)); + if (chLocal == '+' || chLocal == '-') { + chLocal = charAt(bp + (offset++)); + } + for (;;) { + if (chLocal >= '0' && chLocal <= '9') { + chLocal = charAt(bp + (offset++)); + } else { + break; + } + } + } + + int start, count; + if (quote) { + if (chLocal != '"') { + matchStat = NOT_MATCH; + return 0; + } else { + chLocal = charAt(bp + (offset++)); + } + start = bp + fieldName.length + 1; + count = bp + offset - start - 2; + } else { + start = bp + fieldName.length; + count = bp + offset - start - 1; + } + + if ((!exp) && count < 17) { + value = ((float) intVal) / power; + if (negative) { + value = -value; + } + } else { + String text = this.subString(start, count); + value = Float.parseFloat(text); + } + } else if (chLocal == 'n' && charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + matchStat = VALUE_NULL; + value = 0; + offset += 3; + chLocal = charAt(bp + offset++); + + if (quote && chLocal == '"') { + chLocal = charAt(bp + offset++); + } + + for (;;) { + if (chLocal == ',') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == '}') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACE; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(bp + offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return 0; + } else { + matchStat = NOT_MATCH; + return 0; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return value; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + bp += (offset - 1); + token = JSONToken.EOF; + ch = EOI; + } else { + matchStat = NOT_MATCH; + return 0; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return 0; + } + + return value; + } + + public final float scanFloat(char seperator) { + matchStat = UNKNOWN; + + int offset = 0; + char chLocal = charAt(bp + (offset++)); + final boolean quote = chLocal == '"'; + if (quote) { + chLocal = charAt(bp + (offset++)); + } + + boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + float value; + if (chLocal >= '0' && chLocal <= '9') { + long intVal = chLocal - '0'; + for (; ; ) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + continue; + } else { + break; + } + } + + long power = 1; + boolean small = (chLocal == '.'); + if (small) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power = 10; + for (; ; ) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power *= 10; + continue; + } else { + break; + } + } + } else { + matchStat = NOT_MATCH; + return 0; + } + } + + boolean exp = chLocal == 'e' || chLocal == 'E'; + if (exp) { + chLocal = charAt(bp + (offset++)); + if (chLocal == '+' || chLocal == '-') { + chLocal = charAt(bp + (offset++)); + } + for (; ; ) { + if (chLocal >= '0' && chLocal <= '9') { + chLocal = charAt(bp + (offset++)); + } else { + break; + } + } + } +// int start, count; +// if (quote) { +// if (chLocal != '"') { +// matchStat = NOT_MATCH; +// return 0; +// } else { +// chLocal = charAt(bp + (offset++)); +// } +// start = bp + 1; +// count = bp + offset - start - 2; +// } else { +// start = bp; +// count = bp + offset - start - 1; +// } +// String text = this.subString(start, count); +// value = Float.parseFloat(text); + int start, count; + if (quote) { + if (chLocal != '"') { + matchStat = NOT_MATCH; + return 0; + } else { + chLocal = charAt(bp + (offset++)); + } + start = bp + 1; + count = bp + offset - start - 2; + } else { + start = bp; + count = bp + offset - start - 1; + } + + if ((!exp) && count < 17) { + value = ((float) intVal) / power; + if (negative) { + value = -value; + } + } else { + String text = this.subString(start, count); + value = Float.parseFloat(text); + } + } else if (chLocal == 'n' && charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + matchStat = VALUE_NULL; + value = 0; + offset += 3; + chLocal = charAt(bp + offset++); + + if (quote && chLocal == '"') { + chLocal = charAt(bp + offset++); + } + + for (;;) { + if (chLocal == ',') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == ']') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACKET; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(bp + offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return 0; + } else { + matchStat = NOT_MATCH; + return 0; + } + + if (chLocal == seperator) { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return value; + } else { + matchStat = NOT_MATCH; + return value; + } + } + + public double scanDouble(char seperator) { + matchStat = UNKNOWN; + + int offset = 0; + char chLocal = charAt(bp + (offset++)); + final boolean quote = chLocal == '"'; + if (quote) { + chLocal = charAt(bp + (offset++)); + } + + boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + double value; + if (chLocal >= '0' && chLocal <= '9') { + long intVal = chLocal - '0'; + for (; ; ) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + continue; + } else { + break; + } + } + + long power = 1; + boolean small = (chLocal == '.'); + if (small) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power = 10; + for (; ; ) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power *= 10; + continue; + } else { + break; + } + } + } else { + matchStat = NOT_MATCH; + return 0; + } + } + + boolean exp = chLocal == 'e' || chLocal == 'E'; + if (exp) { + chLocal = charAt(bp + (offset++)); + if (chLocal == '+' || chLocal == '-') { + chLocal = charAt(bp + (offset++)); + } + for (; ; ) { + if (chLocal >= '0' && chLocal <= '9') { + chLocal = charAt(bp + (offset++)); + } else { + break; + } + } + } + + int start, count; + if (quote) { + if (chLocal != '"') { + matchStat = NOT_MATCH; + return 0; + } else { + chLocal = charAt(bp + (offset++)); + } + start = bp + 1; + count = bp + offset - start - 2; + } else { + start = bp; + count = bp + offset - start - 1; + } + + if (!exp && count < 20) { + value = ((double) intVal) / power; + if (negative) { + value = -value; + } + } else { + String text = this.subString(start, count); + value = Double.parseDouble(text); + } + } else if (chLocal == 'n' && charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + matchStat = VALUE_NULL; + value = 0; + offset += 3; + chLocal = charAt(bp + offset++); + + if (quote && chLocal == '"') { + chLocal = charAt(bp + offset++); + } + + for (;;) { + if (chLocal == ',') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == ']') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACKET; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(bp + offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return 0; + } else { + matchStat = NOT_MATCH; + return 0; + } + + if (chLocal == seperator) { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return value; + } else { + matchStat = NOT_MATCH; + return value; + } + } + + public BigDecimal scanDecimal(char seperator) { + matchStat = UNKNOWN; + + int offset = 0; + char chLocal = charAt(bp + (offset++)); + final boolean quote = chLocal == '"'; + if (quote) { + chLocal = charAt(bp + (offset++)); + } + + boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + BigDecimal value; + if (chLocal >= '0' && chLocal <= '9') { + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + continue; + } else { + break; + } + } + + boolean small = (chLocal == '.'); + if (small) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + continue; + } else { + break; + } + } + } else { + matchStat = NOT_MATCH; + return null; + } + } + + boolean exp = chLocal == 'e' || chLocal == 'E'; + if (exp) { + chLocal = charAt(bp + (offset++)); + if (chLocal == '+' || chLocal == '-') { + chLocal = charAt(bp + (offset++)); + } + for (;;) { + if (chLocal >= '0' && chLocal <= '9') { + chLocal = charAt(bp + (offset++)); + } else { + break; + } + } + } + + int start, count; + if (quote) { + if (chLocal != '"') { + matchStat = NOT_MATCH; + return null; + } else { + chLocal = charAt(bp + (offset++)); + } + start = bp + 1; + count = bp + offset - start - 2; + } else { + start = bp; + count = bp + offset - start - 1; + } + + char[] chars = this.sub_chars(start, count); + value = new BigDecimal(chars); + } else if (chLocal == 'n' && charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + matchStat = VALUE_NULL; + value = null; + offset += 3; + chLocal = charAt(bp + offset++); + + if (quote && chLocal == '"') { + chLocal = charAt(bp + offset++); + } + + for (;;) { + if (chLocal == ',') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == '}') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACE; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(bp + offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return null; + } else { + matchStat = NOT_MATCH; + return null; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return value; + } + + if (chLocal == ']') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return null; + } + + return value; + } + + public final float[] scanFieldFloatArray(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return null; + } + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + if (chLocal != '[') { + matchStat = NOT_MATCH_NAME; + return null; + } + chLocal = charAt(bp + (offset++)); + + float[] array = new float[16]; + int arrayIndex = 0; + + for (;;) { + int start = bp + offset - 1; + + boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + if (chLocal >= '0' && chLocal <= '9') { + int intVal = chLocal - '0'; + for (; ; ) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + continue; + } else { + break; + } + } + + int power = 1; + boolean small = (chLocal == '.'); + if (small) { + chLocal = charAt(bp + (offset++)); + power = 10; + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + for (; ; ) { + chLocal = charAt(bp + (offset++)); + + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power *= 10; + continue; + } else { + break; + } + } + } else { + matchStat = NOT_MATCH; + return null; + } + } + + boolean exp = chLocal == 'e' || chLocal == 'E'; + if (exp) { + chLocal = charAt(bp + (offset++)); + if (chLocal == '+' || chLocal == '-') { + chLocal = charAt(bp + (offset++)); + } + for (;;) { + if (chLocal >= '0' && chLocal <= '9') { + chLocal = charAt(bp + (offset++)); + } else { + break; + } + } + } + + int count = bp + offset - start - 1; + + float value; + if (!exp && count < 10) { + value = ((float) intVal) / power; + if (negative) { + value = -value; + } + } else { + String text = this.subString(start, count); + value = Float.parseFloat(text); + } + + if (arrayIndex >= array.length) { + float[] tmp = new float[array.length * 3 / 2]; + System.arraycopy(array, 0, tmp, 0, arrayIndex); + array = tmp; + } + array[arrayIndex++] = value; + + if (chLocal == ',') { + chLocal = charAt(bp + (offset++)); + } else if (chLocal == ']') { + chLocal = charAt(bp + (offset++)); + break; + } + } else { + matchStat = NOT_MATCH; + return null; + } + } + + + if (arrayIndex != array.length) { + float[] tmp = new float[arrayIndex]; + System.arraycopy(array, 0, tmp, 0, arrayIndex); + array = tmp; + } + + if (chLocal == ',') { + bp += (offset - 1); + this.next(); + matchStat = VALUE; + token = JSONToken.COMMA; + return array; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += (offset - 1); + this.next(); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += (offset - 1); + this.next(); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += (offset - 1); + this.next(); + } else if (chLocal == EOI) { + bp += (offset - 1); + token = JSONToken.EOF; + ch = EOI; + } else { + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return null; + } + + return array; + } + + public final float[][] scanFieldFloatArray2(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return null; + } + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + + if (chLocal != '[') { + matchStat = NOT_MATCH_NAME; + return null; + } + chLocal = charAt(bp + (offset++)); + + float[][] arrayarray = new float[16][]; + int arrayarrayIndex = 0; + + for (;;) { + if (chLocal == '[') { + chLocal = charAt(bp + (offset++)); + + float[] array = new float[16]; + int arrayIndex = 0; + + for (; ; ) { + int start = bp + offset - 1; + boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + if (chLocal >= '0' && chLocal <= '9') { + int intVal = chLocal - '0'; + for (; ; ) { + chLocal = charAt(bp + (offset++)); + + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + continue; + } else { + break; + } + } + + int power = 1; + if (chLocal == '.') { + chLocal = charAt(bp + (offset++)); + + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power = 10; + for (; ; ) { + chLocal = charAt(bp + (offset++)); + + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power *= 10; + continue; + } else { + break; + } + } + } else { + matchStat = NOT_MATCH; + return null; + } + } + + boolean exp = chLocal == 'e' || chLocal == 'E'; + if (exp) { + chLocal = charAt(bp + (offset++)); + if (chLocal == '+' || chLocal == '-') { + chLocal = charAt(bp + (offset++)); + } + for (;;) { + if (chLocal >= '0' && chLocal <= '9') { + chLocal = charAt(bp + (offset++)); + } else { + break; + } + } + } + + int count = bp + offset - start - 1; + float value; + if (!exp && count < 10) { + value = ((float) intVal) / power; + if (negative) { + value = -value; + } + } else { + String text = this.subString(start, count); + value = Float.parseFloat(text); + } + + if (arrayIndex >= array.length) { + float[] tmp = new float[array.length * 3 / 2]; + System.arraycopy(array, 0, tmp, 0, arrayIndex); + array = tmp; + } + array[arrayIndex++] = value; + + if (chLocal == ',') { + chLocal = charAt(bp + (offset++)); + } else if (chLocal == ']') { + chLocal = charAt(bp + (offset++)); + break; + } + } else { + matchStat = NOT_MATCH; + return null; + } + } + + // compact + if (arrayIndex != array.length) { + float[] tmp = new float[arrayIndex]; + System.arraycopy(array, 0, tmp, 0, arrayIndex); + array = tmp; + } + + if (arrayarrayIndex >= arrayarray.length) { + float[][] tmp = new float[arrayarray.length * 3 / 2][]; + System.arraycopy(array, 0, tmp, 0, arrayIndex); + arrayarray = tmp; + } + arrayarray[arrayarrayIndex++] = array; + + if (chLocal == ',') { + chLocal = charAt(bp + (offset++)); + } else if (chLocal == ']') { + chLocal = charAt(bp + (offset++)); + break; + } + } + } + + // compact + if (arrayarrayIndex != arrayarray.length) { + float[][] tmp = new float[arrayarrayIndex][]; + System.arraycopy(arrayarray, 0, tmp, 0, arrayarrayIndex); + arrayarray = tmp; + } + + if (chLocal == ',') { + bp += (offset - 1); + this.next(); + matchStat = VALUE; + token = JSONToken.COMMA; + return arrayarray; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += (offset - 1); + this.next(); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += (offset - 1); + this.next(); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += (offset - 1); + this.next(); + } else if (chLocal == EOI) { + bp += (offset - 1); + token = JSONToken.EOF; + ch = EOI; + } else { + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return null; + } + + return arrayarray; + } + + public final double scanFieldDouble(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return 0; + } + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + final boolean quote = chLocal == '"'; + if (quote) { + chLocal = charAt(bp + (offset++)); + } + + boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + double value; + if (chLocal >= '0' && chLocal <= '9') { + long intVal = chLocal - '0'; + + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + continue; + } else { + break; + } + } + + long power = 1; + boolean small = (chLocal == '.'); + if (small) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power = 10; + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power *= 10; + continue; + } else { + break; + } + } + } else { + matchStat = NOT_MATCH; + return 0; + } + } + + boolean exp = chLocal == 'e' || chLocal == 'E'; + if (exp) { + chLocal = charAt(bp + (offset++)); + if (chLocal == '+' || chLocal == '-') { + chLocal = charAt(bp + (offset++)); + } + for (;;) { + if (chLocal >= '0' && chLocal <= '9') { + chLocal = charAt(bp + (offset++)); + } else { + break; + } + } + } + + int start, count; + if (quote) { + if (chLocal != '"') { + matchStat = NOT_MATCH; + return 0; + } else { + chLocal = charAt(bp + (offset++)); + } + start = bp + fieldName.length + 1; + count = bp + offset - start - 2; + } else { + start = bp + fieldName.length; + count = bp + offset - start - 1; + } + + if (!exp && count < 20) { + value = ((double) intVal) / power; + if (negative) { + value = -value; + } + } else { + String text = this.subString(start, count); + value = Double.parseDouble(text); + } + } else if (chLocal == 'n' && charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + matchStat = VALUE_NULL; + value = 0; + offset += 3; + chLocal = charAt(bp + offset++); + + if (quote && chLocal == '"') { + chLocal = charAt(bp + offset++); + } + + for (;;) { + if (chLocal == ',') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == '}') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACE; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(bp + offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return 0; + } else { + matchStat = NOT_MATCH; + return 0; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return value; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return 0; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return 0; + } + + return value; + } + + public BigDecimal scanFieldDecimal(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return null; + } + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + final boolean quote = chLocal == '"'; + if (quote) { + chLocal = charAt(bp + (offset++)); + } + + boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + BigDecimal value; + if (chLocal >= '0' && chLocal <= '9') { + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + continue; + } else { + break; + } + } + + boolean small = (chLocal == '.'); + if (small) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + continue; + } else { + break; + } + } + } else { + matchStat = NOT_MATCH; + return null; + } + } + + boolean exp = chLocal == 'e' || chLocal == 'E'; + if (exp) { + chLocal = charAt(bp + (offset++)); + if (chLocal == '+' || chLocal == '-') { + chLocal = charAt(bp + (offset++)); + } + for (;;) { + if (chLocal >= '0' && chLocal <= '9') { + chLocal = charAt(bp + (offset++)); + } else { + break; + } + } + } + + int start, count; + if (quote) { + if (chLocal != '"') { + matchStat = NOT_MATCH; + return null; + } else { + chLocal = charAt(bp + (offset++)); + } + start = bp + fieldName.length + 1; + count = bp + offset - start - 2; + } else { + start = bp + fieldName.length; + count = bp + offset - start - 1; + } + + char[] chars = this.sub_chars(start, count); + value = new BigDecimal(chars); + } else if (chLocal == 'n' && charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + matchStat = VALUE_NULL; + value = null; + offset += 3; + chLocal = charAt(bp + offset++); + + if (quote && chLocal == '"') { + chLocal = charAt(bp + offset++); + } + + for (;;) { + if (chLocal == ',') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == '}') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACE; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(bp + offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return null; + } else { + matchStat = NOT_MATCH; + return null; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return value; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return null; + } + + return value; + } + + public BigInteger scanFieldBigInteger(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return null; + } + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + final boolean quote = chLocal == '"'; + if (quote) { + chLocal = charAt(bp + (offset++)); + } + + boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(bp + (offset++)); + } + + BigInteger value; + if (chLocal >= '0' && chLocal <= '9') { + long intVal = chLocal - '0'; + for (;;) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + continue; + } else { + break; + } + } + + int start, count; + if (quote) { + if (chLocal != '"') { + matchStat = NOT_MATCH; + return null; + } else { + chLocal = charAt(bp + (offset++)); + } + start = bp + fieldName.length + 1; + count = bp + offset - start - 2; + } else { + start = bp + fieldName.length; + count = bp + offset - start - 1; + } + + if (count < 20 || (negative && count < 21)) { + value = BigInteger.valueOf(negative ? -intVal : intVal); + } else { + +// char[] chars = this.sub_chars(negative ? start + 1 : start, count); +// value = new BigInteger(chars, ) + String strVal = this.subString(start, count); + value = new BigInteger(strVal); + } + } else if (chLocal == 'n' && charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + matchStat = VALUE_NULL; + value = null; + offset += 3; + chLocal = charAt(bp + offset++); + + if (quote && chLocal == '"') { + chLocal = charAt(bp + offset++); + } + + for (;;) { + if (chLocal == ',') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == '}') { + bp += offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACE; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(bp + offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return null; + } else { + matchStat = NOT_MATCH; + return null; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return value; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return null; + } + + return value; + } + + public java.util.Date scanFieldDate(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return null; + } + + // int index = bp + fieldName.length; + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + + final java.util.Date dateVal; + if (chLocal == '"'){ + int startIndex = bp + fieldName.length + 1; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); + } + + int startIndex2 = bp + fieldName.length + 1; // must re compute + String stringVal = subString(startIndex2, endIndex - startIndex2); + if (stringVal.indexOf('\\') != -1) { + for (;;) { + int slashCount = 0; + for (int i = endIndex - 1; i >= 0; --i) { + if (charAt(i) == '\\') { + slashCount++; + } else { + break; + } + } + if (slashCount % 2 == 0) { + break; + } + endIndex = indexOf('"', endIndex + 1); + } + + int chars_len = endIndex - (bp + fieldName.length + 1); + char[] chars = sub_chars( bp + fieldName.length + 1, chars_len); + + stringVal = readString(chars, chars_len); + } + + offset += (endIndex - (bp + fieldName.length + 1) + 1); + chLocal = charAt(bp + (offset++)); + + JSONScanner dateLexer = new JSONScanner(stringVal); + try { + if (dateLexer.scanISO8601DateIfMatch(false)) { + Calendar calendar = dateLexer.getCalendar(); + dateVal = calendar.getTime(); + } else { + matchStat = NOT_MATCH; + return null; + } + } finally { + dateLexer.close(); + } + } else if (chLocal == '-' || (chLocal >= '0' && chLocal <= '9')) { + long millis = 0; + + boolean negative = false; + if (chLocal == '-') { + chLocal = charAt(bp + (offset++)); + negative = true; + } + + if (chLocal >= '0' && chLocal <= '9') { + millis = chLocal - '0'; + for (; ; ) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + millis = millis * 10 + (chLocal - '0'); + } else { + break; + } + } + } + + if (millis < 0) { + matchStat = NOT_MATCH; + return null; + } + + if (negative) { + millis = -millis; + } + + dateVal = new java.util.Date(millis); + } else { + matchStat = NOT_MATCH; + return null; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + return dateVal; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return null; + } + + return dateVal; + } + + public java.util.Date scanDate(char seperator) { + matchStat = UNKNOWN; + + int offset = 0; + char chLocal = charAt(bp + (offset++)); + + final java.util.Date dateVal; + if (chLocal == '"'){ + int startIndex = bp + 1; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); + } + + int startIndex2 = bp + 1; // must re compute + String stringVal = subString(startIndex2, endIndex - startIndex2); + if (stringVal.indexOf('\\') != -1) { + for (;;) { + int slashCount = 0; + for (int i = endIndex - 1; i >= 0; --i) { + if (charAt(i) == '\\') { + slashCount++; + } else { + break; + } + } + if (slashCount % 2 == 0) { + break; + } + endIndex = indexOf('"', endIndex + 1); + } + + int chars_len = endIndex - (bp + 1); + char[] chars = sub_chars( bp + 1, chars_len); + + stringVal = readString(chars, chars_len); + } + + offset += (endIndex - (bp + 1) + 1); + chLocal = charAt(bp + (offset++)); + + JSONScanner dateLexer = new JSONScanner(stringVal); + try { + if (dateLexer.scanISO8601DateIfMatch(false)) { + Calendar calendar = dateLexer.getCalendar(); + dateVal = calendar.getTime(); + } else { + matchStat = NOT_MATCH; + return null; + } + } finally { + dateLexer.close(); + } + } else if (chLocal == '-' || (chLocal >= '0' && chLocal <= '9')) { + long millis = 0; + + boolean negative = false; + if (chLocal == '-') { + chLocal = charAt(bp + (offset++)); + negative = true; + } + + if (chLocal >= '0' && chLocal <= '9') { + millis = chLocal - '0'; + for (; ; ) { + chLocal = charAt(bp + (offset++)); + if (chLocal >= '0' && chLocal <= '9') { + millis = millis * 10 + (chLocal - '0'); + } else { + break; + } + } + } + + if (millis < 0) { + matchStat = NOT_MATCH; + return null; + } + + if (negative) { + millis = -millis; + } + + dateVal = new java.util.Date(millis); + } else if (chLocal == 'n' && charAt(bp + offset) == 'u' && charAt(bp + offset + 1) == 'l' && charAt(bp + offset + 2) == 'l') { + matchStat = VALUE_NULL; + dateVal = null; + offset += 3; + chLocal = charAt(bp + offset++); + } else { + matchStat = NOT_MATCH; + return null; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return dateVal; + } + + if (chLocal == ']') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return null; + } + + return dateVal; + } + + public java.util.UUID scanFieldUUID(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return null; + } + + // int index = bp + fieldName.length; + + int offset = fieldName.length; + char chLocal = charAt(bp + (offset++)); + + final java.util.UUID uuid; + if (chLocal == '"') { + int startIndex = bp + fieldName.length + 1; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); + } + + int startIndex2 = bp + fieldName.length + 1; // must re compute + int len = endIndex - startIndex2; + if (len == 36) { + long mostSigBits = 0, leastSigBits = 0; + for (int i = 0; i < 8; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + mostSigBits <<= 4; + mostSigBits |= num; + } + for (int i = 9; i < 13; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + mostSigBits <<= 4; + mostSigBits |= num; + } + for (int i = 14; i < 18; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + mostSigBits <<= 4; + mostSigBits |= num; + } + for (int i = 19; i < 23; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + leastSigBits <<= 4; + leastSigBits |= num; + } + for (int i = 24; i < 36; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + leastSigBits <<= 4; + leastSigBits |= num; + } + uuid = new UUID(mostSigBits, leastSigBits); + + offset += (endIndex - (bp + fieldName.length + 1) + 1); + chLocal = charAt(bp + (offset++)); + } else if (len == 32) { + long mostSigBits = 0, leastSigBits = 0; + for (int i = 0; i < 16; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + mostSigBits <<= 4; + mostSigBits |= num; + } + for (int i = 16; i < 32; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + leastSigBits <<= 4; + leastSigBits |= num; + } + + uuid = new UUID(mostSigBits, leastSigBits); + + offset += (endIndex - (bp + fieldName.length + 1) + 1); + chLocal = charAt(bp + (offset++)); + } else { + matchStat = NOT_MATCH; + return null; + } + } else if (chLocal == 'n' + && charAt(bp + (offset++)) == 'u' + && charAt(bp + (offset++)) == 'l' + && charAt(bp + (offset++)) == 'l') { + uuid = null; + chLocal = charAt(bp + (offset++)); + } else { + matchStat = NOT_MATCH; + return null; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + return uuid; + } + + if (chLocal == '}') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return null; + } + + return uuid; + } + + public java.util.UUID scanUUID(char seperator) { + matchStat = UNKNOWN; + + // int index = bp + fieldName.length; + + int offset = 0; + char chLocal = charAt(bp + (offset++)); + + final java.util.UUID uuid; + if (chLocal == '"') { + int startIndex = bp + 1; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); + } + + int startIndex2 = bp + 1; // must re compute + int len = endIndex - startIndex2; + if (len == 36) { + long mostSigBits = 0, leastSigBits = 0; + for (int i = 0; i < 8; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + mostSigBits <<= 4; + mostSigBits |= num; + } + for (int i = 9; i < 13; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + mostSigBits <<= 4; + mostSigBits |= num; + } + for (int i = 14; i < 18; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + mostSigBits <<= 4; + mostSigBits |= num; + } + for (int i = 19; i < 23; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + leastSigBits <<= 4; + leastSigBits |= num; + } + for (int i = 24; i < 36; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + leastSigBits <<= 4; + leastSigBits |= num; + } + uuid = new UUID(mostSigBits, leastSigBits); + + offset += (endIndex - (bp + 1) + 1); + chLocal = charAt(bp + (offset++)); + } else if (len == 32) { + long mostSigBits = 0, leastSigBits = 0; + for (int i = 0; i < 16; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + mostSigBits <<= 4; + mostSigBits |= num; + } + for (int i = 16; i < 32; ++i) { + char ch = charAt(startIndex2 + i); + int num; + if (ch >= '0' && ch <= '9') { + num = ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + num = 10 + (ch - 'a'); + } else if (ch >= 'A' && ch <= 'F') { + num = 10 + (ch - 'A'); + } else { + matchStat = NOT_MATCH_NAME; + return null; + } + + leastSigBits <<= 4; + leastSigBits |= num; + } + + uuid = new UUID(mostSigBits, leastSigBits); + + offset += (endIndex - (bp + 1) + 1); + chLocal = charAt(bp + (offset++)); + } else { + matchStat = NOT_MATCH; + return null; + } + } else if (chLocal == 'n' + && charAt(bp + (offset++)) == 'u' + && charAt(bp + (offset++)) == 'l' + && charAt(bp + (offset++)) == 'l') { + uuid = null; + chLocal = charAt(bp + (offset++)); + } else { + matchStat = NOT_MATCH; + return null; + } + + if (chLocal == ',') { + bp += offset; + this.ch = this.charAt(bp); + matchStat = VALUE; + return uuid; + } + + if (chLocal == ']') { + chLocal = charAt(bp + (offset++)); + if (chLocal == ',') { + token = JSONToken.COMMA; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == ']') { + token = JSONToken.RBRACKET; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == '}') { + token = JSONToken.RBRACE; + bp += offset; + this.ch = this.charAt(bp); + } else if (chLocal == EOI) { + token = JSONToken.EOF; + bp += (offset - 1); + ch = EOI; + } else { + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } else { + matchStat = NOT_MATCH; + return null; + } + + return uuid; + } + + public final void scanTrue() { + if (ch != 't') { + throw new JSONException("error parse true"); + } + next(); + + if (ch != 'r') { + throw new JSONException("error parse true"); + } + next(); + + if (ch != 'u') { + throw new JSONException("error parse true"); + } + next(); + + if (ch != 'e') { + throw new JSONException("error parse true"); + } + next(); + + if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI + || ch == '\f' || ch == '\b' || ch == ':' || ch == '/') { + token = JSONToken.TRUE; + } else { + throw new JSONException("scan true error"); + } + } + + public final void scanNullOrNew() { + if (ch != 'n') { + throw new JSONException("error parse null or new"); + } + next(); + + if (ch == 'u') { + next(); + if (ch != 'l') { + throw new JSONException("error parse null"); + } + next(); + + if (ch != 'l') { + throw new JSONException("error parse null"); + } + next(); + + if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI + || ch == '\f' || ch == '\b') { + token = JSONToken.NULL; + } else { + throw new JSONException("scan null error"); + } + return; + } + + if (ch != 'e') { + throw new JSONException("error parse new"); + } + next(); + + if (ch != 'w') { + throw new JSONException("error parse new"); + } + next(); + + if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI + || ch == '\f' || ch == '\b') { + token = JSONToken.NEW; + } else { + throw new JSONException("scan new error"); + } + } + + public final void scanFalse() { + if (ch != 'f') { + throw new JSONException("error parse false"); + } + next(); + + if (ch != 'a') { + throw new JSONException("error parse false"); + } + next(); + + if (ch != 'l') { + throw new JSONException("error parse false"); + } + next(); + + if (ch != 's') { + throw new JSONException("error parse false"); + } + next(); + + if (ch != 'e') { + throw new JSONException("error parse false"); + } + next(); + + if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI + || ch == '\f' || ch == '\b' || ch == ':' || ch == '/') { + token = JSONToken.FALSE; + } else { + throw new JSONException("scan false error"); + } + } + + public final void scanIdent() { + np = bp - 1; + hasSpecial = false; + + for (;;) { + sp++; + + next(); + if (Character.isLetterOrDigit(ch)) { + continue; + } + + String ident = stringVal(); + + if ("null".equalsIgnoreCase(ident)) { + token = JSONToken.NULL; + } else if ("new".equals(ident)) { + token = JSONToken.NEW; + } else if ("true".equals(ident)) { + token = JSONToken.TRUE; + } else if ("false".equals(ident)) { + token = JSONToken.FALSE; + } else if ("undefined".equals(ident)) { + token = JSONToken.UNDEFINED; + } else if ("Set".equals(ident)) { + token = JSONToken.SET; + } else if ("TreeSet".equals(ident)) { + token = JSONToken.TREE_SET; + } else { + token = JSONToken.IDENTIFIER; + } + return; + } + } + + public abstract String stringVal(); + + public abstract String subString(int offset, int count); + + protected abstract char[] sub_chars(int offset, int count); + + public static String readString(char[] chars, int chars_len) { + char[] sbuf = new char[chars_len]; + int len = 0; + for (int i = 0; i < chars_len; ++i) { + char ch = chars[i]; + + if (ch != '\\') { + sbuf[len++] = ch; + continue; + } + ch = chars[++i]; + + switch (ch) { + case '0': + sbuf[len++] = '\0'; + break; + case '1': + sbuf[len++] = '\1'; + break; + case '2': + sbuf[len++] = '\2'; + break; + case '3': + sbuf[len++] = '\3'; + break; + case '4': + sbuf[len++] = '\4'; + break; + case '5': + sbuf[len++] = '\5'; + break; + case '6': + sbuf[len++] = '\6'; + break; + case '7': + sbuf[len++] = '\7'; + break; + case 'b': // 8 + sbuf[len++] = '\b'; + break; + case 't': // 9 + sbuf[len++] = '\t'; + break; + case 'n': // 10 + sbuf[len++] = '\n'; + break; + case 'v': // 11 + sbuf[len++] = '\u000B'; + break; + case 'f': // 12 + case 'F': + sbuf[len++] = '\f'; + break; + case 'r': // 13 + sbuf[len++] = '\r'; + break; + case '"': // 34 + sbuf[len++] = '"'; + break; + case '\'': // 39 + sbuf[len++] = '\''; + break; + case '/': // 47 + sbuf[len++] = '/'; + break; + case '\\': // 92 + sbuf[len++] = '\\'; + break; + case 'x': + sbuf[len++] = (char) (digits[chars[++i]] * 16 + digits[chars[++i]]); + break; + case 'u': + sbuf[len++] = (char) Integer.parseInt(new String(new char[] { chars[++i], // + chars[++i], // + chars[++i], // + chars[++i] }), + 16); + break; + default: + throw new JSONException("unclosed.str.lit"); + } + } + return new String(sbuf, 0, len); + } + + protected abstract boolean charArrayCompare(char[] chars); + + public boolean isBlankInput() { + for (int i = 0;; ++i) { + char chLocal = charAt(i); + if (chLocal == EOI) { + token = JSONToken.EOF; + break; + } + + if (!isWhitespace(chLocal)) { + return false; + } + } + + return true; + } + + public final void skipWhitespace() { + for (;;) { + if (ch <= '/') { + if (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t' || ch == '\f' || ch == '\b') { + next(); + continue; + } else if (ch == '/') { + skipComment(); + continue; + } else { + break; + } + } else { + break; + } + } + } + + private void scanStringSingleQuote() { + np = bp; + hasSpecial = false; + char chLocal; + for (;;) { + chLocal = next(); + + if (chLocal == '\'') { + break; + } + + if (chLocal == EOI) { + if (!isEOF()) { + putChar((char) EOI); + continue; + } + throw new JSONException("unclosed single-quote string"); + } + + if (chLocal == '\\') { + if (!hasSpecial) { + hasSpecial = true; + + if (sp > sbuf.length) { + char[] newsbuf = new char[sp * 2]; + System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length); + sbuf = newsbuf; + } + + // text.getChars(offset, offset + count, dest, 0); + this.copyTo(np + 1, sp, sbuf); + // System.arraycopy(buf, np + 1, sbuf, 0, sp); + } + + chLocal = next(); + + switch (chLocal) { + case '0': + putChar('\0'); + break; + case '1': + putChar('\1'); + break; + case '2': + putChar('\2'); + break; + case '3': + putChar('\3'); + break; + case '4': + putChar('\4'); + break; + case '5': + putChar('\5'); + break; + case '6': + putChar('\6'); + break; + case '7': + putChar('\7'); + break; + case 'b': // 8 + putChar('\b'); + break; + case 't': // 9 + putChar('\t'); + break; + case 'n': // 10 + putChar('\n'); + break; + case 'v': // 11 + putChar('\u000B'); + break; + case 'f': // 12 + case 'F': + putChar('\f'); + break; + case 'r': // 13 + putChar('\r'); + break; + case '"': // 34 + putChar('"'); + break; + case '\'': // 39 + putChar('\''); + break; + case '/': // 47 + putChar('/'); + break; + case '\\': // 92 + putChar('\\'); + break; + case 'x': + putChar((char) (digits[next()] * 16 + digits[next()])); + break; + case 'u': + putChar((char) Integer.parseInt(new String(new char[] { next(), next(), next(), next() }), 16)); + break; + default: + this.ch = chLocal; + throw new JSONException("unclosed single-quote string"); + } + continue; + } + + if (!hasSpecial) { + sp++; + continue; + } + + if (sp == sbuf.length) { + putChar(chLocal); + } else { + sbuf[sp++] = chLocal; + } + } + + token = LITERAL_STRING; + this.next(); + } + + /** + * Append a character to sbuf. + */ + protected final void putChar(char ch) { + if (sp == sbuf.length) { + char[] newsbuf = new char[sbuf.length * 2]; + System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length); + sbuf = newsbuf; + } + sbuf[sp++] = ch; + } + + public final void scanHex() { + if (ch != 'x') { + throw new JSONException("illegal state. " + ch); + } + next(); + if (ch != '\'') { + throw new JSONException("illegal state. " + ch); + } + + np = bp; + next(); + + for (int i = 0;;++i) { + char ch = next(); + if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F')) { + sp++; + continue; + } else if (ch == '\'') { + sp++; + next(); + break; + } else { + throw new JSONException("illegal state. " + ch); + } + } + token = JSONToken.HEX; + } + + public final void scanNumber() { + np = bp; + + if (ch == '-') { + sp++; + next(); + } + + for (;;) { + if (ch >= '0' && ch <= '9') { + sp++; + } else { + break; + } + next(); + } + + boolean isDouble = false; + + if (ch == '.') { + sp++; + next(); + isDouble = true; + + for (;;) { + if (ch >= '0' && ch <= '9') { + sp++; + } else { + break; + } + next(); + } + } + + if (ch == 'L') { + sp++; + next(); + } else if (ch == 'S') { + sp++; + next(); + } else if (ch == 'B') { + sp++; + next(); + } else if (ch == 'F') { + sp++; + next(); + isDouble = true; + } else if (ch == 'D') { + sp++; + next(); + isDouble = true; + } else if (ch == 'e' || ch == 'E') { + sp++; + next(); + + if (ch == '+' || ch == '-') { + sp++; + next(); + } + + for (;;) { + if (ch >= '0' && ch <= '9') { + sp++; + } else { + break; + } + next(); + } + + if (ch == 'D' || ch == 'F') { + sp++; + next(); + } + + isDouble = true; + } + + if (isDouble) { + token = JSONToken.LITERAL_FLOAT; + } else { + token = JSONToken.LITERAL_INT; + } + } + + public final long longValue() throws NumberFormatException { + long result = 0; + boolean negative = false; + long limit; + int digit; + + if (np == -1) { + np = 0; + } + + int i = np, max = np + sp; + + if (charAt(np) == '-') { + negative = true; + limit = Long.MIN_VALUE; + i++; + } else { + limit = -Long.MAX_VALUE; + } + long multmin = MULTMIN_RADIX_TEN; + if (i < max) { + digit = charAt(i++) - '0'; + result = -digit; + } + while (i < max) { + // Accumulating negatively avoids surprises near MAX_VALUE + char chLocal = charAt(i++); + + if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B') { + break; + } + + digit = chLocal - '0'; + if (result < multmin) { + throw new NumberFormatException(numberString()); + } + result *= 10; + if (result < limit + digit) { + throw new NumberFormatException(numberString()); + } + result -= digit; + } + + if (negative) { + if (i > np + 1) { + return result; + } else { /* Only got "-" */ + throw new NumberFormatException(numberString()); + } + } else { + return -result; + } + } + + public final Number decimalValue(boolean decimal) { + char chLocal = charAt(np + sp - 1); + try { + if (chLocal == 'F') { + return Float.parseFloat(numberString()); + } + + if (chLocal == 'D') { + return Double.parseDouble(numberString()); + } + + if (decimal) { + return decimalValue(); + } else { + return doubleValue(); + } + } catch (NumberFormatException ex) { + throw new JSONException(ex.getMessage() + ", " + info()); + } + } + + public abstract BigDecimal decimalValue(); + + public static boolean isWhitespace(char ch) { + // 专门调整了判断顺序 + return ch <= ' ' && (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b'); + } + + protected static final long MULTMIN_RADIX_TEN = Long.MIN_VALUE / 10; + protected static final int INT_MULTMIN_RADIX_TEN = Integer.MIN_VALUE / 10; + + protected final static int[] digits = new int[(int) 'f' + 1]; + + static { + for (int i = '0'; i <= '9'; ++i) { + digits[i] = i - '0'; + } + + for (int i = 'a'; i <= 'f'; ++i) { + digits[i] = (i - 'a') + 10; + } + for (int i = 'A'; i <= 'F'; ++i) { + digits[i] = (i - 'A') + 10; + } + } + + /** + * hsf support + * @param fieldName + * @param argTypesCount + * @param typeSymbolTable + * @return + */ + public String[] scanFieldStringArray(char[] fieldName, int argTypesCount, SymbolTable typeSymbolTable) { + throw new UnsupportedOperationException(); + } + + public boolean matchField2(char[] fieldName) { + throw new UnsupportedOperationException(); + } + + public int getFeatures() { + return this.features; + } +} diff --git a/src/main/java/com/alibaba/fastjson/parser/JSONReaderScanner.java b/src/main/java/com/alibaba/fastjson/parser/JSONReaderScanner.java new file mode 100644 index 0000000000..06165bb798 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/JSONReaderScanner.java @@ -0,0 +1,333 @@ +/* + * Copyright 1999-2017 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.parser; + +import java.io.CharArrayReader; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.math.BigDecimal; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.util.IOUtils; + +//这个类,为了性能优化做了很多特别处理,一切都是为了性能!!! + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public final class JSONReaderScanner extends JSONLexerBase { + + private final static ThreadLocal BUF_LOCAL = new ThreadLocal(); + + private Reader reader; + private char[] buf; + private int bufLength; + + public JSONReaderScanner(String input){ + this(input, JSON.DEFAULT_PARSER_FEATURE); + } + + public JSONReaderScanner(String input, int features){ + this(new StringReader(input), features); + } + + public JSONReaderScanner(char[] input, int inputLength){ + this(input, inputLength, JSON.DEFAULT_PARSER_FEATURE); + } + + public JSONReaderScanner(Reader reader){ + this(reader, JSON.DEFAULT_PARSER_FEATURE); + } + + public JSONReaderScanner(Reader reader, int features){ + super(features); + this.reader = reader; + + buf = BUF_LOCAL.get(); + if (buf != null) { + BUF_LOCAL.set(null); + } + + if (buf == null) { + buf = new char[1024 * 16]; + } + + try { + bufLength = reader.read(buf); + } catch (IOException e) { + throw new JSONException(e.getMessage(), e); + } + + bp = -1; + + next(); + if (ch == 65279) { // utf8 bom + next(); + } + } + + public JSONReaderScanner(char[] input, int inputLength, int features){ + this(new CharArrayReader(input, 0, inputLength), features); + } + + public final char charAt(int index) { + if (index >= bufLength) { + if (bufLength == -1) { + if (index < sp) { + return buf[index]; + } + return EOI; + } + + if (bp == 0) { + char[] buf = new char[(this.buf.length * 3) / 2]; + System.arraycopy(this.buf, bp, buf, 0, bufLength); + + int rest = buf.length - bufLength; + try { + int len = reader.read(buf, bufLength, rest); + bufLength += len; + this.buf = buf; + } catch (IOException e) { + throw new JSONException(e.getMessage(), e); + } + } else { + int rest = bufLength - bp; + if (rest > 0) { + System.arraycopy(buf, bp, buf, 0, rest); + } + + try { + bufLength = reader.read(buf, rest, buf.length - rest); + } catch (IOException e) { + throw new JSONException(e.getMessage(), e); + } + + if (bufLength == 0) { + throw new JSONException("illegal state, textLength is zero"); + } + + if (bufLength == -1) { + return EOI; + } + + bufLength += rest; + index -= bp; + np -= bp; + bp = 0; + } + } + + return buf[index]; + } + + public final int indexOf(char ch, int startIndex) { + int offset = startIndex - bp; + for (;; ++offset) { + final int index = bp + offset; + char chLoal = charAt(index); + if (ch == chLoal) { + return offset + bp; + } + if (chLoal == EOI) { + return -1; + } + } + } + + public final String addSymbol(int offset, int len, int hash, final SymbolTable symbolTable) { + return symbolTable.addSymbol(buf, offset, len, hash); + } + + public final char next() { + int index = ++bp; + + if (index >= bufLength) { + if (bufLength == -1) { + return EOI; + } + + if (sp > 0) { + int offset; + offset = bufLength - sp; + if (ch == '"' && offset > 0) { + offset--; + } + System.arraycopy(buf, offset, buf, 0, sp); + } + np = -1; + + index = bp = sp; + + try { + int startPos = bp; + int readLength = buf.length - startPos; + if (readLength == 0) { + char[] newBuf = new char[buf.length * 2]; + System.arraycopy(buf, 0, newBuf, 0, buf.length); + buf = newBuf; + readLength = buf.length - startPos; + } + bufLength = reader.read(buf, bp, readLength); + } catch (IOException e) { + throw new JSONException(e.getMessage(), e); + } + + if (bufLength == 0) { + throw new JSONException("illegal stat, textLength is zero"); + } + + if (bufLength == -1) { + return ch = EOI; + } + + bufLength += bp; + } + + return ch = buf[index]; + } + + protected final void copyTo(int offset, int count, char[] dest) { + System.arraycopy(buf, offset, dest, 0, count); + } + + public final boolean charArrayCompare(char[] chars) { + for (int i = 0; i < chars.length; ++i) { + if (charAt(bp + i) != chars[i]) { + return false; + } + } + + return true; + } + + public byte[] bytesValue() { + if (token == JSONToken.HEX) { + throw new JSONException("TODO"); + } + + return IOUtils.decodeBase64(buf, np + 1, sp); + } + + protected final void arrayCopy(int srcPos, char[] dest, int destPos, int length) { + System.arraycopy(buf, srcPos, dest, destPos, length); + } + + /** + * The value of a literal token, recorded as a string. For integers, leading 0x and 'l' suffixes are suppressed. + */ + public final String stringVal() { + if (!hasSpecial) { + int offset = np + 1; + if (offset < 0) { + throw new IllegalStateException(); + } + if (offset > buf.length - sp) { + throw new IllegalStateException(); + } + return new String(buf, offset, sp); + // return text.substring(np + 1, np + 1 + sp); + } else { + return new String(sbuf, 0, sp); + } + } + + public final String subString(int offset, int count) { + if (count < 0) { + throw new StringIndexOutOfBoundsException(count); + } + return new String(buf, offset, count); + // return text.substring(offset, offset + count); + } + + public final char[] sub_chars(int offset, int count) { + if (count < 0) { + throw new StringIndexOutOfBoundsException(count); + } + + if (offset == 0) { + return buf; + } + char[] chars = new char[count]; + System.arraycopy(buf, offset, chars, 0, count); + return chars; + } + + public final String numberString() { + int offset = np; + if (offset == -1) { + offset = 0; + } + char chLocal = charAt(offset + sp - 1); + + int sp = this.sp; + if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { + sp--; + } + + String value = new String(buf, offset, sp); + return value; + } + + public final BigDecimal decimalValue() { + int offset = np; + if (offset == -1) { + offset = 0; + } + char chLocal = charAt(offset + sp - 1); + + int sp = this.sp; + if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { + sp--; + } + + return new BigDecimal(buf, offset, sp); + } + + public void close() { + super.close(); + + if (buf.length <= 1024 * 64) { + BUF_LOCAL.set(buf); + } + this.buf = null; + + IOUtils.close(reader); + } + + @Override + public boolean isEOF() { + return bufLength == -1 || bp == buf.length || ch == EOI && bp + 1 == buf.length; + } + + public final boolean isBlankInput() { + for (int i = 0;; ++i) { + char chLocal = buf[i]; + if (chLocal == EOI) { + token = JSONToken.EOF; + break; + } + + if (!isWhitespace(chLocal)) { + return false; + } + } + + return true; + } +} diff --git a/src/main/java/com/alibaba/fastjson/parser/JSONScanner.java b/src/main/java/com/alibaba/fastjson/parser/JSONScanner.java index e1eba1fe3a..e1241901cc 100644 --- a/src/main/java/com/alibaba/fastjson/parser/JSONScanner.java +++ b/src/main/java/com/alibaba/fastjson/parser/JSONScanner.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,80 +15,61 @@ */ package com.alibaba.fastjson.parser; -import static com.alibaba.fastjson.parser.JSONToken.COLON; -import static com.alibaba.fastjson.parser.JSONToken.COMMA; -import static com.alibaba.fastjson.parser.JSONToken.EOF; -import static com.alibaba.fastjson.parser.JSONToken.ERROR; -import static com.alibaba.fastjson.parser.JSONToken.LBRACE; -import static com.alibaba.fastjson.parser.JSONToken.LBRACKET; -import static com.alibaba.fastjson.parser.JSONToken.LITERAL_STRING; -import static com.alibaba.fastjson.parser.JSONToken.LPAREN; -import static com.alibaba.fastjson.parser.JSONToken.RBRACE; -import static com.alibaba.fastjson.parser.JSONToken.RBRACKET; -import static com.alibaba.fastjson.parser.JSONToken.RPAREN; - +import java.lang.reflect.Type; import java.math.BigDecimal; -import java.math.BigInteger; import java.util.ArrayList; import java.util.Calendar; +import java.util.Collection; +import java.util.HashSet; +import java.util.TimeZone; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.util.ASMUtils; +import com.alibaba.fastjson.util.IOUtils; +import com.alibaba.fastjson.util.TypeUtils; //这个类,为了性能优化做了很多特别处理,一切都是为了性能!!! /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ -public class JSONScanner implements JSONLexer { - - public final static byte EOI = 0x1A; - - private final char[] buf; - private int bp; - private final int buflen; - private int eofPos; - - /** - * The current character. - */ - private char ch; - - /** - * The token's position, 0-based offset from beginning of text. - */ - private int pos; - - /** - * A character buffer for literals. - */ - private char[] sbuf; - private int sp; +public final class JSONScanner extends JSONLexerBase { - /** - * number start position - */ - private int np; + private final String text; + private final int len; - /** - * The token, set by nextToken(). - */ - private int token; + public JSONScanner(String input){ + this(input, JSON.DEFAULT_PARSER_FEATURE); + } - private Keywords keywods = Keywords.DEFAULT_KEYWORDS; + public JSONScanner(String input, int features){ + super(features); - private final static ThreadLocal sbufRef = new ThreadLocal(); + text = input; + len = text.length(); + bp = -1; - private int features = JSON.DEFAULT_PARSER_FEATURE; + next(); + if (ch == 65279) { // utf-8 bom + next(); + } + } - private Calendar calendar = null; + public final char charAt(int index) { + if (index >= len) { + return EOI; + } - public JSONScanner(String input){ - this(input, JSON.DEFAULT_PARSER_FEATURE); + return text.charAt(index); } - public JSONScanner(String input, int features){ - this(input.toCharArray(), input.length(), features); + public final char next() { + int index = ++bp; + return ch = (index >= this.len ? // + EOI // + : text.charAt(index)); } public JSONScanner(char[] input, int inputLength){ @@ -96,913 +77,1255 @@ public JSONScanner(char[] input, int inputLength){ } public JSONScanner(char[] input, int inputLength, int features){ - this.features = features; + this(new String(input, 0, inputLength), features); + } - sbuf = sbufRef.get(); // new char[1024]; - if (sbuf == null) { - sbuf = new char[64]; - sbufRef.set(sbuf); - } + protected final void copyTo(int offset, int count, char[] dest) { + text.getChars(offset, offset + count, dest, 0); + } - eofPos = inputLength; + static boolean charArrayCompare(String src, int offset, char[] dest) { + final int destLen = dest.length; + if (destLen + offset > src.length()) { + return false; + } - if (inputLength == input.length) { - if (input.length > 0 && isWhitespace(input[input.length - 1])) { - inputLength--; - } else { - char[] newInput = new char[inputLength + 1]; - System.arraycopy(input, 0, newInput, 0, input.length); - input = newInput; + for (int i = 0; i < destLen; ++i) { + if (dest[i] != src.charAt(offset + i)) { + return false; } } - buf = input; - buflen = inputLength; - buf[buflen] = EOI; - bp = -1; - ch = buf[++bp]; + return true; + } + + public final boolean charArrayCompare(char[] chars) { + return charArrayCompare(text, bp, chars); } - public final int getBufferPosition() { - return bp; + public final int indexOf(char ch, int startIndex) { + return text.indexOf(ch, startIndex); } - public void reset(int mark, char mark_ch, int token) { - this.bp = mark; - this.ch = mark_ch; - this.token = token; + public final String addSymbol(int offset, int len, int hash, final SymbolTable symbolTable) { + return symbolTable.addSymbol(text, offset, len, hash); } - public boolean isBlankInput() { - for (int i = 0; i < buflen; ++i) { - if (!isWhitespace(buf[i])) { - return false; + public byte[] bytesValue() { + if (token == JSONToken.HEX) { + int start = np + 1, len = sp; + if (len % 2 != 0) { + throw new JSONException("illegal state. " + len); } - } - return true; - } + byte[] bytes = new byte[len / 2]; + for (int i = 0; i < bytes.length; ++i) { + char c0 = text.charAt(start + i * 2); + char c1 = text.charAt(start + i * 2 + 1); - public static final boolean isWhitespace(char ch) { - // 专门调整了判断顺序 - return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b'; - } + int b0 = c0 - (c0 <= 57 ? 48 : 55); + int b1 = c1 - (c1 <= 57 ? 48 : 55); + bytes[i] = (byte) ((b0 << 4) | b1); + } - /** - * Report an error at the current token position using the provided arguments. - */ - private void lexError(String key, Object... args) { - token = ERROR; + return bytes; + } + + return IOUtils.decodeBase64(text, np + 1, sp); } /** - * Return the current token, set by nextToken(). + * The value of a literal token, recorded as a string. For integers, leading 0x and 'l' suffixes are suppressed. */ - public final int token() { - return token; - } - - private static boolean[] whitespaceFlags = new boolean[256]; - static { - whitespaceFlags[' '] = true; - whitespaceFlags['\n'] = true; - whitespaceFlags['\r'] = true; - whitespaceFlags['\t'] = true; - whitespaceFlags['\f'] = true; - whitespaceFlags['\b'] = true; + public final String stringVal() { + if (!hasSpecial) { + return this.subString(np + 1, sp); + } else { + return new String(sbuf, 0, sp); + } } - public final void skipWhitespace() { - for (;;) { - if (whitespaceFlags[ch]) { - ch = buf[++bp]; - continue; + public final String subString(int offset, int count) { + if (ASMUtils.IS_ANDROID) { + if (count < sbuf.length) { + text.getChars(offset, offset + count, sbuf, 0); + return new String(sbuf, 0, count); } else { - break; + char[] chars = new char[count]; + text.getChars(offset, offset + count, chars, 0); + return new String(chars); } + } else { + return text.substring(offset, offset + count); } } - public final char getCurrent() { - return ch; + public final char[] sub_chars(int offset, int count) { + if (ASMUtils.IS_ANDROID && count < sbuf.length) { + text.getChars(offset, offset + count, sbuf, 0); + return sbuf; + } else { + char[] chars = new char[count]; + text.getChars(offset, offset + count, chars, 0); + return chars; + } } - public final void nextTokenWithColon() { - for (;;) { - if (ch == ':') { - ch = buf[++bp]; - nextToken(); - return; - } - - if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b') { - ch = buf[++bp]; - continue; - } + public final String numberString() { + char chLocal = charAt(np + sp - 1); - throw new JSONException("not match ':'"); + int sp = this.sp; + if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { + sp--; } + + return this.subString(np, sp); } - public final void nextTokenWithColon(int expect) { - for (;;) { - if (ch == ':') { - ch = buf[++bp]; - break; - } + public final BigDecimal decimalValue() { + char chLocal = charAt(np + sp - 1); - if (isWhitespace(ch)) { - ch = buf[++bp]; - continue; - } + int sp = this.sp; + if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { + sp--; + } - throw new JSONException("not match ':'"); + int offset = np, count = sp; + if (count < sbuf.length) { + text.getChars(offset, offset + count, sbuf, 0); + return new BigDecimal(sbuf, 0, count); + } else { + char[] chars = new char[count]; + text.getChars(offset, offset + count, chars, 0); + return new BigDecimal(chars); } + } - for (;;) { - if (expect == JSONToken.LITERAL_INT) { - if (ch >= '0' && ch <= '9') { - sp = 0; - pos = bp; - scanNumber(); - return; - } + public boolean scanISO8601DateIfMatch() { + return scanISO8601DateIfMatch(true); + } - if (ch == '"') { - sp = 0; - pos = bp; - scanString(); - return; - } - } else if (expect == JSONToken.LITERAL_STRING) { - if (ch == '"') { - sp = 0; - pos = bp; - scanString(); - return; - } + public boolean scanISO8601DateIfMatch(boolean strict) { + int rest = len - bp; + return scanISO8601DateIfMatch(strict, rest); + } - if (ch >= '0' && ch <= '9') { - sp = 0; - pos = bp; - scanNumber(); - return; - } + private boolean scanISO8601DateIfMatch(boolean strict, int rest) { + if (rest < 8) { + return false; + } - } else if (expect == JSONToken.LBRACE) { - if (ch == '{') { - token = JSONToken.LBRACE; - ch = buf[++bp]; - return; - } - if (ch == '[') { - token = JSONToken.LBRACKET; - ch = buf[++bp]; - return; + char c0 = charAt(bp); + char c1 = charAt(bp + 1); + char c2 = charAt(bp + 2); + char c3 = charAt(bp + 3); + char c4 = charAt(bp + 4); + char c5 = charAt(bp + 5); + char c6 = charAt(bp + 6); + char c7 = charAt(bp + 7); + + if ((!strict) && rest > 13) { + char c_r0 = charAt(bp + rest - 1); + char c_r1 = charAt(bp + rest - 2); + if (c0 == '/' && c1 == 'D' && c2 == 'a' && c3 == 't' && c4 == 'e' && c5 == '(' && c_r0 == '/' + && c_r1 == ')') { + int plusIndex = -1; + for (int i = 6; i < rest; ++i) { + char c = charAt(bp + i); + if (c == '+') { + plusIndex = i; + } else if (c < '0' || c > '9') { + break; + } } - } else if (expect == JSONToken.LBRACKET) { - if (ch == '[') { - token = JSONToken.LBRACKET; - ch = buf[++bp]; - return; + if (plusIndex == -1) { + return false; } + int offset = bp + 6; + String numberText = this.subString(offset, bp + plusIndex - offset); + long millis = Long.parseLong(numberText); - if (ch == '{') { - token = JSONToken.LBRACE; - ch = buf[++bp]; - return; - } - } + calendar = Calendar.getInstance(timeZone, locale); + calendar.setTimeInMillis(millis); - if (isWhitespace(ch)) { - ch = buf[++bp]; - continue; + token = JSONToken.LITERAL_ISO8601_DATE; + return true; } - - nextToken(); - break; } - } - public final void incrementBufferPosition() { - ch = buf[++bp]; - } + char c10; + if (rest == 8 + || rest == 14 + || (rest == 16 && ((c10 = charAt(bp + 10)) == 'T' || c10 == ' ')) + || (rest == 17 && charAt(bp + 6) != '-')) { + if (strict) { + return false; + } - public final void resetStringPosition() { - this.sp = 0; - } + char y0, y1, y2, y3, M0, M1, d0, d1; - public void nextToken(int expect) { - for (;;) { - switch (expect) { - case JSONToken.LBRACE: - if (ch == '{') { - token = JSONToken.LBRACE; - ch = buf[++bp]; - return; - } - if (ch == '[') { - token = JSONToken.LBRACKET; - ch = buf[++bp]; - return; - } - break; - case JSONToken.COMMA: - if (ch == ',') { - token = JSONToken.COMMA; - ch = buf[++bp]; - return; - } - if (ch == '}') { - token = JSONToken.RBRACE; - ch = buf[++bp]; - return; - } - if (ch == ']') { - token = JSONToken.RBRACKET; - ch = buf[++bp]; - return; - } + char c8 = charAt(bp + 8); - if (ch == EOI) { - token = JSONToken.EOF; - return; - } - break; - case JSONToken.LITERAL_INT: - if (ch >= '0' && ch <= '9') { - sp = 0; - pos = bp; - scanNumber(); - return; - } + final boolean c_47 = c4 == '-' && c7 == '-'; + final boolean sperate16 = c_47 && rest == 16; + final boolean sperate17 = c_47 && rest == 17; + if (sperate17 || sperate16) { + y0 = c0; + y1 = c1; + y2 = c2; + y3 = c3; + M0 = c5; + M1 = c6; + d0 = c8; + d1 = charAt(bp + 9); + } else { + y0 = c0; + y1 = c1; + y2 = c2; + y3 = c3; + M0 = c4; + M1 = c5; + d0 = c6; + d1 = c7; + } - if (ch == '"') { - sp = 0; - pos = bp; - scanString(); - return; - } - if (ch == '[') { - token = JSONToken.LBRACKET; - ch = buf[++bp]; - return; - } + if (!checkDate(y0, y1, y2, y3, M0, M1, d0, d1)) { + return false; + } - if (ch == '{') { - token = JSONToken.LBRACE; - ch = buf[++bp]; - return; - } + setCalendar(y0, y1, y2, y3, M0, M1, d0, d1); - break; - case JSONToken.LITERAL_STRING: - if (ch == '"') { - sp = 0; - pos = bp; - scanString(); - return; - } + int hour, minute, seconds, millis; + if (rest != 8) { + char c9 = charAt(bp + 9); + c10 = charAt(bp + 10); + char c11 = charAt(bp + 11); + char c12 = charAt(bp + 12); + char c13 = charAt(bp + 13); - if (ch >= '0' && ch <= '9') { - sp = 0; - pos = bp; - scanNumber(); - return; - } + char h0, h1, m0, m1, s0, s1; - if (ch == '[') { - token = JSONToken.LBRACKET; - ch = buf[++bp]; - return; - } + if ((sperate17 && c10 == 'T' && c13 == ':' && charAt(bp + 16) == 'Z') + || (sperate16 && (c10 == ' ' || c10 == 'T') && c13 == ':')) { + h0 = c11; + h1 = c12; + m0 = charAt(bp + 14); + m1 = charAt(bp + 15); + s0 = '0'; + s1 = '0'; + } else { + h0 = c8; + h1 = c9; + m0 = c10; + m1 = c11; + s0 = c12; + s1 = c13; + } - if (ch == '{') { - token = JSONToken.LBRACE; - ch = buf[++bp]; - return; - } - break; - case JSONToken.LBRACKET: - if (ch == '[') { - token = JSONToken.LBRACKET; - ch = buf[++bp]; - return; - } + if (!checkTime(h0, h1, m0, m1, s0, s1)) { + return false; + } - if (ch == '{') { - token = JSONToken.LBRACE; - ch = buf[++bp]; - return; + if (rest == 17 && !sperate17) { + char S0 = charAt(bp + 14); + char S1 = charAt(bp + 15); + char S2 = charAt(bp + 16); + if (S0 < '0' || S0 > '9') { + return false; } - break; - case JSONToken.RBRACKET: - if (ch == ']') { - token = JSONToken.RBRACKET; - ch = buf[++bp]; - return; + if (S1 < '0' || S1 > '9') { + return false; } - case JSONToken.EOF: - if (ch == EOI) { - token = JSONToken.EOF; - return; + if (S2 < '0' || S2 > '9') { + return false; } - break; - default: - break; - } - if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b') { - ch = buf[++bp]; - continue; + millis = (S0 - '0') * 100 + (S1 - '0') * 10 + (S2 - '0'); + } else { + millis = 0; + } + + hour = (h0 - '0') * 10 + (h1 - '0'); + minute = (m0 - '0') * 10 + (m1 - '0'); + seconds = (s0 - '0') * 10 + (s1 - '0'); + } else { + hour = 0; + minute = 0; + seconds = 0; + millis = 0; } - nextToken(); - break; - } - } + calendar.set(Calendar.HOUR_OF_DAY, hour); + calendar.set(Calendar.MINUTE, minute); + calendar.set(Calendar.SECOND, seconds); + calendar.set(Calendar.MILLISECOND, millis); - public final void nextToken() { - sp = 0; + token = JSONToken.LITERAL_ISO8601_DATE; + return true; + } - for (;;) { - pos = bp; + if (rest < 9) { + return false; + } - if (ch == '"') { - scanString(); - return; + char c8 = charAt(bp + 8); + char c9 = charAt(bp + 9); + + int date_len = 10; + char y0, y1, y2, y3, M0, M1, d0, d1; + if ((c4 == '-' && c7 == '-') // cn + || (c4 == '/' && c7 == '/') // tw yyyy/mm/dd + ) { + y0 = c0; + y1 = c1; + y2 = c2; + y3 = c3; + M0 = c5; + M1 = c6; + d0 = c8; + d1 = c9; + } else if ((c4 == '-' && c6 == '-') // cn yyyy-m-dd + ) { + y0 = c0; + y1 = c1; + y2 = c2; + y3 = c3; + M0 = '0'; + M1 = c5; + + if (c8 == ' ') { + d0 = '0'; + d1 = c7; + date_len = 8; + } else { + d0 = c7; + d1 = c8; + date_len = 9; + } + } else if ((c2 == '.' && c5 == '.') // de dd.mm.yyyy + || (c2 == '-' && c5 == '-') // in dd-mm-yyyy + ) { + d0 = c0; + d1 = c1; + M0 = c3; + M1 = c4; + y0 = c6; + y1 = c7; + y2 = c8; + y3 = c9; + } else { + if (c4 == '年' || c4 == '년') { + y0 = c0; + y1 = c1; + y2 = c2; + y3 = c3; + + if (c7 == '月' || c7 == '월') { + M0 = c5; + M1 = c6; + if (c9 == '日' || c9 == '일') { + d0 = '0'; + d1 = c8; + } else if (charAt(bp + 10) == '日' || charAt(bp + 10) == '일'){ + d0 = c8; + d1 = c9; + date_len = 11; + } else { + return false; + } + } else if (c6 == '月' || c6 == '월') { + M0 = '0'; + M1 = c5; + if (c8 == '日' || c8 == '일') { + d0 = '0'; + d1 = c7; + } else if (c9 == '日' || c9 == '일'){ + d0 = c7; + d1 = c8; + } else { + return false; + } + } else { + return false; + } + } else { + return false; } + } - if (ch == ',') { - ch = buf[++bp]; - token = COMMA; - return; - } + if (!checkDate(y0, y1, y2, y3, M0, M1, d0, d1)) { + return false; + } - if (ch >= '0' && ch <= '9') { - scanNumber(); - return; - } + setCalendar(y0, y1, y2, y3, M0, M1, d0, d1); - if (ch == '-') { - scanNumber(); - return; + char t = charAt(bp + date_len); + if (t == 'T' || (t == ' ' && !strict)) { + if (rest < date_len + 9) { // "0000-00-00T00:00:00".length() + return false; } + } else if (t == '"' || t == EOI || t == '日' || t == '일') { + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); - switch (ch) { - case '\'': - if (!isEnabled(Feature.AllowSingleQuotes)) { - throw new JSONException("Feature.AllowSingleQuotes is false"); - } - scanStringSingleQuote(); - return; - case ' ': - case '\t': - case '\b': - case '\f': - case '\n': - case '\r': - ch = buf[++bp]; - break; - case 't': // true - scanTrue(); - return; - case 'f': // false - scanFalse(); - return; - case 'n': // new,null - scanNullOrNew(); - return; - case 'D': // Date - scanIdent(); - return; - case '(': - ch = buf[++bp]; - token = LPAREN; - return; - case ')': - ch = buf[++bp]; - token = RPAREN; - return; - case '[': - ch = buf[++bp]; - token = LBRACKET; - return; - case ']': - ch = buf[++bp]; - token = RBRACKET; - return; - case '{': - ch = buf[++bp]; - token = LBRACE; - return; - case '}': - ch = buf[++bp]; - token = RBRACE; - return; - case ':': - ch = buf[++bp]; - token = COLON; - return; - default: - if (bp == buflen || ch == EOI && bp + 1 == buflen) { // JLS - if (token == EOF) { - throw new JSONException("EOF error"); - } + ch = charAt(bp += date_len); - token = EOF; - pos = bp = eofPos; - } else { - lexError("illegal.char", String.valueOf((int) ch)); - ch = buf[++bp]; - } + token = JSONToken.LITERAL_ISO8601_DATE; + return true; + } else if (t == '+' || t == '-') { + if (len == date_len + 6) { + if (charAt(bp + date_len + 3) != ':' // + || charAt(bp + date_len + 4) != '0' // + || charAt(bp + date_len + 5) != '0') { + return false; + } - return; + setTime('0', '0', '0', '0', '0', '0'); + calendar.set(Calendar.MILLISECOND, 0); + setTimeZone(t, charAt(bp + date_len + 1), charAt(bp + date_len + 2)); + return true; } + return false; + } else { + return false; } - } + if (charAt(bp + date_len + 3) != ':') { + return false; + } + if (charAt(bp + date_len + 6) != ':') { + return false; + } - boolean hasSpecial; + char h0 = charAt(bp + date_len + 1); + char h1 = charAt(bp + date_len + 2); + char m0 = charAt(bp + date_len + 4); + char m1 = charAt(bp + date_len + 5); + char s0 = charAt(bp + date_len + 7); + char s1 = charAt(bp + date_len + 8); - public final void scanStringSingleQuote() { - np = bp; - hasSpecial = false; - char ch; - for (;;) { - ch = buf[++bp]; + if (!checkTime(h0, h1, m0, m1, s0, s1)) { + return false; + } - if (ch == '\'') { - break; - } + setTime(h0, h1, m0, m1, s0, s1); - if (ch == EOI) { - throw new JSONException("unclosed single-quote string"); + char dot = charAt(bp + date_len + 9); + if (dot == '.') { + if (rest < date_len + 11) { // // 0000-00-00T00:00:00.000 + return false; } + } else { + calendar.set(Calendar.MILLISECOND, 0); - if (ch == '\\') { - if (!hasSpecial) { - hasSpecial = true; - - if (sp > sbuf.length) { - char[] newsbuf = new char[sp * 2]; - System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length); - sbuf = newsbuf; - } - - System.arraycopy(buf, np + 1, sbuf, 0, sp); - } + ch = charAt(bp += (date_len + 9)); - ch = buf[++bp]; + token = JSONToken.LITERAL_ISO8601_DATE; - switch (ch) { - case '"': - putChar('"'); - break; - case '\\': - putChar('\\'); - break; - case '/': - putChar('/'); - break; - case '\'': - putChar('\''); - break; - case 'b': - putChar('\b'); - break; - case 'f': - case 'F': - putChar('\f'); - break; - case 'n': - putChar('\n'); - break; - case 'r': - putChar('\r'); - break; - case 't': - putChar('\t'); - break; - case 'u': - char c1 = ch = buf[++bp]; - char c2 = ch = buf[++bp]; - char c3 = ch = buf[++bp]; - char c4 = ch = buf[++bp]; - int val = Integer.parseInt(new String(new char[] { c1, c2, c3, c4 }), 16); - putChar((char) val); - break; - default: - this.ch = ch; - throw new JSONException("unclosed single-quote string"); + if (dot == 'Z') {// UTC + // bugfix https://github.com/alibaba/fastjson/issues/376 + if (calendar.getTimeZone().getRawOffset() != 0) { + String[] timeZoneIDs = TimeZone.getAvailableIDs(0);// 没有+ 和 - 默认相对0 + if (timeZoneIDs.length > 0) { + TimeZone timeZone = TimeZone.getTimeZone(timeZoneIDs[0]); + calendar.setTimeZone(timeZone); + } } - continue; } + return true; + } - if (!hasSpecial) { - sp++; - continue; - } + char S0 = charAt(bp + date_len + 10); + if (S0 < '0' || S0 > '9') { + return false; + } + int millis = S0 - '0'; + int millisLen = 1; - if (sp == sbuf.length) { - putChar(ch); - } else { - sbuf[sp++] = ch; + if (rest > date_len + 11) { + char S1 = charAt(bp + date_len + 11); + if (S1 >= '0' && S1 <= '9') { + millis = millis * 10 + (S1 - '0'); + millisLen = 2; } } - token = LITERAL_STRING; - this.ch = buf[++bp]; - } + if (millisLen == 2) { + char S2 = charAt(bp + date_len + 12); + if (S2 >= '0' && S2 <= '9') { + millis = millis * 10 + (S2 - '0'); + millisLen = 3; + } + } - public final void scanString() { - np = bp; - hasSpecial = false; - char ch; - for (;;) { - ch = buf[++bp]; + calendar.set(Calendar.MILLISECOND, millis); - if (ch == '\"') { - break; + int timzeZoneLength = 0; + char timeZoneFlag = charAt(bp + date_len + 10 + millisLen); + if (timeZoneFlag == '+' || timeZoneFlag == '-') { + char t0 = charAt(bp + date_len + 10 + millisLen + 1); + if (t0 < '0' || t0 > '1') { + return false; } - if (ch == '\\') { - if (!hasSpecial) { - hasSpecial = true; + char t1 = charAt(bp + date_len + 10 + millisLen + 2); + if (t1 < '0' || t1 > '9') { + return false; + } - if (sp >= sbuf.length) { - int newCapcity = sbuf.length * 2; - if (sp > newCapcity) { - newCapcity = sp; - } - char[] newsbuf = new char[newCapcity]; - System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length); - sbuf = newsbuf; - } + char t2 = charAt(bp + date_len + 10 + millisLen + 3); + char t3 = '0', t4 = '0'; + if (t2 == ':') { // ThreeLetterISO8601TimeZone + t3 = charAt(bp + date_len + 10 + millisLen + 4); + if (t3 != '0' && t3 != '3') { + return false; + } - System.arraycopy(buf, np + 1, sbuf, 0, sp); + t4 = charAt(bp + date_len + 10 + millisLen + 5); + if (t4 != '0') { + return false; } + timzeZoneLength = 6; + } else if (t2 == '0') { // TwoLetterISO8601TimeZone + t3 = charAt(bp + date_len + 10 + millisLen + 4); + if (t3 != '0' && t3 != '3') { + return false; + } + timzeZoneLength = 5; + } else { + timzeZoneLength = 3; + } - ch = buf[++bp]; + setTimeZone(timeZoneFlag, t0, t1, t3, t4); - switch (ch) { - case '"': - putChar('"'); - break; - case '\\': - putChar('\\'); - break; - case '/': - putChar('/'); - break; - case 'b': - putChar('\b'); - break; - case 'f': - case 'F': - putChar('\f'); - break; - case 'n': - putChar('\n'); - break; - case 'r': - putChar('\r'); - break; - case 't': - putChar('\t'); - break; - case 'x': - char x1 = ch = buf[++bp]; - char x2 = ch = buf[++bp]; - - int x_val = digits[x1] * 16 + digits[x2]; - char x_char = (char) x_val; - putChar(x_char); - break; - case 'u': - char u1 = ch = buf[++bp]; - char u2 = ch = buf[++bp]; - char u3 = ch = buf[++bp]; - char u4 = ch = buf[++bp]; - int val = Integer.parseInt(new String(new char[] { u1, u2, u3, u4 }), 16); - putChar((char) val); - break; - default: - this.ch = ch; - throw new JSONException("unclosed string : " + ch); + } else if (timeZoneFlag == 'Z') {// UTC + timzeZoneLength = 1; + if (calendar.getTimeZone().getRawOffset() != 0) { + String[] timeZoneIDs = TimeZone.getAvailableIDs(0); + if (timeZoneIDs.length > 0) { + TimeZone timeZone = TimeZone.getTimeZone(timeZoneIDs[0]); + calendar.setTimeZone(timeZone); } - continue; - } - - if (!hasSpecial) { - sp++; - continue; } + } - if (sp == sbuf.length) { - putChar(ch); - } else { - sbuf[sp++] = ch; - } + char end = charAt(bp + (date_len + 10 + millisLen + timzeZoneLength)); + if (end != EOI && end != '"') { + return false; } + ch = charAt(bp += (date_len + 10 + millisLen + timzeZoneLength)); - token = LITERAL_STRING; - this.ch = buf[++bp]; + token = JSONToken.LITERAL_ISO8601_DATE; + return true; } - public final String scanSymbolUnQuoted(final SymbolTable symbolTable) { - final boolean[] firstIdentifierFlags = CharTypes.firstIdentifierFlags; - final char first = ch; + protected void setTime(char h0, char h1, char m0, char m1, char s0, char s1) { + int hour = (h0 - '0') * 10 + (h1 - '0'); + int minute = (m0 - '0') * 10 + (m1 - '0'); + int seconds = (s0 - '0') * 10 + (s1 - '0'); + calendar.set(Calendar.HOUR_OF_DAY, hour); + calendar.set(Calendar.MINUTE, minute); + calendar.set(Calendar.SECOND, seconds); + } - final boolean firstFlag = ch >= firstIdentifierFlags.length || firstIdentifierFlags[first]; - if (!firstFlag) { - throw new JSONException("illegal identifier : " + ch); - } + protected void setTimeZone(char timeZoneFlag, char t0, char t1) { + setTimeZone(timeZoneFlag, t0, t1, '0', '0'); + } - final boolean[] identifierFlags = CharTypes.identifierFlags; + protected void setTimeZone(char timeZoneFlag, char t0, char t1, char t3, char t4) { + int timeZoneOffset = ((t0 - '0') * 10 + (t1 - '0')) * 3600 * 1000; - int hash = first; + timeZoneOffset += ((t3 - '0') * 10 + (t4 - '0')) * 60 * 1000; - np = bp; - sp = 1; - char ch; - for (;;) { - ch = buf[++bp]; + if (timeZoneFlag == '-') { + timeZoneOffset = -timeZoneOffset; + } - if (ch < identifierFlags.length) { - if (!identifierFlags[ch]) { - break; - } + if (calendar.getTimeZone().getRawOffset() != timeZoneOffset) { + String[] timeZoneIDs = TimeZone.getAvailableIDs(timeZoneOffset); + if (timeZoneIDs.length > 0) { + TimeZone timeZone = TimeZone.getTimeZone(timeZoneIDs[0]); + calendar.setTimeZone(timeZone); + } + } + } + + private boolean checkTime(char h0, char h1, char m0, char m1, char s0, char s1) { + if (h0 == '0') { + if (h1 < '0' || h1 > '9') { + return false; + } + } else if (h0 == '1') { + if (h1 < '0' || h1 > '9') { + return false; } + } else if (h0 == '2') { + if (h1 < '0' || h1 > '4') { + return false; + } + } else { + return false; + } - hash = 31 * hash + ch; + if (m0 >= '0' && m0 <= '5') { + if (m1 < '0' || m1 > '9') { + return false; + } + } else if (m0 == '6') { + if (m1 != '0') { + return false; + } + } else { + return false; + } - sp++; - continue; + if (s0 >= '0' && s0 <= '5') { + if (s1 < '0' || s1 > '9') { + return false; + } + } else if (s0 == '6') { + if (s1 != '0') { + return false; + } + } else { + return false; } - this.ch = buf[bp]; - token = JSONToken.IDENTIFIER; + return true; + } - return symbolTable.addSymbol(buf, np, sp, hash); + private void setCalendar(char y0, char y1, char y2, char y3, char M0, char M1, char d0, char d1) { + calendar = Calendar.getInstance(timeZone, locale); + int year = (y0 - '0') * 1000 + (y1 - '0') * 100 + (y2 - '0') * 10 + (y3 - '0'); + int month = (M0 - '0') * 10 + (M1 - '0') - 1; + int day = (d0 - '0') * 10 + (d1 - '0'); +// calendar.set(year, month, day); + calendar.set(Calendar.YEAR, year); + calendar.set(Calendar.MONTH, month); + calendar.set(Calendar.DAY_OF_MONTH, day); } - public final static int NOT_MATCH = -1; - public final static int NOT_MATCH_NAME = -2; - public final static int UNKOWN = 0; - public final static int OBJECT = 1; - public final static int ARRAY = 2; - public final static int VALUE = 3; - public final static int END = 4; - - public boolean matchField(char[] fieldName) { - final int fieldNameLength = fieldName.length; - for (int i = 0; i < fieldNameLength; ++i) { - if (fieldName[i] != buf[bp + i]) { + static boolean checkDate(char y0, char y1, char y2, char y3, char M0, char M1, int d0, int d1) { + if (y0 < '1' || y0 > '3') { + return false; + } + if (y1 < '0' || y1 > '9') { + return false; + } + if (y2 < '0' || y2 > '9') { + return false; + } + if (y3 < '0' || y3 > '9') { + return false; + } + + if (M0 == '0') { + if (M1 < '1' || M1 > '9') { + return false; + } + } else if (M0 == '1') { + if (M1 != '0' && M1 != '1' && M1 != '2') { return false; } + } else { + return false; } - bp = bp + fieldNameLength; - ch = buf[bp]; - - if (ch == '{') { - ch = buf[++bp]; - token = JSONToken.LBRACE; - } else if (ch == '[') { - ch = buf[++bp]; - token = JSONToken.LBRACKET; + if (d0 == '0') { + if (d1 < '1' || d1 > '9') { + return false; + } + } else if (d0 == '1' || d0 == '2') { + if (d1 < '0' || d1 > '9') { + return false; + } + } else if (d0 == '3') { + if (d1 != '0' && d1 != '1') { + return false; + } } else { - nextToken(); + return false; } return true; } - public int matchStat = UNKOWN; + @Override + public boolean isEOF() { + return bp == len || ch == EOI && bp + 1 == len; + } - public String scanFieldString(char[] fieldName) { - matchStat = UNKOWN; + public int scanFieldInt(char[] fieldName) { + matchStat = UNKNOWN; + int startPos = this.bp; + char startChar = this.ch; - final int fieldNameLength = fieldName.length; - for (int i = 0; i < fieldNameLength; ++i) { - if (fieldName[i] != buf[bp + i]) { - matchStat = NOT_MATCH_NAME; - return null; - } + if (!charArrayCompare(text, bp, fieldName)) { + matchStat = NOT_MATCH_NAME; + return 0; } - int index = bp + fieldNameLength; + int index = bp + fieldName.length; - char ch = buf[index++]; - if (ch != '"') { - matchStat = NOT_MATCH; - return null; + char ch = charAt(index++); + + final boolean quote = ch == '"'; + + if (quote) { + ch = charAt(index++); } - String strVal; - int start = index; - for (;;) { - ch = buf[index++]; - if (ch == '\"') { - bp = index; - this.ch = ch = buf[bp]; - strVal = new String(buf, start, index - start - 1); - break; + final boolean negative = ch == '-'; + if (negative) { + ch = charAt(index++); + } + + int value; + if (ch >= '0' && ch <= '9') { + value = ch - '0'; + for (;;) { + ch = charAt(index++); + if (ch >= '0' && ch <= '9') { + value = value * 10 + (ch - '0'); + } else if (ch == '.') { + matchStat = NOT_MATCH; + return 0; + } else { + break; + } } - if (ch == '\\') { + if (value < 0) { matchStat = NOT_MATCH; - return null; + return 0; + } + + if (quote) { + if (ch != '"') { + matchStat = NOT_MATCH; + return 0; + } else { + ch = charAt(index++); + } + } + + for (;;) { + if (ch == ',' || ch == '}') { + bp = index - 1; + break; + } else if(isWhitespace(ch)) { + ch = charAt(index++); + continue; + } else { + matchStat = NOT_MATCH; + return 0; + } } + } else { + matchStat = NOT_MATCH; + return 0; } if (ch == ',') { - this.ch = buf[++bp]; + this.ch = charAt(++bp); matchStat = VALUE; - return strVal; - } else if (ch == '}') { - ch = buf[++bp]; - if (ch == ',') { - token = JSONToken.COMMA; - this.ch = buf[++bp]; - } else if (ch == ']') { - token = JSONToken.RBRACKET; - this.ch = buf[++bp]; - } else if (ch == '}') { - token = JSONToken.RBRACE; - this.ch = buf[++bp]; - } else if (ch == EOI) { - token = JSONToken.EOF; - } else { - matchStat = NOT_MATCH; - return null; + token = JSONToken.COMMA; + return negative ? -value : value; + } + + if (ch == '}') { + bp = index - 1; + ch = charAt(++bp); + for (; ; ) { + if (ch == ',') { + token = JSONToken.COMMA; + this.ch = charAt(++bp); + break; + } else if (ch == ']') { + token = JSONToken.RBRACKET; + this.ch = charAt(++bp); + break; + } else if (ch == '}') { + token = JSONToken.RBRACE; + this.ch = charAt(++bp); + break; + } else if (ch == EOI) { + token = JSONToken.EOF; + break; + } else if (isWhitespace(ch)) { + ch = charAt(++bp); + continue; + } else { + this.bp = startPos; + this.ch = startChar; + matchStat = NOT_MATCH; + return 0; + } } matchStat = END; - } else { - matchStat = NOT_MATCH; - return null; } - return strVal; + return negative ? -value : value; } - - public String scanFieldSymbol(char[] fieldName, final SymbolTable symbolTable) { - matchStat = UNKOWN; - final int fieldNameLength = fieldName.length; - for (int i = 0; i < fieldNameLength; ++i) { - if (fieldName[i] != buf[bp + i]) { + public String scanFieldString(char[] fieldName) { + matchStat = UNKNOWN; + int startPos = this.bp; + char startChar = this.ch; + + for (;;) { + if (!charArrayCompare(text, bp, fieldName)) { + if (isWhitespace(ch)) { + next(); + continue; + } matchStat = NOT_MATCH_NAME; - return null; + return stringDefaultValue(); + } else { + break; } } - int index = bp + fieldNameLength; + int index = bp + fieldName.length; - char ch = buf[index++]; + char ch = charAt(index++); if (ch != '"') { matchStat = NOT_MATCH; - return null; + + return stringDefaultValue(); } - String strVal; - int start = index; - int hash = 0; - for (;;) { - ch = buf[index++]; - if (ch == '\"') { - bp = index; - this.ch = ch = buf[bp]; - strVal = symbolTable.addSymbol(buf, start, index - start - 1, hash); - break; + final String strVal; + { + int startIndex = index; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); } - - hash = 31 * hash + ch; - if (ch == '\\') { - matchStat = NOT_MATCH; - return null; + String stringVal = subString(startIndex, endIndex - startIndex); + if (stringVal.indexOf('\\') != -1) { + for (;;) { + int slashCount = 0; + for (int i = endIndex - 1; i >= 0; --i) { + if (charAt(i) == '\\') { + slashCount++; + } else { + break; + } + } + if (slashCount % 2 == 0) { + break; + } + endIndex = indexOf('"', endIndex + 1); + } + + int chars_len = endIndex - (bp + fieldName.length + 1); + char[] chars = sub_chars(bp + fieldName.length + 1, chars_len); + + stringVal = readString(chars, chars_len); + } + + ch = charAt(endIndex + 1); + + for (;;) { + if (ch == ',' || ch == '}') { + bp = endIndex + 1; + this.ch = ch; + strVal = stringVal; + break; + } else if (isWhitespace(ch)) { + endIndex++; + ch = charAt(endIndex + 1); + } else { + matchStat = NOT_MATCH; + + return stringDefaultValue(); + } } } if (ch == ',') { - this.ch = buf[++bp]; + this.ch = charAt(++bp); matchStat = VALUE; return strVal; - } else if (ch == '}') { - ch = buf[++bp]; + } else { + //condition ch == '}' is always 'true' + ch = charAt(++bp); if (ch == ',') { token = JSONToken.COMMA; - this.ch = buf[++bp]; + this.ch = charAt(++bp); } else if (ch == ']') { token = JSONToken.RBRACKET; - this.ch = buf[++bp]; + this.ch = charAt(++bp); } else if (ch == '}') { token = JSONToken.RBRACE; - this.ch = buf[++bp]; + this.ch = charAt(++bp); } else if (ch == EOI) { token = JSONToken.EOF; } else { + this.bp = startPos; + this.ch = startChar; matchStat = NOT_MATCH; - return null; + return stringDefaultValue(); } matchStat = END; - } else { - matchStat = NOT_MATCH; - return null; } - return strVal; } - public ArrayList scanFieldStringArray(char[] fieldName) { - matchStat = UNKOWN; - - ArrayList list = new ArrayList(); + public java.util.Date scanFieldDate(char[] fieldName) { + matchStat = UNKNOWN; + int startPos = this.bp; + char startChar = this.ch; - final int fieldNameLength = fieldName.length; - for (int i = 0; i < fieldNameLength; ++i) { - if (fieldName[i] != buf[bp + i]) { - matchStat = NOT_MATCH_NAME; - return null; - } + if (!charArrayCompare(text, bp, fieldName)) { + matchStat = NOT_MATCH_NAME; + return null; } - int index = bp + fieldNameLength; + int index = bp + fieldName.length; - char ch = buf[index++]; - - if (ch != '[') { - matchStat = NOT_MATCH; - return null; - } + char ch = charAt(index++); - ch = buf[index++]; + final java.util.Date dateVal; + if (ch == '"') { + int startIndex = index; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); + } - for (;;) { - if (ch != '"') { + int rest = endIndex - startIndex; + bp = index; + if (scanISO8601DateIfMatch(false, rest)) { + dateVal = calendar.getTime(); + } else { + bp = startPos; matchStat = NOT_MATCH; return null; } + ch = charAt(endIndex + 1); + bp = startPos; - String strVal; - int start = index; - for (;;) { - ch = buf[index++]; - if (ch == '\"') { - strVal = new String(buf, start, index - start - 1); - list.add(strVal); - ch = buf[index++]; + for (; ; ) { + if (ch == ',' || ch == '}') { + bp = endIndex + 1; + this.ch = ch; break; - } - - if (ch == '\\') { + } else if (isWhitespace(ch)) { + endIndex++; + ch = charAt(endIndex + 1); + } else { matchStat = NOT_MATCH; + return null; } } + } else if (ch == '-' || (ch >= '0' && ch <= '9')) { + long millis = 0; - if (ch == ',') { - ch = buf[index++]; - continue; - } - - if (ch == ']') { - ch = buf[index++]; - break; + boolean negative = false; + if (ch == '-') { + ch = charAt(index++); + negative = true; } + if (ch >= '0' && ch <= '9') { + millis = ch - '0'; + for (; ; ) { + ch = charAt(index++); + if (ch >= '0' && ch <= '9') { + millis = millis * 10 + (ch - '0'); + } else { + if (ch == ',' || ch == '}') { + bp = index - 1; + } + break; + } + } + } + + if (millis < 0) { + matchStat = NOT_MATCH; + return null; + } + + if (negative) { + millis = -millis; + } + + dateVal = new java.util.Date(millis); + } else { matchStat = NOT_MATCH; + return null; } - bp = index; if (ch == ',') { - this.ch = buf[bp]; + this.ch = charAt(++bp); matchStat = VALUE; - return list; - } else if (ch == '}') { - ch = buf[bp]; + token = JSONToken.COMMA; + return dateVal; + } else { + //condition ch == '}' is always 'true' + ch = charAt(++bp); if (ch == ',') { token = JSONToken.COMMA; - this.ch = buf[++bp]; + this.ch = charAt(++bp); } else if (ch == ']') { token = JSONToken.RBRACKET; - this.ch = buf[++bp]; + this.ch = charAt(++bp); } else if (ch == '}') { token = JSONToken.RBRACE; - this.ch = buf[++bp]; + this.ch = charAt(++bp); } else if (ch == EOI) { token = JSONToken.EOF; - this.ch = ch; } else { + this.bp = startPos; + this.ch = startChar; + matchStat = NOT_MATCH; + return null; + } + matchStat = END; + } + return dateVal; + } + + public long scanFieldSymbol(char[] fieldName) { + matchStat = UNKNOWN; + + if (!charArrayCompare(text, bp, fieldName)) { + matchStat = NOT_MATCH_NAME; + return 0; + } + + int index = bp + fieldName.length; + + char ch = charAt(index++); + if (ch != '"') { + matchStat = NOT_MATCH; + return 0; + } + + long hash = 0xcbf29ce484222325L; + for (;;) { + ch = charAt(index++); + if (ch == '\"') { + bp = index; + this.ch = ch = charAt(bp); + break; + } else if (index > len) { + matchStat = NOT_MATCH; + return 0; + } + + hash ^= ch; + hash *= 0x100000001b3L; + } + + for (;;) { + if (ch == ',') { + this.ch = charAt(++bp); + matchStat = VALUE; + return hash; + } else if (ch == '}') { + next(); + skipWhitespace(); + ch = getCurrent(); + if (ch == ',') { + token = JSONToken.COMMA; + this.ch = charAt(++bp); + } else if (ch == ']') { + token = JSONToken.RBRACKET; + this.ch = charAt(++bp); + } else if (ch == '}') { + token = JSONToken.RBRACE; + this.ch = charAt(++bp); + } else if (ch == EOI) { + token = JSONToken.EOF; + } else { + matchStat = NOT_MATCH; + return 0; + } + matchStat = END; + break; + } else if (isWhitespace(ch)) { + ch = charAt(++bp); + continue; + } else { + matchStat = NOT_MATCH; + return 0; + } + } + + return hash; + } + + public Collection newCollectionByType(Class type){ + if (type.isAssignableFrom(HashSet.class)) { + HashSet list = new HashSet(); + return list; + } else if (type.isAssignableFrom(ArrayList.class)) { + ArrayList list2 = new ArrayList(); + return list2; + } else { + try { + Collection list = (Collection) type.newInstance(); + return list; + } catch (Exception e) { + throw new JSONException(e.getMessage(), e); + } + } + } + + @SuppressWarnings("unchecked") + public Collection scanFieldStringArray(char[] fieldName, Class type) { + matchStat = UNKNOWN; + + if (!charArrayCompare(text, bp, fieldName)) { + matchStat = NOT_MATCH_NAME; + return null; + } + + Collection list = newCollectionByType(type); + +// if (type.isAssignableFrom(HashSet.class)) { +// list = new HashSet(); +// } else if (type.isAssignableFrom(ArrayList.class)) { +// list = new ArrayList(); +// } else { +// try { +// list = (Collection) type.newInstance(); +// } catch (Exception e) { +// throw new JSONException(e.getMessage(), e); +// } +// } + + int index = bp + fieldName.length; + + char ch = charAt(index++); + + if (ch == '[') { + ch = charAt(index++); + + for (;;) { + if (ch == '"') { + int startIndex = index; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); + } + + String stringVal = subString(startIndex, endIndex - startIndex); + if (stringVal.indexOf('\\') != -1) { + for (;;) { + int slashCount = 0; + for (int i = endIndex - 1; i >= 0; --i) { + if (charAt(i) == '\\') { + slashCount++; + } else { + break; + } + } + if (slashCount % 2 == 0) { + break; + } + endIndex = indexOf('"', endIndex + 1); + } + + int chars_len = endIndex - startIndex; + char[] chars = sub_chars(startIndex, chars_len); + + stringVal = readString(chars, chars_len); + } + + index = endIndex + 1; + ch = charAt(index++); + + list.add(stringVal); + } else if (ch == 'n' && text.startsWith("ull", index)) { + index += 3; + ch = charAt(index++); + list.add(null); + } else if (ch == ']' && list.size() == 0) { + ch = charAt(index++); + break; + } else { + matchStat = NOT_MATCH; + return null; + } + + if (ch == ',') { + ch = charAt(index++); + continue; + } + + if (ch == ']') { + ch = charAt(index++); + while (isWhitespace(ch)) { + ch = charAt(index++); + } + break; + } + matchStat = NOT_MATCH; return null; } + } else if (text.startsWith("ull", index)) { + index += 3; + ch = charAt(index++); + list = null; + } else { + matchStat = NOT_MATCH; + return null; + } + + bp = index; + if (ch == ',') { + this.ch = charAt(bp); + matchStat = VALUE; + return list; + } else if (ch == '}') { + ch = charAt(bp); + for (;;) { + if (ch == ',') { + token = JSONToken.COMMA; + this.ch = charAt(++bp); + break; + } else if (ch == ']') { + token = JSONToken.RBRACKET; + this.ch = charAt(++bp); + break; + } else if (ch == '}') { + token = JSONToken.RBRACE; + this.ch = charAt(++bp); + break; + } else if (ch == EOI) { + token = JSONToken.EOF; + this.ch = ch; + break; + } else { + boolean space = false; + while (isWhitespace(ch)) { + ch = charAt(index++); + bp = index; + space = true; + } + if (space) { + continue; + } + + matchStat = NOT_MATCH; + return null; + } + } + matchStat = END; } else { matchStat = NOT_MATCH; @@ -1012,191 +1335,294 @@ public ArrayList scanFieldStringArray(char[] fieldName) { return list; } - public int scanFieldInt(char[] fieldName) { - matchStat = UNKOWN; + public long scanFieldLong(char[] fieldName) { + matchStat = UNKNOWN; + int startPos = this.bp; + char startChar = this.ch; - final int fieldNameLength = fieldName.length; - for (int i = 0; i < fieldNameLength; ++i) { - if (fieldName[i] != buf[bp + i]) { - matchStat = NOT_MATCH_NAME; - return 0; - } + if (!charArrayCompare(text, bp, fieldName)) { + matchStat = NOT_MATCH_NAME; + return 0; } - int index = bp + fieldNameLength; + int index = bp + fieldName.length; - char ch = buf[index++]; + char ch = charAt(index++); - int value; + final boolean quote = ch == '"'; + if (quote) { + ch = charAt(index++); + } + + boolean negative = false; + if (ch == '-') { + ch = charAt(index++); + negative = true; + } + + long value; if (ch >= '0' && ch <= '9') { - value = digits[ch]; + value = ch - '0'; for (;;) { - ch = buf[index++]; + ch = charAt(index++); if (ch >= '0' && ch <= '9') { - value = value * 10 + digits[ch]; + value = value * 10 + (ch - '0'); } else if (ch == '.') { matchStat = NOT_MATCH; return 0; } else { - bp = index - 1; + if (quote) { + if (ch != '"') { + matchStat = NOT_MATCH; + return 0; + } else { + ch = charAt(index++); + } + } + + if (ch == ',' || ch == '}') { + bp = index - 1; + } break; } } - if (value < 0) { + + boolean valid = value >= 0 || (value == -9223372036854775808L && negative); + if (!valid) { + this.bp = startPos; + this.ch = startChar; matchStat = NOT_MATCH; return 0; } } else { + this.bp = startPos; + this.ch = startChar; matchStat = NOT_MATCH; return 0; } - if (ch == ',') { - ch = buf[++bp]; - matchStat = VALUE; - token = JSONToken.COMMA; - return value; - } - - if (ch == '}') { - ch = buf[++bp]; + for (;;) { if (ch == ',') { + this.ch = charAt(++bp); + matchStat = VALUE; token = JSONToken.COMMA; - this.ch = buf[++bp]; - } else if (ch == ']') { - token = JSONToken.RBRACKET; - this.ch = buf[++bp]; + return negative ? -value : value; } else if (ch == '}') { - token = JSONToken.RBRACE; - this.ch = buf[++bp]; - } else if (ch == EOI) { - token = JSONToken.EOF; + ch = charAt(++bp); + for (;;) { + if (ch == ',') { + token = JSONToken.COMMA; + this.ch = charAt(++bp); + break; + } else if (ch == ']') { + token = JSONToken.RBRACKET; + this.ch = charAt(++bp); + break; + } else if (ch == '}') { + token = JSONToken.RBRACE; + this.ch = charAt(++bp); + break; + } else if (ch == EOI) { + token = JSONToken.EOF; + break; + } else if (isWhitespace(ch)) { + ch = charAt(++bp); + } else { + this.bp = startPos; + this.ch = startChar; + matchStat = NOT_MATCH; + return 0; + } + } + matchStat = END; + break; + } else if (isWhitespace(ch)) { + bp = index; + ch = charAt(index++); + continue; } else { matchStat = NOT_MATCH; return 0; } - matchStat = END; } - return value; + return negative ? -value : value; } public boolean scanFieldBoolean(char[] fieldName) { - matchStat = UNKOWN; + matchStat = UNKNOWN; - final int fieldNameLength = fieldName.length; - for (int i = 0; i < fieldNameLength; ++i) { - if (fieldName[i] != buf[bp + i]) { - matchStat = NOT_MATCH_NAME; - return false; - } + if (!charArrayCompare(text, bp, fieldName)) { + matchStat = NOT_MATCH_NAME; + return false; } - int index = bp + fieldNameLength; + int startPos = bp; + int index = bp + fieldName.length; + + char ch = charAt(index++); - char ch = buf[index++]; + final boolean quote = ch == '"'; + if (quote) { + ch = charAt(index++); + } boolean value; if (ch == 't') { - if (buf[index++] != 'r') { + if (charAt(index++) != 'r') { + matchStat = NOT_MATCH; + return false; + } + if (charAt(index++) != 'u') { matchStat = NOT_MATCH; return false; } - if (buf[index++] != 'u') { + if (charAt(index++) != 'e') { matchStat = NOT_MATCH; return false; } - if (buf[index++] != 'e') { + + if (quote && charAt(index++) != '"') { matchStat = NOT_MATCH; return false; } bp = index; - ch = buf[bp]; + ch = charAt(bp); value = true; } else if (ch == 'f') { - if (buf[index++] != 'a') { + if (charAt(index++) != 'a') { + matchStat = NOT_MATCH; + return false; + } + if (charAt(index++) != 'l') { + matchStat = NOT_MATCH; + return false; + } + if (charAt(index++) != 's') { matchStat = NOT_MATCH; return false; } - if (buf[index++] != 'l') { + if (charAt(index++) != 'e') { matchStat = NOT_MATCH; return false; } - if (buf[index++] != 's') { + + if (quote && charAt(index++) != '"') { matchStat = NOT_MATCH; return false; } - if (buf[index++] != 'e') { + + bp = index; + ch = charAt(bp); + value = false; + } else if (ch == '1') { + if (quote && charAt(index++) != '"') { + matchStat = NOT_MATCH; + return false; + } + + bp = index; + ch = charAt(bp); + value = true; + } else if (ch == '0') { + if (quote && charAt(index++) != '"') { matchStat = NOT_MATCH; return false; } bp = index; - ch = buf[bp]; + ch = charAt(bp); value = false; } else { matchStat = NOT_MATCH; return false; } - if (ch == ',') { - ch = buf[++bp]; - matchStat = VALUE; - token = JSONToken.COMMA; - } else if (ch == '}') { - ch = buf[++bp]; + for (;;) { if (ch == ',') { + this.ch = charAt(++bp); + matchStat = VALUE; token = JSONToken.COMMA; - this.ch = buf[++bp]; - } else if (ch == ']') { - token = JSONToken.RBRACKET; - this.ch = buf[++bp]; + break; } else if (ch == '}') { - token = JSONToken.RBRACE; - this.ch = buf[++bp]; - } else if (ch == EOI) { - token = JSONToken.EOF; + ch = charAt(++bp); + for (;;) { + if (ch == ',') { + token = JSONToken.COMMA; + this.ch = charAt(++bp); + } else if (ch == ']') { + token = JSONToken.RBRACKET; + this.ch = charAt(++bp); + } else if (ch == '}') { + token = JSONToken.RBRACE; + this.ch = charAt(++bp); + } else if (ch == EOI) { + token = JSONToken.EOF; + } else if (isWhitespace(ch)) { + ch = charAt(++bp); + continue; + } else { + matchStat = NOT_MATCH; + return false; + } + break; + } + matchStat = END; + break; + } else if (isWhitespace(ch)) { + ch = charAt(++bp); } else { + bp = startPos; + ch = charAt(bp); matchStat = NOT_MATCH; return false; } - matchStat = END; - } else { - matchStat = NOT_MATCH; - return false; } return value; } - public long scanFieldLong(char[] fieldName) { - matchStat = UNKOWN; + public final int scanInt(char expectNext) { + matchStat = UNKNOWN; - final int fieldNameLength = fieldName.length; - for (int i = 0; i < fieldNameLength; ++i) { - if (fieldName[i] != buf[bp + i]) { - matchStat = NOT_MATCH_NAME; - return 0; - } + int offset = bp; + char chLocal = charAt(offset++); + + while (isWhitespace(chLocal)) { + chLocal = charAt(offset++); } - int index = bp + fieldNameLength; + final boolean quote = chLocal == '"'; - char ch = buf[index++]; + if (quote) { + chLocal = charAt(offset++); + } - long value; - if (ch >= '0' && ch <= '9') { - value = digits[ch]; + final boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(offset++); + } + + int value; + if (chLocal >= '0' && chLocal <= '9') { + value = chLocal - '0'; for (;;) { - ch = buf[index++]; - if (ch >= '0' && ch <= '9') { - value = value * 10 + digits[ch]; - } else if (ch == '.') { - token = NOT_MATCH; + chLocal = charAt(offset++); + if (chLocal >= '0' && chLocal <= '9') { + value = value * 10 + (chLocal - '0'); + } else if (chLocal == '.') { + matchStat = NOT_MATCH; return 0; } else { - bp = index - 1; + if (quote) { + if (chLocal != '"') { + matchStat = NOT_MATCH; + return 0; + } else { + chLocal = charAt(offset++); + } + } break; } } @@ -1204,75 +1630,102 @@ public long scanFieldLong(char[] fieldName) { matchStat = NOT_MATCH; return 0; } - } else { - matchStat = NOT_MATCH; - return 0; - } + } else if (chLocal == 'n' + && charAt(offset++) == 'u' + && charAt(offset++) == 'l' + && charAt(offset++) == 'l') { + matchStat = VALUE_NULL; + value = 0; + chLocal = charAt(offset++); - if (ch == ',') { - ch = buf[++bp]; - matchStat = VALUE; - token = JSONToken.COMMA; - return value; - } else if (ch == '}') { - ch = buf[++bp]; - if (ch == ',') { - token = JSONToken.COMMA; - this.ch = buf[++bp]; - } else if (ch == ']') { - token = JSONToken.RBRACKET; - this.ch = buf[++bp]; - } else if (ch == '}') { - token = JSONToken.RBRACE; - this.ch = buf[++bp]; - } else if (ch == EOI) { - token = JSONToken.EOF; - } else { - matchStat = NOT_MATCH; - return 0; + if (quote && chLocal == '"') { + chLocal = charAt(offset++); } - matchStat = END; + + for (;;) { + if (chLocal == ',') { + bp = offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == ']') { + bp = offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACKET; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return 0; } else { matchStat = NOT_MATCH; return 0; } - return value; + for (;;) { + if (chLocal == expectNext) { + bp = offset; + this.ch = charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return negative ? -value : value; + } else { + if (isWhitespace(chLocal)) { + chLocal = charAt(offset++); + continue; + } + matchStat = NOT_MATCH; + return negative ? -value : value; + } + } } - public float scanFieldFloat(char[] fieldName) { - matchStat = UNKOWN; + public double scanDouble(char seperator) { + matchStat = UNKNOWN; - final int fieldNameLength = fieldName.length; - for (int i = 0; i < fieldNameLength; ++i) { - if (fieldName[i] != buf[bp + i]) { - matchStat = NOT_MATCH_NAME; - return 0; - } + int offset = bp; + char chLocal = charAt(offset++); + final boolean quote = chLocal == '"'; + if (quote) { + chLocal = charAt(offset++); } - int index = bp + fieldNameLength; - - char ch = buf[index++]; + boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(offset++); + } - float value; - if (ch >= '0' && ch <= '9') { - int start = index - 1; - for (;;) { - ch = buf[index++]; - if (ch >= '0' && ch <= '9') { + double value; + if (chLocal >= '0' && chLocal <= '9') { + long intVal = chLocal - '0'; + for (; ; ) { + chLocal = charAt(offset++); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); continue; } else { break; } } - if (ch == '.') { - ch = buf[index++]; - if (ch >= '0' && ch <= '9') { - for (;;) { - ch = buf[index++]; - if (ch >= '0' && ch <= '9') { + long power = 1; + boolean small = (chLocal == '.'); + if (small) { + chLocal = charAt(offset++); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power = 10; + for (; ; ) { + chLocal = charAt(offset++); + if (chLocal >= '0' && chLocal <= '9') { + intVal = intVal * 10 + (chLocal - '0'); + power *= 10; continue; } else { break; @@ -1284,900 +1737,464 @@ public float scanFieldFloat(char[] fieldName) { } } - bp = index - 1; - String text = new String(buf, start, index - start - 1); - value = Float.parseFloat(text); + boolean exp = chLocal == 'e' || chLocal == 'E'; + if (exp) { + chLocal = charAt(offset++); + if (chLocal == '+' || chLocal == '-') { + chLocal = charAt(offset++); + } + for (; ; ) { + if (chLocal >= '0' && chLocal <= '9') { + chLocal = charAt(offset++); + } else { + break; + } + } + } + + int start, count; + if (quote) { + if (chLocal != '"') { + matchStat = NOT_MATCH; + return 0; + } else { + chLocal = charAt(offset++); + } + start = bp + 1; + count = offset - start - 2; + } else { + start = bp; + count = offset - start - 1; + } + + if (!exp && count < 20) { + value = ((double) intVal) / power; + if (negative) { + value = -value; + } + } else { + String text = this.subString(start, count); + value = Double.parseDouble(text); + } + } else if (chLocal == 'n' + && charAt(offset++) == 'u' + && charAt(offset++) == 'l' + && charAt(offset++) == 'l') { + matchStat = VALUE_NULL; + value = 0; + chLocal = charAt(offset++); + + if (quote && chLocal == '"') { + chLocal = charAt(offset++); + } + + for (;;) { + if (chLocal == ',') { + bp = offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == ']') { + bp = offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACKET; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return 0; } else { matchStat = NOT_MATCH; return 0; } - if (ch == ',') { - ch = buf[++bp]; + if (chLocal == seperator) { + bp = offset; + this.ch = this.charAt(bp); matchStat = VALUE; token = JSONToken.COMMA; return value; - } else if (ch == '}') { - ch = buf[++bp]; - if (ch == ',') { - token = JSONToken.COMMA; - this.ch = buf[++bp]; - } else if (ch == ']') { - token = JSONToken.RBRACKET; - this.ch = buf[++bp]; - } else if (ch == '}') { - token = JSONToken.RBRACE; - this.ch = buf[++bp]; - } else if (ch == EOI) { - token = JSONToken.EOF; - } else { + } else { + matchStat = NOT_MATCH; + return value; + } + } + + public long scanLong(char seperator) { + matchStat = UNKNOWN; + + int offset = bp; + char chLocal = charAt(offset++); + final boolean quote = chLocal == '"'; + + if (quote) { + chLocal = charAt(offset++); + } + + final boolean negative = chLocal == '-'; + if (negative) { + chLocal = charAt(offset++); + } + + long value; + if (chLocal >= '0' && chLocal <= '9') { + value = chLocal - '0'; + for (;;) { + chLocal = charAt(offset++); + if (chLocal >= '0' && chLocal <= '9') { + value = value * 10 + (chLocal - '0'); + } else if (chLocal == '.') { + matchStat = NOT_MATCH; + return 0; + } else { + if (quote) { + if (chLocal != '"') { + matchStat = NOT_MATCH; + return 0; + } else { + chLocal = charAt(offset++); + } + } + break; + } + } + + boolean valid = value >= 0 || (value == -9223372036854775808L && negative); + if (!valid) { matchStat = NOT_MATCH; return 0; } - matchStat = END; + } else if (chLocal == 'n' + && charAt(offset++) == 'u' + && charAt(offset++) == 'l' + && charAt(offset++) == 'l') { + matchStat = VALUE_NULL; + value = 0; + chLocal = charAt(offset++); + + if (quote && chLocal == '"') { + chLocal = charAt(offset++); + } + + for (;;) { + if (chLocal == ',') { + bp = offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.COMMA; + return value; + } else if (chLocal == ']') { + bp = offset; + this.ch = charAt(bp); + matchStat = VALUE_NULL; + token = JSONToken.RBRACKET; + return value; + } else if (isWhitespace(chLocal)) { + chLocal = charAt(offset++); + continue; + } + break; + } + matchStat = NOT_MATCH; + return 0; } else { matchStat = NOT_MATCH; return 0; } - return value; - } - - public double scanFieldDouble(char[] fieldName) { - matchStat = UNKOWN; + for (;;) { + if (chLocal == seperator) { + bp = offset; + this.ch = charAt(bp); + matchStat = VALUE; + token = JSONToken.COMMA; + return negative ? -value : value; + } else { + if (isWhitespace(chLocal)) { + chLocal = charAt(offset++); + continue; + } - final int fieldNameLength = fieldName.length; - for (int i = 0; i < fieldNameLength; ++i) { - if (fieldName[i] != buf[bp + i]) { - matchStat = NOT_MATCH_NAME; - return 0; + matchStat = NOT_MATCH; + return value; } } + } - int index = bp + fieldNameLength; + public java.util.Date scanDate(char seperator) { + matchStat = UNKNOWN; + int startPos = this.bp; + char startChar = this.ch; - char ch = buf[index++]; + int index = bp; - double value; - if (ch >= '0' && ch <= '9') { - int start = index - 1; - for (;;) { - ch = buf[index++]; - if (ch >= '0' && ch <= '9') { - continue; - } else { + char ch = charAt(index++); + + final java.util.Date dateVal; + if (ch == '"') { + int startIndex = index; + int endIndex = indexOf('"', startIndex); + if (endIndex == -1) { + throw new JSONException("unclosed str"); + } + + int rest = endIndex - startIndex; + bp = index; + if (scanISO8601DateIfMatch(false, rest)) { + dateVal = calendar.getTime(); + } else { + bp = startPos; + this.ch = startChar; + matchStat = NOT_MATCH; + return null; + } + ch = charAt(endIndex + 1); + bp = startPos; + + for (; ; ) { + if (ch == ',' || ch == ']') { + bp = endIndex + 1; + this.ch = ch; break; + } else if (isWhitespace(ch)) { + endIndex++; + ch = charAt(endIndex + 1); + } else { + this.bp = startPos; + this.ch = startChar; + matchStat = NOT_MATCH; + + return null; } } + } else if (ch == '-' || (ch >= '0' && ch <= '9')) { + long millis = 0; - if (ch == '.') { - ch = buf[index++]; - if (ch >= '0' && ch <= '9') { - for (;;) { - ch = buf[index++]; - if (ch >= '0' && ch <= '9') { - continue; - } else { - break; + boolean negative = false; + if (ch == '-') { + ch = charAt(index++); + negative = true; + } + + if (ch >= '0' && ch <= '9') { + millis = ch - '0'; + for (; ; ) { + ch = charAt(index++); + if (ch >= '0' && ch <= '9') { + millis = millis * 10 + (ch - '0'); + } else { + if (ch == ',' || ch == ']') { + bp = index - 1; } + break; } - } else { - matchStat = NOT_MATCH; - return 0; } } - bp = index - 1; - String text = new String(buf, start, index - start - 1); - value = Double.parseDouble(text); + if (millis < 0) { + this.bp = startPos; + this.ch = startChar; + matchStat = NOT_MATCH; + return null; + } + + if (negative) { + millis = -millis; + } + + dateVal = new java.util.Date(millis); + } else if (ch == 'n' + && charAt(index++) == 'u' + && charAt(index++) == 'l' + && charAt(index++) == 'l') { + dateVal = null; + ch = charAt(index); + bp = index; } else { + this.bp = startPos; + this.ch = startChar; matchStat = NOT_MATCH; - return 0; + + return null; } if (ch == ',') { - ch = buf[++bp]; + this.ch = charAt(++bp); matchStat = VALUE; - token = JSONToken.COMMA; - } else if (ch == '}') { - ch = buf[++bp]; + return dateVal; + } else { + //condition ch == '}' is always 'true' + ch = charAt(++bp); if (ch == ',') { token = JSONToken.COMMA; - this.ch = buf[++bp]; + this.ch = charAt(++bp); } else if (ch == ']') { token = JSONToken.RBRACKET; - this.ch = buf[++bp]; + this.ch = charAt(++bp); } else if (ch == '}') { token = JSONToken.RBRACE; - this.ch = buf[++bp]; + this.ch = charAt(++bp); } else if (ch == EOI) { + this.ch = EOI; token = JSONToken.EOF; } else { + this.bp = startPos; + this.ch = startChar; matchStat = NOT_MATCH; - return 0; + return null; } matchStat = END; - } else { - matchStat = NOT_MATCH; - return 0; } + return dateVal; + } - return value; + protected final void arrayCopy(int srcPos, char[] dest, int destPos, int length) { + text.getChars(srcPos, srcPos + length, dest, destPos); } - // public int scanField2(char[] fieldName, Object object, FieldDeserializer fieldDeserializer) { - // return NOT_MATCH; - // } + public String info() { + return "pos " + bp // + + ", json : " // + + (text.length() < 65536 // + ? text // + : text.substring(0, 65536)); + } - public String scanSymbol(final SymbolTable symbolTable) { - skipWhitespace(); + // for hsf support + public String[] scanFieldStringArray(char[] fieldName, int argTypesCount, SymbolTable typeSymbolTable) { + int startPos = bp; + char starChar = ch; - if (ch == '"') { - return scanSymbol(symbolTable, '"'); + while (isWhitespace(ch)) { + next(); } - if (ch == '\'') { - if (!isEnabled(Feature.AllowSingleQuotes)) { - throw new JSONException("syntax error"); + int offset; + char ch; + if (fieldName != null) { + matchStat = UNKNOWN; + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return null; } - return scanSymbol(symbolTable, '\''); - } + offset = bp + fieldName.length; + ch = text.charAt(offset++); + while (isWhitespace(ch)) { + ch = text.charAt(offset++); + } - if (ch == '}') { - ch = buf[++bp]; - token = JSONToken.RBRACE; - return null; - } + if (ch == ':') { + ch = text.charAt(offset++); + } else { + matchStat = NOT_MATCH; + return null; + } - if (ch == ',') { - ch = buf[++bp]; - token = JSONToken.COMMA; - return null; + while (isWhitespace(ch)) { + ch = text.charAt(offset++); + } + } else { + offset = bp + 1; + ch = this.ch; } - if (ch == EOI) { - token = JSONToken.EOF; + if (ch == '[') { + bp = offset; + this.ch = text.charAt(bp); + } else if (ch == 'n' && text.startsWith("ull", bp + 1)) { + bp += 4; + this.ch = text.charAt(bp); + return null; + } else { + matchStat = NOT_MATCH; return null; } - if (!isEnabled(Feature.AllowUnQuotedFieldNames)) { - throw new JSONException("syntax error"); - } - - return scanSymbolUnQuoted(symbolTable); - } - - public final String scanSymbol(final SymbolTable symbolTable, final char quote) { - int hash = 0; - - np = bp; - sp = 0; - boolean hasSpecial = false; - char ch; + String[] types = argTypesCount >= 0 ? new String[argTypesCount] : new String[4]; + int typeIndex = 0; for (;;) { - ch = buf[++bp]; - - if (ch == quote) { - break; + while (isWhitespace(this.ch)) { + next(); } - if (ch == EOI) { - throw new JSONException("unclosed.str"); + if (this.ch != '\"') { + this.bp = startPos; + this.ch = starChar; + matchStat = NOT_MATCH; + return null; } - if (ch == '\\') { - if (!hasSpecial) { - hasSpecial = true; - - if (sp >= sbuf.length) { - int newCapcity = sbuf.length * 2; - if (sp > newCapcity) { - newCapcity = sp; - } - char[] newsbuf = new char[newCapcity]; - System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length); - sbuf = newsbuf; - } - - System.arraycopy(buf, np + 1, sbuf, 0, sp); - } - - ch = buf[++bp]; - - switch (ch) { - case '"': - hash = 31 * hash + (int) '"'; - putChar('"'); - break; - case '\\': - hash = 31 * hash + (int) '\\'; - putChar('\\'); - break; - case '/': - hash = 31 * hash + (int) '/'; - putChar('/'); - break; - case 'b': - hash = 31 * hash + (int) '\b'; - putChar('\b'); - break; - case 'f': - case 'F': - hash = 31 * hash + (int) '\f'; - putChar('\f'); - break; - case 'n': - hash = 31 * hash + (int) '\n'; - putChar('\n'); - break; - case 'r': - hash = 31 * hash + (int) '\r'; - putChar('\r'); - break; - case 't': - hash = 31 * hash + (int) '\t'; - putChar('\t'); - break; - case 'u': - char c1 = ch = buf[++bp]; - char c2 = ch = buf[++bp]; - char c3 = ch = buf[++bp]; - char c4 = ch = buf[++bp]; - int val = Integer.parseInt(new String(new char[] { c1, c2, c3, c4 }), 16); - hash = 31 * hash + val; - putChar((char) val); - break; - default: - this.ch = ch; - throw new JSONException("unclosed.str.lit"); - } - continue; + String type = scanSymbol(typeSymbolTable, '"'); + if (typeIndex == types.length) { + int newCapacity = types.length + (types.length >> 1) + 1; + String[] array = new String[newCapacity]; + System.arraycopy(types, 0, array, 0, types.length); + types = array; } - - hash = 31 * hash + ch; - - if (!hasSpecial) { - sp++; - continue; + types[typeIndex++] = type; + while (isWhitespace(this.ch)) { + next(); } - - if (sp == sbuf.length) { - putChar(ch); - } else { - sbuf[sp++] = ch; + if (this.ch == ',') { + next(); + continue; } + break; + } + if (types.length != typeIndex) { + String[] array = new String[typeIndex]; + System.arraycopy(types, 0, array, 0, typeIndex); + types = array; } - token = LITERAL_STRING; - this.ch = buf[++bp]; + while (isWhitespace(this.ch)) { + next(); + } - if (!hasSpecial) { - return symbolTable.addSymbol(buf, np + 1, sp, hash); + if (this.ch == ']') { + next(); } else { - return symbolTable.addSymbol(sbuf, 0, sp, hash); + this.bp = startPos; + this.ch = starChar; + matchStat = NOT_MATCH; + return null; } + + return types; } - public void scanTrue() { - if (buf[bp++] != 't') { - throw new JSONException("error parse true"); + public boolean matchField2(char[] fieldName) { + while (isWhitespace(ch)) { + next(); } - if (buf[bp++] != 'r') { - throw new JSONException("error parse true"); - } - if (buf[bp++] != 'u') { - throw new JSONException("error parse true"); - } - if (buf[bp++] != 'e') { - throw new JSONException("error parse true"); + + if (!charArrayCompare(fieldName)) { + matchStat = NOT_MATCH_NAME; + return false; } - ch = buf[bp]; + int offset = bp + fieldName.length; + char ch = text.charAt(offset++); + while (isWhitespace(ch)) { + ch = text.charAt(offset++); + } - if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI || ch == '\f' || ch == '\b') { - token = JSONToken.TRUE; + if (ch == ':') { + this.bp = offset; + this.ch = charAt(bp); + return true; } else { - throw new JSONException("scan true error"); + matchStat = NOT_MATCH_NAME; + return false; } - } - public void scanNullOrNew() { - if (buf[bp++] != 'n') { - throw new JSONException("error parse null or new"); - } - - if (buf[bp] == 'u') { - bp++; - if (buf[bp++] != 'l') { - throw new JSONException("error parse true"); - } - if (buf[bp++] != 'l') { - throw new JSONException("error parse true"); - } - ch = buf[bp]; - - if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI || ch == '\f' || ch == '\b') { - token = JSONToken.NULL; - } else { - throw new JSONException("scan true error"); - } - return; - } - - if (buf[bp] != 'e') { - throw new JSONException("error parse e"); - } - - bp++; - if (buf[bp++] != 'w') { - throw new JSONException("error parse w"); - } - ch = buf[bp]; - - if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI || ch == '\f' || ch == '\b') { - token = JSONToken.NEW; - } else { - throw new JSONException("scan true error"); - } - } - - public void scanFalse() { - if (buf[bp++] != 'f') { - throw new JSONException("error parse false"); - } - if (buf[bp++] != 'a') { - throw new JSONException("error parse false"); - } - if (buf[bp++] != 'l') { - throw new JSONException("error parse false"); - } - if (buf[bp++] != 's') { - throw new JSONException("error parse false"); - } - if (buf[bp++] != 'e') { - throw new JSONException("error parse false"); - } - - ch = buf[bp]; - - if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI || ch == '\f' || ch == '\b') { - token = JSONToken.FALSE; - } else { - throw new JSONException("scan false error"); - } - } - - public void scanIdent() { - np = bp - 1; - hasSpecial = false; - - for (;;) { - sp++; - - ch = buf[++bp]; - if (Character.isLetterOrDigit(ch)) { - continue; - } - - String ident = stringVal(); - - Integer tok = keywods.getKeyword(ident); - if (tok != null) { - token = tok; - } else { - token = JSONToken.IDENTIFIER; - } - return; - } - } - - public void scanNumber() { - np = bp; - - if (ch == '-') { - sp++; - ch = buf[++bp]; - } - - for (;;) { - if (ch >= '0' && ch <= '9') { - sp++; - } else { - break; - } - ch = buf[++bp]; - } - - boolean isDouble = false; - - if (ch == '.') { - sp++; - ch = buf[++bp]; - isDouble = true; - - for (;;) { - if (ch >= '0' && ch <= '9') { - sp++; - } else { - break; - } - ch = buf[++bp]; - } - } - - if (ch == 'e' || ch == 'E') { - sp++; - ch = buf[++bp]; - - if (ch == '+' || ch == '-') { - sp++; - ch = buf[++bp]; - } - - for (;;) { - if (ch >= '0' && ch <= '9') { - sp++; - } else { - break; - } - ch = buf[++bp]; - } - - isDouble = true; - } - - if (isDouble) { - token = JSONToken.LITERAL_FLOAT; - } else { - token = JSONToken.LITERAL_INT; - } - } - - /** - * Append a character to sbuf. - */ - private final void putChar(char ch) { - if (sp == sbuf.length) { - char[] newsbuf = new char[sbuf.length * 2]; - System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length); - sbuf = newsbuf; - } - sbuf[sp++] = ch; - } - - /** - * Return the current token's position: a 0-based offset from beginning of the raw input stream (before unicode - * translation) - */ - public final int pos() { - return pos; - } - - /** - * The value of a literal token, recorded as a string. For integers, leading 0x and 'l' suffixes are suppressed. - */ - public final String stringVal() { - if (!hasSpecial) { - return new String(buf, np + 1, sp); - } else { - return new String(sbuf, 0, sp); - } - } - - public final String symbol(SymbolTable symbolTable) { - if (symbolTable == null) { - if (!hasSpecial) { - return new String(buf, np + 1, sp); - } else { - return new String(sbuf, 0, sp); - } - } - - if (!hasSpecial) { - return symbolTable.addSymbol(buf, np + 1, sp); - } else { - return symbolTable.addSymbol(sbuf, 0, sp); - } - } - - private static final long MULTMIN_RADIX_TEN = Long.MIN_VALUE / 10; - private static final long N_MULTMAX_RADIX_TEN = -Long.MAX_VALUE / 10; - - private static final int INT_MULTMIN_RADIX_TEN = Integer.MIN_VALUE / 10; - private static final int INT_N_MULTMAX_RADIX_TEN = -Integer.MAX_VALUE / 10; - - private final static int[] digits = new int[(int) 'f' + 1]; - - static { - for (int i = '0'; i <= '9'; ++i) { - digits[i] = i - '0'; - } - - for (int i = 'a'; i <= 'f'; ++i) { - digits[i] = (i - 'a') + 10; - } - for (int i = 'A'; i <= 'F'; ++i) { - digits[i] = (i - 'A') + 10; - } - } - - public Number integerValue() throws NumberFormatException { - long result = 0; - boolean negative = false; - int i = np, max = np + sp; - long limit; - long multmin; - int digit; - - if (buf[np] == '-') { - negative = true; - limit = Long.MIN_VALUE; - i++; - } else { - limit = -Long.MAX_VALUE; - } - multmin = negative ? MULTMIN_RADIX_TEN : N_MULTMAX_RADIX_TEN; - if (i < max) { - digit = digits[buf[i++]]; - result = -digit; - } - while (i < max) { - // Accumulating negatively avoids surprises near MAX_VALUE - digit = digits[buf[i++]]; - if (result < multmin) { - return new BigInteger(numberString()); - } - result *= 10; - if (result < limit + digit) { - return new BigInteger(numberString()); - } - result -= digit; - } - - if (negative) { - if (i > np + 1) { - if (result >= Integer.MIN_VALUE) { - return (int) result; - } - return result; - } else { /* Only got "-" */ - throw new NumberFormatException(numberString()); - } - } else { - result = -result; - if (result <= Integer.MAX_VALUE) { - return (int) result; - } - return result; - } - } - - public long longValue() throws NumberFormatException { - long result = 0; - boolean negative = false; - int i = np, max = np + sp; - long limit; - long multmin; - int digit; - - if (buf[np] == '-') { - negative = true; - limit = Long.MIN_VALUE; - i++; - } else { - limit = -Long.MAX_VALUE; - } - multmin = negative ? MULTMIN_RADIX_TEN : N_MULTMAX_RADIX_TEN; - if (i < max) { - digit = digits[buf[i++]]; - result = -digit; - } - while (i < max) { - // Accumulating negatively avoids surprises near MAX_VALUE - digit = digits[buf[i++]]; - if (result < multmin) { - throw new NumberFormatException(numberString()); - } - result *= 10; - if (result < limit + digit) { - throw new NumberFormatException(numberString()); - } - result -= digit; - } - - if (negative) { - if (i > np + 1) { - return result; - } else { /* Only got "-" */ - throw new NumberFormatException(numberString()); - } - } else { - return -result; - } - } - - public int intValue() { - int result = 0; - boolean negative = false; - int i = np, max = np + sp; - int limit; - int multmin; - int digit; - - if (buf[np] == '-') { - negative = true; - limit = Integer.MIN_VALUE; - i++; - } else { - limit = -Integer.MAX_VALUE; - } - multmin = negative ? INT_MULTMIN_RADIX_TEN : INT_N_MULTMAX_RADIX_TEN; - if (i < max) { - digit = digits[buf[i++]]; - result = -digit; - } - while (i < max) { - // Accumulating negatively avoids surprises near MAX_VALUE - digit = digits[buf[i++]]; - if (result < multmin) { - throw new NumberFormatException(numberString()); - } - result *= 10; - if (result < limit + digit) { - throw new NumberFormatException(numberString()); - } - result -= digit; - } - - if (negative) { - if (i > np + 1) { - return result; - } else { /* Only got "-" */ - throw new NumberFormatException(numberString()); - } - } else { - return -result; - } - } - - public final String numberString() { - return new String(buf, np, sp); - } - - public float floatValue() { - return Float.parseFloat(numberString()); - } - - public double doubleValue() { - return Double.parseDouble(numberString()); - } - - public BigDecimal decimalValue() { - return new BigDecimal(buf, np, sp); - } - - public void config(Feature feature, boolean state) { - features = Feature.config(features, feature, state); - } - - public boolean isEnabled(Feature feature) { - return Feature.isEnabled(this.features, feature); - } - - public final int ISO8601_LEN_0 = "0000-00-00".length(); - public final int ISO8601_LEN_1 = "0000-00-00T00:00:00".length(); - public final int ISO8601_LEN_2 = "0000-00-00T00:00:00.000".length(); - - public boolean scanISO8601DateIfMatch() { - int rest = buflen - bp; - - if (rest < ISO8601_LEN_0) { - return false; - } - - char y0 = buf[bp]; - char y1 = buf[bp + 1]; - char y2 = buf[bp + 2]; - char y3 = buf[bp + 3]; - if (y0 != '1' && y0 != '2') { - return false; - } - if (y1 < '0' || y1 > '9') { - return false; - } - if (y2 < '0' || y2 > '9') { - return false; - } - if (y3 < '0' || y3 > '9') { - return false; - } - - if (buf[bp + 4] != '-') { - return false; - } - - char M0 = buf[bp + 5]; - char M1 = buf[bp + 6]; - if (M0 == '0') { - if (M1 < '1' || M1 > '9') { - return false; - } - } else if (M0 == '1') { - if (M1 != '0' && M1 != '1' && M1 != '2') { - return false; - } - } else { - return false; - } - - if (buf[bp + 7] != '-') { - return false; - } - - char d0 = buf[bp + 8]; - char d1 = buf[bp + 9]; - if (d0 == '0') { - if (d1 < '1' || d1 > '9') { - return false; - } - } else if (d0 == '1' || d0 == '2') { - if (d1 < '0' || d1 > '9') { - return false; - } - } else if (d0 == '3') { - if (d1 != '0' && d1 != '1') { - return false; - } - } else { - return false; - } - - calendar = Calendar.getInstance(); - int year = digits[y0] * 1000 + digits[y1] * 100 + digits[y2] * 10 + digits[y3]; - int month = digits[M0] * 10 + digits[M1] - 1; - int day = digits[d0] * 10 + digits[d1]; - calendar.set(Calendar.YEAR, year); - calendar.set(Calendar.MONTH, month); - calendar.set(Calendar.DAY_OF_MONTH, day); - - char t = buf[bp + 10]; - if (t == 'T') { - if (rest < ISO8601_LEN_1) { - return false; - } - } else { - calendar.set(Calendar.HOUR_OF_DAY, 0); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MILLISECOND, 0); - - ch = buf[bp += 10]; - - token = JSONToken.LITERAL_ISO8601_DATE; - return true; - } - - char h0 = buf[bp + 11]; - char h1 = buf[bp + 12]; - if (h0 == '0') { - if (h1 < '0' || h1 > '9') { - return false; - } - } else if (h0 == '1') { - if (h1 < '0' || h1 > '9') { - return false; - } - } else if (h0 == '2') { - if (h1 < '0' || h1 > '4') { - return false; - } - } else { - return false; - } - - if (buf[bp + 13] != ':') { - return false; - } - - char m0 = buf[bp + 14]; - char m1 = buf[bp + 15]; - if (m0 >= '0' && m0 <= '5') { - if (m1 < '0' || m1 > '9') { - return false; - } - } else if (m0 == '6') { - if (m1 != '0') { - return false; - } - } else { - return false; - } - - if (buf[bp + 16] != ':') { - return false; - } - - char s0 = buf[bp + 17]; - char s1 = buf[bp + 18]; - if (s0 >= '0' && s0 <= '5') { - if (s1 < '0' || s1 > '9') { - return false; - } - } else if (s0 == '6') { - if (s1 != '0') { - return false; - } - } else { - return false; - } - - int hour = digits[h0] * 10 + digits[h1]; - int minute = digits[m0] * 10 + digits[m1]; - int seconds = digits[s0] * 10 + digits[s1]; - calendar.set(Calendar.HOUR_OF_DAY, hour); - calendar.set(Calendar.MINUTE, minute); - calendar.set(Calendar.SECOND, seconds); - - char dot = buf[bp + 19]; - if (dot == '.') { - if (rest < ISO8601_LEN_2) { - return false; - } - } else { - calendar.set(Calendar.MILLISECOND, 0); - - ch = buf[bp += 19]; - - token = JSONToken.LITERAL_ISO8601_DATE; - return true; - } - - char S0 = buf[bp + 20]; - char S1 = buf[bp + 21]; - char S2 = buf[bp + 22]; - if (S0 < '0' || S0 > '9') { - return false; - } - if (S1 < '0' || S1 > '9') { - return false; - } - if (S2 < '0' || S2 > '9') { - return false; - } - - int millis = digits[S0] * 100 + digits[S1] * 10 + digits[S2]; - calendar.set(Calendar.MILLISECOND, millis); - - ch = buf[bp += 23]; - - token = JSONToken.LITERAL_ISO8601_DATE; - return true; - } - - public Calendar getCalendar() { - return this.calendar; - } - - public boolean isEOF() { - switch (token) { - case JSONToken.EOF: - return true; - case JSONToken.ERROR: - return false; - case JSONToken.RBRACE: - return false; - default: - return false; - } - // for (int i = bp; i < buflen; ++i) { - // char ch = buf[i]; - // if (!isWhitespace(ch)) { - // return false; - // } - // } - // - // return true; } } diff --git a/src/main/java/com/alibaba/fastjson/parser/JSONToken.java b/src/main/java/com/alibaba/fastjson/parser/JSONToken.java old mode 100644 new mode 100755 index 86451e4faf..31279b456f --- a/src/main/java/com/alibaba/fastjson/parser/JSONToken.java +++ b/src/main/java/com/alibaba/fastjson/parser/JSONToken.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,10 @@ package com.alibaba.fastjson.parser; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public class JSONToken { - // public final static int ERROR = 1; // @@ -59,9 +58,18 @@ public class JSONToken { public final static int IDENTIFIER = 18; // public final static int FIELD_NAME = 19; - + public final static int EOF = 20; + public final static int SET = 21; + public final static int TREE_SET = 22; + + public final static int UNDEFINED = 23; // undefined + + public final static int SEMI = 24; + public final static int DOT = 25; + public final static int HEX = 26; + public static String name(int value) { switch (value) { case ERROR: @@ -98,14 +106,26 @@ public static String name(int value) { return ","; case COLON: return ":"; + case SEMI: + return ";"; + case DOT: + return "."; case IDENTIFIER: return "ident"; case FIELD_NAME: return "fieldName"; case EOF: return "EOF"; + case SET: + return "Set"; + case TREE_SET: + return "TreeSet"; + case UNDEFINED: + return "undefined"; + case HEX: + return "hex"; default: - return "Unkown"; + return "Unknown"; } } } diff --git a/src/main/java/com/alibaba/fastjson/parser/JavaBeanMapping.java b/src/main/java/com/alibaba/fastjson/parser/JavaBeanMapping.java deleted file mode 100644 index 2edc4bbc48..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/JavaBeanMapping.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.alibaba.fastjson.parser; - -@Deprecated -public class JavaBeanMapping extends ParserConfig { - private final static JavaBeanMapping instance = new JavaBeanMapping(); - - public static JavaBeanMapping getGlobalInstance() { - return instance; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/Keywords.java b/src/main/java/com/alibaba/fastjson/parser/Keywords.java deleted file mode 100644 index 56c52c2016..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/Keywords.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.parser; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author wenshao - */ -public class Keywords { - - private final Map keywords; - - public static Keywords DEFAULT_KEYWORDS; - - static { - Map map = new HashMap(); - map.put("null", JSONToken.NULL); - map.put("new", JSONToken.NEW); - map.put("true", JSONToken.TRUE); - map.put("false", JSONToken.FALSE); - DEFAULT_KEYWORDS = new Keywords(map); - } - - public Keywords(Map keywords){ - this.keywords = keywords; - } - - public Integer getKeyword(String key) { - return keywords.get(key); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/parser/ParseContext.java b/src/main/java/com/alibaba/fastjson/parser/ParseContext.java new file mode 100755 index 0000000000..2b215cdaa5 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/ParseContext.java @@ -0,0 +1,34 @@ +package com.alibaba.fastjson.parser; + +import java.lang.reflect.Type; + +public class ParseContext { + + public Object object; + public final ParseContext parent; + public final Object fieldName; + public Type type; + private transient String path; + + public ParseContext(ParseContext parent, Object object, Object fieldName){ + this.parent = parent; + this.object = object; + this.fieldName = fieldName; + } + + public String toString() { + if (path == null) { + if (parent == null) { + path = "$"; + } else { + if (fieldName instanceof Integer) { + path = parent.toString() + "[" + fieldName + "]"; + } else { + path = parent.toString() + "." + fieldName; + } + } + } + + return path; + } +} diff --git a/src/main/java/com/alibaba/fastjson/parser/ParserConfig.java b/src/main/java/com/alibaba/fastjson/parser/ParserConfig.java index 32a2ec6610..74f41c3849 100644 --- a/src/main/java/com/alibaba/fastjson/parser/ParserConfig.java +++ b/src/main/java/com/alibaba/fastjson/parser/ParserConfig.java @@ -1,424 +1,1036 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.parser; - -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.URI; -import java.net.URL; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; -import java.util.TreeMap; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicIntegerArray; -import java.util.concurrent.atomic.AtomicLongArray; -import java.util.regex.Pattern; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.JSONObject; -import com.alibaba.fastjson.parser.deserializer.ASMDeserializerFactory; -import com.alibaba.fastjson.parser.deserializer.ASMJavaBeanDeserializer; -import com.alibaba.fastjson.parser.deserializer.ArrayDeserializer; -import com.alibaba.fastjson.parser.deserializer.ArrayListStringDeserializer; -import com.alibaba.fastjson.parser.deserializer.ArrayListStringFieldDeserializer; -import com.alibaba.fastjson.parser.deserializer.ArrayListTypeDeserializer; -import com.alibaba.fastjson.parser.deserializer.ArrayListTypeFieldDeserializer; -import com.alibaba.fastjson.parser.deserializer.AtomicIntegerArrayDeserializer; -import com.alibaba.fastjson.parser.deserializer.AtomicLongArrayDeserializer; -import com.alibaba.fastjson.parser.deserializer.AutowiredObjectDeserializer; -import com.alibaba.fastjson.parser.deserializer.BigDecimalDeserializer; -import com.alibaba.fastjson.parser.deserializer.BigIntegerDeserializer; -import com.alibaba.fastjson.parser.deserializer.BooleanDeserializer; -import com.alibaba.fastjson.parser.deserializer.BooleanFieldDeserializer; -import com.alibaba.fastjson.parser.deserializer.ByteDeserializer; -import com.alibaba.fastjson.parser.deserializer.CharacterDeserializer; -import com.alibaba.fastjson.parser.deserializer.CharsetDeserializer; -import com.alibaba.fastjson.parser.deserializer.CollectionDeserializer; -import com.alibaba.fastjson.parser.deserializer.ConcurrentHashMapDeserializer; -import com.alibaba.fastjson.parser.deserializer.DateDeserializer; -import com.alibaba.fastjson.parser.deserializer.DefaultFieldDeserializer; -import com.alibaba.fastjson.parser.deserializer.DefaultObjectDeserializer; -import com.alibaba.fastjson.parser.deserializer.DoubleDeserializer; -import com.alibaba.fastjson.parser.deserializer.EnumDeserializer; -import com.alibaba.fastjson.parser.deserializer.FieldDeserializer; -import com.alibaba.fastjson.parser.deserializer.FileDeserializer; -import com.alibaba.fastjson.parser.deserializer.FloatDeserializer; -import com.alibaba.fastjson.parser.deserializer.HashMapDeserializer; -import com.alibaba.fastjson.parser.deserializer.InetAddressDeserializer; -import com.alibaba.fastjson.parser.deserializer.InetSocketAddressDeserializer; -import com.alibaba.fastjson.parser.deserializer.IntegerDeserializer; -import com.alibaba.fastjson.parser.deserializer.IntegerFieldDeserializer; -import com.alibaba.fastjson.parser.deserializer.JSONArrayDeserializer; -import com.alibaba.fastjson.parser.deserializer.JSONObjectDeserializer; -import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; -import com.alibaba.fastjson.parser.deserializer.JavaObjectDeserializer; -import com.alibaba.fastjson.parser.deserializer.LinkedHashMapDeserializer; -import com.alibaba.fastjson.parser.deserializer.LocaleDeserializer; -import com.alibaba.fastjson.parser.deserializer.LongDeserializer; -import com.alibaba.fastjson.parser.deserializer.LongFieldDeserializer; -import com.alibaba.fastjson.parser.deserializer.NumberDeserializer; -import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; -import com.alibaba.fastjson.parser.deserializer.PatternDeserializer; -import com.alibaba.fastjson.parser.deserializer.ShortDeserializer; -import com.alibaba.fastjson.parser.deserializer.SqlDateDeserializer; -import com.alibaba.fastjson.parser.deserializer.StringDeserializer; -import com.alibaba.fastjson.parser.deserializer.StringFieldDeserializer; -import com.alibaba.fastjson.parser.deserializer.ThrowableDeserializer; -import com.alibaba.fastjson.parser.deserializer.TimeZoneDeserializer; -import com.alibaba.fastjson.parser.deserializer.TimestampDeserializer; -import com.alibaba.fastjson.parser.deserializer.TreeMapDeserializer; -import com.alibaba.fastjson.parser.deserializer.URIDeserializer; -import com.alibaba.fastjson.parser.deserializer.URLDeserializer; -import com.alibaba.fastjson.parser.deserializer.UUIDDeserializer; -import com.alibaba.fastjson.util.FieldInfo; -import com.alibaba.fastjson.util.IdentityHashMap; -import com.alibaba.fastjson.util.ServiceLoader; - -/** - * @author wenshao - */ -public class ParserConfig { - - public static ParserConfig getGlobalInstance() { - return global; - } - - private final Set> primitiveClasses = new HashSet>(); - - private static ParserConfig global = new ParserConfig(); - - private final IdentityHashMap derializers = new IdentityHashMap(); - - private DefaultObjectDeserializer defaultSerializer = new DefaultObjectDeserializer(); - - private boolean asmEnable = true; - - protected final SymbolTable symbolTable = new SymbolTable(); - - public DefaultObjectDeserializer getDefaultSerializer() { - return defaultSerializer; - } - - public ParserConfig(){ - primitiveClasses.add(boolean.class); - primitiveClasses.add(Boolean.class); - - primitiveClasses.add(char.class); - primitiveClasses.add(Character.class); - - primitiveClasses.add(byte.class); - primitiveClasses.add(Byte.class); - - primitiveClasses.add(short.class); - primitiveClasses.add(Short.class); - - primitiveClasses.add(int.class); - primitiveClasses.add(Integer.class); - - primitiveClasses.add(long.class); - primitiveClasses.add(Long.class); - - primitiveClasses.add(float.class); - primitiveClasses.add(Float.class); - - primitiveClasses.add(double.class); - primitiveClasses.add(Double.class); - - primitiveClasses.add(BigInteger.class); - primitiveClasses.add(BigDecimal.class); - - primitiveClasses.add(String.class); - primitiveClasses.add(java.util.Date.class); - primitiveClasses.add(java.sql.Date.class); - primitiveClasses.add(java.sql.Time.class); - primitiveClasses.add(java.sql.Timestamp.class); - - derializers.put(java.sql.Timestamp.class, TimestampDeserializer.instance); - derializers.put(java.sql.Date.class, SqlDateDeserializer.instance); - derializers.put(java.util.Date.class, DateDeserializer.instance); - - derializers.put(JSONObject.class, JSONObjectDeserializer.instance); - derializers.put(JSONArray.class, JSONArrayDeserializer.instance); - - derializers.put(Map.class, HashMapDeserializer.instance); - derializers.put(HashMap.class, HashMapDeserializer.instance); - derializers.put(LinkedHashMap.class, LinkedHashMapDeserializer.instance); - derializers.put(TreeMap.class, TreeMapDeserializer.instance); - derializers.put(ConcurrentMap.class, ConcurrentHashMapDeserializer.instance); - derializers.put(ConcurrentHashMap.class, ConcurrentHashMapDeserializer.instance); - - derializers.put(Collection.class, CollectionDeserializer.instance); - derializers.put(List.class, CollectionDeserializer.instance); - derializers.put(ArrayList.class, CollectionDeserializer.instance); - - derializers.put(Object.class, JavaObjectDeserializer.instance); - derializers.put(String.class, StringDeserializer.instance); - derializers.put(char.class, CharacterDeserializer.instance); - derializers.put(Character.class, CharacterDeserializer.instance); - derializers.put(byte.class, ByteDeserializer.instance); - derializers.put(Byte.class, ByteDeserializer.instance); - derializers.put(short.class, ShortDeserializer.instance); - derializers.put(Short.class, ShortDeserializer.instance); - derializers.put(int.class, IntegerDeserializer.instance); - derializers.put(Integer.class, IntegerDeserializer.instance); - derializers.put(long.class, LongDeserializer.instance); - derializers.put(Long.class, LongDeserializer.instance); - derializers.put(BigInteger.class, BigIntegerDeserializer.instance); - derializers.put(BigDecimal.class, BigDecimalDeserializer.instance); - derializers.put(float.class, FloatDeserializer.instance); - derializers.put(Float.class, FloatDeserializer.instance); - derializers.put(double.class, DoubleDeserializer.instance); - derializers.put(Double.class, DoubleDeserializer.instance); - derializers.put(boolean.class, BooleanDeserializer.instance); - derializers.put(Boolean.class, BooleanDeserializer.instance); - - derializers.put(UUID.class, UUIDDeserializer.instance); - derializers.put(TimeZone.class, TimeZoneDeserializer.instance); - derializers.put(Locale.class, LocaleDeserializer.instance); - derializers.put(InetAddress.class, InetAddressDeserializer.instance); - derializers.put(Inet4Address.class, InetAddressDeserializer.instance); - derializers.put(Inet6Address.class, InetAddressDeserializer.instance); - derializers.put(InetSocketAddress.class, InetSocketAddressDeserializer.instance); - derializers.put(File.class, FileDeserializer.instance); - derializers.put(URI.class, URIDeserializer.instance); - derializers.put(URL.class, URLDeserializer.instance); - derializers.put(Pattern.class, PatternDeserializer.instance); - derializers.put(Charset.class, CharsetDeserializer.instance); - derializers.put(Number.class, NumberDeserializer.instance); - derializers.put(AtomicIntegerArray.class, AtomicIntegerArrayDeserializer.instance); - derializers.put(AtomicLongArray.class, AtomicLongArrayDeserializer.instance); - - - } - - public boolean isAsmEnable() { - return asmEnable; - } - - public void setAsmEnable(boolean asmEnable) { - this.asmEnable = asmEnable; - } - - public SymbolTable getSymbolTable() { - return symbolTable; - } - - public IdentityHashMap getDerializers() { - return derializers; - } - - public ObjectDeserializer getDeserializer(Type type) { - ObjectDeserializer derializer = this.derializers.get(type); - if (derializer != null) { - return derializer; - } - - if (type instanceof Class) { - return getDeserializer((Class) type, type); - } - - if (type instanceof ParameterizedType) { - Type rawType = ((ParameterizedType) type).getRawType(); - return getDeserializer((Class) rawType, type); - } - - return this.defaultSerializer; - } - - public ObjectDeserializer getDeserializer(Class clazz, Type type) { - ObjectDeserializer derializer = derializers.get(type); - if (derializer != null) { - return derializer; - } - - final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - for (AutowiredObjectDeserializer autowired : ServiceLoader.load(AutowiredObjectDeserializer.class, classLoader)) { - for (Type forType : autowired.getAutowiredFor()) { - derializers.put(forType, autowired); - } - } - - derializer = derializers.get(type); - if (derializer != null) { - return derializer; - } - - if (clazz.isEnum()) { - derializer = new EnumDeserializer(clazz); - } else if (clazz.isArray()) { - return ArrayDeserializer.instance; - } else if (clazz == Set.class || clazz == Collection.class || clazz == List.class || clazz == ArrayList.class) { - if (type instanceof ParameterizedType) { - Type itemType = ((ParameterizedType) type).getActualTypeArguments()[0]; - if (itemType == String.class) { - derializer = ArrayListStringDeserializer.instance; - } else { - derializer = new ArrayListTypeDeserializer(itemType); - } - } else { - derializer = CollectionDeserializer.instance; - } - } else if (Collection.class.isAssignableFrom(clazz)) { - derializer = CollectionDeserializer.instance; - } else if (Map.class.isAssignableFrom(clazz)) { - derializer = this.defaultSerializer; - } else if (Throwable.class.isAssignableFrom(clazz)) { - derializer = new ThrowableDeserializer(this, clazz); - } else { - derializer = createJavaBeanDeserializer(clazz); - } - - putDeserializer(type, derializer); - - return derializer; - } - - public ObjectDeserializer createJavaBeanDeserializer(Class clazz) { - if (clazz == Class.class) { - return this.defaultSerializer; - } - - if (!Modifier.isPublic(clazz.getModifiers())) { - return new JavaBeanDeserializer(this, clazz); - } - - if (!asmEnable) { - return new JavaBeanDeserializer(this, clazz); - } - - try { - return ASMDeserializerFactory.getInstance().createJavaBeanDeserializer(this, clazz); - } catch (Exception e) { - throw new JSONException("create asm deserializer error, " + clazz.getName(), e); - } - } - - public FieldDeserializer createFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo) { - boolean asmEnable = this.asmEnable; - - Method method = fieldInfo.getMethod(); - - if (!Modifier.isPublic(clazz.getModifiers())) { - asmEnable = false; - } - - if (method.getParameterTypes()[0] == Class.class) { - asmEnable = false; - } - - if (!asmEnable) { - return createFieldDeserializerWithoutASM(mapping, clazz, fieldInfo); - } - - try { - return ASMDeserializerFactory.getInstance().createFieldDeserializer(mapping, clazz, fieldInfo); - } catch (Throwable e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return createFieldDeserializerWithoutASM(mapping, clazz, fieldInfo); - } - - public FieldDeserializer createFieldDeserializerWithoutASM(ParserConfig mapping, Class clazz, FieldInfo fieldInfo) { - Method method = fieldInfo.getMethod(); - Class fieldClass = method.getParameterTypes()[0]; - - if (fieldClass == boolean.class || fieldClass == Boolean.class) { - return new BooleanFieldDeserializer(mapping, clazz, fieldInfo); - } - - if (fieldClass == int.class || fieldClass == Integer.class) { - return new IntegerFieldDeserializer(mapping, clazz, fieldInfo); - } - - if (fieldClass == long.class || fieldClass == Long.class) { - return new LongFieldDeserializer(mapping, clazz, fieldInfo); - } - - if (fieldClass == String.class) { - return new StringFieldDeserializer(mapping, clazz, fieldInfo); - } - - if (fieldClass == List.class || fieldClass == ArrayList.class) { - Type fieldType = method.getGenericParameterTypes()[0]; - Type itemType = ((ParameterizedType) fieldType).getActualTypeArguments()[0]; - if (itemType == String.class) { - return new ArrayListStringFieldDeserializer(mapping, clazz, fieldInfo); - } - - return new ArrayListTypeFieldDeserializer(mapping, clazz, fieldInfo); - } - - return new DefaultFieldDeserializer(mapping, clazz, fieldInfo); - } - - public void putDeserializer(Type type, ObjectDeserializer deserializer) { - derializers.put(type, deserializer); - } - - public ObjectDeserializer getDeserializer(FieldInfo fieldInfo) { - return getDeserializer(fieldInfo.getFieldClass(), fieldInfo.getFieldType()); - } - - public boolean isPrimitive(Class clazz) { - return primitiveClasses.contains(clazz); - } - - public static Field getField(Class clazz, String fieldName) { - try { - return clazz.getDeclaredField(fieldName); - } catch (Exception e) { - return null; - } - } - - public Map getFieldDeserializers(Class clazz) { - ObjectDeserializer deserizer = getDeserializer(clazz); - - if (deserizer instanceof JavaBeanDeserializer) { - return ((JavaBeanDeserializer) deserizer).getFieldDeserializerMap(); - } else if (deserizer instanceof ASMJavaBeanDeserializer) { - return ((ASMJavaBeanDeserializer) deserizer).getInnterSerializer().getFieldDeserializerMap(); - } else { - return Collections.emptyMap(); - } - } - -} +/* + * Copyright 1999-2017 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.parser; + +import java.io.Closeable; +import java.io.File; +import java.io.Serializable; +import java.lang.ref.SoftReference; +import java.lang.ref.WeakReference; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URL; +import java.nio.charset.Charset; +import java.security.AccessControlException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicIntegerArray; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicLongArray; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; + +import com.alibaba.fastjson.*; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.deserializer.*; +import com.alibaba.fastjson.serializer.*; +import com.alibaba.fastjson.util.*; +import com.alibaba.fastjson.util.IdentityHashMap; +import com.alibaba.fastjson.util.ServiceLoader; + +import javax.sql.DataSource; +import javax.xml.datatype.XMLGregorianCalendar; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class ParserConfig { + + public final static String DENY_PROPERTY = "fastjson.parser.deny"; + public final static String AUTOTYPE_ACCEPT = "fastjson.parser.autoTypeAccept"; + public final static String AUTOTYPE_SUPPORT_PROPERTY = "fastjson.parser.autoTypeSupport"; + + public static final String[] DENYS; + private static final String[] AUTO_TYPE_ACCEPT_LIST; + public static final boolean AUTO_SUPPORT; + + static { + { + String property = IOUtils.getStringProperty(DENY_PROPERTY); + DENYS = splitItemsFormProperty(property); + } + { + String property = IOUtils.getStringProperty(AUTOTYPE_SUPPORT_PROPERTY); + AUTO_SUPPORT = "true".equals(property); + } + { + String property = IOUtils.getStringProperty(AUTOTYPE_ACCEPT); + String[] items = splitItemsFormProperty(property); + if (items == null) { + items = new String[0]; + } + AUTO_TYPE_ACCEPT_LIST = items; + } + } + + public static ParserConfig getGlobalInstance() { + return global; + } + + public static ParserConfig global = new ParserConfig(); + + private final IdentityHashMap deserializers = new IdentityHashMap(); + + private boolean asmEnable = !ASMUtils.IS_ANDROID; + + public final SymbolTable symbolTable = new SymbolTable(4096); + + public PropertyNamingStrategy propertyNamingStrategy; + + protected ClassLoader defaultClassLoader; + + protected ASMDeserializerFactory asmFactory; + + private static boolean awtError = false; + private static boolean jdk8Error = false; + + private boolean autoTypeSupport = AUTO_SUPPORT; + private long[] denyHashCodes; + private long[] acceptHashCodes; + + + public final boolean fieldBased; + + public boolean compatibleWithJavaBean = TypeUtils.compatibleWithJavaBean; + + { + denyHashCodes = new long[]{ + -8720046426850100497L, + -8165637398350707645L, + -8109300701639721088L, + -8083514888460375884L, + -7966123100503199569L, + -7921218830998286408L, + -7768608037458185275L, + -7766605818834748097L, + -6835437086156813536L, + -6179589609550493385L, + -5194641081268104286L, + -4837536971810737970L, + -4082057040235125754L, + -3935185854875733362L, + -2753427844400776271L, + -2364987994247679115L, + -2262244760619952081L, + -1872417015366588117L, + -1589194880214235129L, + -254670111376247151L, + -190281065685395680L, + 33238344207745342L, + 313864100207897507L, + 1073634739308289776L, + 1203232727967308606L, + 1502845958873959152L, + 3547627781654598988L, + 3730752432285826863L, + 3794316665763266033L, + 4147696707147271408L, + 5347909877633654828L, + 5450448828334921485L, + 5688200883751798389L, + 5751393439502795295L, + 5944107969236155580L, + 6742705432718011780L, + 7017492163108594270L, + 7179336928365889465L, + 7442624256860549330L, + 8389032537095247355L, + 8838294710098435315L + }; + + long[] hashCodes = new long[AUTO_TYPE_ACCEPT_LIST.length]; + for (int i = 0; i < AUTO_TYPE_ACCEPT_LIST.length; i++) { + hashCodes[i] = TypeUtils.fnv1a_64(AUTO_TYPE_ACCEPT_LIST[i]); + } + Arrays.sort(hashCodes); + acceptHashCodes = hashCodes; + } + + public ParserConfig(){ + this(false); + } + + public ParserConfig(boolean fieldBase){ + this(null, null, fieldBase); + } + + public ParserConfig(ClassLoader parentClassLoader){ + this(null, parentClassLoader, false); + } + + public ParserConfig(ASMDeserializerFactory asmFactory){ + this(asmFactory, null, false); + } + + private ParserConfig(ASMDeserializerFactory asmFactory, ClassLoader parentClassLoader, boolean fieldBased){ + this.fieldBased = fieldBased; + if (asmFactory == null && !ASMUtils.IS_ANDROID) { + try { + if (parentClassLoader == null) { + asmFactory = new ASMDeserializerFactory(new ASMClassLoader()); + } else { + asmFactory = new ASMDeserializerFactory(parentClassLoader); + } + } catch (ExceptionInInitializerError error) { + // skip + } catch (AccessControlException error) { + // skip + } catch (NoClassDefFoundError error) { + // skip + } + } + + this.asmFactory = asmFactory; + + if (asmFactory == null) { + asmEnable = false; + } + + initDeserializers(); + + addItemsToDeny(DENYS); + addItemsToAccept(AUTO_TYPE_ACCEPT_LIST); + + } + + private void initDeserializers() { + deserializers.put(SimpleDateFormat.class, MiscCodec.instance); + deserializers.put(java.sql.Timestamp.class, SqlDateDeserializer.instance_timestamp); + deserializers.put(java.sql.Date.class, SqlDateDeserializer.instance); + deserializers.put(java.sql.Time.class, TimeDeserializer.instance); + deserializers.put(java.util.Date.class, DateCodec.instance); + deserializers.put(Calendar.class, CalendarCodec.instance); + deserializers.put(XMLGregorianCalendar.class, CalendarCodec.instance); + + deserializers.put(JSONObject.class, MapDeserializer.instance); + deserializers.put(JSONArray.class, CollectionCodec.instance); + + deserializers.put(Map.class, MapDeserializer.instance); + deserializers.put(HashMap.class, MapDeserializer.instance); + deserializers.put(LinkedHashMap.class, MapDeserializer.instance); + deserializers.put(TreeMap.class, MapDeserializer.instance); + deserializers.put(ConcurrentMap.class, MapDeserializer.instance); + deserializers.put(ConcurrentHashMap.class, MapDeserializer.instance); + + deserializers.put(Collection.class, CollectionCodec.instance); + deserializers.put(List.class, CollectionCodec.instance); + deserializers.put(ArrayList.class, CollectionCodec.instance); + + deserializers.put(Object.class, JavaObjectDeserializer.instance); + deserializers.put(String.class, StringCodec.instance); + deserializers.put(StringBuffer.class, StringCodec.instance); + deserializers.put(StringBuilder.class, StringCodec.instance); + deserializers.put(char.class, CharacterCodec.instance); + deserializers.put(Character.class, CharacterCodec.instance); + deserializers.put(byte.class, NumberDeserializer.instance); + deserializers.put(Byte.class, NumberDeserializer.instance); + deserializers.put(short.class, NumberDeserializer.instance); + deserializers.put(Short.class, NumberDeserializer.instance); + deserializers.put(int.class, IntegerCodec.instance); + deserializers.put(Integer.class, IntegerCodec.instance); + deserializers.put(long.class, LongCodec.instance); + deserializers.put(Long.class, LongCodec.instance); + deserializers.put(BigInteger.class, BigIntegerCodec.instance); + deserializers.put(BigDecimal.class, BigDecimalCodec.instance); + deserializers.put(float.class, FloatCodec.instance); + deserializers.put(Float.class, FloatCodec.instance); + deserializers.put(double.class, NumberDeserializer.instance); + deserializers.put(Double.class, NumberDeserializer.instance); + deserializers.put(boolean.class, BooleanCodec.instance); + deserializers.put(Boolean.class, BooleanCodec.instance); + deserializers.put(Class.class, MiscCodec.instance); + deserializers.put(char[].class, new CharArrayCodec()); + + deserializers.put(AtomicBoolean.class, BooleanCodec.instance); + deserializers.put(AtomicInteger.class, IntegerCodec.instance); + deserializers.put(AtomicLong.class, LongCodec.instance); + deserializers.put(AtomicReference.class, ReferenceCodec.instance); + + deserializers.put(WeakReference.class, ReferenceCodec.instance); + deserializers.put(SoftReference.class, ReferenceCodec.instance); + + deserializers.put(UUID.class, MiscCodec.instance); + deserializers.put(TimeZone.class, MiscCodec.instance); + deserializers.put(Locale.class, MiscCodec.instance); + deserializers.put(Currency.class, MiscCodec.instance); + deserializers.put(InetAddress.class, MiscCodec.instance); + deserializers.put(Inet4Address.class, MiscCodec.instance); + deserializers.put(Inet6Address.class, MiscCodec.instance); + deserializers.put(InetSocketAddress.class, MiscCodec.instance); + deserializers.put(File.class, MiscCodec.instance); + deserializers.put(URI.class, MiscCodec.instance); + deserializers.put(URL.class, MiscCodec.instance); + deserializers.put(Pattern.class, MiscCodec.instance); + deserializers.put(Charset.class, MiscCodec.instance); + deserializers.put(JSONPath.class, MiscCodec.instance); + deserializers.put(Number.class, NumberDeserializer.instance); + deserializers.put(AtomicIntegerArray.class, AtomicCodec.instance); + deserializers.put(AtomicLongArray.class, AtomicCodec.instance); + deserializers.put(StackTraceElement.class, StackTraceElementDeserializer.instance); + + deserializers.put(Serializable.class, JavaObjectDeserializer.instance); + deserializers.put(Cloneable.class, JavaObjectDeserializer.instance); + deserializers.put(Comparable.class, JavaObjectDeserializer.instance); + deserializers.put(Closeable.class, JavaObjectDeserializer.instance); + + deserializers.put(JSONPObject.class, new JSONPDeserializer()); + } + + private static String[] splitItemsFormProperty(final String property ){ + if (property != null && property.length() > 0) { + return property.split(","); + } + return null; + } + + public void configFromPropety(Properties properties) { + { + String property = properties.getProperty(DENY_PROPERTY); + String[] items = splitItemsFormProperty(property); + addItemsToDeny(items); + } + { + String property = properties.getProperty(AUTOTYPE_ACCEPT); + String[] items = splitItemsFormProperty(property); + addItemsToAccept(items); + } + { + String property = properties.getProperty(AUTOTYPE_SUPPORT_PROPERTY); + if ("true".equals(property)) { + this.autoTypeSupport = true; + } else if ("false".equals(property)) { + this.autoTypeSupport = false; + } + } + } + + private void addItemsToDeny(final String[] items){ + if (items == null){ + return; + } + + for (int i = 0; i < items.length; ++i) { + String item = items[i]; + this.addDeny(item); + } + } + + private void addItemsToAccept(final String[] items){ + if (items == null){ + return; + } + + for (int i = 0; i < items.length; ++i) { + String item = items[i]; + this.addAccept(item); + } + } + + public boolean isAutoTypeSupport() { + return autoTypeSupport; + } + + public void setAutoTypeSupport(boolean autoTypeSupport) { + this.autoTypeSupport = autoTypeSupport; + } + + public boolean isAsmEnable() { + return asmEnable; + } + + public void setAsmEnable(boolean asmEnable) { + this.asmEnable = asmEnable; + } + + public IdentityHashMap getDeserializers() { + return deserializers; + } + + public ObjectDeserializer getDeserializer(Type type) { + ObjectDeserializer derializer = this.deserializers.get(type); + if (derializer != null) { + return derializer; + } + + if (type instanceof Class) { + return getDeserializer((Class) type, type); + } + + if (type instanceof ParameterizedType) { + Type rawType = ((ParameterizedType) type).getRawType(); + if (rawType instanceof Class) { + return getDeserializer((Class) rawType, type); + } else { + return getDeserializer(rawType); + } + } + + if (type instanceof WildcardType) { + WildcardType wildcardType = (WildcardType) type; + Type[] upperBounds = wildcardType.getUpperBounds(); + if (upperBounds.length == 1) { + Type upperBoundType = upperBounds[0]; + return getDeserializer(upperBoundType); + } + } + + return JavaObjectDeserializer.instance; + } + + public ObjectDeserializer getDeserializer(Class clazz, Type type) { + ObjectDeserializer derializer = deserializers.get(type); + if (derializer != null) { + return derializer; + } + + if (type == null) { + type = clazz; + } + + derializer = deserializers.get(type); + if (derializer != null) { + return derializer; + } + + { + JSONType annotation = TypeUtils.getAnnotation(clazz,JSONType.class); + if (annotation != null) { + Class mappingTo = annotation.mappingTo(); + if (mappingTo != Void.class) { + return getDeserializer(mappingTo, mappingTo); + } + } + } + + if (type instanceof WildcardType || type instanceof TypeVariable || type instanceof ParameterizedType) { + derializer = deserializers.get(clazz); + } + + if (derializer != null) { + return derializer; + } + + String className = clazz.getName(); + className = className.replace('$', '.'); + + if (className.startsWith("java.awt.") // + && AwtCodec.support(clazz)) { + if (!awtError) { + String[] names = new String[] { + "java.awt.Point", + "java.awt.Font", + "java.awt.Rectangle", + "java.awt.Color" + }; + + try { + for (String name : names) { + if (name.equals(className)) { + deserializers.put(Class.forName(name), derializer = AwtCodec.instance); + return derializer; + } + } + } catch (Throwable e) { + // skip + awtError = true; + } + + derializer = AwtCodec.instance; + } + } + + if (!jdk8Error) { + try { + if (className.startsWith("java.time.")) { + String[] names = new String[] { + "java.time.LocalDateTime", + "java.time.LocalDate", + "java.time.LocalTime", + "java.time.ZonedDateTime", + "java.time.OffsetDateTime", + "java.time.OffsetTime", + "java.time.ZoneOffset", + "java.time.ZoneRegion", + "java.time.ZoneId", + "java.time.Period", + "java.time.Duration", + "java.time.Instant" + }; + + for (String name : names) { + if (name.equals(className)) { + deserializers.put(Class.forName(name), derializer = Jdk8DateCodec.instance); + return derializer; + } + } + } else if (className.startsWith("java.util.Optional")) { + String[] names = new String[] { + "java.util.Optional", + "java.util.OptionalDouble", + "java.util.OptionalInt", + "java.util.OptionalLong" + }; + for (String name : names) { + if (name.equals(className)) { + deserializers.put(Class.forName(name), derializer = OptionalCodec.instance); + return derializer; + } + } + } + } catch (Throwable e) { + // skip + jdk8Error = true; + } + } + + if (className.equals("java.nio.file.Path")) { + deserializers.put(clazz, derializer = MiscCodec.instance); + } + + if (clazz == Map.Entry.class) { + deserializers.put(clazz, derializer = MiscCodec.instance); + } + + final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + try { + for (AutowiredObjectDeserializer autowired : ServiceLoader.load(AutowiredObjectDeserializer.class, + classLoader)) { + for (Type forType : autowired.getAutowiredFor()) { + deserializers.put(forType, autowired); + } + } + } catch (Exception ex) { + // skip + } + + if (derializer == null) { + derializer = deserializers.get(type); + } + + if (derializer != null) { + return derializer; + } + + if (clazz.isEnum()) { + Class deserClass = null; + JSONType jsonType = clazz.getAnnotation(JSONType.class); + if (jsonType != null) { + deserClass = jsonType.deserializer(); + try { + derializer = (ObjectDeserializer) deserClass.newInstance(); + deserializers.put(clazz, derializer); + return derializer; + } catch (Throwable error) { + // skip + } + } + + derializer = new EnumDeserializer(clazz); + } else if (clazz.isArray()) { + derializer = ObjectArrayCodec.instance; + } else if (clazz == Set.class || clazz == HashSet.class || clazz == Collection.class || clazz == List.class + || clazz == ArrayList.class) { + derializer = CollectionCodec.instance; + } else if (Collection.class.isAssignableFrom(clazz)) { + derializer = CollectionCodec.instance; + } else if (Map.class.isAssignableFrom(clazz)) { + derializer = MapDeserializer.instance; + } else if (Throwable.class.isAssignableFrom(clazz)) { + derializer = new ThrowableDeserializer(this, clazz); + } else if (PropertyProcessable.class.isAssignableFrom(clazz)) { + derializer = new PropertyProcessableDeserializer((Class)clazz); + } else { + derializer = createJavaBeanDeserializer(clazz, type); + } + + putDeserializer(type, derializer); + + return derializer; + } + + /** + * + * @since 1.2.25 + */ + public void initJavaBeanDeserializers(Class... classes) { + if (classes == null) { + return; + } + + for (Class type : classes) { + if (type == null) { + continue; + } + ObjectDeserializer deserializer = createJavaBeanDeserializer(type, type); + putDeserializer(type, deserializer); + } + } + + public ObjectDeserializer createJavaBeanDeserializer(Class clazz, Type type) { + boolean asmEnable = this.asmEnable & !this.fieldBased; + if (asmEnable) { + JSONType jsonType = TypeUtils.getAnnotation(clazz,JSONType.class); + + if (jsonType != null) { + Class deserializerClass = jsonType.deserializer(); + if (deserializerClass != Void.class) { + try { + Object deseralizer = deserializerClass.newInstance(); + if (deseralizer instanceof ObjectDeserializer) { + return (ObjectDeserializer) deseralizer; + } + } catch (Throwable e) { + // skip + } + } + + asmEnable = jsonType.asm(); + } + + if (asmEnable) { + Class superClass = JavaBeanInfo.getBuilderClass(clazz, jsonType); + if (superClass == null) { + superClass = clazz; + } + + for (;;) { + if (!Modifier.isPublic(superClass.getModifiers())) { + asmEnable = false; + break; + } + + superClass = superClass.getSuperclass(); + if (superClass == Object.class || superClass == null) { + break; + } + } + } + } + + if (clazz.getTypeParameters().length != 0) { + asmEnable = false; + } + + if (asmEnable && asmFactory != null && asmFactory.classLoader.isExternalClass(clazz)) { + asmEnable = false; + } + + if (asmEnable) { + asmEnable = ASMUtils.checkName(clazz.getSimpleName()); + } + + if (asmEnable) { + if (clazz.isInterface()) { + asmEnable = false; + } + JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, type, propertyNamingStrategy); + + if (asmEnable && beanInfo.fields.length > 200) { + asmEnable = false; + } + + Constructor defaultConstructor = beanInfo.defaultConstructor; + if (asmEnable && defaultConstructor == null && !clazz.isInterface()) { + asmEnable = false; + } + + for (FieldInfo fieldInfo : beanInfo.fields) { + if (fieldInfo.getOnly) { + asmEnable = false; + break; + } + + Class fieldClass = fieldInfo.fieldClass; + if (!Modifier.isPublic(fieldClass.getModifiers())) { + asmEnable = false; + break; + } + + if (fieldClass.isMemberClass() && !Modifier.isStatic(fieldClass.getModifiers())) { + asmEnable = false; + break; + } + + if (fieldInfo.getMember() != null // + && !ASMUtils.checkName(fieldInfo.getMember().getName())) { + asmEnable = false; + break; + } + + JSONField annotation = fieldInfo.getAnnotation(); + if (annotation != null // + && ((!ASMUtils.checkName(annotation.name())) // + || annotation.format().length() != 0 // + || annotation.deserializeUsing() != Void.class // + || annotation.unwrapped()) + || (fieldInfo.method != null && fieldInfo.method.getParameterTypes().length > 1)) { + asmEnable = false; + break; + } + + if (fieldClass.isEnum()) { // EnumDeserializer + ObjectDeserializer fieldDeser = this.getDeserializer(fieldClass); + if (!(fieldDeser instanceof EnumDeserializer)) { + asmEnable = false; + break; + } + } + } + } + + if (asmEnable) { + if (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) { + asmEnable = false; + } + } + + if (!asmEnable) { + return new JavaBeanDeserializer(this, clazz, type); + } + + JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, type, propertyNamingStrategy); + try { + return asmFactory.createJavaBeanDeserializer(this, beanInfo); + // } catch (VerifyError e) { + // e.printStackTrace(); + // return new JavaBeanDeserializer(this, clazz, type); + } catch (NoSuchMethodException ex) { + return new JavaBeanDeserializer(this, clazz, type); + } catch (JSONException asmError) { + return new JavaBeanDeserializer(this, beanInfo); + } catch (Exception e) { + throw new JSONException("create asm deserializer error, " + clazz.getName(), e); + } + } + + public FieldDeserializer createFieldDeserializer(ParserConfig mapping, // + JavaBeanInfo beanInfo, // + FieldInfo fieldInfo) { + Class clazz = beanInfo.clazz; + Class fieldClass = fieldInfo.fieldClass; + + Class deserializeUsing = null; + JSONField annotation = fieldInfo.getAnnotation(); + if (annotation != null) { + deserializeUsing = annotation.deserializeUsing(); + if (deserializeUsing == Void.class) { + deserializeUsing = null; + } + } + + if (deserializeUsing == null && (fieldClass == List.class || fieldClass == ArrayList.class)) { + return new ArrayListTypeFieldDeserializer(mapping, clazz, fieldInfo); + } + + return new DefaultFieldDeserializer(mapping, clazz, fieldInfo); + } + + public void putDeserializer(Type type, ObjectDeserializer deserializer) { + deserializers.put(type, deserializer); + } + + public ObjectDeserializer getDeserializer(FieldInfo fieldInfo) { + return getDeserializer(fieldInfo.fieldClass, fieldInfo.fieldType); + } + + /** + * @deprecated internal method, dont call + */ + public boolean isPrimitive(Class clazz) { + return isPrimitive2(clazz); + } + + /** + * @deprecated internal method, dont call + */ + public static boolean isPrimitive2(Class clazz) { + return clazz.isPrimitive() // + || clazz == Boolean.class // + || clazz == Character.class // + || clazz == Byte.class // + || clazz == Short.class // + || clazz == Integer.class // + || clazz == Long.class // + || clazz == Float.class // + || clazz == Double.class // + || clazz == BigInteger.class // + || clazz == BigDecimal.class // + || clazz == String.class // + || clazz == java.util.Date.class // + || clazz == java.sql.Date.class // + || clazz == java.sql.Time.class // + || clazz == java.sql.Timestamp.class // + || clazz.isEnum() // + ; + } + + /** + * fieldName,field ,先生成fieldName的快照,减少之后的findField的轮询 + * + * @param clazz + * @param fieldCacheMap :map<fieldName ,Field> + */ + public static void parserAllFieldToCache(Class clazz,Map fieldCacheMap){ + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + String fieldName = field.getName(); + if (!fieldCacheMap.containsKey(fieldName)) { + fieldCacheMap.put(fieldName, field); + } + } + if (clazz.getSuperclass() != null && clazz.getSuperclass() != Object.class) { + parserAllFieldToCache(clazz.getSuperclass(), fieldCacheMap); + } + } + + public static Field getFieldFromCache(String fieldName, Map fieldCacheMap) { + Field field = fieldCacheMap.get(fieldName); + + if (field == null) { + field = fieldCacheMap.get("_" + fieldName); + } + + if (field == null) { + field = fieldCacheMap.get("m_" + fieldName); + } + + if (field == null) { + char c0 = fieldName.charAt(0); + if (c0 >= 'a' && c0 <= 'z') { + char[] chars = fieldName.toCharArray(); + chars[0] -= 32; // lower + String fieldNameX = new String(chars); + field = fieldCacheMap.get(fieldNameX); + } + + if (fieldName.length() > 2) { + char c1 = fieldName.charAt(1); + if (fieldName.length() > 2 + && c0 >= 'a' && c0 <= 'z' + && c1 >= 'A' && c1 <= 'Z') { + for (Map.Entry entry : fieldCacheMap.entrySet()) { + if (fieldName.equalsIgnoreCase(entry.getKey())) { + field = entry.getValue(); + break; + } + } + } + } + } + + return field; + } + + public ClassLoader getDefaultClassLoader() { + return defaultClassLoader; + } + + public void setDefaultClassLoader(ClassLoader defaultClassLoader) { + this.defaultClassLoader = defaultClassLoader; + } + + public void addDeny(String name) { + if (name == null || name.length() == 0) { + return; + } + + long hash = TypeUtils.fnv1a_64(name); + if (Arrays.binarySearch(this.denyHashCodes, hash) >= 0) { + return; + } + + long[] hashCodes = new long[this.denyHashCodes.length + 1]; + hashCodes[hashCodes.length - 1] = hash; + System.arraycopy(this.denyHashCodes, 0, hashCodes, 0, this.denyHashCodes.length); + Arrays.sort(hashCodes); + this.denyHashCodes = hashCodes; + } + + public void addAccept(String name) { + if (name == null || name.length() == 0) { + return; + } + + long hash = TypeUtils.fnv1a_64(name); + if (Arrays.binarySearch(this.acceptHashCodes, hash) >= 0) { + return; + } + + long[] hashCodes = new long[this.acceptHashCodes.length + 1]; + hashCodes[hashCodes.length - 1] = hash; + System.arraycopy(this.acceptHashCodes, 0, hashCodes, 0, this.acceptHashCodes.length); + Arrays.sort(hashCodes); + this.acceptHashCodes = hashCodes; + } + + public Class checkAutoType(String typeName, Class expectClass) { + return checkAutoType(typeName, expectClass, JSON.DEFAULT_PARSER_FEATURE); + } + + public Class checkAutoType(String typeName, Class expectClass, int features) { + if (typeName == null) { + return null; + } + + if (typeName.length() >= 128 || typeName.length() < 3) { + throw new JSONException("autoType is not support. " + typeName); + } + + String className = typeName.replace('$', '.'); + Class clazz = null; + + final long BASIC = 0xcbf29ce484222325L; + final long PRIME = 0x100000001b3L; + + final long h1 = (BASIC ^ className.charAt(0)) * PRIME; + if (h1 == 0xaf64164c86024f1aL) { // [ + throw new JSONException("autoType is not support. " + typeName); + } + + if ((h1 ^ className.charAt(className.length() - 1)) * PRIME == 0x9198507b5af98f0L) { + throw new JSONException("autoType is not support. " + typeName); + } + + final long h3 = (((((BASIC ^ className.charAt(0)) + * PRIME) + ^ className.charAt(1)) + * PRIME) + ^ className.charAt(2)) + * PRIME; + + if (autoTypeSupport || expectClass != null) { + long hash = h3; + for (int i = 3; i < className.length(); ++i) { + hash ^= className.charAt(i); + hash *= PRIME; + if (Arrays.binarySearch(acceptHashCodes, hash) >= 0) { + clazz = TypeUtils.loadClass(typeName, defaultClassLoader, false); + if (clazz != null) { + return clazz; + } + } + if (Arrays.binarySearch(denyHashCodes, hash) >= 0 && TypeUtils.getClassFromMapping(typeName) == null) { + throw new JSONException("autoType is not support. " + typeName); + } + } + } + + if (clazz == null) { + clazz = TypeUtils.getClassFromMapping(typeName); + } + + if (clazz == null) { + clazz = deserializers.findClass(typeName); + } + + if (clazz != null) { + if (expectClass != null + && clazz != java.util.HashMap.class + && !expectClass.isAssignableFrom(clazz)) { + throw new JSONException("type not match. " + typeName + " -> " + expectClass.getName()); + } + + return clazz; + } + + if (!autoTypeSupport) { + long hash = h3; + for (int i = 3; i < className.length(); ++i) { + char c = className.charAt(i); + hash ^= c; + hash *= PRIME; + + if (Arrays.binarySearch(denyHashCodes, hash) >= 0) { + throw new JSONException("autoType is not support. " + typeName); + } + + if (Arrays.binarySearch(acceptHashCodes, hash) >= 0) { + if (clazz == null) { + clazz = TypeUtils.loadClass(typeName, defaultClassLoader, false); + } + + if (expectClass != null && expectClass.isAssignableFrom(clazz)) { + throw new JSONException("type not match. " + typeName + " -> " + expectClass.getName()); + } + + return clazz; + } + } + } + + if (clazz == null) { + clazz = TypeUtils.loadClass(typeName, defaultClassLoader, false); + } + + if (clazz != null) { + if (TypeUtils.getAnnotation(clazz,JSONType.class) != null) { + return clazz; + } + + if (ClassLoader.class.isAssignableFrom(clazz) // classloader is danger + || DataSource.class.isAssignableFrom(clazz) // dataSource can load jdbc driver + ) { + throw new JSONException("autoType is not support. " + typeName); + } + + if (expectClass != null) { + if (expectClass.isAssignableFrom(clazz)) { + return clazz; + } else { + throw new JSONException("type not match. " + typeName + " -> " + expectClass.getName()); + } + } + + JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, clazz, propertyNamingStrategy); + if (beanInfo.creatorConstructor != null && autoTypeSupport) { + throw new JSONException("autoType is not support. " + typeName); + } + } + + final int mask = Feature.SupportAutoType.mask; + boolean autoTypeSupport = this.autoTypeSupport + || (features & mask) != 0 + || (JSON.DEFAULT_PARSER_FEATURE & mask) != 0; + + if (!autoTypeSupport) { + throw new JSONException("autoType is not support. " + typeName); + } + + return clazz; + } + + public void clearDeserializers() { + this.deserializers.clear(); + this.initDeserializers(); + } +} diff --git a/src/main/java/com/alibaba/fastjson/parser/SymbolTable.java b/src/main/java/com/alibaba/fastjson/parser/SymbolTable.java old mode 100644 new mode 100755 index c7e7fdcc4d..1346a4feb4 --- a/src/main/java/com/alibaba/fastjson/parser/SymbolTable.java +++ b/src/main/java/com/alibaba/fastjson/parser/SymbolTable.java @@ -1,151 +1,128 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.parser; - -/** - * @author wenshao - */ -public class SymbolTable { - - public static final int DEFAULT_TABLE_SIZE = 128; - - private final Entry[] buckets; - private final String[] symbols; - private final char[][] symbols_char; - - private final int indexMask; - - public SymbolTable(){ - this(DEFAULT_TABLE_SIZE); - } - - public SymbolTable(int tableSize){ - this.indexMask = tableSize - 1; - this.buckets = new Entry[tableSize]; - this.symbols = new String[tableSize]; - this.symbols_char = new char[tableSize][]; - } - - /** - * Adds the specified symbol to the symbol table and returns a reference to the unique symbol. If the symbol already - * exists, the previous symbol reference is returned instead, in order guarantee that symbol references remain - * unique. - * - * @param symbol The new symbol. - */ - public String addSymbol(String symbol) { - return addSymbol(symbol.toCharArray(), 0, symbol.length(), symbol.hashCode()); - } - - - public String addSymbol(char[] buffer, int offset, int len) { - // search for identical symbol - int hash = hash(buffer, offset, len); - return addSymbol(buffer, offset, len, hash); - } - - /** - * Adds the specified symbol to the symbol table and returns a reference to the unique symbol. If the symbol already - * exists, the previous symbol reference is returned instead, in order guarantee that symbol references remain - * unique. - * - * @param buffer The buffer containing the new symbol. - * @param offset The offset into the buffer of the new symbol. - * @param len The length of the new symbol in the buffer. - */ - public String addSymbol(char[] buffer, int offset, int len, int hash) { - // int bucket = indexFor(hash, tableSize); - final int bucket = hash & indexMask; - - String sym = symbols[bucket]; - - boolean match = true; - - if (sym != null) { - if (sym.length() == len) { - char[] characters = symbols_char[bucket]; - - for (int i = 0; i < len; i++) { - if (buffer[offset + i] != characters[i]) { - match = false; - break; - } - } - - if (match) { - return sym; - } - } else { - match = false; - } - } - - OUTER: for (Entry entry = buckets[bucket]; entry != null; entry = entry.next) { - char[] characters = entry.characters; - if (len == characters.length && hash == entry.hashCode) { - for (int i = 0; i < len; i++) { - if (buffer[offset + i] != characters[i]) { - continue OUTER; - } - } - return entry.symbol; - } - } - - Entry entry = new Entry(buffer, offset, len, hash, buckets[bucket]); - buckets[bucket] = entry; // 并发是处理时会导致缓存丢失,但不影响正确性 - if (match) { - symbols[bucket] = entry.symbol; - symbols_char[bucket] = entry.characters; - } - return entry.symbol; - } - - public static final int hash(char[] buffer, int offset, int len) { - int h = 0; - int off = offset; - - for (int i = 0; i < len; i++) { - h = 31 * h + buffer[off++]; - } - return h; - } - - protected static final class Entry { - - public final String symbol; - public final int hashCode; - - public final char[] characters; - public final byte[] bytes; - - public Entry next; - - /** - * Constructs a new entry from the specified symbol information and next entry reference. - */ - public Entry(char[] ch, int offset, int length, int hash, Entry next){ - characters = new char[length]; - System.arraycopy(ch, offset, characters, 0, length); - symbol = new String(characters).intern(); - this.next = next; - this.hashCode = hash; - this.bytes = null; - } - - } - -} +/* + * Copyright 1999-2017 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.parser; + +import com.alibaba.fastjson.JSON; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class SymbolTable { + + private final String[] symbols; + private final int indexMask; + + public SymbolTable(int tableSize){ + this.indexMask = tableSize - 1; + this.symbols = new String[tableSize]; + + this.addSymbol("$ref", 0, 4, "$ref".hashCode()); + this.addSymbol(JSON.DEFAULT_TYPE_KEY, 0, JSON.DEFAULT_TYPE_KEY.length(), JSON.DEFAULT_TYPE_KEY.hashCode()); + } + + public String addSymbol(char[] buffer, int offset, int len) { + // search for identical symbol + int hash = hash(buffer, offset, len); + return addSymbol(buffer, offset, len, hash); + } + + /** + * Adds the specified symbol to the symbol table and returns a reference to the unique symbol. If the symbol already + * exists, the previous symbol reference is returned instead, in order guarantee that symbol references remain + * unique. + * + * @param buffer The buffer containing the new symbol. + * @param offset The offset into the buffer of the new symbol. + * @param len The length of the new symbol in the buffer. + */ + public String addSymbol(char[] buffer, int offset, int len, int hash) { + final int bucket = hash & indexMask; + + String symbol = symbols[bucket]; + if (symbol != null) { + boolean eq = true; + if (hash == symbol.hashCode() // + && len == symbol.length()) { + for (int i = 0; i < len; i++) { + if (buffer[offset + i] != symbol.charAt(i)) { + eq = false; + break; + } + } + } else { + eq = false; + } + + if (eq) { + return symbol; + } else { + return new String(buffer, offset, len); + } + } + + symbol = new String(buffer, offset, len).intern(); + symbols[bucket] = symbol; + return symbol; + } + + public String addSymbol(String buffer, int offset, int len, int hash) { + return addSymbol(buffer, offset, len, hash, false); + } + + public String addSymbol(String buffer, int offset, int len, int hash, boolean replace) { + final int bucket = hash & indexMask; + + String symbol = symbols[bucket]; + if (symbol != null) { + if (hash == symbol.hashCode() // + && len == symbol.length() // + && buffer.startsWith(symbol, offset)) { + return symbol; + } + + String str = subString(buffer, offset, len); + + if (replace) { + symbols[bucket] = str; + } + + return str; + } + + symbol = len == buffer.length() // + ? buffer // + : subString(buffer, offset, len); + symbol = symbol.intern(); + symbols[bucket] = symbol; + return symbol; + } + + private static String subString(String src, int offset, int len) { + char[] chars = new char[len]; + src.getChars(offset, offset + len, chars, 0); + return new String(chars); + } + + public static int hash(char[] buffer, int offset, int len) { + int h = 0; + int off = offset; + + for (int i = 0; i < len; i++) { + h = 31 * h + buffer[off++]; + } + return h; + } +} \ No newline at end of file diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ASMDeserializerFactory.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ASMDeserializerFactory.java old mode 100644 new mode 100755 index 292ac56d51..26a9f3d44a --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ASMDeserializerFactory.java +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/ASMDeserializerFactory.java @@ -1,101 +1,555 @@ package com.alibaba.fastjson.parser.deserializer; -import static com.alibaba.fastjson.util.ASMUtils.getDesc; -import static com.alibaba.fastjson.util.ASMUtils.getType; +import static com.alibaba.fastjson.util.ASMUtils.desc; +import static com.alibaba.fastjson.util.ASMUtils.type; import java.lang.reflect.Constructor; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.TreeSet; import java.util.concurrent.atomic.AtomicLong; import com.alibaba.fastjson.asm.ClassWriter; -import com.alibaba.fastjson.asm.FieldVisitor; +import com.alibaba.fastjson.asm.FieldWriter; import com.alibaba.fastjson.asm.Label; import com.alibaba.fastjson.asm.MethodVisitor; +import com.alibaba.fastjson.asm.MethodWriter; import com.alibaba.fastjson.asm.Opcodes; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser.ResolveTask; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONScanner; +import com.alibaba.fastjson.parser.JSONLexerBase; import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParseContext; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.SymbolTable; -import com.alibaba.fastjson.parser.deserializer.ASMJavaBeanDeserializer.InnerJavaBeanDeserializer; import com.alibaba.fastjson.util.ASMClassLoader; import com.alibaba.fastjson.util.FieldInfo; +import com.alibaba.fastjson.util.JavaBeanInfo; +import com.alibaba.fastjson.util.TypeUtils; public class ASMDeserializerFactory implements Opcodes { - private static final ASMDeserializerFactory instance = new ASMDeserializerFactory(); + public final ASMClassLoader classLoader; + protected final AtomicLong seed = new AtomicLong(); - private ASMClassLoader classLoader = new ASMClassLoader(); + final static String DefaultJSONParser = type(DefaultJSONParser.class); + final static String JSONLexerBase = type(JSONLexerBase.class); - private final AtomicLong seed = new AtomicLong(); - - public String getGenClassName(Class clazz) { - return "Fastjson_ASM_" + clazz.getSimpleName() + "_" + seed.incrementAndGet(); + public ASMDeserializerFactory(ClassLoader parentClassLoader){ + classLoader = parentClassLoader instanceof ASMClassLoader // + ? (ASMClassLoader) parentClassLoader // + : new ASMClassLoader(parentClassLoader); } + + public ObjectDeserializer createJavaBeanDeserializer(ParserConfig config, JavaBeanInfo beanInfo) throws Exception { + Class clazz = beanInfo.clazz; + if (clazz.isPrimitive()) { + throw new IllegalArgumentException("not support type :" + clazz.getName()); + } + + String className = "FastjsonASMDeserializer_" + seed.incrementAndGet() + "_" + clazz.getSimpleName(); + String classNameType; + String classNameFull; + + Package pkg = ASMDeserializerFactory.class.getPackage(); + if (pkg != null) { + String packageName = pkg.getName(); + classNameType = packageName.replace('.', '/') + "/" + className; + classNameFull = packageName + "." + className; + } else { + classNameType = className; + classNameFull = className; + } - public String getGenFieldDeserializer(Class clazz, FieldInfo fieldInfo) { - Method method = fieldInfo.getMethod(); - return "Fastjson_ASM__Field_" + clazz.getSimpleName() + "_" + method.getName() + "_" + seed.incrementAndGet(); + ClassWriter cw = new ClassWriter(); + cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, classNameType, type(JavaBeanDeserializer.class), null); + + _init(cw, new Context(classNameType, config, beanInfo, 3)); + _createInstance(cw, new Context(classNameType, config, beanInfo, 3)); + _deserialze(cw, new Context(classNameType, config, beanInfo, 5)); + + _deserialzeArrayMapping(cw, new Context(classNameType, config, beanInfo, 4)); + byte[] code = cw.toByteArray(); + + Class deserClass = classLoader.defineClassPublic(classNameFull, code, 0, code.length); + Constructor constructor = deserClass.getConstructor(ParserConfig.class, JavaBeanInfo.class); + Object instance = constructor.newInstance(config, beanInfo); + + return (ObjectDeserializer) instance; } - public ASMDeserializerFactory(){ + private void _setFlag(MethodVisitor mw, Context context, int i) { + String varName = "_asm_flag_" + (i / 32); + mw.visitVarInsn(ILOAD, context.var(varName)); + mw.visitLdcInsn(1 << i); + mw.visitInsn(IOR); + mw.visitVarInsn(ISTORE, context.var(varName)); } - public final static ASMDeserializerFactory getInstance() { - return instance; + private void _isFlag(MethodVisitor mw, Context context, int i, Label label) { + mw.visitVarInsn(ILOAD, context.var("_asm_flag_" + (i / 32))); + mw.visitLdcInsn(1 << i); + mw.visitInsn(IAND); + + mw.visitJumpInsn(IFEQ, label); } - public ObjectDeserializer createJavaBeanDeserializer(ParserConfig config, Class clazz) throws Exception { - if (clazz.isPrimitive()) { - throw new IllegalArgumentException("not support type :" + clazz.getName()); + private void _deserialzeArrayMapping(ClassWriter cw, Context context) { + MethodVisitor mw = new MethodWriter(cw, ACC_PUBLIC, "deserialzeArrayMapping", + "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", + null, null); + + defineVarLexer(context, mw); + + _createInstance(context, mw); + + FieldInfo[] sortedFieldInfoList = context.beanInfo.sortedFields; + int fieldListSize = sortedFieldInfoList.length; + for (int i = 0; i < fieldListSize; ++i) { + final boolean last = (i == fieldListSize - 1); + final char seperator = last ? ']' : ','; + + FieldInfo fieldInfo = sortedFieldInfoList[i]; + Class fieldClass = fieldInfo.fieldClass; + Type fieldType = fieldInfo.fieldType; + if (fieldClass == byte.class // + || fieldClass == short.class // + || fieldClass == int.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanInt", "(C)I"); + mw.visitVarInsn(ISTORE, context.var(fieldInfo.name + "_asm")); + } else if (fieldClass == Byte.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanInt", "(C)I"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); + + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + mw.visitLabel(valueNullEnd_); + } else if (fieldClass == Short.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanInt", "(C)I"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;"); + + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + mw.visitLabel(valueNullEnd_); + } else if (fieldClass == Integer.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanInt", "(C)I"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); + + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + mw.visitLabel(valueNullEnd_); + } else if (fieldClass == long.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanLong", "(C)J"); + mw.visitVarInsn(LSTORE, context.var(fieldInfo.name + "_asm", 2)); + + } else if (fieldClass == Long.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanLong", "(C)J"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"); + + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + mw.visitLabel(valueNullEnd_); + } else if (fieldClass == boolean.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanBoolean", "(C)Z"); + mw.visitVarInsn(ISTORE, context.var(fieldInfo.name + "_asm")); + } else if (fieldClass == float.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFloat", "(C)F"); + mw.visitVarInsn(FSTORE, context.var(fieldInfo.name + "_asm")); + + } else if (fieldClass == Float.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFloat", "(C)F"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); + + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + mw.visitLabel(valueNullEnd_); + + } else if (fieldClass == double.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanDouble", "(C)D"); + mw.visitVarInsn(DSTORE, context.var(fieldInfo.name + "_asm", 2)); + + } else if (fieldClass == Double.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanDouble", "(C)D"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"); + + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + mw.visitLabel(valueNullEnd_); + + } else if (fieldClass == char.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanString", "(C)Ljava/lang/String;"); + mw.visitInsn(ICONST_0); + mw.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "charAt", "(I)C"); + mw.visitVarInsn(ISTORE, context.var(fieldInfo.name + "_asm")); + } else if (fieldClass == String.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanString", "(C)Ljava/lang/String;"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + + } else if (fieldClass == BigDecimal.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanDecimal", "(C)Ljava/math/BigDecimal;"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + + } else if (fieldClass == java.util.Date.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanDate", "(C)Ljava/util/Date;"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + + } else if (fieldClass == java.util.UUID.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanUUID", "(C)Ljava/util/UUID;"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + + } else if (fieldClass.isEnum()) { + Label enumNumIf_ = new Label(); + Label enumNumErr_ = new Label(); + Label enumStore_ = new Label(); + Label enumQuote_ = new Label(); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "getCurrent", "()C"); + mw.visitInsn(DUP); + mw.visitVarInsn(ISTORE, context.var("ch")); + mw.visitLdcInsn((int) 'n'); + mw.visitJumpInsn(IF_ICMPEQ, enumQuote_); + + mw.visitVarInsn(ILOAD, context.var("ch")); + mw.visitLdcInsn((int) '\"'); + mw.visitJumpInsn(IF_ICMPNE, enumNumIf_); + + mw.visitLabel(enumQuote_); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldClass))); + mw.visitVarInsn(ALOAD, 1); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getSymbolTable", "()" + desc(SymbolTable.class)); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanEnum", + "(Ljava/lang/Class;" + desc(SymbolTable.class) + "C)Ljava/lang/Enum;"); + mw.visitJumpInsn(GOTO, enumStore_); + + // (ch >= '0' && ch <= '9') { + mw.visitLabel(enumNumIf_); + mw.visitVarInsn(ILOAD, context.var("ch")); + mw.visitLdcInsn((int) '0'); + mw.visitJumpInsn(IF_ICMPLT, enumNumErr_); + + mw.visitVarInsn(ILOAD, context.var("ch")); + mw.visitLdcInsn((int) '9'); + mw.visitJumpInsn(IF_ICMPGT, enumNumErr_); + + _getFieldDeser(context, mw, fieldInfo); + mw.visitTypeInsn(CHECKCAST, type(EnumDeserializer.class)); // cast + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanInt", "(C)I"); + mw.visitMethodInsn(INVOKEVIRTUAL, type(EnumDeserializer.class), "valueOf", "(I)Ljava/lang/Enum;"); + mw.visitJumpInsn(GOTO, enumStore_); + + mw.visitLabel(enumNumErr_); + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, type(JavaBeanDeserializer.class), "scanEnum", + "(L" + JSONLexerBase + ";C)Ljava/lang/Enum;"); + + mw.visitLabel(enumStore_); + mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + } else if (Collection.class.isAssignableFrom(fieldClass)) { + + Class itemClass = TypeUtils.getCollectionItemClass(fieldType); + if (itemClass == String.class) { + if (fieldClass == List.class || fieldClass == Collections.class || fieldClass == ArrayList.class) { + mw.visitTypeInsn(NEW, type(ArrayList.class)); + mw.visitInsn(DUP); + mw.visitMethodInsn(INVOKESPECIAL, type(ArrayList.class), "", "()V"); + } else { + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldClass))); + mw.visitMethodInsn(INVOKESTATIC, type(TypeUtils.class), "createCollection", + "(Ljava/lang/Class;)Ljava/util/Collection;"); + } + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanStringArray", "(Ljava/util/Collection;C)V"); + + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + + mw.visitLabel(valueNullEnd_); + + } else { + Label notError_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); + mw.visitVarInsn(ISTORE, context.var("token")); + + mw.visitVarInsn(ILOAD, context.var("token")); + int token = i == 0 ? JSONToken.LBRACKET : JSONToken.COMMA; + mw.visitLdcInsn(token); + mw.visitJumpInsn(IF_ICMPEQ, notError_); + + mw.visitVarInsn(ALOAD, 1); // DefaultJSONParser + mw.visitVarInsn(ILOAD, context.var("token")); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "throwException", "(I)V"); + + mw.visitLabel(notError_); + + Label quickElse_ = new Label(), quickEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "getCurrent", "()C"); + mw.visitVarInsn(BIPUSH, '['); + mw.visitJumpInsn(IF_ICMPNE, quickElse_); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "next", "()C"); + mw.visitInsn(POP); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.LBRACKET); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "setToken", "(I)V"); + mw.visitJumpInsn(GOTO, quickEnd_); + + mw.visitLabel(quickElse_); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.LBRACKET); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "nextToken", "(I)V"); + mw.visitLabel(quickEnd_); + + _newCollection(mw, fieldClass, i, false); + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + _getCollectionFieldItemDeser(context, mw, fieldInfo, itemClass); + mw.visitVarInsn(ALOAD, 1); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(itemClass))); + mw.visitVarInsn(ALOAD, 3); + mw.visitMethodInsn(INVOKESTATIC, type(JavaBeanDeserializer.class), + "parseArray", + "(Ljava/util/Collection;" // + + desc(ObjectDeserializer.class) // + + "L" + DefaultJSONParser + ";" // + + "Ljava/lang/reflect/Type;Ljava/lang/Object;)V"); + } + } else if (fieldClass.isArray()) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONToken.LBRACKET); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "nextToken", "(I)V"); + + mw.visitVarInsn(ALOAD, Context.parser); + mw.visitVarInsn(ALOAD, 0); + mw.visitLdcInsn(i); + mw.visitMethodInsn(INVOKEVIRTUAL, type(JavaBeanDeserializer.class), "getFieldType", + "(I)Ljava/lang/reflect/Type;"); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "parseObject", + "(Ljava/lang/reflect/Type;)Ljava/lang/Object;"); + + mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + } else { + Label objElseIf_ = new Label(); + Label objEndIf_ = new Label(); + + if (fieldClass == java.util.Date.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "getCurrent", "()C"); + mw.visitLdcInsn((int) '1'); + mw.visitJumpInsn(IF_ICMPNE, objElseIf_); + + mw.visitTypeInsn(NEW, type(java.util.Date.class)); + mw.visitInsn(DUP); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanLong", "(C)J"); + + mw.visitMethodInsn(INVOKESPECIAL, type(java.util.Date.class), "", "(J)V"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + + mw.visitJumpInsn(GOTO, objEndIf_); + } + + mw.visitLabel(objElseIf_); + + _quickNextToken(context, mw, JSONToken.LBRACKET); + + _deserObject(context, mw, fieldInfo, fieldClass, i); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); + mw.visitLdcInsn(JSONToken.RBRACKET); + mw.visitJumpInsn(IF_ICMPEQ, objEndIf_); +// mw.visitInsn(POP); +// mw.visitInsn(POP); + + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, context.var("lexer")); + if (!last) { + mw.visitLdcInsn(JSONToken.COMMA); + } else { + mw.visitLdcInsn(JSONToken.RBRACKET); + } + mw.visitMethodInsn(INVOKESPECIAL, // + type(JavaBeanDeserializer.class), // + "check", "(" + desc(JSONLexer.class) + "I)V"); + + mw.visitLabel(objEndIf_); + continue; + } } - String className = getGenClassName(clazz); + _batchSet(context, mw, false); - ClassWriter cw = new ClassWriter(); - cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, className, getType(ASMJavaBeanDeserializer.class), null); + Label quickElse_ = new Label(), quickElseIf_ = new Label(), quickElseIfEOI_ = new Label(), + quickEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "getCurrent", "()C"); + mw.visitInsn(DUP); + mw.visitVarInsn(ISTORE, context.var("ch")); + mw.visitVarInsn(BIPUSH, ','); + mw.visitJumpInsn(IF_ICMPNE, quickElseIf_); - List fieldInfoList = new ArrayList(); - JavaBeanDeserializer.computeSetters(clazz, fieldInfoList); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "next", "()C"); + mw.visitInsn(POP); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.COMMA); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "setToken", "(I)V"); + mw.visitJumpInsn(GOTO, quickEnd_); - _init(cw, new Context(fieldInfoList, className, config, clazz, 3)); - _createInstance(cw, new Context(fieldInfoList, className, config, clazz, 3)); - _parseField(cw, new Context(fieldInfoList, className, config, clazz, 4)); - _deserialze(cw, new Context(fieldInfoList, className, config, clazz, 3)); + mw.visitLabel(quickElseIf_); + mw.visitVarInsn(ILOAD, context.var("ch")); + mw.visitVarInsn(BIPUSH, ']'); + mw.visitJumpInsn(IF_ICMPNE, quickElseIfEOI_); - byte[] code = cw.toByteArray(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "next", "()C"); + mw.visitInsn(POP); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.RBRACKET); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "setToken", "(I)V"); + mw.visitJumpInsn(GOTO, quickEnd_); - // org.apache.commons.io.IOUtils.write(code, new - // java.io.FileOutputStream("/usr/alibaba/workspace/fastjson-asm/target/classes/" + className + ".class")); + mw.visitLabel(quickElseIfEOI_); + mw.visitVarInsn(ILOAD, context.var("ch")); + mw.visitVarInsn(BIPUSH, (char) JSONLexer.EOI); + mw.visitJumpInsn(IF_ICMPNE, quickElse_); - Class exampleClass = classLoader.defineClassPublic(className, code, 0, code.length); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "next", "()C"); + mw.visitInsn(POP); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.EOF); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "setToken", "(I)V"); + mw.visitJumpInsn(GOTO, quickEnd_); - Constructor constructor = exampleClass.getConstructor(ParserConfig.class, Class.class); - Object instance = constructor.newInstance(config, clazz); + mw.visitLabel(quickElse_); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.COMMA); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "nextToken", "(I)V"); - return (ObjectDeserializer) instance; + mw.visitLabel(quickEnd_); + + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitInsn(ARETURN); + mw.visitMaxs(5, context.variantIndex); + mw.visitEnd(); } - void _deserialze(ClassWriter cw, Context context) { - if (context.getFieldInfoList().size() == 0) { + private void _deserialze(ClassWriter cw, Context context) { + if (context.fieldInfoList.length == 0) { return; } - for (FieldInfo fieldInfo : context.getFieldInfoList()) { - Class fieldClass = fieldInfo.getMethod().getParameterTypes()[0]; - Type fieldType = fieldInfo.getMethod().getGenericParameterTypes()[0]; + for (FieldInfo fieldInfo : context.fieldInfoList) { + Class fieldClass = fieldInfo.fieldClass; + Type fieldType = fieldInfo.fieldType; if (fieldClass == char.class) { return; @@ -115,121 +569,425 @@ void _deserialze(ClassWriter cw, Context context) { } } - Collections.sort(context.getFieldInfoList()); + JavaBeanInfo beanInfo = context.beanInfo; + context.fieldInfoList = beanInfo.sortedFields; - MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "deserialze", "(" + getDesc(DefaultExtJSONParser.class) - + getDesc(Type.class) + ")Ljava/lang/Object;", - null, null); + MethodVisitor mw = new MethodWriter(cw, ACC_PUBLIC, "deserialze", + "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;Ljava/lang/Object;I)Ljava/lang/Object;", + null, null); Label reset_ = new Label(); Label super_ = new Label(); + Label return_ = new Label(); Label end_ = new Label(); - mw.visitVarInsn(ALOAD, 1); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getLexer", "()" + getDesc(JSONLexer.class)); - mw.visitTypeInsn(CHECKCAST, getType(JSONScanner.class)); // cast - mw.visitVarInsn(ASTORE, context.var("lexer")); + defineVarLexer(context, mw); + + { + Label next_ = new Label(); + + // isSupportArrayToBean + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); + mw.visitLdcInsn(JSONToken.LBRACKET); + mw.visitJumpInsn(IF_ICMPNE, next_); + + if ((beanInfo.parserFeatures & Feature.SupportArrayToBean.mask) == 0) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ILOAD, 4); + mw.visitLdcInsn(Feature.SupportArrayToBean.mask); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "isEnabled", "(II)Z"); + mw.visitJumpInsn(IFEQ, next_); + } + + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, Context.parser); + mw.visitVarInsn(ALOAD, 2); + mw.visitVarInsn(ALOAD, 3); + mw.visitInsn(ACONST_NULL); //mw.visitVarInsn(ALOAD, 5); + mw.visitMethodInsn(INVOKESPECIAL, // + context.className, // + "deserialzeArrayMapping", // + "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); + mw.visitInsn(ARETURN); + + mw.visitLabel(next_); + // deserialzeArrayMapping + } mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitFieldInsn(GETSTATIC, getType(Feature.class), "SortFeidFastMatch", "L" + getType(Feature.class) + ";"); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "isEnabled", "(" + "L" + getType(Feature.class) - + ";" + ")Z"); + mw.visitLdcInsn(Feature.SortFeidFastMatch.mask); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "isEnabled", "(I)Z"); + mw.visitJumpInsn(IFEQ, super_); mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "getBufferPosition", "()I"); - mw.visitVarInsn(ISTORE, context.var("mark")); + mw.visitLdcInsn(context.clazz.getName()); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanType", "(Ljava/lang/String;)I"); + + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.NOT_MATCH); + mw.visitJumpInsn(IF_ICMPEQ, super_); + + mw.visitVarInsn(ALOAD, 1); // parser + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getContext", "()" + desc(ParseContext.class)); + mw.visitVarInsn(ASTORE, context.var("mark_context")); + + // ParseContext context = parser.getContext(); + mw.visitInsn(ICONST_0); + mw.visitVarInsn(ISTORE, context.var("matchedCount")); + + _createInstance(context, mw); + + { + mw.visitVarInsn(ALOAD, 1); // parser + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getContext", "()" + desc(ParseContext.class)); + mw.visitVarInsn(ASTORE, context.var("context")); + + mw.visitVarInsn(ALOAD, 1); // parser + mw.visitVarInsn(ALOAD, context.var("context")); + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitVarInsn(ALOAD, 3); // fieldName + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "setContext", // + "(" + desc(ParseContext.class) + "Ljava/lang/Object;Ljava/lang/Object;)" + + desc(ParseContext.class)); + mw.visitVarInsn(ASTORE, context.var("childContext")); + } mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "getCurrent", "()C"); - mw.visitVarInsn(ISTORE, context.var("mark_ch")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.END); + mw.visitJumpInsn(IF_ICMPEQ, return_); + + mw.visitInsn(ICONST_0); // UNKOWN + mw.visitIntInsn(ISTORE, context.var("matchStat")); + + int fieldListSize = context.fieldInfoList.length; + for (int i = 0; i < fieldListSize; i += 32) { + mw.visitInsn(ICONST_0); + mw.visitVarInsn(ISTORE, context.var("_asm_flag_" + (i / 32))); + } mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "token", "()I"); - mw.visitVarInsn(ISTORE, context.var("mark_token")); + mw.visitLdcInsn(Feature.InitStringFieldAsEmpty.mask); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "isEnabled", "(I)Z"); + mw.visitIntInsn(ISTORE, context.var("initStringFieldAsEmpty")); + + // declare and init + for (int i = 0; i < fieldListSize; ++i) { + FieldInfo fieldInfo = context.fieldInfoList[i]; + Class fieldClass = fieldInfo.fieldClass; + + if (fieldClass == boolean.class // + || fieldClass == byte.class // + || fieldClass == short.class // + || fieldClass == int.class) { + mw.visitInsn(ICONST_0); + mw.visitVarInsn(ISTORE, context.var(fieldInfo.name + "_asm")); + } else if (fieldClass == long.class) { + mw.visitInsn(LCONST_0); + mw.visitVarInsn(LSTORE, context.var(fieldInfo.name + "_asm", 2)); + } else if (fieldClass == float.class) { + mw.visitInsn(FCONST_0); + mw.visitVarInsn(FSTORE, context.var(fieldInfo.name + "_asm")); + } else if (fieldClass == double.class) { + mw.visitInsn(DCONST_0); + mw.visitVarInsn(DSTORE, context.var(fieldInfo.name + "_asm", 2)); + } else { + if (fieldClass == String.class) { + Label flagEnd_ = new Label(); + Label flagElse_ = new Label(); + mw.visitVarInsn(ILOAD, context.var("initStringFieldAsEmpty")); + mw.visitJumpInsn(IFEQ, flagElse_); + _setFlag(mw, context, i); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "stringDefaultValue", "()Ljava/lang/String;"); + mw.visitJumpInsn(GOTO, flagEnd_); + + mw.visitLabel(flagElse_); + mw.visitInsn(ACONST_NULL); + + mw.visitLabel(flagEnd_); + } else { + mw.visitInsn(ACONST_NULL); + } - for (int i = 0, size = context.getFieldInfoList().size(); i < size; ++i) { - FieldInfo fieldInfo = context.getFieldInfoList().get(i); - Class fieldClass = fieldInfo.getMethod().getParameterTypes()[0]; - Type fieldType = fieldInfo.getMethod().getGenericParameterTypes()[0]; + mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + } + } - mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitVarInsn(ALOAD, 0); - mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); - if (fieldClass == boolean.class) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "scanFieldBoolean", "([C)Z"); - mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); + for (int i = 0; i < fieldListSize; ++i) { + FieldInfo fieldInfo = context.fieldInfoList[i]; + Class fieldClass = fieldInfo.fieldClass; + Type fieldType = fieldInfo.fieldType; + + Label notMatch_ = new Label(); + if (fieldClass == boolean.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldBoolean", "([C)Z"); + mw.visitVarInsn(ISTORE, context.var(fieldInfo.name + "_asm")); } else if (fieldClass == byte.class) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "scanFieldInt", "([C)I"); - mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); + mw.visitVarInsn(ISTORE, context.var(fieldInfo.name + "_asm")); + + } else if (fieldClass == Byte.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); + + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + mw.visitLabel(valueNullEnd_); } else if (fieldClass == short.class) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "scanFieldInt", "([C)I"); - mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); + mw.visitVarInsn(ISTORE, context.var(fieldInfo.name + "_asm")); + + } else if (fieldClass == Short.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;"); + + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + mw.visitLabel(valueNullEnd_); } else if (fieldClass == int.class) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "scanFieldInt", "([C)I"); - mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); + mw.visitVarInsn(ISTORE, context.var(fieldInfo.name + "_asm")); + + } else if (fieldClass == Integer.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); + + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + mw.visitLabel(valueNullEnd_); } else if (fieldClass == long.class) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "scanFieldLong", "([C)J"); - mw.visitVarInsn(LSTORE, context.var(fieldInfo.getName() + "_asm", 2)); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldLong", "([C)J"); + mw.visitVarInsn(LSTORE, context.var(fieldInfo.name + "_asm", 2)); + + } else if (fieldClass == Long.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldLong", "([C)J"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"); + + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + mw.visitLabel(valueNullEnd_); } else if (fieldClass == float.class) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "scanFieldFloat", "([C)F"); - mw.visitVarInsn(FSTORE, context.var(fieldInfo.getName() + "_asm")); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldFloat", "([C)F"); + mw.visitVarInsn(FSTORE, context.var(fieldInfo.name + "_asm")); + + } else if (fieldClass == Float.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldFloat", "([C)F"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + mw.visitLabel(valueNullEnd_); } else if (fieldClass == double.class) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "scanFieldDouble", "([C)D"); - mw.visitVarInsn(DSTORE, context.var(fieldInfo.getName() + "_asm", 2)); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldDouble", "([C)D"); + mw.visitVarInsn(DSTORE, context.var(fieldInfo.name + "_asm", 2)); - } else if (fieldClass == String.class) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "scanFieldString", - "([C)Ljava/lang/String;"); - mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); + } else if (fieldClass == Double.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldDouble", "([C)D"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"); - } else if (fieldClass.isEnum()) { - Label enumNull_ = new Label(); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + Label valueNullEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.VALUE_NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNullEnd_); mw.visitInsn(ACONST_NULL); - mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast - mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); - mw.visitVarInsn(ALOAD, 1); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultExtJSONParser.class), "getSymbolTable", - "()" + getDesc(SymbolTable.class)); + mw.visitLabel(valueNullEnd_); + } else if (fieldClass == String.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldString", "([C)Ljava/lang/String;"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "scanFieldSymbol", - "([C" + getDesc(SymbolTable.class) + ")Ljava/lang/String;"); - mw.visitInsn(DUP); - mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm_enumName")); + } else if (fieldClass == java.util.Date.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldDate", "([C)Ljava/util/Date;"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); - mw.visitJumpInsn(IFNULL, enumNull_); - mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm_enumName")); - mw.visitMethodInsn(INVOKESTATIC, getType(fieldClass), "valueOf", "(Ljava/lang/String;)" - + getDesc(fieldClass)); - mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); - mw.visitLabel(enumNull_); + } else if (fieldClass == java.util.UUID.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldUUID", "([C)Ljava/util/UUID;"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + } else if (fieldClass == BigDecimal.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldDecimal", "([C)Ljava/math/BigDecimal;"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + } else if (fieldClass == BigInteger.class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldBigInteger", "([C)Ljava/math/BigInteger;"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + } else if (fieldClass == int[].class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldIntArray", "([C)[I"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + } else if (fieldClass == float[].class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldFloatArray", "([C)[F"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + } else if (fieldClass == float[][].class) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldFloatArray2", "([C)[[F"); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + } else if (fieldClass.isEnum()) { + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + _getFieldDeser(context, mw, fieldInfo); + mw.visitMethodInsn(INVOKEVIRTUAL, type(JavaBeanDeserializer.class), "scanEnum" + , "(L" + JSONLexerBase + ";[C" + desc(ObjectDeserializer.class) + ")Ljava/lang/Enum;"); + mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + +// } else if (fieldClass.isEnum()) { +// mw.visitVarInsn(ALOAD, context.var("lexer")); +// mw.visitVarInsn(ALOAD, 0); +// mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); +// Label enumNull_ = new Label(); +// mw.visitInsn(ACONST_NULL); +// mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast +// mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); +// +// mw.visitVarInsn(ALOAD, 1); +// +// mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getSymbolTable", "()" + desc(SymbolTable.class)); +// +// mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldSymbol", +// "([C" + desc(SymbolTable.class) + ")Ljava/lang/String;"); +// mw.visitInsn(DUP); +// mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm_enumName")); +// +// mw.visitJumpInsn(IFNULL, enumNull_); +// +// mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm_enumName")); +// mw.visitMethodInsn(INVOKEVIRTUAL, type(String.class), "length", "()I"); +// mw.visitJumpInsn(IFEQ, enumNull_); +// +// mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm_enumName")); +// mw.visitMethodInsn(INVOKESTATIC, type(fieldClass), "valueOf", +// "(Ljava/lang/String;)" + desc(fieldClass)); +// mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); +// mw.visitLabel(enumNull_); } else if (Collection.class.isAssignableFrom(fieldClass)) { - Class itemType = (Class) ((ParameterizedType) fieldType).getActualTypeArguments()[0]; - if (itemType == String.class) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "scanFieldStringArray", - "([C)" + getDesc(ArrayList.class)); - mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + + Class itemClass = TypeUtils.getCollectionItemClass(fieldType); + + if (itemClass == String.class) { + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldClass))); // cast + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldStringArray", + "([CLjava/lang/Class;)" + desc(Collection.class)); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); } else { - _deserialze_list_obj(context, mw, reset_, fieldInfo, fieldClass, itemType); + _deserialze_list_obj(context, mw, reset_, fieldInfo, fieldClass, itemClass, i); - if (i == size - 1) { + if (i == fieldListSize - 1) { _deserialize_endCheck(context, mw, reset_); } continue; } - } else { - _deserialze_obj(context, mw, reset_, fieldInfo, fieldClass); + _deserialze_obj(context, mw, reset_, fieldInfo, fieldClass, i); - if (i == size - 1) { + if (i == fieldListSize - 1) { _deserialize_endCheck(context, mw, reset_); } @@ -237,387 +995,776 @@ void _deserialze(ClassWriter cw, Context context) { } mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitFieldInsn(GETFIELD, getType(JSONScanner.class), "matchStat", "I"); - mw.visitFieldInsn(GETSTATIC, getType(JSONScanner.class), "NOT_MATCH", "I"); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + Label flag_ = new Label(); + // mw.visitInsn(DUP); + mw.visitJumpInsn(IFLE, flag_); + _setFlag(mw, context, i); + mw.visitLabel(flag_); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitInsn(DUP); + mw.visitVarInsn(ISTORE, context.var("matchStat")); + + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.NOT_MATCH); mw.visitJumpInsn(IF_ICMPEQ, reset_); - if (i == size - 1) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitJumpInsn(IFLE, notMatch_); + + // increment matchedCount + mw.visitVarInsn(ILOAD, context.var("matchedCount")); + mw.visitInsn(ICONST_1); + mw.visitInsn(IADD); + mw.visitVarInsn(ISTORE, context.var("matchedCount")); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.END); + mw.visitJumpInsn(IF_ICMPEQ, end_); + + mw.visitLabel(notMatch_); + + if (i == fieldListSize - 1) { mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitFieldInsn(GETFIELD, getType(JSONScanner.class), "matchStat", "I"); - mw.visitFieldInsn(GETSTATIC, getType(JSONScanner.class), "END", "I"); + mw.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.END); mw.visitJumpInsn(IF_ICMPNE, reset_); } + } // endFor + + mw.visitLabel(end_); + + if (!context.clazz.isInterface() && !Modifier.isAbstract(context.clazz.getModifiers())) { + _batchSet(context, mw); } - mw.visitTypeInsn(NEW, getType(context.getClazz())); - mw.visitInsn(DUP); - mw.visitMethodInsn(INVOKESPECIAL, getType(context.getClazz()), "", "()V"); - mw.visitVarInsn(ASTORE, context.var("instance")); + mw.visitLabel(return_); - for (int i = 0, size = context.getFieldInfoList().size(); i < size; ++i) { - FieldInfo fieldInfo = context.getFieldInfoList().get(i); - Class fieldClass = fieldInfo.getMethod().getParameterTypes()[0]; - Type fieldType = fieldInfo.getMethod().getGenericParameterTypes()[0]; + _setContext(context, mw); + mw.visitVarInsn(ALOAD, context.var("instance")); - mw.visitVarInsn(ALOAD, context.var("instance")); - if (fieldClass == boolean.class) { - mw.visitVarInsn(ILOAD, context.var(fieldInfo.getName() + "_asm")); - } else if (fieldClass == byte.class) { - mw.visitVarInsn(ILOAD, context.var(fieldInfo.getName() + "_asm")); - } else if (fieldClass == short.class) { - mw.visitVarInsn(ILOAD, context.var(fieldInfo.getName() + "_asm")); - } else if (fieldClass == int.class) { - mw.visitVarInsn(ILOAD, context.var(fieldInfo.getName() + "_asm")); - } else if (fieldClass == long.class) { - mw.visitVarInsn(LLOAD, context.var(fieldInfo.getName() + "_asm")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(context.getClazz()), fieldInfo.getMethod().getName(), "(J)V"); - continue; - } else if (fieldClass == float.class) { - mw.visitVarInsn(FLOAD, context.var(fieldInfo.getName() + "_asm")); - } else if (fieldClass == double.class) { - mw.visitVarInsn(DLOAD, context.var(fieldInfo.getName() + "_asm", 2)); - } else if (fieldClass == String.class) { - mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); - } else if (fieldClass.isEnum()) { - mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); - } else if (Collection.class.isAssignableFrom(fieldClass)) { - Type itemType = ((ParameterizedType) fieldType).getActualTypeArguments()[0]; - if (itemType == String.class) { - mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); - mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast - } else { - mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); - } - } else { - mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); - } - mw.visitMethodInsn(INVOKEVIRTUAL, getType(fieldInfo.getMethod().getDeclaringClass()), - fieldInfo.getMethod().getName(), getDesc(fieldInfo.getMethod())); + Method buildMethod = context.beanInfo.buildMethod; + if (buildMethod != null) { + mw.visitMethodInsn(INVOKEVIRTUAL, type(context.getInstClass()), buildMethod.getName(), + "()" + desc(buildMethod.getReturnType())); } - mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitInsn(ARETURN); mw.visitLabel(reset_); - // void reset(int mark, char mark_ch) - mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitVarInsn(ILOAD, context.var("mark")); - mw.visitVarInsn(ILOAD, context.var("mark_ch")); - mw.visitVarInsn(ILOAD, context.var("mark_token")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "reset", "(ICI)V"); + _batchSet(context, mw); + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, 1); + mw.visitVarInsn(ALOAD, 2); + mw.visitVarInsn(ALOAD, 3); + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitVarInsn(ILOAD, 4); + + + int flagSize = (fieldListSize / 32); + + if (fieldListSize != 0 && (fieldListSize % 32) != 0) { + flagSize += 1; + } + + if (flagSize == 1) { + mw.visitInsn(ICONST_1); + } else { + mw.visitIntInsn(BIPUSH, flagSize); + } + mw.visitIntInsn(NEWARRAY, T_INT); + for (int i = 0; i < flagSize; ++i) { + mw.visitInsn(DUP); + if (i == 0) { + mw.visitInsn(ICONST_0); + } else if (i == 1) { + mw.visitInsn(ICONST_1); + } else { + mw.visitIntInsn(BIPUSH, i); + } + mw.visitVarInsn(ILOAD, context.var("_asm_flag_" + i)); + mw.visitInsn(IASTORE); + } + + mw.visitMethodInsn(INVOKEVIRTUAL, type(JavaBeanDeserializer.class), + "parseRest", "(L" + DefaultJSONParser + + ";Ljava/lang/reflect/Type;Ljava/lang/Object;Ljava/lang/Object;I[I)Ljava/lang/Object;"); + mw.visitTypeInsn(CHECKCAST, type(context.clazz)); // cast + mw.visitInsn(ARETURN); mw.visitLabel(super_); mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, 1); mw.visitVarInsn(ALOAD, 2); - mw.visitMethodInsn(INVOKESPECIAL, getType(ASMJavaBeanDeserializer.class), "deserialze", - "(" + getDesc(DefaultExtJSONParser.class) + getDesc(Type.class) + ")Ljava/lang/Object;"); + mw.visitVarInsn(ALOAD, 3); + mw.visitVarInsn(ILOAD, 4); + mw.visitMethodInsn(INVOKESPECIAL, type(JavaBeanDeserializer.class), // + "deserialze", // + "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;Ljava/lang/Object;I)Ljava/lang/Object;"); mw.visitInsn(ARETURN); - mw.visitLabel(end_); - - mw.visitMaxs(4, context.getVariantCount()); + mw.visitMaxs(10, context.variantIndex); mw.visitEnd(); + + } + + private void defineVarLexer(Context context, MethodVisitor mw) { + mw.visitVarInsn(ALOAD, 1); + mw.visitFieldInsn(GETFIELD, DefaultJSONParser, "lexer", desc(JSONLexer.class)); + mw.visitTypeInsn(CHECKCAST, JSONLexerBase); // cast + mw.visitVarInsn(ASTORE, context.var("lexer")); + } + + private void _createInstance(Context context, MethodVisitor mw) { + JavaBeanInfo beanInfo = context.beanInfo; + Constructor defaultConstructor = beanInfo.defaultConstructor; + if (Modifier.isPublic(defaultConstructor.getModifiers())) { + mw.visitTypeInsn(NEW, type(context.getInstClass())); + mw.visitInsn(DUP); + + mw.visitMethodInsn(INVOKESPECIAL, type(defaultConstructor.getDeclaringClass()), "", "()V"); + + mw.visitVarInsn(ASTORE, context.var("instance")); + } else { + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, 1); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, type(JavaBeanDeserializer.class), "clazz", "Ljava/lang/Class;"); + mw.visitMethodInsn(INVOKESPECIAL, type(JavaBeanDeserializer.class), "createInstance", + "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;)Ljava/lang/Object;"); + mw.visitTypeInsn(CHECKCAST, type(context.getInstClass())); // cast + mw.visitVarInsn(ASTORE, context.var("instance")); + } + } + + private void _batchSet(Context context, MethodVisitor mw) { + _batchSet(context, mw, true); + } + + private void _batchSet(Context context, MethodVisitor mw, boolean flag) { + for (int i = 0, size = context.fieldInfoList.length; i < size; ++i) { + Label notSet_ = new Label(); + + if (flag) { + _isFlag(mw, context, i, notSet_); + } + + FieldInfo fieldInfo = context.fieldInfoList[i]; + _loadAndSet(context, mw, fieldInfo); + + if (flag) { + mw.visitLabel(notSet_); + } + } + } + + private void _loadAndSet(Context context, MethodVisitor mw, FieldInfo fieldInfo) { + Class fieldClass = fieldInfo.fieldClass; + Type fieldType = fieldInfo.fieldType; + + if (fieldClass == boolean.class) { + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitVarInsn(ILOAD, context.var(fieldInfo.name + "_asm")); + _set(context, mw, fieldInfo); + } else if (fieldClass == byte.class // + || fieldClass == short.class // + || fieldClass == int.class // + || fieldClass == char.class) { + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitVarInsn(ILOAD, context.var(fieldInfo.name + "_asm")); + _set(context, mw, fieldInfo); + } else if (fieldClass == long.class) { + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitVarInsn(LLOAD, context.var(fieldInfo.name + "_asm", 2)); + if (fieldInfo.method != null) { + mw.visitMethodInsn(INVOKEVIRTUAL, type(context.getInstClass()), fieldInfo.method.getName(), + desc(fieldInfo.method)); + if (!fieldInfo.method.getReturnType().equals(Void.TYPE)) { + mw.visitInsn(POP); + } + } else { + mw.visitFieldInsn(PUTFIELD, type(fieldInfo.declaringClass), fieldInfo.field.getName(), + desc(fieldInfo.fieldClass)); + } + } else if (fieldClass == float.class) { + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitVarInsn(FLOAD, context.var(fieldInfo.name + "_asm")); + _set(context, mw, fieldInfo); + } else if (fieldClass == double.class) { + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitVarInsn(DLOAD, context.var(fieldInfo.name + "_asm", 2)); + _set(context, mw, fieldInfo); + } else if (fieldClass == String.class) { + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm")); + _set(context, mw, fieldInfo); + } else if (fieldClass.isEnum()) { + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm")); + _set(context, mw, fieldInfo); + } else if (Collection.class.isAssignableFrom(fieldClass)) { + mw.visitVarInsn(ALOAD, context.var("instance")); + Type itemType = TypeUtils.getCollectionItemClass(fieldType); + if (itemType == String.class) { + mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm")); + mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast + } else { + mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm")); + } + _set(context, mw, fieldInfo); + + } else { + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm")); + _set(context, mw, fieldInfo); + } + } + + private void _set(Context context, MethodVisitor mw, FieldInfo fieldInfo) { + Method method = fieldInfo.method; + if (method != null) { + Class declaringClass = method.getDeclaringClass(); + mw.visitMethodInsn(declaringClass.isInterface() ? INVOKEINTERFACE : INVOKEVIRTUAL, type(fieldInfo.declaringClass), method.getName(), desc(method)); + + if (!fieldInfo.method.getReturnType().equals(Void.TYPE)) { + mw.visitInsn(POP); + } + } else { + mw.visitFieldInsn(PUTFIELD, type(fieldInfo.declaringClass), fieldInfo.field.getName(), + desc(fieldInfo.fieldClass)); + } + } + + private void _setContext(Context context, MethodVisitor mw) { + mw.visitVarInsn(ALOAD, 1); // parser + mw.visitVarInsn(ALOAD, context.var("context")); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "setContext", "(" + desc(ParseContext.class) + ")V"); + + Label endIf_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("childContext")); + mw.visitJumpInsn(IFNULL, endIf_); + + mw.visitVarInsn(ALOAD, context.var("childContext")); + mw.visitVarInsn(ALOAD, context.var("instance")); + mw.visitFieldInsn(PUTFIELD, type(ParseContext.class), "object", "Ljava/lang/Object;"); + + mw.visitLabel(endIf_); } private void _deserialize_endCheck(Context context, MethodVisitor mw, Label reset_) { + mw.visitIntInsn(ILOAD, context.var("matchedCount")); + mw.visitJumpInsn(IFLE, reset_); + mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "token", "()I"); - mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "RBRACE", "I"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); + mw.visitLdcInsn(JSONToken.RBRACE); mw.visitJumpInsn(IF_ICMPNE, reset_); - mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "COMMA", "I"); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "nextToken", "(I)V"); + // mw.visitLabel(nextToken_); + _quickNextTokenComma(context, mw); } private void _deserialze_list_obj(Context context, MethodVisitor mw, Label reset_, FieldInfo fieldInfo, - Class fieldClass, Class itemType) { - // _asm_list_item_deser__ + Class fieldClass, Class itemType, int i) { + Label _end_if = new Label(); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "matchField", "([C)Z"); - mw.visitJumpInsn(IFEQ, reset_); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "matchField", "([C)Z"); + mw.visitJumpInsn(IFEQ, _end_if); - Label notNull_ = new Label(); - mw.visitVarInsn(ALOAD, 0); - mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_list_item_deser__", - getDesc(ObjectDeserializer.class)); - mw.visitJumpInsn(IFNONNULL, notNull_); + _setFlag(mw, context, i); - mw.visitVarInsn(ALOAD, 0); + Label valueNotNull_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); + mw.visitLdcInsn(JSONToken.NULL); + mw.visitJumpInsn(IF_ICMPNE, valueNotNull_); - mw.visitVarInsn(ALOAD, 1); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultExtJSONParser.class), "getConfig", - "()" + getDesc(ParserConfig.class)); - mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(getDesc(itemType))); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(ParserConfig.class), "getDeserializer", - "(" + getDesc(Type.class) + ")" + getDesc(ObjectDeserializer.class)); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.COMMA); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "nextToken", "(I)V"); + mw.visitJumpInsn(GOTO, _end_if); + // loop_end_ - mw.visitFieldInsn(PUTFIELD, context.getClassName(), fieldInfo.getName() + "_asm_list_item_deser__", - getDesc(ObjectDeserializer.class)); + mw.visitLabel(valueNotNull_); - mw.visitLabel(notNull_); + Label storeCollection_ = new Label(), endSet_ = new Label(), lbacketNormal_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); + mw.visitLdcInsn(JSONToken.SET); + mw.visitJumpInsn(IF_ICMPNE, endSet_); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.LBRACKET); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "nextToken", "(I)V"); + + _newCollection(mw, fieldClass, i, true); + + mw.visitJumpInsn(GOTO, storeCollection_); + + mw.visitLabel(endSet_); // if (lexer.token() != JSONToken.LBRACKET) reset mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "token", "()I"); - mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "LBRACKET", "I"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); + mw.visitLdcInsn(JSONToken.LBRACKET); + mw.visitJumpInsn(IF_ICMPEQ, lbacketNormal_); + + // if (lexer.token() == JSONToken.LBRACE) reset + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); + mw.visitLdcInsn(JSONToken.LBRACE); mw.visitJumpInsn(IF_ICMPNE, reset_); - mw.visitVarInsn(ALOAD, 0); - mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_list_item_deser__", - getDesc(ObjectDeserializer.class)); - mw.visitMethodInsn(INVOKEINTERFACE, getType(ObjectDeserializer.class), "getFastMatchToken", "()I"); - mw.visitVarInsn(ISTORE, context.var("fastMatchToken")); + _newCollection(mw, fieldClass, i, false); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); - mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitVarInsn(ILOAD, context.var("fastMatchToken")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "nextToken", "(I)V"); + _getCollectionFieldItemDeser(context, mw, fieldInfo, itemType); + mw.visitVarInsn(ALOAD, 1); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(itemType))); + mw.visitInsn(ICONST_0); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); + mw.visitMethodInsn(INVOKEINTERFACE, type(ObjectDeserializer.class), "deserialze", + "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;Ljava/lang/Object;)Ljava/lang/Object;"); + mw.visitVarInsn(ASTORE, context.var("list_item_value")); - mw.visitTypeInsn(NEW, getType(ArrayList.class)); - mw.visitInsn(DUP); - mw.visitMethodInsn(INVOKESPECIAL, getType(ArrayList.class), "", "()V"); - mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast - mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); + mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm")); + mw.visitVarInsn(ALOAD, context.var("list_item_value")); + if (fieldClass.isInterface()) { + mw.visitMethodInsn(INVOKEINTERFACE, type(fieldClass), "add", "(Ljava/lang/Object;)Z"); + } else { + mw.visitMethodInsn(INVOKEVIRTUAL, type(fieldClass), "add", "(Ljava/lang/Object;)Z"); + } + mw.visitInsn(POP); + + mw.visitJumpInsn(GOTO, _end_if); + + mw.visitLabel(lbacketNormal_); + + _newCollection(mw, fieldClass, i, false); + + mw.visitLabel(storeCollection_); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + + boolean isPrimitive = ParserConfig.isPrimitive2(fieldInfo.fieldClass); + _getCollectionFieldItemDeser(context, mw, fieldInfo, itemType); + if (isPrimitive) { + mw.visitMethodInsn(INVOKEINTERFACE, type(ObjectDeserializer.class), "getFastMatchToken", "()I"); + mw.visitVarInsn(ISTORE, context.var("fastMatchToken")); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ILOAD, context.var("fastMatchToken")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "nextToken", "(I)V"); + } else { + mw.visitInsn(POP); + mw.visitLdcInsn(JSONToken.LBRACE); + mw.visitVarInsn(ISTORE, context.var("fastMatchToken")); + + _quickNextToken(context, mw, JSONToken.LBRACE); + } + + { // setContext + mw.visitVarInsn(ALOAD, 1); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getContext", "()" + desc(ParseContext.class)); + mw.visitVarInsn(ASTORE, context.var("listContext")); + + mw.visitVarInsn(ALOAD, 1); // parser + mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm")); + mw.visitLdcInsn(fieldInfo.name); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "setContext", + "(Ljava/lang/Object;Ljava/lang/Object;)" + desc(ParseContext.class)); + mw.visitInsn(POP); + } Label loop_ = new Label(); Label loop_end_ = new Label(); // for (;;) { + mw.visitInsn(ICONST_0); + mw.visitVarInsn(ISTORE, context.var("i")); mw.visitLabel(loop_); - // if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { - // while (lexer.token() == JSONToken.COMMA) { - // lexer.nextToken(); - // continue; - // } - // } - // mw.visitVarInsn(ALOAD, context.var("lexer")); - // mw.visitFieldInsn(GETSTATIC, getType(Feature.class), "AllowArbitraryCommas", "L" + getType(Feature.class) + - // ";"); - // mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "isEnabled", "(" + "L" + getType(Feature.class) - // + ";" + ")Z"); - - // if (lexer.token() == JSONToken.RBRACKET) { - // break; - // } - mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "token", "()I"); - mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "RBRACKET", "I"); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); + mw.visitLdcInsn(JSONToken.RBRACKET); + mw.visitJumpInsn(IF_ICMPEQ, loop_end_); // Object value = itemDeserializer.deserialze(parser, null); // array.add(value); mw.visitVarInsn(ALOAD, 0); - mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_list_item_deser__", - getDesc(ObjectDeserializer.class)); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_list_item_deser__", + desc(ObjectDeserializer.class)); mw.visitVarInsn(ALOAD, 1); - mw.visitInsn(ACONST_NULL); - mw.visitMethodInsn(INVOKEINTERFACE, getType(ObjectDeserializer.class), "deserialze", - "(Lcom/alibaba/fastjson/parser/DefaultExtJSONParser;Ljava/lang/reflect/Type;)Ljava/lang/Object;"); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(itemType))); + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); + mw.visitMethodInsn(INVOKEINTERFACE, type(ObjectDeserializer.class), "deserialze", + "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;Ljava/lang/Object;)Ljava/lang/Object;"); mw.visitVarInsn(ASTORE, context.var("list_item_value")); - mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); + mw.visitIincInsn(context.var("i"), 1); + + mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm")); mw.visitVarInsn(ALOAD, context.var("list_item_value")); if (fieldClass.isInterface()) { - mw.visitMethodInsn(INVOKEINTERFACE, getType(fieldClass), "add", "(Ljava/lang/Object;)Z"); + mw.visitMethodInsn(INVOKEINTERFACE, type(fieldClass), "add", "(Ljava/lang/Object;)Z"); } else { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(fieldClass), "add", "(Ljava/lang/Object;)Z"); + mw.visitMethodInsn(INVOKEVIRTUAL, type(fieldClass), "add", "(Ljava/lang/Object;)Z"); } mw.visitInsn(POP); - // if (lexer.token() == JSONToken.COMMA) { - // lexer.nextToken(itemDeserializer.getFastMatchToken()); - // continue; - // } + mw.visitVarInsn(ALOAD, 1); + mw.visitVarInsn(ALOAD, context.var(fieldInfo.name + "_asm")); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "checkListResolve", "(Ljava/util/Collection;)V"); + mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "token", "()I"); - mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "COMMA", "I"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); + mw.visitLdcInsn(JSONToken.COMMA); mw.visitJumpInsn(IF_ICMPNE, loop_); - mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitVarInsn(ILOAD, context.var("fastMatchToken")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "nextToken", "(I)V"); + if (isPrimitive) { + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ILOAD, context.var("fastMatchToken")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "nextToken", "(I)V"); + } else { + _quickNextToken(context, mw, JSONToken.LBRACE); + } + mw.visitJumpInsn(GOTO, loop_); mw.visitLabel(loop_end_); + // mw.visitVarInsn(ASTORE, context.var("context")); + // parser.setContext(context); + { // setContext + mw.visitVarInsn(ALOAD, 1); // parser + mw.visitVarInsn(ALOAD, context.var("listContext")); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "setContext", "(" + desc(ParseContext.class) + ")V"); + } + mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "token", "()I"); - mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "RBRACKET", "I"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); + mw.visitLdcInsn(JSONToken.RBRACKET); mw.visitJumpInsn(IF_ICMPNE, reset_); - mw.visitVarInsn(ALOAD, context.var("lexer")); - mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "COMMA", "I"); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "nextToken", "(I)V"); + _quickNextTokenComma(context, mw); // lexer.nextToken(JSONToken.COMMA); + mw.visitLabel(_end_if); } - private void _deserialze_obj(Context context, MethodVisitor mw, Label reset_, FieldInfo fieldInfo, - Class fieldClass) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONScanner.class), "matchField", "([C)Z"); - mw.visitJumpInsn(IFEQ, reset_); + private void _quickNextToken(Context context, MethodVisitor mw, int token) { + Label quickElse_ = new Label(), quickEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "getCurrent", "()C"); + if (token == JSONToken.LBRACE) { + mw.visitVarInsn(BIPUSH, '{'); + } else if (token == JSONToken.LBRACKET) { + mw.visitVarInsn(BIPUSH, '['); + } else { + throw new IllegalStateException(); + } + + mw.visitJumpInsn(IF_ICMPNE, quickElse_); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "next", "()C"); + mw.visitInsn(POP); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(token); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "setToken", "(I)V"); + mw.visitJumpInsn(GOTO, quickEnd_); + + mw.visitLabel(quickElse_); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(token); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "nextToken", "(I)V"); + + mw.visitLabel(quickEnd_); + } + + private void _quickNextTokenComma(Context context, MethodVisitor mw) { + Label quickElse_ = new Label(), quickElseIf0_ = new Label(), quickElseIf1_ = new Label(), quickElseIf2_ = new Label(), quickEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "getCurrent", "()C"); + mw.visitInsn(DUP); + mw.visitVarInsn(ISTORE, context.var("ch")); + mw.visitVarInsn(BIPUSH, ','); + mw.visitJumpInsn(IF_ICMPNE, quickElseIf0_); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "next", "()C"); + mw.visitInsn(POP); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.COMMA); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "setToken", "(I)V"); + mw.visitJumpInsn(GOTO, quickEnd_); + + mw.visitLabel(quickElseIf0_); + mw.visitVarInsn(ILOAD, context.var("ch")); + mw.visitVarInsn(BIPUSH, '}'); + mw.visitJumpInsn(IF_ICMPNE, quickElseIf1_); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "next", "()C"); + mw.visitInsn(POP); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.RBRACE); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "setToken", "(I)V"); + mw.visitJumpInsn(GOTO, quickEnd_); + + mw.visitLabel(quickElseIf1_); + mw.visitVarInsn(ILOAD, context.var("ch")); + mw.visitVarInsn(BIPUSH, ']'); + mw.visitJumpInsn(IF_ICMPNE, quickElseIf2_); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "next", "()C"); + mw.visitInsn(POP); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.RBRACKET); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "setToken", "(I)V"); + mw.visitJumpInsn(GOTO, quickEnd_); + + mw.visitLabel(quickElseIf2_); + mw.visitVarInsn(ILOAD, context.var("ch")); + mw.visitVarInsn(BIPUSH, JSONLexer.EOI); + mw.visitJumpInsn(IF_ICMPNE, quickElse_); + + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitLdcInsn(JSONToken.EOF); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "setToken", "(I)V"); + mw.visitJumpInsn(GOTO, quickEnd_); + + mw.visitLabel(quickElse_); + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "nextToken", "()V"); + mw.visitLabel(quickEnd_); + } + + private void _getCollectionFieldItemDeser(Context context, MethodVisitor mw, FieldInfo fieldInfo, + Class itemType) { Label notNull_ = new Label(); mw.visitVarInsn(ALOAD, 0); - mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_deser__", - getDesc(ObjectDeserializer.class)); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_list_item_deser__", + desc(ObjectDeserializer.class)); mw.visitJumpInsn(IFNONNULL, notNull_); mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, 1); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultExtJSONParser.class), "getConfig", - "()" + getDesc(ParserConfig.class)); - mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(getDesc(fieldInfo.getMethod().getParameterTypes()[0]))); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(ParserConfig.class), "getDeserializer", - "(" + getDesc(Type.class) + ")" + getDesc(ObjectDeserializer.class)); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getConfig", "()" + desc(ParserConfig.class)); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(itemType))); + mw.visitMethodInsn(INVOKEVIRTUAL, type(ParserConfig.class), "getDeserializer", + "(Ljava/lang/reflect/Type;)" + desc(ObjectDeserializer.class)); - mw.visitFieldInsn(PUTFIELD, context.getClassName(), fieldInfo.getName() + "_asm_deser__", - getDesc(ObjectDeserializer.class)); + mw.visitFieldInsn(PUTFIELD, context.className, fieldInfo.name + "_asm_list_item_deser__", + desc(ObjectDeserializer.class)); mw.visitLabel(notNull_); - mw.visitVarInsn(ALOAD, 0); - mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_deser__", - getDesc(ObjectDeserializer.class)); - mw.visitVarInsn(ALOAD, 1); - mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(getDesc(fieldInfo.getMethod().getParameterTypes()[0]))); - mw.visitMethodInsn(INVOKEINTERFACE, getType(ObjectDeserializer.class), "deserialze", - "(" + getDesc(DefaultExtJSONParser.class) + getDesc(Type.class) + ")Ljava/lang/Object;"); - mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast - mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_list_item_deser__", + desc(ObjectDeserializer.class)); + } + private void _newCollection(MethodVisitor mw, Class fieldClass, int i, boolean set) { + if (fieldClass.isAssignableFrom(ArrayList.class) && !set) { + mw.visitTypeInsn(NEW, "java/util/ArrayList"); + mw.visitInsn(DUP); + mw.visitMethodInsn(INVOKESPECIAL, "java/util/ArrayList", "", "()V"); + } else if (fieldClass.isAssignableFrom(LinkedList.class) && !set) { + mw.visitTypeInsn(NEW, type(LinkedList.class)); + mw.visitInsn(DUP); + mw.visitMethodInsn(INVOKESPECIAL, type(LinkedList.class), "", "()V"); + } else if (fieldClass.isAssignableFrom(HashSet.class)) { + mw.visitTypeInsn(NEW, type(HashSet.class)); + mw.visitInsn(DUP); + mw.visitMethodInsn(INVOKESPECIAL, type(HashSet.class), "", "()V"); + } else if (fieldClass.isAssignableFrom(TreeSet.class)) { + mw.visitTypeInsn(NEW, type(TreeSet.class)); + mw.visitInsn(DUP); + mw.visitMethodInsn(INVOKESPECIAL, type(TreeSet.class), "", "()V"); + } else if (fieldClass.isAssignableFrom(LinkedHashSet.class)) { + mw.visitTypeInsn(NEW, type(LinkedHashSet.class)); + mw.visitInsn(DUP); + mw.visitMethodInsn(INVOKESPECIAL, type(LinkedHashSet.class), "", "()V"); + } else if (set) { + mw.visitTypeInsn(NEW, type(HashSet.class)); + mw.visitInsn(DUP); + mw.visitMethodInsn(INVOKESPECIAL, type(HashSet.class), "", "()V"); + } else { + mw.visitVarInsn(ALOAD, 0); + mw.visitLdcInsn(i); + mw.visitMethodInsn(INVOKEVIRTUAL, type(JavaBeanDeserializer.class), "getFieldType", + "(I)Ljava/lang/reflect/Type;"); + mw.visitMethodInsn(INVOKESTATIC, type(TypeUtils.class), "createCollection", + "(Ljava/lang/reflect/Type;)Ljava/util/Collection;"); + } + mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast } - public FieldDeserializer createFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo) - throws Exception { - Class fieldClass = fieldInfo.getFieldClass(); + private void _deserialze_obj(Context context, MethodVisitor mw, Label reset_, FieldInfo fieldInfo, + Class fieldClass, int i) { + Label matched_ = new Label(); + Label _end_if = new Label(); - if (fieldClass == int.class || fieldClass == long.class || fieldClass == String.class) { - return createStringFieldDeserializer(mapping, clazz, fieldInfo); - } + mw.visitVarInsn(ALOAD, context.var("lexer")); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "matchField", "([C)Z"); + mw.visitJumpInsn(IFNE, matched_); + mw.visitInsn(ACONST_NULL); + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); - FieldDeserializer fieldDeserializer = mapping.createFieldDeserializerWithoutASM(mapping, clazz, fieldInfo); - return fieldDeserializer; - } + mw.visitJumpInsn(GOTO, _end_if); - public FieldDeserializer createStringFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo) - throws Exception { - Class fieldClass = fieldInfo.getFieldClass(); - Method method = fieldInfo.getMethod(); + mw.visitLabel(matched_); - String className = getGenFieldDeserializer(clazz, fieldInfo); + _setFlag(mw, context, i); - ClassWriter cw = new ClassWriter(); - Class superClass; - if (fieldClass == int.class) { - superClass = IntegerFieldDeserializer.class; - } else if (fieldClass == long.class) { - superClass = LongFieldDeserializer.class; - } else { - superClass = StringFieldDeserializer.class; - } + // increment matchedCount + mw.visitVarInsn(ILOAD, context.var("matchedCount")); + mw.visitInsn(ICONST_1); + mw.visitInsn(IADD); + mw.visitVarInsn(ISTORE, context.var("matchedCount")); - cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, className, getType(superClass), null); + _deserObject(context, mw, fieldInfo, fieldClass, i); - { - MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "", "(" + getDesc(ParserConfig.class) - + getDesc(Class.class) + getDesc(FieldInfo.class) - + ")V", null, null); - mw.visitVarInsn(ALOAD, 0); - mw.visitVarInsn(ALOAD, 1); - mw.visitVarInsn(ALOAD, 2); - mw.visitVarInsn(ALOAD, 3); - mw.visitMethodInsn(INVOKESPECIAL, getType(superClass), "", "(" + getDesc(ParserConfig.class) - + getDesc(Class.class) - + getDesc(FieldInfo.class) + ")V"); + mw.visitVarInsn(ALOAD, 1); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getResolveStatus", "()I"); + mw.visitLdcInsn(com.alibaba.fastjson.parser.DefaultJSONParser.NeedToResolve); + mw.visitJumpInsn(IF_ICMPNE, _end_if); - mw.visitInsn(RETURN); - mw.visitMaxs(4, 6); - mw.visitEnd(); - } + mw.visitVarInsn(ALOAD, 1); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getLastResolveTask", "()" + desc(ResolveTask.class)); + mw.visitVarInsn(ASTORE, context.var("resolveTask")); - if (fieldClass == int.class) { - MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "setValue", "(" + getDesc(Object.class) + "I)V", null, null); - mw.visitVarInsn(ALOAD, 1); - mw.visitTypeInsn(CHECKCAST, getType(method.getDeclaringClass())); // cast - mw.visitVarInsn(ILOAD, 2); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(method.getDeclaringClass()), method.getName(), "(I)V"); + mw.visitVarInsn(ALOAD, context.var("resolveTask")); + mw.visitVarInsn(ALOAD, 1); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getContext", "()" + desc(ParseContext.class)); + mw.visitFieldInsn(PUTFIELD, type(ResolveTask.class), "ownerContext", desc(ParseContext.class)); - mw.visitInsn(RETURN); - mw.visitMaxs(3, 3); - mw.visitEnd(); - } else if (fieldClass == long.class) { - MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "setValue", "(" + getDesc(Object.class) + "J)V", null, null); - mw.visitVarInsn(ALOAD, 1); - mw.visitTypeInsn(CHECKCAST, getType(method.getDeclaringClass())); // cast - mw.visitVarInsn(LLOAD, 2); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(method.getDeclaringClass()), method.getName(), "(J)V"); + mw.visitVarInsn(ALOAD, context.var("resolveTask")); + mw.visitVarInsn(ALOAD, 0); + mw.visitLdcInsn(fieldInfo.name); + mw.visitMethodInsn(INVOKEVIRTUAL, type(JavaBeanDeserializer.class), "getFieldDeserializer", + "(Ljava/lang/String;)" + desc(FieldDeserializer.class)); + mw.visitFieldInsn(PUTFIELD, type(ResolveTask.class), "fieldDeserializer", desc(FieldDeserializer.class)); - mw.visitInsn(RETURN); - mw.visitMaxs(3, 4); - mw.visitEnd(); - } else { - // public void setValue(Object object, Object value) - MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "setValue", "(" + getDesc(Object.class) - + getDesc(Object.class) + ")V", null, null); + mw.visitVarInsn(ALOAD, 1); + mw.visitLdcInsn(com.alibaba.fastjson.parser.DefaultJSONParser.NONE); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "setResolveStatus", "(I)V"); + + mw.visitLabel(_end_if); + + } + + private void _deserObject(Context context, MethodVisitor mw, FieldInfo fieldInfo, Class fieldClass, int i) { + _getFieldDeser(context, mw, fieldInfo); + + Label instanceOfElse_ = new Label(), instanceOfEnd_ = new Label(); + if ((fieldInfo.parserFeatures & Feature.SupportArrayToBean.mask) != 0) { + mw.visitInsn(DUP); + mw.visitTypeInsn(INSTANCEOF, type(JavaBeanDeserializer.class)); + mw.visitJumpInsn(IFEQ, instanceOfElse_); + + mw.visitTypeInsn(CHECKCAST, type(JavaBeanDeserializer.class)); // cast mw.visitVarInsn(ALOAD, 1); - mw.visitTypeInsn(CHECKCAST, getType(method.getDeclaringClass())); // cast - mw.visitVarInsn(ALOAD, 2); - mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast - mw.visitMethodInsn(INVOKEVIRTUAL, getType(method.getDeclaringClass()), method.getName(), - "(" + getDesc(fieldClass) + ")V"); + if (fieldInfo.fieldType instanceof Class) { + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldInfo.fieldClass))); + } else { + mw.visitVarInsn(ALOAD, 0); + mw.visitLdcInsn(i); + mw.visitMethodInsn(INVOKEVIRTUAL, type(JavaBeanDeserializer.class), "getFieldType", + "(I)Ljava/lang/reflect/Type;"); + } + mw.visitLdcInsn(fieldInfo.name); + mw.visitLdcInsn(fieldInfo.parserFeatures); + mw.visitMethodInsn(INVOKEVIRTUAL, type(JavaBeanDeserializer.class), "deserialze", + "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;Ljava/lang/Object;I)Ljava/lang/Object;"); + mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + + mw.visitJumpInsn(GOTO, instanceOfEnd_); + + mw.visitLabel(instanceOfElse_); + } - mw.visitInsn(RETURN); - mw.visitMaxs(3, 3); - mw.visitEnd(); + mw.visitVarInsn(ALOAD, 1); + if (fieldInfo.fieldType instanceof Class) { + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldInfo.fieldClass))); + } else { + mw.visitVarInsn(ALOAD, 0); + mw.visitLdcInsn(i); + mw.visitMethodInsn(INVOKEVIRTUAL, type(JavaBeanDeserializer.class), "getFieldType", + "(I)Ljava/lang/reflect/Type;"); } + mw.visitLdcInsn(fieldInfo.name); + mw.visitMethodInsn(INVOKEINTERFACE, type(ObjectDeserializer.class), "deserialze", + "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;Ljava/lang/Object;)Ljava/lang/Object;"); + mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast + mw.visitVarInsn(ASTORE, context.var(fieldInfo.name + "_asm")); + + mw.visitLabel(instanceOfEnd_); + } - byte[] code = cw.toByteArray(); + private void _getFieldDeser(Context context, MethodVisitor mw, FieldInfo fieldInfo) { + Label notNull_ = new Label(); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_deser__", desc(ObjectDeserializer.class)); + mw.visitJumpInsn(IFNONNULL, notNull_); - Class exampleClass = classLoader.defineClassPublic(className, code, 0, code.length); + mw.visitVarInsn(ALOAD, 0); - Constructor constructor = exampleClass.getConstructor(ParserConfig.class, Class.class, FieldInfo.class); - Object instance = constructor.newInstance(mapping, clazz, fieldInfo); + mw.visitVarInsn(ALOAD, 1); + mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getConfig", "()" + desc(ParserConfig.class)); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldInfo.fieldClass))); + mw.visitMethodInsn(INVOKEVIRTUAL, type(ParserConfig.class), "getDeserializer", + "(Ljava/lang/reflect/Type;)" + desc(ObjectDeserializer.class)); - return (FieldDeserializer) instance; + mw.visitFieldInsn(PUTFIELD, context.className, fieldInfo.name + "_asm_deser__", desc(ObjectDeserializer.class)); + + mw.visitLabel(notNull_); + + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_deser__", desc(ObjectDeserializer.class)); } static class Context { - private int variantIndex = 4; + static final int parser = 1; + static final int type = 2; + static final int fieldName = 3; - private Map variants = new HashMap(); + private int variantIndex = -1; + private final Map variants = new HashMap(); - private Class clazz; - private List fieldInfoList; - private String className; + private final Class clazz; + private final JavaBeanInfo beanInfo; + private final String className; + private FieldInfo[] fieldInfoList; - public Context(List fieldInfoList, String className, ParserConfig config, Class clazz, - int initVariantIndex){ + public Context(String className, ParserConfig config, JavaBeanInfo beanInfo, int initVariantIndex){ this.className = className; - this.fieldInfoList = fieldInfoList; - this.clazz = clazz; + this.clazz = beanInfo.clazz; this.variantIndex = initVariantIndex; + this.beanInfo = beanInfo; + fieldInfoList = beanInfo.fields; } - public String getClassName() { - return className; - } - - public List getFieldInfoList() { - return fieldInfoList; - } - - public Class getClazz() { - return clazz; - } + public Class getInstClass() { + Class instClass = beanInfo.builderClass; + if (instClass == null) { + instClass = clazz; + } - public int getVariantCount() { - return variantIndex; + return instClass; } public int var(String name, int increment) { @@ -641,59 +1788,48 @@ public int var(String name) { } private void _init(ClassWriter cw, Context context) { - for (int i = 0, size = context.getFieldInfoList().size(); i < size; ++i) { - FieldInfo fieldInfo = context.getFieldInfoList().get(i); + for (int i = 0, size = context.fieldInfoList.length; i < size; ++i) { + FieldInfo fieldInfo = context.fieldInfoList[i]; - // public FieldVisitor visitField(final int access, final String name, final String desc, final String - // signature, final Object value) { - FieldVisitor fw = cw.visitField(ACC_PUBLIC, fieldInfo.getName() + "_asm_prefix__", "[C"); + FieldWriter fw = new FieldWriter(cw, ACC_PUBLIC, fieldInfo.name + "_asm_prefix__", "[C"); fw.visitEnd(); } - for (int i = 0, size = context.getFieldInfoList().size(); i < size; ++i) { - FieldInfo fieldInfo = context.getFieldInfoList().get(i); - Class fieldClass = fieldInfo.getMethod().getParameterTypes()[0]; + for (int i = 0, size = context.fieldInfoList.length; i < size; ++i) { + FieldInfo fieldInfo = context.fieldInfoList[i]; + Class fieldClass = fieldInfo.fieldClass; if (fieldClass.isPrimitive()) { continue; } - if (fieldClass.isEnum()) { - - } else if (Collection.class.isAssignableFrom(fieldClass)) { - FieldVisitor fw = cw.visitField(ACC_PUBLIC, fieldInfo.getName() + "_asm_list_item_deser__", - getDesc(ObjectDeserializer.class)); + if (Collection.class.isAssignableFrom(fieldClass)) { + FieldWriter fw = new FieldWriter(cw, ACC_PUBLIC, fieldInfo.name + "_asm_list_item_deser__", + desc(ObjectDeserializer.class)); fw.visitEnd(); } else { - FieldVisitor fw = cw.visitField(ACC_PUBLIC, fieldInfo.getName() + "_asm_deser__", - getDesc(ObjectDeserializer.class)); + FieldWriter fw = new FieldWriter(cw, ACC_PUBLIC, fieldInfo.name + "_asm_deser__", + desc(ObjectDeserializer.class)); fw.visitEnd(); } } - MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "", "(" + getDesc(ParserConfig.class) - + getDesc(Class.class) + ")V", null, null); + MethodVisitor mw = new MethodWriter(cw, ACC_PUBLIC, "", + "(" + desc(ParserConfig.class) + desc(JavaBeanInfo.class) + ")V", null, null); mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, 1); mw.visitVarInsn(ALOAD, 2); - mw.visitMethodInsn(INVOKESPECIAL, getType(ASMJavaBeanDeserializer.class), "", - "(" + getDesc(ParserConfig.class) + getDesc(Class.class) + ")V"); - - mw.visitVarInsn(ALOAD, 0); - mw.visitFieldInsn(GETFIELD, getType(ASMJavaBeanDeserializer.class), "serializer", - getDesc(InnerJavaBeanDeserializer.class)); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JavaBeanDeserializer.class), "getFieldDeserializerMap", - "()" + getDesc(Map.class)); - mw.visitInsn(POP); + mw.visitMethodInsn(INVOKESPECIAL, type(JavaBeanDeserializer.class), "", + "(" + desc(ParserConfig.class) + desc(JavaBeanInfo.class) + ")V"); // init fieldNamePrefix - for (int i = 0, size = context.getFieldInfoList().size(); i < size; ++i) { - FieldInfo fieldInfo = context.getFieldInfoList().get(i); + for (int i = 0, size = context.fieldInfoList.length; i < size; ++i) { + FieldInfo fieldInfo = context.fieldInfoList[i]; mw.visitVarInsn(ALOAD, 0); - mw.visitLdcInsn("\"" + fieldInfo.getName() + "\":"); // public char[] toCharArray() - mw.visitMethodInsn(INVOKEVIRTUAL, getType(String.class), "toCharArray", "()" + getDesc(char[].class)); - mw.visitFieldInsn(PUTFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); + mw.visitLdcInsn("\"" + fieldInfo.name + "\":"); // public char[] toCharArray() + mw.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "toCharArray", "()[C"); + mw.visitFieldInsn(PUTFIELD, context.className, fieldInfo.name + "_asm_prefix__", "[C"); } @@ -703,35 +1839,22 @@ private void _init(ClassWriter cw, Context context) { } private void _createInstance(ClassWriter cw, Context context) { - MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "createInstance", "(" + getDesc(DefaultExtJSONParser.class) - + getDesc(Type.class) + ")Ljava/lang/Object;", - null, null); - mw.visitTypeInsn(NEW, getType(context.getClazz())); + Constructor defaultConstructor = context.beanInfo.defaultConstructor; + if (!Modifier.isPublic(defaultConstructor.getModifiers())) { + return; + } + + MethodVisitor mw = new MethodWriter(cw, ACC_PUBLIC, "createInstance", + "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;)Ljava/lang/Object;", + null, null); + + mw.visitTypeInsn(NEW, type(context.getInstClass())); mw.visitInsn(DUP); - mw.visitMethodInsn(INVOKESPECIAL, getType(context.getClazz()), "", "()V"); + mw.visitMethodInsn(INVOKESPECIAL, type(context.getInstClass()), "", "()V"); + mw.visitInsn(ARETURN); mw.visitMaxs(3, 3); mw.visitEnd(); } - private void _parseField(ClassWriter cw, Context context) { - // public boolean parseField(DefaultExtJSONParser parser, String key, Object object) { - - MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "parseField", "(" + getDesc(DefaultExtJSONParser.class) - + getDesc(String.class) + getDesc(Object.class) - + ")Z", null, null); - - mw.visitVarInsn(ALOAD, 0); - mw.visitVarInsn(ALOAD, 1); - mw.visitVarInsn(ALOAD, 2); - mw.visitVarInsn(ALOAD, 3); - mw.visitMethodInsn(INVOKESPECIAL, getType(ASMJavaBeanDeserializer.class), "parseField", - "(" + getDesc(DefaultExtJSONParser.class) + getDesc(String.class) + getDesc(Object.class) - + ")Z"); - mw.visitInsn(IRETURN); - mw.visitMaxs(5, context.getVariantCount() + 1); - mw.visitEnd(); - - } - } diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ASMJavaBeanDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ASMJavaBeanDeserializer.java deleted file mode 100644 index 1a2efeb96e..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ASMJavaBeanDeserializer.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.Feature; -import com.alibaba.fastjson.parser.JSONScanner; -import com.alibaba.fastjson.parser.ParserConfig; -import com.alibaba.fastjson.util.FieldInfo; - -public abstract class ASMJavaBeanDeserializer implements ObjectDeserializer { - - protected InnerJavaBeanDeserializer serializer; - - public ASMJavaBeanDeserializer(ParserConfig mapping, Class clazz){ - serializer = new InnerJavaBeanDeserializer(mapping, clazz); - - serializer.getFieldDeserializerMap(); - } - - public abstract Object createInstance(DefaultExtJSONParser parser, Type type); - - public InnerJavaBeanDeserializer getInnterSerializer() { - return serializer; - } - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type type) { - return (T) serializer.deserialze(parser, type); - } - - public int getFastMatchToken() { - return serializer.getFastMatchToken(); - } - - public FieldDeserializer createFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo) { - return mapping.createFieldDeserializer(mapping, clazz, fieldInfo); - } - - public boolean parseField(DefaultExtJSONParser parser, String key, Object object) { - JSONScanner lexer = (JSONScanner) parser.getLexer(); // xxx - - FieldDeserializer fieldDeserializer = serializer.getFieldDeserializerMap().get(key); - - if (fieldDeserializer == null) { - if (!parser.isEnabled(Feature.IgnoreNotMatch)) { - throw new JSONException("setter not found, class " + serializer.getClass() + ", property " + key); - } - - lexer.nextTokenWithColon(); - parser.parse(); // skip - - return false; - } - - lexer.nextTokenWithColon(fieldDeserializer.getFastMatchToken()); - fieldDeserializer.parseField(parser, object); - return true; - } - - public final class InnerJavaBeanDeserializer extends JavaBeanDeserializer { - - private InnerJavaBeanDeserializer(ParserConfig mapping, Class clazz){ - super(mapping, clazz); - } - - public boolean parseField(DefaultExtJSONParser parser, String key, Object object) { - return ASMJavaBeanDeserializer.this.parseField(parser, key, object); - } - - public FieldDeserializer createFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo) { - return ASMJavaBeanDeserializer.this.createFieldDeserializer(mapping, clazz, fieldInfo); - } - } - -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/AbstractDateDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/AbstractDateDeserializer.java new file mode 100755 index 0000000000..9ffb278310 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/AbstractDateDeserializer.java @@ -0,0 +1,142 @@ +package com.alibaba.fastjson.parser.deserializer; + +import java.lang.reflect.Type; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.*; +import com.alibaba.fastjson.util.TypeUtils; + +public abstract class AbstractDateDeserializer extends ContextObjectDeserializer implements ObjectDeserializer { + + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + return deserialze(parser, clazz, fieldName, null, 0); + } + + @Override + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName, String format, int features) { + JSONLexer lexer = parser.lexer; + + Object val; + if (lexer.token() == JSONToken.LITERAL_INT) { + val = lexer.longValue(); + lexer.nextToken(JSONToken.COMMA); + } else if (lexer.token() == JSONToken.LITERAL_STRING) { + String strVal = lexer.stringVal(); + + if (format != null) { + SimpleDateFormat simpleDateFormat = null; + try { + simpleDateFormat = new SimpleDateFormat(format,JSON.defaultLocale); + } catch (IllegalArgumentException ex) { + if (format.equals("yyyy-MM-ddTHH:mm:ss.SSS")) { + format = "yyyy-MM-dd'T'HH:mm:ss.SSS"; + simpleDateFormat = new SimpleDateFormat(format); + } else if (format.equals("yyyy-MM-ddTHH:mm:ss")) { + format = "yyyy-MM-dd'T'HH:mm:ss"; + simpleDateFormat = new SimpleDateFormat(format); + } + } + + try { + val = simpleDateFormat.parse(strVal); + } catch (ParseException ex) { + if (format.equals("yyyy-MM-dd'T'HH:mm:ss.SSS") // + && strVal.length() == 19) { + try { + val = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(strVal); + } catch (ParseException ex2) { + // skip + val = null; + } + } else { + // skip + val = null; + } + } + } else { + val = null; + } + + if (val == null) { + val = strVal; + lexer.nextToken(JSONToken.COMMA); + + if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) { + JSONScanner iso8601Lexer = new JSONScanner(strVal); + if (iso8601Lexer.scanISO8601DateIfMatch()) { + val = iso8601Lexer.getCalendar().getTime(); + } + iso8601Lexer.close(); + } + } + } else if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(); + val = null; + } else if (lexer.token() == JSONToken.LBRACE) { + lexer.nextToken(); + + String key; + if (lexer.token() == JSONToken.LITERAL_STRING) { + key = lexer.stringVal(); + + if (JSON.DEFAULT_TYPE_KEY.equals(key)) { + lexer.nextToken(); + parser.accept(JSONToken.COLON); + + String typeName = lexer.stringVal(); + Class type = parser.getConfig().checkAutoType(typeName, null, lexer.getFeatures()); + if (type != null) { + clazz = type; + } + + parser.accept(JSONToken.LITERAL_STRING); + parser.accept(JSONToken.COMMA); + } + + lexer.nextTokenWithColon(JSONToken.LITERAL_INT); + } else { + throw new JSONException("syntax error"); + } + + long timeMillis; + if (lexer.token() == JSONToken.LITERAL_INT) { + timeMillis = lexer.longValue(); + lexer.nextToken(); + } else { + throw new JSONException("syntax error : " + lexer.tokenName()); + } + + val = timeMillis; + + parser.accept(JSONToken.RBRACE); + } else if (parser.getResolveStatus() == DefaultJSONParser.TypeNameRedirect) { + parser.setResolveStatus(DefaultJSONParser.NONE); + parser.accept(JSONToken.COMMA); + + if (lexer.token() == JSONToken.LITERAL_STRING) { + if (!"val".equals(lexer.stringVal())) { + throw new JSONException("syntax error"); + } + lexer.nextToken(); + } else { + throw new JSONException("syntax error"); + } + + parser.accept(JSONToken.COLON); + + val = parser.parse(); + + parser.accept(JSONToken.RBRACE); + } else { + val = parser.parse(); + } + + return (T) cast(parser, clazz, fieldName, val); + } + + protected abstract T cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object value); +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayDeserializer.java deleted file mode 100644 index e3c86459a3..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayDeserializer.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Array; -import java.lang.reflect.Type; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.TypeUtils; - -public class ArrayDeserializer implements ObjectDeserializer { - - public final static ArrayDeserializer instance = new ArrayDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - if (parser.getLexer().token() == JSONToken.NULL) { - parser.getLexer().nextToken(JSONToken.COMMA); - return null; - } - - JSONArray array = new JSONArray(); - parser.parseArray(array); - - return toObjectArray(parser, (Class) clazz, array); - } - - @SuppressWarnings("unchecked") - private T toObjectArray(DefaultExtJSONParser parser, Class clazz, JSONArray array) { - int size = array.size(); - - Class componentType = clazz.getComponentType(); - Object objArray = Array.newInstance(componentType, size); - for (int i = 0; i < size; ++i) { - Object value = array.get(i); - - if (componentType.isArray()) { - Object element = toObjectArray(parser, componentType, (JSONArray) value); - Array.set(objArray, i, element); - } else { - Object element = TypeUtils.cast(value, componentType, parser.getConfig()); - Array.set(objArray, i, element); - } - } - return (T) objArray; // TODO - } - - public int getFastMatchToken() { - return JSONToken.LBRACKET; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListStringDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListStringDeserializer.java deleted file mode 100644 index e07c130dc1..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListStringDeserializer.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.Feature; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; - -public class ArrayListStringDeserializer implements ObjectDeserializer { - - public final static ArrayListStringDeserializer instance = new ArrayListStringDeserializer(); - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public T deserialze(DefaultExtJSONParser parser, Type type) { - ArrayList list = new ArrayList(); - - parseArray(parser, list); - - return (T) list; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static void parseArray(DefaultExtJSONParser parser, Collection array) { - JSONLexer lexer = parser.getLexer(); - - if (lexer.token() != JSONToken.LBRACKET) { - throw new JSONException("exepct '[', but " + lexer.token()); - } - - lexer.nextToken(JSONToken.LITERAL_STRING); - - for (;;) { - if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { - while (lexer.token() == JSONToken.COMMA) { - lexer.nextToken(); - continue; - } - } - - if (lexer.token() == JSONToken.RBRACKET) { - break; - } - - String value; - if (lexer.token() == JSONToken.LITERAL_STRING) { - value = lexer.stringVal(); - lexer.nextToken(JSONToken.COMMA); - } else { - Object obj = parser.parse(); - if (obj == null) { - value = null; - } else { - value = obj.toString(); - } - } - - array.add(value); - - if (lexer.token() == JSONToken.COMMA) { - lexer.nextToken(JSONToken.LITERAL_STRING); - continue; - } - } - - lexer.nextToken(JSONToken.COMMA); - } - - public int getFastMatchToken() { - return JSONToken.LBRACKET; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListStringFieldDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListStringFieldDeserializer.java deleted file mode 100644 index 583e920c9e..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListStringFieldDeserializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.util.ArrayList; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.parser.ParserConfig; -import com.alibaba.fastjson.util.FieldInfo; - -public class ArrayListStringFieldDeserializer extends FieldDeserializer { - - public ArrayListStringFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo){ - super(clazz, fieldInfo); - - } - - public int getFastMatchToken() { - return JSONToken.LBRACKET; - } - - @Override - public void parseField(DefaultExtJSONParser parser, Object object) { - ArrayList list = new ArrayList(); - - ArrayListStringDeserializer.parseArray(parser, list); - - setValue(object, list); - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListTypeDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListTypeDeserializer.java deleted file mode 100644 index 903e175814..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListTypeDeserializer.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.ArrayList; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class ArrayListTypeDeserializer implements ObjectDeserializer { - - private Type itemType; - - public ArrayListTypeDeserializer(Type type){ - this.itemType = type; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public T deserialze(DefaultExtJSONParser parser, Type type) { - ArrayList list = new ArrayList(); - - parser.parseArray(itemType, list); - - return (T) list; - } - - public int getFastMatchToken() { - return JSONToken.LBRACKET; - } - -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListTypeFieldDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListTypeFieldDeserializer.java old mode 100644 new mode 100755 index bc91445b3b..45ecb95846 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListTypeFieldDeserializer.java +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListTypeFieldDeserializer.java @@ -2,16 +2,20 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Collection; +import java.util.Map; -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.JSONLexer; import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParseContext; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.util.FieldInfo; +import com.alibaba.fastjson.util.ParameterizedTypeImpl; public class ArrayListTypeFieldDeserializer extends FieldDeserializer { @@ -22,8 +26,20 @@ public class ArrayListTypeFieldDeserializer extends FieldDeserializer { public ArrayListTypeFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo){ super(clazz, fieldInfo); - this.itemType = ((ParameterizedType) getFieldType()).getActualTypeArguments()[0]; - + Type fieldType = fieldInfo.fieldType; + if (fieldType instanceof ParameterizedType) { + Type argType = ((ParameterizedType) fieldInfo.fieldType).getActualTypeArguments()[0]; + if (argType instanceof WildcardType) { + WildcardType wildcardType = (WildcardType) argType; + Type[] upperBounds = wildcardType.getUpperBounds(); + if (upperBounds.length == 1) { + argType = upperBounds[0]; + } + } + this.itemType = argType; + } else { + this.itemType = Object.class; + } } public int getFastMatchToken() { @@ -32,55 +48,151 @@ public int getFastMatchToken() { @SuppressWarnings("rawtypes") @Override - public void parseField(DefaultExtJSONParser parser, Object object) { - if (parser.getLexer().token() == JSONToken.NULL) { + public void parseField(DefaultJSONParser parser, Object object, Type objectType, Map fieldValues) { + JSONLexer lexer = parser.lexer; + final int token = lexer.token(); + if (token == JSONToken.NULL + || (token == JSONToken.LITERAL_STRING && lexer.stringVal().length() == 0)) { setValue(object, null); return; } ArrayList list = new ArrayList(); - parseArray(parser, list); + ParseContext context = parser.getContext(); - setValue(object, list); + parser.setContext(context, object, fieldInfo.name); + parseArray(parser, objectType, list); + parser.setContext(context); + + if (object == null) { + fieldValues.put(fieldInfo.name, list); + } else { + setValue(object, list); + } } @SuppressWarnings({ "unchecked", "rawtypes" }) - public final void parseArray(DefaultExtJSONParser parser, Collection array) { - final JSONLexer lexer = parser.getLexer(); + public final void parseArray(DefaultJSONParser parser, Type objectType, Collection array) { + Type itemType = this.itemType; + ObjectDeserializer itemTypeDeser = this.deserializer; + + if (objectType instanceof ParameterizedType) { + if (itemType instanceof TypeVariable) { + TypeVariable typeVar = (TypeVariable) itemType; + ParameterizedType paramType = (ParameterizedType) objectType; + + Class objectClass = null; + if (paramType.getRawType() instanceof Class) { + objectClass = (Class) paramType.getRawType(); + } - if (lexer.token() != JSONToken.LBRACKET) { - throw new JSONException("exepct '[', but " + JSONToken.name(lexer.token())); - } + int paramIndex = -1; + if (objectClass != null) { + for (int i = 0, size = objectClass.getTypeParameters().length; i < size; ++i) { + TypeVariable item = objectClass.getTypeParameters()[i]; + if (item.getName().equals(typeVar.getName())) { + paramIndex = i; + break; + } + } + } - if (deserializer == null) { - deserializer = parser.getConfig().getDeserializer(itemType); - itemFastMatchToken = deserializer.getFastMatchToken(); + if (paramIndex != -1) { + itemType = paramType.getActualTypeArguments()[paramIndex]; + if (!itemType.equals(this.itemType)) { + itemTypeDeser = parser.getConfig().getDeserializer(itemType); + } + } + } else if (itemType instanceof ParameterizedType) { + ParameterizedType parameterizedItemType = (ParameterizedType) itemType; + Type[] itemActualTypeArgs = parameterizedItemType.getActualTypeArguments(); + if (itemActualTypeArgs.length == 1 && itemActualTypeArgs[0] instanceof TypeVariable) { + TypeVariable typeVar = (TypeVariable) itemActualTypeArgs[0]; + ParameterizedType paramType = (ParameterizedType) objectType; + + Class objectClass = null; + if (paramType.getRawType() instanceof Class) { + objectClass = (Class) paramType.getRawType(); + } + + int paramIndex = -1; + if (objectClass != null) { + for (int i = 0, size = objectClass.getTypeParameters().length; i < size; ++i) { + TypeVariable item = objectClass.getTypeParameters()[i]; + if (item.getName().equals(typeVar.getName())) { + paramIndex = i; + break; + } + } + + } + + if (paramIndex != -1) { + itemActualTypeArgs[0] = paramType.getActualTypeArguments()[paramIndex]; + itemType = new ParameterizedTypeImpl(itemActualTypeArgs, parameterizedItemType.getOwnerType(), parameterizedItemType.getRawType()); + } + } + } + } else if (itemType instanceof TypeVariable && objectType instanceof Class) { + Class objectClass = (Class) objectType; + TypeVariable typeVar = (TypeVariable) itemType; + objectClass.getTypeParameters(); + + for (int i = 0, size = objectClass.getTypeParameters().length; i < size; ++i) { + TypeVariable item = objectClass.getTypeParameters()[i]; + if (item.getName().equals(typeVar.getName())) { + Type[] bounds = item.getBounds(); + if (bounds.length == 1) { + itemType = bounds[0]; + } + break; + } + } } - lexer.nextToken(itemFastMatchToken); + final JSONLexer lexer = parser.lexer; - for (;;) { - if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { - while (lexer.token() == JSONToken.COMMA) { - lexer.nextToken(); + final int token = lexer.token(); + if (token == JSONToken.LBRACKET) { + if (itemTypeDeser == null) { + itemTypeDeser = deserializer = parser.getConfig().getDeserializer(itemType); + itemFastMatchToken = deserializer.getFastMatchToken(); + } + + lexer.nextToken(itemFastMatchToken); + + for (int i = 0;; ++i) { + if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { + while (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(); + continue; + } + } + + if (lexer.token() == JSONToken.RBRACKET) { + break; + } + + Object val = itemTypeDeser.deserialze(parser, itemType, i); + array.add(val); + + parser.checkListResolve(array); + + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(itemFastMatchToken); continue; } } - if (lexer.token() == JSONToken.RBRACKET) { - break; + lexer.nextToken(JSONToken.COMMA); + } else { + if (itemTypeDeser == null) { + itemTypeDeser = deserializer = parser.getConfig().getDeserializer(itemType); } - - Object val = deserializer.deserialze(parser, itemType); + Object val = itemTypeDeser.deserialze(parser, itemType, 0); array.add(val); - - if (lexer.token() == JSONToken.COMMA) { - lexer.nextToken(itemFastMatchToken); - continue; - } + parser.checkListResolve(array); } - - lexer.nextToken(JSONToken.COMMA); } } diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/AtomicIntegerArrayDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/AtomicIntegerArrayDeserializer.java deleted file mode 100644 index 3e3f3bcfaf..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/AtomicIntegerArrayDeserializer.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.concurrent.atomic.AtomicIntegerArray; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class AtomicIntegerArrayDeserializer implements ObjectDeserializer { - - public final static AtomicIntegerArrayDeserializer instance = new AtomicIntegerArrayDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - if (parser.getLexer().token() == JSONToken.NULL) { - parser.getLexer().nextToken(JSONToken.COMMA); - return null; - } - - JSONArray array = new JSONArray(); - parser.parseArray(array); - - AtomicIntegerArray atomicArray = new AtomicIntegerArray(array.size()); - for (int i = 0; i < array.size(); ++i) { - atomicArray.set(i, array.getInteger(i)); - } - - return (T) atomicArray; - } - - public int getFastMatchToken() { - return JSONToken.LBRACKET; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/AtomicLongArrayDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/AtomicLongArrayDeserializer.java deleted file mode 100644 index d1815466b5..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/AtomicLongArrayDeserializer.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.concurrent.atomic.AtomicLongArray; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class AtomicLongArrayDeserializer implements ObjectDeserializer { - - public final static AtomicLongArrayDeserializer instance = new AtomicLongArrayDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - if (parser.getLexer().token() == JSONToken.NULL) { - parser.getLexer().nextToken(JSONToken.COMMA); - return null; - } - - JSONArray array = new JSONArray(); - parser.parseArray(array); - - AtomicLongArray atomicArray = new AtomicLongArray(array.size()); - for (int i = 0; i < array.size(); ++i) { - atomicArray.set(i, array.getLong(i)); - } - - return (T) atomicArray; - } - - public int getFastMatchToken() { - return JSONToken.LBRACKET; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/AutowiredObjectDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/AutowiredObjectDeserializer.java old mode 100644 new mode 100755 diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/BigDecimalDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/BigDecimalDeserializer.java deleted file mode 100644 index 46e68b011d..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/BigDecimalDeserializer.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.math.BigDecimal; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.TypeUtils; - -public class BigDecimalDeserializer implements ObjectDeserializer { - - public final static BigDecimalDeserializer instance = new BigDecimalDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - return (T) deserialze(parser); - } - - @SuppressWarnings("unchecked") - public static T deserialze(DefaultExtJSONParser parser) { - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.LITERAL_INT) { - long val = lexer.longValue(); - lexer.nextToken(JSONToken.COMMA); - return (T) new BigDecimal(val); - } - - if (lexer.token() == JSONToken.LITERAL_FLOAT) { - BigDecimal val = lexer.decimalValue(); - lexer.nextToken(JSONToken.COMMA); - return (T) val; - } - - Object value = parser.parse(); - - if (value == null) { - return null; - } - - return (T) TypeUtils.castToBigDecimal(value); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_INT; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/BigIntegerDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/BigIntegerDeserializer.java deleted file mode 100644 index a388f79c29..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/BigIntegerDeserializer.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.math.BigInteger; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.TypeUtils; - -public class BigIntegerDeserializer implements ObjectDeserializer { - - public final static BigIntegerDeserializer instance = new BigIntegerDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - return (T) deserialze(parser); - } - - @SuppressWarnings("unchecked") - public static T deserialze(DefaultExtJSONParser parser) { - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.LITERAL_INT) { - String val = lexer.numberString(); - lexer.nextToken(JSONToken.COMMA); - return (T) new BigInteger(val); - } - - Object value = parser.parse(); - - if (value == null) { - return null; - } - - return (T) TypeUtils.castToBigInteger(value); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_INT; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/BooleanDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/BooleanDeserializer.java deleted file mode 100644 index 8343f796a8..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/BooleanDeserializer.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.TypeUtils; - -public class BooleanDeserializer implements ObjectDeserializer { - public final static BooleanDeserializer instance = new BooleanDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - return (T) deserialze(parser); - } - - @SuppressWarnings("unchecked") - public static T deserialze(DefaultExtJSONParser parser) { - final JSONLexer lexer = parser.getLexer(); - - if (lexer.token() == JSONToken.TRUE) { - lexer.nextToken(JSONToken.COMMA); - return (T) Boolean.TRUE; - } - - if (lexer.token() == JSONToken.FALSE) { - lexer.nextToken(JSONToken.COMMA); - return (T) Boolean.FALSE; - } - - if (lexer.token() == JSONToken.LITERAL_INT) { - int intValue = lexer.intValue(); - lexer.nextToken(JSONToken.COMMA); - - if (intValue == 1) { - return (T) Boolean.TRUE; - } else { - return (T) Boolean.FALSE; - } - } - - Object value = parser.parse(); - - if (value == null) { - return null; - } - - return (T) TypeUtils.castToBoolean(value); - } - - public int getFastMatchToken() { - return JSONToken.TRUE; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/BooleanFieldDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/BooleanFieldDeserializer.java deleted file mode 100644 index b323479327..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/BooleanFieldDeserializer.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.parser.ParserConfig; -import com.alibaba.fastjson.util.FieldInfo; -import com.alibaba.fastjson.util.TypeUtils; - -public class BooleanFieldDeserializer extends FieldDeserializer { - - public BooleanFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo){ - super(clazz, fieldInfo); - } - - @Override - public void parseField(DefaultExtJSONParser parser, Object object) { - Boolean value; - - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.TRUE) { - lexer.nextToken(JSONToken.COMMA); - setValue(object, true); - return; - } - - if (lexer.token() == JSONToken.LITERAL_INT) { - int val = lexer.intValue(); - lexer.nextToken(JSONToken.COMMA); - if (val == 1) { - setValue(object, true); - } else { - setValue(object, false); - } - return; - } - - if (lexer.token() == JSONToken.NULL) { - value = null; - lexer.nextToken(JSONToken.COMMA); - - if (getFieldClass() == boolean.class) { - // skip - return; - } - - setValue(object, null); - return; - } - - if (lexer.token() == JSONToken.FALSE) { - lexer.nextToken(JSONToken.COMMA); - setValue(object, false); - return; - } - - Object obj = parser.parse(); - - value = TypeUtils.castToBoolean(obj); - - if (value == null && getFieldClass() == boolean.class) { - // skip - return; - } - - setValue(object, value); - } - - public int getFastMatchToken() { - return JSONToken.TRUE; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ByteDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ByteDeserializer.java deleted file mode 100644 index 6ae28b0fdd..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ByteDeserializer.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.TypeUtils; - -public class ByteDeserializer implements ObjectDeserializer { - public final static ByteDeserializer instance = new ByteDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Object value = parser.parse(); - - if (value == null) { - return null; - } - - return (T) TypeUtils.castToByte(value); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_INT; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/CharacterDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/CharacterDeserializer.java deleted file mode 100644 index 5edc71c918..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/CharacterDeserializer.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.TypeUtils; - -public class CharacterDeserializer implements ObjectDeserializer { - public final static CharacterDeserializer instance = new CharacterDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Object value = parser.parse(); - - if (value == null) { - return null; - } - - return (T) TypeUtils.castToChar(value); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_STRING; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/CharsetDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/CharsetDeserializer.java deleted file mode 100644 index fda770293f..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/CharsetDeserializer.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.nio.charset.Charset; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class CharsetDeserializer implements ObjectDeserializer { - public final static CharsetDeserializer instance = new CharsetDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Object value = parser.parse(); - - if (value == null) { - return null; - } - - String charset = (String) value; - - return (T) Charset.forName(charset); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_STRING; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/CollectionDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/CollectionDeserializer.java deleted file mode 100644 index edd52ea698..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/CollectionDeserializer.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class CollectionDeserializer implements ObjectDeserializer { - - public final static CollectionDeserializer instance = new CollectionDeserializer(); - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public T deserialze(DefaultExtJSONParser parser, Type type) { - if (parser.getLexer().token() == JSONToken.NULL) { - parser.getLexer().nextToken(JSONToken.COMMA); - return null; - } - - Collection list = null; - if (type instanceof Class) { - Class clazz = (Class) type; - if (clazz.isAssignableFrom(HashSet.class)) { - list = new HashSet(); - } else if (clazz.isAssignableFrom(ArrayList.class)) { - list = new ArrayList(); - } else { - try { - list = (Collection) clazz.newInstance(); - } catch (Exception e) { - throw new JSONException("create instane error, class " + clazz.getName()); - } - } - } - - if (list == null) { - list = new ArrayList(); - } - - Type itemType; - if (type instanceof ParameterizedType) { - itemType = ((ParameterizedType) type).getActualTypeArguments()[0]; - } else { - itemType = Object.class; - } - parser.parseArray(itemType, list); - - return (T) list; - } - - public int getFastMatchToken() { - return JSONToken.LBRACKET; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ConcurrentHashMapDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ConcurrentHashMapDeserializer.java deleted file mode 100644 index f716d6e901..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ConcurrentHashMapDeserializer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class ConcurrentHashMapDeserializer implements ObjectDeserializer { - public final static ConcurrentHashMapDeserializer instance = new ConcurrentHashMapDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Map map = new ConcurrentHashMap(); - parser.parseObject(map); - return (T) map; - } - - public int getFastMatchToken() { - return JSONToken.LBRACE; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ContextObjectDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ContextObjectDeserializer.java new file mode 100644 index 0000000000..953442c2a4 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/ContextObjectDeserializer.java @@ -0,0 +1,13 @@ +package com.alibaba.fastjson.parser.deserializer; + +import java.lang.reflect.Type; + +import com.alibaba.fastjson.parser.DefaultJSONParser; + +public abstract class ContextObjectDeserializer implements ObjectDeserializer { + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + return deserialze(parser, type, fieldName, null, 0); + } + + public abstract T deserialze(DefaultJSONParser parser, Type type, Object fieldName, String format, int features); +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/DateDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/DateDeserializer.java deleted file mode 100644 index f313144630..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/DateDeserializer.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONScanner; -import com.alibaba.fastjson.parser.JSONToken; - -public class DateDeserializer implements ObjectDeserializer { - - public final static DateDeserializer instance = new DateDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Object val = parser.parse(); - - if (val == null) { - return null; - } - - if (val instanceof java.util.Date) { - return (T) val; - } else if (val instanceof Number) { - return (T) new java.util.Date(((Number) val).longValue()); - } else if (val instanceof String) { - String strVal = (String) val; - if (strVal.length() == 0) { - return null; - } - - JSONScanner dateLexer = new JSONScanner(strVal); - if (dateLexer.scanISO8601DateIfMatch()) { - return (T) dateLexer.getCalendar().getTime(); - } - - long longVal = Long.parseLong(strVal); - return (T) new java.util.Date(longVal); - } - - throw new JSONException("parse error"); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_INT; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/DefaultFieldDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/DefaultFieldDeserializer.java old mode 100644 new mode 100755 index 4af4afe682..1524d50c36 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/DefaultFieldDeserializer.java +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/DefaultFieldDeserializer.java @@ -1,33 +1,140 @@ package com.alibaba.fastjson.parser.deserializer; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.util.Map; +import java.util.zip.GZIPInputStream; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser.ResolveTask; import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParseContext; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.util.FieldInfo; public class DefaultFieldDeserializer extends FieldDeserializer { - private ObjectDeserializer fieldValueDeserilizer; + protected ObjectDeserializer fieldValueDeserilizer; + protected boolean customDeserilizer = false; - public DefaultFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo){ + public DefaultFieldDeserializer(ParserConfig config, Class clazz, FieldInfo fieldInfo){ super(clazz, fieldInfo); + JSONField annotation = fieldInfo.getAnnotation(); + if (annotation != null) { + Class deserializeUsing = annotation.deserializeUsing(); + customDeserilizer = deserializeUsing != null && deserializeUsing != Void.class; + } } - @Override - public void parseField(DefaultExtJSONParser parser, Object object) { + public ObjectDeserializer getFieldValueDeserilizer(ParserConfig config) { if (fieldValueDeserilizer == null) { - fieldValueDeserilizer = parser.getConfig().getDeserializer(fieldInfo); + JSONField annotation = fieldInfo.getAnnotation(); + if (annotation != null && annotation.deserializeUsing() != Void.class) { + Class deserializeUsing = annotation.deserializeUsing(); + try { + fieldValueDeserilizer = (ObjectDeserializer) deserializeUsing.newInstance(); + } catch (Exception ex) { + throw new JSONException("create deserializeUsing ObjectDeserializer error", ex); + } + } else { + fieldValueDeserilizer = config.getDeserializer(fieldInfo.fieldClass, fieldInfo.fieldType); + } + } + + return fieldValueDeserilizer; + } + + @Override + public void parseField(DefaultJSONParser parser, Object object, Type objectType, Map fieldValues) { + if (this.fieldValueDeserilizer == null) { + getFieldValueDeserilizer(parser.getConfig()); + } + + ObjectDeserializer fieldValueDeserilizer = this.fieldValueDeserilizer; + Type fieldType = fieldInfo.fieldType; + if (objectType instanceof ParameterizedType) { + ParseContext objContext = parser.getContext(); + if (objContext != null) { + objContext.type = objectType; + } + if (fieldType != objectType) { + fieldType = FieldInfo.getFieldType(this.clazz, objectType, fieldType); + fieldValueDeserilizer = parser.getConfig().getDeserializer(fieldType); + } } - Object value = fieldValueDeserilizer.deserialze(parser, getFieldType()); - setValue(object, value); + // ContextObjectDeserializer + Object value; + if (fieldValueDeserilizer instanceof JavaBeanDeserializer && fieldInfo.parserFeatures != 0) { + JavaBeanDeserializer javaBeanDeser = (JavaBeanDeserializer) fieldValueDeserilizer; + value = javaBeanDeser.deserialze(parser, fieldType, fieldInfo.name, fieldInfo.parserFeatures); + } else { + if (this.fieldInfo.format != null && fieldValueDeserilizer instanceof ContextObjectDeserializer) { + value = ((ContextObjectDeserializer) fieldValueDeserilizer) // + .deserialze(parser, + fieldType, + fieldInfo.name, + fieldInfo.format, + fieldInfo.parserFeatures); + } else { + value = fieldValueDeserilizer.deserialze(parser, fieldType, fieldInfo.name); + } + } + + if (value instanceof byte[] + && ("gzip".equals(fieldInfo.format) || "gzip,base64".equals(fieldInfo.format))) { + byte[] bytes = (byte[]) value; + GZIPInputStream gzipIn = null; + try { + gzipIn = new GZIPInputStream(new ByteArrayInputStream(bytes)); + + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + for (;;) { + byte[] buf = new byte[1024]; + int len = gzipIn.read(buf); + if (len == -1) { + break; + } + if (len > 0) { + byteOut.write(buf, 0, len); + } + } + value = byteOut.toByteArray(); + + } catch (IOException ex) { + throw new JSONException("unzip bytes error.", ex); + } + } + + if (parser.getResolveStatus() == DefaultJSONParser.NeedToResolve) { + ResolveTask task = parser.getLastResolveTask(); + task.fieldDeserializer = this; + task.ownerContext = parser.getContext(); + parser.setResolveStatus(DefaultJSONParser.NONE); + } else { + if (object == null) { + fieldValues.put(fieldInfo.name, value); + } else { + setValue(object, value); + } + } } public int getFastMatchToken() { if (fieldValueDeserilizer != null) { - return fieldValueDeserilizer.getFastMatchToken(); + return fieldValueDeserilizer.getFastMatchToken(); } - + return JSONToken.LITERAL_INT; } + + public void parseFieldUnwrapped(DefaultJSONParser parser, Object object, Type objectType, Map fieldValues) { + throw new JSONException("TODO"); + } } diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/DefaultObjectDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/DefaultObjectDeserializer.java deleted file mode 100644 index 19af17fdf8..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/DefaultObjectDeserializer.java +++ /dev/null @@ -1,293 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.Feature; -import com.alibaba.fastjson.parser.JSONScanner; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.ASMClassLoader; - -public class DefaultObjectDeserializer implements ObjectDeserializer { - - public DefaultObjectDeserializer(){ - } - - public void parseMap(DefaultExtJSONParser parser, Map map, Type valueType) { - JSONScanner lexer = (JSONScanner) parser.getLexer(); - - if (lexer.token() != JSONToken.LBRACE) { - throw new JSONException("syntax error, expect {, actual " + lexer.token()); - } - - for (;;) { - lexer.skipWhitespace(); - char ch = lexer.getCurrent(); - if (parser.isEnabled(Feature.AllowArbitraryCommas)) { - while (ch == ',') { - lexer.incrementBufferPosition(); - lexer.skipWhitespace(); - ch = lexer.getCurrent(); - } - } - - String key; - if (ch == '"') { - key = lexer.scanSymbol(parser.getSymbolTable(), '"'); - lexer.skipWhitespace(); - ch = lexer.getCurrent(); - if (ch != ':') { - throw new JSONException("expect ':' at " + lexer.pos()); - } - } else if (ch == '}') { - lexer.incrementBufferPosition(); - lexer.resetStringPosition(); - return; - } else if (ch == '\'') { - if (!parser.isEnabled(Feature.AllowSingleQuotes)) { - throw new JSONException("syntax error"); - } - - key = lexer.scanSymbol(parser.getSymbolTable(), '\''); - lexer.skipWhitespace(); - ch = lexer.getCurrent(); - if (ch != ':') { - throw new JSONException("expect ':' at " + lexer.pos()); - } - } else { - if (!parser.isEnabled(Feature.AllowUnQuotedFieldNames)) { - throw new JSONException("syntax error"); - } - - key = lexer.scanSymbolUnQuoted(parser.getSymbolTable()); - lexer.skipWhitespace(); - ch = lexer.getCurrent(); - if (ch != ':') { - throw new JSONException("expect ':' at " + lexer.pos() + ", actual " + ch); - } - } - - lexer.incrementBufferPosition(); - lexer.skipWhitespace(); - ch = lexer.getCurrent(); - - lexer.resetStringPosition(); - - Object value; - lexer.nextToken(); - - if (lexer.token() == JSONToken.NULL) { - value = null; - lexer.nextToken(); - } else { - value = parser.parseObject(valueType); - } - - map.put(key, value); - - if (lexer.token() == JSONToken.RBRACE) { - lexer.nextToken(); - return; - } - } - } - - public void parseObject(DefaultExtJSONParser parser, Object object) { - Class clazz = object.getClass(); - Map setters = parser.getConfig().getFieldDeserializers(clazz); - - JSONScanner lexer = (JSONScanner) parser.getLexer(); // xxx - - if (lexer.token() != JSONToken.LBRACE) { - throw new JSONException("syntax error, expect {, actual " + lexer.token()); - } - - final Object[] args = new Object[1]; - - for (;;) { - // lexer.scanSymbol - String key = lexer.scanSymbol(parser.getSymbolTable()); - - if (key == null) { - if (lexer.token() == JSONToken.RBRACE) { - lexer.nextToken(JSONToken.COMMA); - break; - } - if (lexer.token() == JSONToken.COMMA) { - if (parser.isEnabled(Feature.AllowArbitraryCommas)) { - continue; - } - } - } - - FieldDeserializer fieldDeser = setters.get(key); - if (fieldDeser == null) { - if (!parser.isEnabled(Feature.IgnoreNotMatch)) { - throw new JSONException("setter not found, class " + clazz.getName() + ", property " + key); - } - - lexer.nextTokenWithColon(); - parser.parse(); // skip - - if (lexer.token() == JSONToken.RBRACE) { - lexer.nextToken(); - return; - } - - continue; - } else { - Method method = fieldDeser.getMethod(); - Class fieldClass = method.getParameterTypes()[0]; - Type fieldType = method.getGenericParameterTypes()[0]; - if (fieldClass == int.class) { - lexer.nextTokenWithColon(JSONToken.LITERAL_INT); - args[0] = IntegerDeserializer.deserialze(parser); - } else if (fieldClass == String.class) { - lexer.nextTokenWithColon(JSONToken.LITERAL_STRING); - args[0] = StringDeserializer.deserialze(parser); - } else if (fieldClass == long.class) { - lexer.nextTokenWithColon(JSONToken.LITERAL_INT); - args[0] = LongDeserializer.deserialze(parser); - } else if (fieldClass == List.class) { - lexer.nextTokenWithColon(JSONToken.LBRACE); - args[0] = CollectionDeserializer.instance.deserialze(parser, fieldType); - } else { - ObjectDeserializer fieldValueDeserializer = parser.getConfig().getDeserializer(fieldClass, fieldType); - - lexer.nextTokenWithColon(fieldValueDeserializer.getFastMatchToken()); - args[0] = fieldValueDeserializer.deserialze(parser, fieldType); - } - - try { - method.invoke(object, args); - } catch (Exception e) { - throw new JSONException("set proprety error, " + method.getName(), e); - } - } - - if (lexer.token() == JSONToken.COMMA) { - continue; - } - - if (lexer.token() == JSONToken.RBRACE) { - lexer.nextToken(JSONToken.COMMA); - return; - } - } - } - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type type) { - if (type instanceof Class) { - return deserialze(parser, (Class) type); - } - - if (type instanceof ParameterizedType) { - return (T) deserialze(parser, (ParameterizedType) type); - } - - if (type instanceof TypeVariable) { - return (T) parser.parse(); - } - - if (type instanceof WildcardType) { - return (T) parser.parse(); - } - - throw new JSONException("not support type : " + type); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public T deserialze(DefaultExtJSONParser parser, ParameterizedType type) { - try { - Type rawType = type.getRawType(); - if (rawType instanceof Class) { - Class rawClass = (Class) rawType; - - if (Map.class.isAssignableFrom(rawClass)) { - Map map; - - if (Modifier.isAbstract(rawClass.getModifiers())) { - if (rawClass == Map.class) { - map = new HashMap(); - } else if (rawClass == SortedMap.class) { - map = new TreeMap(); - } else if (rawClass == ConcurrentMap.class) { - map = new ConcurrentHashMap(); - } else { - throw new JSONException("can not create instance : " + rawClass); - } - } else { - if (rawClass == HashMap.class) { - map = new HashMap(); - } else { - map = (Map) rawClass.newInstance(); - } - } - - Type valueType = type.getActualTypeArguments()[1]; - - parseMap(parser, map, valueType); - - return (T) map; - } - - } - - throw new JSONException("not support type : " + type); - } catch (JSONException e) { - throw e; - } catch (Throwable e) { - throw new JSONException(e.getMessage(), e); - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public T deserialze(DefaultExtJSONParser parser, Class clazz) { - Object value = null; - if (clazz.isAssignableFrom(HashMap.class)) { - value = new HashMap(); - } else if (clazz.isAssignableFrom(TreeMap.class)) { - value = new TreeMap(); - } else if (clazz.isAssignableFrom(ConcurrentHashMap.class)) { - value = new ConcurrentHashMap(); - } - - if (clazz == Class.class) { - Object classValue = parser.parse(); - if (classValue == null) { - return null; - } - - if (classValue instanceof String) { - return (T) ASMClassLoader.forName((String) classValue); - } - } - - try { - parseObject(parser, value); - return (T) value; - } catch (JSONException e) { - throw e; - } catch (Throwable e) { - throw new JSONException(e.getMessage(), e); - } - } - - public int getFastMatchToken() { - return JSONToken.LBRACE; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/DoubleDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/DoubleDeserializer.java deleted file mode 100644 index 6141755561..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/DoubleDeserializer.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.TypeUtils; - -public class DoubleDeserializer implements ObjectDeserializer { - - public final static DoubleDeserializer instance = new DoubleDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - return (T) deserialze(parser); - } - - @SuppressWarnings("unchecked") - public static T deserialze(DefaultExtJSONParser parser) { - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.LITERAL_INT) { - String val = lexer.numberString(); - lexer.nextToken(JSONToken.COMMA); - return (T) Double.valueOf(Double.parseDouble(val)); - } - - if (lexer.token() == JSONToken.LITERAL_FLOAT) { - String val = lexer.numberString(); - lexer.nextToken(JSONToken.COMMA); - return (T) Double.valueOf(Double.parseDouble(val)); - } - - Object value = parser.parse(); - - if (value == null) { - return null; - } - - return (T) TypeUtils.castToDouble(value); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_INT; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/EnumDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/EnumDeserializer.java old mode 100644 new mode 100755 index cf2dffd20c..19bf69e794 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/EnumDeserializer.java +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/EnumDeserializer.java @@ -1,65 +1,146 @@ package com.alibaba.fastjson.parser.deserializer; -import java.lang.reflect.Method; +import java.lang.reflect.Field; import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; +import java.util.*; import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONLexer; import com.alibaba.fastjson.parser.JSONToken; @SuppressWarnings("rawtypes") public class EnumDeserializer implements ObjectDeserializer { - private final Class enumClass; - - private final Map ordinalMap = new HashMap(); - private final Map nameMap = new HashMap(); + protected final Class enumClass; + protected final Enum[] enums; + protected final Enum[] ordinalEnums; + protected long[] enumNameHashCodes; public EnumDeserializer(Class enumClass){ this.enumClass = enumClass; - try { - Method valueMethod = enumClass.getMethod("values"); - Object[] values = (Object[]) valueMethod.invoke(null); - for (Object value : values) { - Enum e = (Enum) value; - ordinalMap.put(e.ordinal(), e); - nameMap.put(e.name(), e); + ordinalEnums = (Enum[]) enumClass.getEnumConstants(); + + Map enumMap = new HashMap(); + for (int i = 0; i < ordinalEnums.length; ++i) { + Enum e = ordinalEnums[i]; + String name = e.name(); + + JSONField jsonField = null; + try { + Field field = enumClass.getField(name); + jsonField = field.getAnnotation(JSONField.class); + if (jsonField != null) { + String jsonFieldName = jsonField.name(); + if (jsonFieldName != null && jsonFieldName.length() > 0) { + name = jsonFieldName; + } + } + } catch (Exception ex) { + // skip + } + + long hash = 0xcbf29ce484222325L; + long hash_lower = 0xcbf29ce484222325L; + for (int j = 0; j < name.length(); ++j) { + char ch = name.charAt(j); + + hash ^= ch; + hash_lower ^= ((ch >= 'A' && ch <= 'Z') ? (ch + 32) : ch); + + hash *= 0x100000001b3L; + hash_lower *= 0x100000001b3L; + } + + enumMap.put(hash, e); + if (hash != hash_lower) { + enumMap.put(hash_lower, e); + } + + if (jsonField != null) { + for (String alterName : jsonField.alternateNames()) { + long alterNameHash = 0xcbf29ce484222325L; + for (int j = 0; j < alterName.length(); ++j) { + char ch = alterName.charAt(j); + alterNameHash ^= ch; + alterNameHash *= 0x100000001b3L; + } + if (alterNameHash != hash && alterNameHash != hash_lower) { + enumMap.put(alterNameHash, e); + } + } } - } catch (Exception ex) { - throw new JSONException("init enum values error, " + enumClass.getName()); } + + this.enumNameHashCodes = new long[enumMap.size()]; + { + int i = 0; + for (Long h : enumMap.keySet()) { + enumNameHashCodes[i++] = h; + } + Arrays.sort(this.enumNameHashCodes); + } + + this.enums = new Enum[enumNameHashCodes.length]; + for (int i = 0; i < this.enumNameHashCodes.length; ++i) { + long hash = enumNameHashCodes[i]; + Enum e = enumMap.get(hash); + this.enums[i] = e; + } + } + + public Enum getEnumByHashCode(long hashCode) { + if (enums == null) { + return null; + } + + int enumIndex = Arrays.binarySearch(this.enumNameHashCodes, hashCode); + + if (enumIndex < 0) { + return null; + } + + return enums[enumIndex]; + } + + public Enum valueOf(int ordinal) { + return ordinalEnums[ordinal]; } @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type type) { + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { try { Object value; - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.LITERAL_INT) { - value = lexer.intValue(); + final JSONLexer lexer = parser.lexer; + final int token = lexer.token(); + if (token == JSONToken.LITERAL_INT) { + int intValue = lexer.intValue(); lexer.nextToken(JSONToken.COMMA); - T e = (T) ordinalMap.get(value); - if (e == null) { - throw new JSONException("parse enum " + enumClass.getName() + " error, value : " + value); + if (intValue < 0 || intValue > ordinalEnums.length) { + throw new JSONException("parse enum " + enumClass.getName() + " error, value : " + intValue); } - return e; - } else if (lexer.token() == JSONToken.LITERAL_STRING) { - String strVal = lexer.stringVal(); + + return (T) ordinalEnums[intValue]; + } else if (token == JSONToken.LITERAL_STRING) { + String name = lexer.stringVal(); lexer.nextToken(JSONToken.COMMA); - if (strVal.length() == 0) { + if (name.length() == 0) { return (T) null; } - value = nameMap.get(strVal); + long hash = 0xcbf29ce484222325L; + for (int j = 0; j < name.length(); ++j) { + char ch = name.charAt(j); + hash ^= ch; + hash *= 0x100000001b3L; + } - return (T) Enum.valueOf((Class) enumClass, strVal); - } else if (lexer.token() == JSONToken.NULL) { + return (T) getEnumByHashCode(hash); + } else if (token == JSONToken.NULL) { value = null; lexer.nextToken(JSONToken.COMMA); @@ -71,7 +152,7 @@ public T deserialze(DefaultExtJSONParser parser, Type type) { throw new JSONException("parse enum " + enumClass.getName() + " error, value : " + value); } catch (JSONException e) { throw e; - } catch (Throwable e) { + } catch (Exception e) { throw new JSONException(e.getMessage(), e); } } diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraProcessable.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraProcessable.java new file mode 100644 index 0000000000..229684a3aa --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraProcessable.java @@ -0,0 +1,10 @@ +package com.alibaba.fastjson.parser.deserializer; + +/** + * + * @author wenshao[szujobs@hotmail.com] + * @since 1.2.9 + */ +public interface ExtraProcessable { + void processExtra(String key, Object value); +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraProcessor.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraProcessor.java new file mode 100644 index 0000000000..9dcb7645f7 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraProcessor.java @@ -0,0 +1,11 @@ +package com.alibaba.fastjson.parser.deserializer; + +/** + * + * @author wenshao[szujobs@hotmail.com] + * @since 1.1.34 + */ +public interface ExtraProcessor extends ParseProcess { + + void processExtra(Object object, String key, Object value); +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraTypeProvider.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraTypeProvider.java new file mode 100644 index 0000000000..4b03794181 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraTypeProvider.java @@ -0,0 +1,12 @@ +package com.alibaba.fastjson.parser.deserializer; + +import java.lang.reflect.Type; + +/** + * @author wenshao[szujobs@hotmail.com] + * @since 1.1.34 + */ +public interface ExtraTypeProvider extends ParseProcess { + + Type getExtraType(Object object, String key); +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/FieldDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/FieldDeserializer.java old mode 100644 new mode 100755 index c1451c15a9..c9956fd354 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/FieldDeserializer.java +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/FieldDeserializer.java @@ -1,61 +1,169 @@ package com.alibaba.fastjson.parser.deserializer; +import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.serializer.BeanContext; import com.alibaba.fastjson.util.FieldInfo; public abstract class FieldDeserializer { - protected final FieldInfo fieldInfo; - - protected final Class clazz; - - public FieldDeserializer(Class clazz, FieldInfo fieldInfo) { - this.clazz = clazz; - this.fieldInfo = fieldInfo; - } - - public Method getMethod() { - return fieldInfo.getMethod(); - } - - public Class getFieldClass() { - return fieldInfo.getFieldClass(); - } - - public Type getFieldType() { - return fieldInfo.getFieldType(); - } - - public abstract void parseField(DefaultExtJSONParser parser, Object object); - - public abstract int getFastMatchToken(); - - public void setValue(Object object, boolean value) { - setValue(object, Boolean.valueOf(value)); - } - - public void setValue(Object object, int value) { - setValue(object, Integer.valueOf(value)); - } - - public void setValue(Object object, long value) { - setValue(object, Long.valueOf(value)); - } - - public void setValue(Object object, String value) { - setValue(object, (Object) value); - } - - public void setValue(Object object, Object value) { - try { - fieldInfo.getMethod().invoke(object, value); - } catch (Exception e) { - throw new JSONException("set property error, " - + fieldInfo.getMethod().toString(), e); - } - } + public final FieldInfo fieldInfo; + + protected final Class clazz; + + protected BeanContext beanContext; + + public FieldDeserializer(Class clazz, FieldInfo fieldInfo){ + this.clazz = clazz; + this.fieldInfo = fieldInfo; + } + + public abstract void parseField(DefaultJSONParser parser, Object object, Type objectType, + Map fieldValues); + + public int getFastMatchToken() { + return 0; + } + + public void setValue(Object object, boolean value) { + setValue(object, Boolean.valueOf(value)); + } + + public void setValue(Object object, int value) { + setValue(object, Integer.valueOf(value)); + } + + public void setValue(Object object, long value) { + setValue(object, Long.valueOf(value)); + } + + public void setValue(Object object, String value) { + setValue(object, (Object) value); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void setValue(Object object, Object value) { + if (value == null // + && fieldInfo.fieldClass.isPrimitive()) { + return; + } else if (fieldInfo.fieldClass == String.class + && fieldInfo.format != null + && fieldInfo.format.equals("trim")){ + value = ((String) value).trim(); + } + + try { + Method method = fieldInfo.method; + if (method != null) { + if (fieldInfo.getOnly) { + if (fieldInfo.fieldClass == AtomicInteger.class) { + AtomicInteger atomic = (AtomicInteger) method.invoke(object); + if (atomic != null) { + atomic.set(((AtomicInteger) value).get()); + } + } else if (fieldInfo.fieldClass == AtomicLong.class) { + AtomicLong atomic = (AtomicLong) method.invoke(object); + if (atomic != null) { + atomic.set(((AtomicLong) value).get()); + } + } else if (fieldInfo.fieldClass == AtomicBoolean.class) { + AtomicBoolean atomic = (AtomicBoolean) method.invoke(object); + if (atomic != null) { + atomic.set(((AtomicBoolean) value).get()); + } + } else if (Map.class.isAssignableFrom(method.getReturnType())) { + Map map = (Map) method.invoke(object); + if (map != null) { + if (map == Collections.emptyMap() + || map.getClass().getName().startsWith("java.util.Collections$Unmodifiable")) { + // skip + return; + } + + map.putAll((Map) value); + } + } else { + Collection collection = (Collection) method.invoke(object); + if (collection != null && value != null) { + if (collection == Collections.emptySet() + || collection == Collections.emptyList() + || collection.getClass().getName().startsWith("java.util.Collections$Unmodifiable")) { + // skip + return; + } + + collection.clear(); + collection.addAll((Collection) value); + } + } + } else { + method.invoke(object, value); + } + } else { + final Field field = fieldInfo.field; + + if (fieldInfo.getOnly) { + if (fieldInfo.fieldClass == AtomicInteger.class) { + AtomicInteger atomic = (AtomicInteger) field.get(object); + if (atomic != null) { + atomic.set(((AtomicInteger) value).get()); + } + } else if (fieldInfo.fieldClass == AtomicLong.class) { + AtomicLong atomic = (AtomicLong) field.get(object); + if (atomic != null) { + atomic.set(((AtomicLong) value).get()); + } + } else if (fieldInfo.fieldClass == AtomicBoolean.class) { + AtomicBoolean atomic = (AtomicBoolean) field.get(object); + if (atomic != null) { + atomic.set(((AtomicBoolean) value).get()); + } + } else if (Map.class.isAssignableFrom(fieldInfo.fieldClass)) { + Map map = (Map) field.get(object); + if (map != null) { + if (map == Collections.emptyMap() + || map.getClass().getName().startsWith("java.util.Collections$Unmodifiable")) { + // skip + return; + } + map.putAll((Map) value); + } + } else { + Collection collection = (Collection) field.get(object); + if (collection != null && value != null) { + if (collection == Collections.emptySet() + || collection == Collections.emptyList() + || collection.getClass().getName().startsWith("java.util.Collections$Unmodifiable")) { + // skip + return; + } + + collection.clear(); + collection.addAll((Collection) value); + } + } + } else { + if (field != null) { + field.set(object, value); + } + } + } + } catch (Exception e) { + throw new JSONException("set property error, " + fieldInfo.name, e); + } + } + + public void setWrappedValue(String key, Object value) { + throw new JSONException("TODO"); + } } diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/FieldTypeResolver.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/FieldTypeResolver.java new file mode 100644 index 0000000000..0342442206 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/FieldTypeResolver.java @@ -0,0 +1,7 @@ +package com.alibaba.fastjson.parser.deserializer; + +import java.lang.reflect.Type; + +public interface FieldTypeResolver extends ParseProcess { + Type resolve(Object object, String fieldName); +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/FileDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/FileDeserializer.java deleted file mode 100644 index 47d708213e..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/FileDeserializer.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.io.File; -import java.lang.reflect.Type; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class FileDeserializer implements ObjectDeserializer { - public final static FileDeserializer instance = new FileDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Object value = parser.parse(); - - if (value == null) { - return null; - } - - String path = (String) value; - - return (T) new File(path); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_STRING; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/FloatDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/FloatDeserializer.java deleted file mode 100644 index 8c06de002e..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/FloatDeserializer.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.TypeUtils; - -public class FloatDeserializer implements ObjectDeserializer { - - public final static FloatDeserializer instance = new FloatDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - return (T) deserialze(parser); - } - - @SuppressWarnings("unchecked") - public static T deserialze(DefaultExtJSONParser parser) { - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.LITERAL_INT) { - String val = lexer.numberString(); - lexer.nextToken(JSONToken.COMMA); - return (T) Float.valueOf(Float.parseFloat(val)); - } - - if (lexer.token() == JSONToken.LITERAL_FLOAT) { - float val = lexer.floatValue(); - lexer.nextToken(JSONToken.COMMA); - return (T) Float.valueOf(val); - } - - Object value = parser.parse(); - - if (value == null) { - return null; - } - - return (T) TypeUtils.castToFloat(value); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_INT; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/HashMapDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/HashMapDeserializer.java deleted file mode 100644 index 726c92a867..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/HashMapDeserializer.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; - -public class HashMapDeserializer implements ObjectDeserializer { - - public final static HashMapDeserializer instance = new HashMapDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type type) { - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.NULL) { - lexer.nextToken(JSONToken.COMMA); - return null; - } - - Map map = new HashMap(); - parser.parseObject(map); - return (T) map; - } - - public int getFastMatchToken() { - return JSONToken.LBRACE; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/InetAddressDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/InetAddressDeserializer.java deleted file mode 100644 index f19ec8701f..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/InetAddressDeserializer.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.net.InetAddress; -import java.net.UnknownHostException; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class InetAddressDeserializer implements ObjectDeserializer { - - public final static InetAddressDeserializer instance = new InetAddressDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - - String host = (String) parser.parse(); - - if (host == null) { - return null; - } - - if (host.length() == 0) { - return null; - } - - try { - return (T) InetAddress.getByName(host); - } catch (UnknownHostException e) { - throw new JSONException("deserialize error", e); - } - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_STRING; - } - -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/InetSocketAddressDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/InetSocketAddressDeserializer.java deleted file mode 100644 index d470aeacc6..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/InetSocketAddressDeserializer.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.net.InetAddress; -import java.net.InetSocketAddress; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; - -public class InetSocketAddressDeserializer implements ObjectDeserializer { - - public final static InetSocketAddressDeserializer instance = new InetSocketAddressDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - JSONLexer lexer = parser.getLexer(); - - if (lexer.token() == JSONToken.NULL) { - lexer.nextToken(); - return null; - } - - parser.accept(JSONToken.LBRACE); - - InetAddress address = null; - int port = 0; - for (;;) { - String key = lexer.symbol(parser.getSymbolTable()); - lexer.nextToken(); - - if (key.equals("address")) { - parser.accept(JSONToken.COLON); - address = parser.parseObject(InetAddress.class); - } else if (key.equals("port")) { - parser.accept(JSONToken.COLON); - if (lexer.token() != JSONToken.LITERAL_INT) { - throw new JSONException("port is not int"); - } - port = lexer.intValue(); - lexer.nextToken(); - } else { - parser.accept(JSONToken.COLON); - parser.parse(); - } - - if (lexer.token() == JSONToken.COMMA) { - lexer.nextToken(); - continue; - } - - break; - } - - parser.accept(JSONToken.RBRACE); - - return (T) new InetSocketAddress(address, port); - } - - public int getFastMatchToken() { - return JSONToken.LBRACE; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/IntegerDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/IntegerDeserializer.java deleted file mode 100644 index 5559737cc3..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/IntegerDeserializer.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.math.BigDecimal; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.TypeUtils; - -public class IntegerDeserializer implements ObjectDeserializer { - public final static IntegerDeserializer instance = new IntegerDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - return (T) deserialze(parser); - } - - @SuppressWarnings("unchecked") - public static T deserialze(DefaultExtJSONParser parser) { - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.LITERAL_INT) { - int val = lexer.intValue(); - lexer.nextToken(JSONToken.COMMA); - return (T) Integer.valueOf(val); - } - - if (lexer.token() == JSONToken.LITERAL_FLOAT) { - BigDecimal decimalValue = lexer.decimalValue(); - lexer.nextToken(JSONToken.COMMA); - return (T) Integer.valueOf(decimalValue.intValue()); - } - - Object value = parser.parse(); - - if (value == null) { - return null; - } - - return (T) TypeUtils.castToInt(value); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_INT; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/IntegerFieldDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/IntegerFieldDeserializer.java deleted file mode 100644 index 7b2ce0f821..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/IntegerFieldDeserializer.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.parser.ParserConfig; -import com.alibaba.fastjson.util.FieldInfo; -import com.alibaba.fastjson.util.TypeUtils; - -public class IntegerFieldDeserializer extends FieldDeserializer { - - public IntegerFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo){ - super(clazz, fieldInfo); - } - - @Override - public void parseField(DefaultExtJSONParser parser, Object object) { - Integer value; - - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.LITERAL_INT) { - int val = lexer.intValue(); - lexer.nextToken(JSONToken.COMMA); - setValue(object, val); - return; - } else if (lexer.token() == JSONToken.NULL) { - value = null; - lexer.nextToken(JSONToken.COMMA); - } else { - Object obj = parser.parse(); - - value = TypeUtils.castToInt(obj); - } - - if (value == null && getFieldClass() == int.class) { - // skip - return; - } - - setValue(object, value); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_INT; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/JSONArrayDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/JSONArrayDeserializer.java deleted file mode 100644 index 7f0fbadde4..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/JSONArrayDeserializer.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class JSONArrayDeserializer implements ObjectDeserializer { - public final static JSONArrayDeserializer instance = new JSONArrayDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - JSONArray array = new JSONArray(); - parser.parseArray(array); - return (T) array; - } - - public int getFastMatchToken() { - return JSONToken.LBRACKET; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/JSONObjectDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/JSONObjectDeserializer.java deleted file mode 100644 index 5870971ca5..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/JSONObjectDeserializer.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class JSONObjectDeserializer implements ObjectDeserializer { - public final static JSONObjectDeserializer instance = new JSONObjectDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - return (T) parser.parseObject(); - } - - public int getFastMatchToken() { - return JSONToken.LBRACE; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/JSONPDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/JSONPDeserializer.java new file mode 100644 index 0000000000..c947950d57 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/JSONPDeserializer.java @@ -0,0 +1,64 @@ +package com.alibaba.fastjson.parser.deserializer; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONPObject; +import com.alibaba.fastjson.parser.*; + +import java.lang.reflect.Type; + +/** + * Created by wenshao on 21/02/2017. + */ +public class JSONPDeserializer implements ObjectDeserializer { + public static final JSONPDeserializer instance = new JSONPDeserializer(); + + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + JSONLexerBase lexer = (JSONLexerBase) parser.getLexer(); + + SymbolTable symbolTable = parser.getSymbolTable(); + + String funcName = lexer.scanSymbolUnQuoted(symbolTable); + lexer.nextToken(); + + int tok = lexer.token(); + + if (tok == JSONToken.DOT) { + String name = lexer.scanSymbolUnQuoted(parser.getSymbolTable()); + funcName += "."; + funcName += name; + lexer.nextToken(); + tok = lexer.token(); + } + + JSONPObject jsonp = new JSONPObject(funcName); + + if (tok != JSONToken.LPAREN) { + throw new JSONException("illegal jsonp : " + lexer.info()); + } + lexer.nextToken(); + for (;;) { + Object arg = parser.parse(); + jsonp.addParameter(arg); + + tok = lexer.token(); + if (tok == JSONToken.COMMA) { + lexer.nextToken(); + } else if (tok == JSONToken.RPAREN) { + lexer.nextToken(); + break; + } else { + throw new JSONException("illegal jsonp : " + lexer.info()); + } + } + tok = lexer.token(); + if (tok == JSONToken.SEMI) { + lexer.nextToken(); + } + + return (T) jsonp; + } + + public int getFastMatchToken() { + return 0; + } +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/JavaBeanDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/JavaBeanDeserializer.java old mode 100644 new mode 100755 index 38d21331bd..5a2f4497cd --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/JavaBeanDeserializer.java +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/JavaBeanDeserializer.java @@ -1,227 +1,1377 @@ package com.alibaba.fastjson.parser.deserializer; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; +import java.lang.reflect.*; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser.ResolveTask; import com.alibaba.fastjson.parser.Feature; -import com.alibaba.fastjson.parser.JSONScanner; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONLexerBase; import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParseContext; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.util.FieldInfo; +import com.alibaba.fastjson.util.JavaBeanInfo; +import com.alibaba.fastjson.util.TypeUtils; public class JavaBeanDeserializer implements ObjectDeserializer { - private final Map setters = new IdentityHashMap(); + private final FieldDeserializer[] fieldDeserializers; + protected final FieldDeserializer[] sortedFieldDeserializers; + protected final Class clazz; + public final JavaBeanInfo beanInfo; + private ConcurrentMap extraFieldDeserializers; - private final List fieldDeserializers = new ArrayList(); + private final Map alterNameFieldDeserializers; - private final Class clazz; + private transient long[] smartMatchHashArray; + private transient short[] smartMatchHashArrayMapping; - private Constructor constructor; + private transient long[] hashArray; + private transient short[] hashArrayMapping; + + public JavaBeanDeserializer(ParserConfig config, Class clazz) { + this(config, clazz, clazz); + } - public Map getFieldDeserializerMap() { - return setters; + public JavaBeanDeserializer(ParserConfig config, Class clazz, Type type){ + this(config // + , JavaBeanInfo.build(clazz, type, config.propertyNamingStrategy, config.fieldBased, config.compatibleWithJavaBean) + ); } + + public JavaBeanDeserializer(ParserConfig config, JavaBeanInfo beanInfo){ + this.clazz = beanInfo.clazz; + this.beanInfo = beanInfo; - public JavaBeanDeserializer(ParserConfig mapping, Class clazz){ - this.clazz = clazz; + Map alterNameFieldDeserializers = null; + sortedFieldDeserializers = new FieldDeserializer[beanInfo.sortedFields.length]; + for (int i = 0, size = beanInfo.sortedFields.length; i < size; ++i) { + FieldInfo fieldInfo = beanInfo.sortedFields[i]; + FieldDeserializer fieldDeserializer = config.createFieldDeserializer(config, beanInfo, fieldInfo); - if (!Modifier.isAbstract(clazz.getModifiers())) { - try { - constructor = clazz.getDeclaredConstructor(); - constructor.setAccessible(true); - } catch (NoSuchMethodException e) { - throw new JSONException("class not has default constructor : " + clazz.getName()); + sortedFieldDeserializers[i] = fieldDeserializer; + + for (String name : fieldInfo.alternateNames) { + if (alterNameFieldDeserializers == null) { + alterNameFieldDeserializers = new HashMap(); + } + alterNameFieldDeserializers.put(name, fieldDeserializer); } } + this.alterNameFieldDeserializers = alterNameFieldDeserializers; - List fieldInfoList = new ArrayList(); + fieldDeserializers = new FieldDeserializer[beanInfo.fields.length]; + for (int i = 0, size = beanInfo.fields.length; i < size; ++i) { + FieldInfo fieldInfo = beanInfo.fields[i]; + FieldDeserializer fieldDeserializer = getFieldDeserializer(fieldInfo.name); + fieldDeserializers[i] = fieldDeserializer; + } + } - computeSetters(clazz, fieldInfoList); + public FieldDeserializer getFieldDeserializer(String key) { + return getFieldDeserializer(key, null); + } - for (FieldInfo fieldInfo : fieldInfoList) { - addFieldDeserializer(mapping, clazz, fieldInfo); + public FieldDeserializer getFieldDeserializer(String key, int[] setFlags) { + if (key == null) { + return null; } + + int low = 0; + int high = sortedFieldDeserializers.length - 1; + + while (low <= high) { + int mid = (low + high) >>> 1; + + String fieldName = sortedFieldDeserializers[mid].fieldInfo.name; + + int cmp = fieldName.compareTo(key); + + if (cmp < 0) { + low = mid + 1; + } else if (cmp > 0) { + high = mid - 1; + } else { + if (isSetFlag(mid, setFlags)) { + return null; + } + + return sortedFieldDeserializers[mid]; // key found + } + } + + if(this.alterNameFieldDeserializers != null){ + return this.alterNameFieldDeserializers.get(key); + } + + return null; // key not found. } - public static void computeSetters(Class clazz, List fieldInfoList) { - for (Method method : clazz.getMethods()) { - String methodName = method.getName(); - if (methodName.length() < 4) { - continue; + public FieldDeserializer getFieldDeserializer(long hash) { + if (this.hashArray == null) { + long[] hashArray = new long[sortedFieldDeserializers.length]; + for (int i = 0; i < sortedFieldDeserializers.length; i++) { + hashArray[i] = TypeUtils.fnv1a_64(sortedFieldDeserializers[i].fieldInfo.name); } + Arrays.sort(hashArray); + this.hashArray = hashArray; + } - if (Modifier.isStatic(method.getModifiers())) { - continue; + int pos = Arrays.binarySearch(hashArray, hash); + if (pos < 0) { + return null; + } + + if (hashArrayMapping == null) { + short[] mapping = new short[hashArray.length]; + Arrays.fill(mapping, (short) -1); + for (int i = 0; i < sortedFieldDeserializers.length; i++) { + int p = Arrays.binarySearch(hashArray + , TypeUtils.fnv1a_64(sortedFieldDeserializers[i].fieldInfo.name)); + if (p >= 0) { + mapping[p] = (short) i; + } } + hashArrayMapping = mapping; + } + + int setterIndex = hashArrayMapping[pos]; + if (setterIndex != -1) { + return sortedFieldDeserializers[setterIndex]; + } + + return null; // key not found. + } + + static boolean isSetFlag(int i, int[] setFlags) { + if (setFlags == null) { + return false; + } - if (!method.getReturnType().equals(Void.TYPE)) { - continue; + int flagIndex = i / 32; + int bitIndex = i % 32; + if (flagIndex < setFlags.length) { + if ((setFlags[flagIndex] & (1 << bitIndex)) != 0) { + return true; } + } - if (method.getParameterTypes().length != 1) { - continue; + return false; + } + + public Object createInstance(DefaultJSONParser parser, Type type) { + if (type instanceof Class) { + if (clazz.isInterface()) { + Class clazz = (Class) type; + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + final JSONObject obj = new JSONObject(); + Object proxy = Proxy.newProxyInstance(loader, new Class[] { clazz }, obj); + return proxy; } + } - JSONField annotation = method.getAnnotation(JSONField.class); + if (beanInfo.defaultConstructor == null && beanInfo.factoryMethod == null) { + return null; + } - if (annotation != null) { - if (!annotation.deserialize()) { - continue; - } + if (beanInfo.factoryMethod != null && beanInfo.defaultConstructorParameterSize > 0) { + return null; + } - if (annotation.name().length() != 0) { - String propertyName = annotation.name(); - fieldInfoList.add(new FieldInfo(propertyName, method, null)); - method.setAccessible(true); - continue; + Object object; + try { + Constructor constructor = beanInfo.defaultConstructor; + if (beanInfo.defaultConstructorParameterSize == 0) { + if (constructor != null) { + object = constructor.newInstance(); + } else { + object = beanInfo.factoryMethod.invoke(null); + } + } else { + ParseContext context = parser.getContext(); + if (context == null || context.object == null) { + throw new JSONException("can't create non-static inner class instance."); } - } - - if (methodName.startsWith("set") && Character.isUpperCase(methodName.charAt(3))) { - String propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); - Field field = getField(clazz, propertyName); - if (field != null) { + final String typeName; + if (type instanceof Class) { + typeName = ((Class) type).getName(); + } else { + throw new JSONException("can't create non-static inner class instance."); + } - JSONField fieldAnnotation = field.getAnnotation(JSONField.class); + final int lastIndex = typeName.lastIndexOf('$'); + String parentClassName = typeName.substring(0, lastIndex); - if (fieldAnnotation != null && fieldAnnotation.name().length() != 0) { - propertyName = fieldAnnotation.name(); + Object ctxObj = context.object; + String parentName = ctxObj.getClass().getName(); - fieldInfoList.add(new FieldInfo(propertyName, method, field)); - continue; + Object param = null; + if (!parentName.equals(parentClassName)) { + ParseContext parentContext = context.parent; + if (parentContext != null + && parentContext.object != null + && ("java.util.ArrayList".equals(parentName) + || "java.util.List".equals(parentName) + || "java.util.Collection".equals(parentName) + || "java.util.Map".equals(parentName) + || "java.util.HashMap".equals(parentName))) { + parentName = parentContext.object.getClass().getName(); + if (parentName.equals(parentClassName)) { + param = parentContext.object; + } } + } else { + param = ctxObj; } - fieldInfoList.add(new FieldInfo(propertyName, method, null)); - method.setAccessible(true); + if (param == null) { + throw new JSONException("can't create non-static inner class instance."); + } + + object = constructor.newInstance(param); } + } catch (JSONException e) { + throw e; + } catch (Exception e) { + throw new JSONException("create instance error, class " + clazz.getName(), e); } - } - private void addFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo) { - FieldDeserializer fieldDeserializer = createFieldDeserializer(mapping, clazz, fieldInfo); + if (parser != null // + && parser.lexer.isEnabled(Feature.InitStringFieldAsEmpty)) { + for (FieldInfo fieldInfo : beanInfo.fields) { + if (fieldInfo.fieldClass == String.class) { + try { + fieldInfo.set(object, ""); + } catch (Exception e) { + throw new JSONException("create instance error, class " + clazz.getName(), e); + } + } + } + } - setters.put(fieldInfo.getName().intern(), fieldDeserializer); - fieldDeserializers.add(fieldDeserializer); + return object; + } + + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + return deserialze(parser, type, fieldName, 0); } - public FieldDeserializer createFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo) { - return mapping.createFieldDeserializer(mapping, clazz, fieldInfo); + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName, int features) { + return deserialze(parser, type, fieldName, null, features, null); } - public static Field getField(Class clazz, String fieldName) { - try { - return clazz.getDeclaredField(fieldName); - } catch (Exception e) { - return null; + @SuppressWarnings({ "unchecked" }) + public T deserialzeArrayMapping(DefaultJSONParser parser, Type type, Object fieldName, Object object) { + final JSONLexer lexer = parser.lexer; // xxx + if (lexer.token() != JSONToken.LBRACKET) { + throw new JSONException("error"); } - } - public Object createInstance(DefaultExtJSONParser parser, Type type) { + object = createInstance(parser, type); - Object object; - try { - object = constructor.newInstance(); - } catch (Exception e) { - throw new JSONException("create instance error, class " + clazz.getName(), e); + for (int i = 0, size = sortedFieldDeserializers.length; i < size; ++i) { + final char seperator = (i == size - 1) ? ']' : ','; + FieldDeserializer fieldDeser = sortedFieldDeserializers[i]; + Class fieldClass = fieldDeser.fieldInfo.fieldClass; + if (fieldClass == int.class) { + int value = lexer.scanInt(seperator); + fieldDeser.setValue(object, value); + } else if (fieldClass == String.class) { + String value = lexer.scanString(seperator); + fieldDeser.setValue(object, value); + } else if (fieldClass == long.class) { + long value = lexer.scanLong(seperator); + fieldDeser.setValue(object, value); + } else if (fieldClass.isEnum()) { + char ch = lexer.getCurrent(); + + Object value; + if (ch == '\"' || ch == 'n') { + value = lexer.scanEnum(fieldClass, parser.getSymbolTable(), seperator); + } else if (ch >= '0' && ch <= '9') { + int ordinal = lexer.scanInt(seperator); + + EnumDeserializer enumDeser = (EnumDeserializer) ((DefaultFieldDeserializer) fieldDeser).getFieldValueDeserilizer(parser.getConfig()); + value = enumDeser.valueOf(ordinal); + } else { + value = scanEnum(lexer, seperator); + } + + fieldDeser.setValue(object, value); + } else if (fieldClass == boolean.class) { + boolean value = lexer.scanBoolean(seperator); + fieldDeser.setValue(object, value); + } else if (fieldClass == float.class) { + float value = lexer.scanFloat(seperator); + fieldDeser.setValue(object, value); + } else if (fieldClass == double.class) { + double value = lexer.scanDouble(seperator); + fieldDeser.setValue(object, value); + } else if (fieldClass == java.util.Date.class && lexer.getCurrent() == '1') { + long longValue = lexer.scanLong(seperator); + fieldDeser.setValue(object, new java.util.Date(longValue)); + } else if (fieldClass == BigDecimal.class) { + BigDecimal value = lexer.scanDecimal(seperator); + fieldDeser.setValue(object, value); + } else { + lexer.nextToken(JSONToken.LBRACKET); + Object value = parser.parseObject(fieldDeser.fieldInfo.fieldType, fieldDeser.fieldInfo.name); + fieldDeser.setValue(object, value); + + if (lexer.token() == JSONToken.RBRACKET) { + break; + } + + check(lexer, seperator == ']' ? JSONToken.RBRACKET : JSONToken.COMMA); + // parser.accept(seperator == ']' ? JSONToken.RBRACKET : JSONToken.COMMA); + } } + lexer.nextToken(JSONToken.COMMA); - return object; + return (T) object; + } + + protected void check(final JSONLexer lexer, int token) { + if (lexer.token() != token) { + throw new JSONException("syntax error"); + } + } + + protected Enum scanEnum(JSONLexer lexer, char seperator) { + throw new JSONException("illegal enum. " + lexer.info()); } - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type type) { - JSONScanner lexer = (JSONScanner) parser.getLexer(); // xxx + @SuppressWarnings({ "unchecked", "rawtypes" }) + protected T deserialze(DefaultJSONParser parser, // + Type type, // + Object fieldName, // + Object object, // + int features, // + int[] setFlags) { + if (type == JSON.class || type == JSONObject.class) { + return (T) parser.parse(); + } + + final JSONLexerBase lexer = (JSONLexerBase) parser.lexer; // xxx + final ParserConfig config = parser.getConfig(); - if (lexer.token() == JSONToken.NULL) { + int token = lexer.token(); + if (token == JSONToken.NULL) { lexer.nextToken(JSONToken.COMMA); return null; } - Object object = createInstance(parser, type); - - if (lexer.token() != JSONToken.LBRACE) { - throw new JSONException("syntax error, expect {, actual " + JSONToken.name(lexer.token())); + ParseContext context = parser.getContext(); + if (object != null && context != null) { + context = context.parent; } + ParseContext childContext = null; - for (;;) { + try { + Map fieldValues = null; + + if (token == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + if (object == null) { + object = createInstance(parser, type); + } + return (T) object; + } + + if (token == JSONToken.LBRACKET) { + final int mask = Feature.SupportArrayToBean.mask; + boolean isSupportArrayToBean = (beanInfo.parserFeatures & mask) != 0 // + || lexer.isEnabled(Feature.SupportArrayToBean) // + || (features & mask) != 0 + ; + if (isSupportArrayToBean) { + return deserialzeArrayMapping(parser, type, fieldName, object); + } + } + + if (token != JSONToken.LBRACE && token != JSONToken.COMMA) { + if (lexer.isBlankInput()) { + return null; + } + + if (token == JSONToken.LITERAL_STRING) { + String strVal = lexer.stringVal(); + if (strVal.length() == 0) { + lexer.nextToken(); + return null; + } + + if (beanInfo.jsonType != null) { + for (Class seeAlsoClass : beanInfo.jsonType.seeAlso()) { + if (Enum.class.isAssignableFrom(seeAlsoClass)) { + try { + Enum e = Enum.valueOf((Class) seeAlsoClass, strVal); + return (T) e; + } catch (IllegalArgumentException e) { + // skip + } + } + } + } + } else if (token == JSONToken.LITERAL_ISO8601_DATE) { + Calendar calendar = lexer.getCalendar(); + } + + if (token == JSONToken.LBRACKET && lexer.getCurrent() == ']') { + lexer.next(); + lexer.nextToken(); + return null; + } + + StringBuffer buf = (new StringBuffer()) // + .append("syntax error, expect {, actual ") // + .append(lexer.tokenName()) // + .append(", pos ") // + .append(lexer.pos()); + + if (fieldName instanceof String) { + buf // + .append(", fieldName ") // + .append(fieldName); + } + + buf.append(", fastjson-version ").append(JSON.VERSION); + + throw new JSONException(buf.toString()); + } + + if (parser.resolveStatus == DefaultJSONParser.TypeNameRedirect) { + parser.resolveStatus = DefaultJSONParser.NONE; + } + + String typeKey = beanInfo.typeKey; + for (int fieldIndex = 0;; fieldIndex++) { + String key = null; + FieldDeserializer fieldDeser = null; + FieldInfo fieldInfo = null; + Class fieldClass = null; + JSONField feildAnnotation = null; + boolean customDeserilizer = false; + if (fieldIndex < sortedFieldDeserializers.length) { + fieldDeser = sortedFieldDeserializers[fieldIndex]; + fieldInfo = fieldDeser.fieldInfo; + fieldClass = fieldInfo.fieldClass; + feildAnnotation = fieldInfo.getAnnotation(); + if (feildAnnotation != null && fieldDeser instanceof DefaultFieldDeserializer) { + customDeserilizer = ((DefaultFieldDeserializer) fieldDeser).customDeserilizer; + } + } + + boolean matchField = false; + boolean valueParsed = false; + + Object fieldValue = null; + if (fieldDeser != null) { + char[] name_chars = fieldInfo.name_chars; + if (customDeserilizer && lexer.matchField(name_chars)) { + matchField = true; + } else if (fieldClass == int.class || fieldClass == Integer.class) { + fieldValue = lexer.scanFieldInt(name_chars); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (fieldClass == long.class || fieldClass == Long.class) { + fieldValue = lexer.scanFieldLong(name_chars); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (fieldClass == String.class) { + fieldValue = lexer.scanFieldString(name_chars); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (fieldClass == java.util.Date.class && fieldInfo.format == null) { + fieldValue = lexer.scanFieldDate(name_chars); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (fieldClass == BigDecimal.class) { + fieldValue = lexer.scanFieldDecimal(name_chars); - String key = lexer.scanSymbol(parser.getSymbolTable()); + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (fieldClass == BigInteger.class) { + fieldValue = lexer.scanFieldBigInteger(name_chars); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (fieldClass == boolean.class || fieldClass == Boolean.class) { + fieldValue = lexer.scanFieldBoolean(name_chars); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (fieldClass == float.class || fieldClass == Float.class) { + fieldValue = lexer.scanFieldFloat(name_chars); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (fieldClass == double.class || fieldClass == Double.class) { + fieldValue = lexer.scanFieldDouble(name_chars); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (fieldClass.isEnum() // + && parser.getConfig().getDeserializer(fieldClass) instanceof EnumDeserializer + && (feildAnnotation == null || feildAnnotation.deserializeUsing() == Void.class) + ) { + if (fieldDeser instanceof DefaultFieldDeserializer) { + ObjectDeserializer fieldValueDeserilizer = ((DefaultFieldDeserializer) fieldDeser).fieldValueDeserilizer; + fieldValue = this.scanEnum(lexer, name_chars, fieldValueDeserilizer); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } + } else if (fieldClass == int[].class) { + fieldValue = lexer.scanFieldIntArray(name_chars); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (fieldClass == float[].class) { + fieldValue = lexer.scanFieldFloatArray(name_chars); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (fieldClass == float[][].class) { + fieldValue = lexer.scanFieldFloatArray2(name_chars); + + if (lexer.matchStat > 0) { + matchField = true; + valueParsed = true; + } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { + continue; + } + } else if (lexer.matchField(name_chars)) { + matchField = true; + } else { + continue; + } + } + + if (!matchField) { + key = lexer.scanSymbol(parser.symbolTable); + + if (key == null) { + token = lexer.token(); + if (token == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + break; + } + if (token == JSONToken.COMMA) { + if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { + continue; + } + } + } + + if ("$ref" == key && context != null) { + lexer.nextTokenWithColon(JSONToken.LITERAL_STRING); + token = lexer.token(); + if (token == JSONToken.LITERAL_STRING) { + String ref = lexer.stringVal(); + if ("@".equals(ref)) { + object = context.object; + } else if ("..".equals(ref)) { + ParseContext parentContext = context.parent; + if (parentContext.object != null) { + object = parentContext.object; + } else { + parser.addResolveTask(new ResolveTask(parentContext, ref)); + parser.resolveStatus = DefaultJSONParser.NeedToResolve; + } + } else if ("$".equals(ref)) { + ParseContext rootContext = context; + while (rootContext.parent != null) { + rootContext = rootContext.parent; + } + + if (rootContext.object != null) { + object = rootContext.object; + } else { + parser.addResolveTask(new ResolveTask(rootContext, ref)); + parser.resolveStatus = DefaultJSONParser.NeedToResolve; + } + } else { + if (ref.indexOf('\\') > 0) { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < ref.length(); ++i) { + char ch = ref.charAt(i); + if (ch == '\\') { + ch = ref.charAt(++i); + } + buf.append(ch); + } + ref = buf.toString(); + } + Object refObj = parser.resolveReference(ref); + if (refObj != null) { + object = refObj; + } else { + parser.addResolveTask(new ResolveTask(context, ref)); + parser.resolveStatus = DefaultJSONParser.NeedToResolve; + } + } + } else { + throw new JSONException("illegal ref, " + JSONToken.name(token)); + } + + lexer.nextToken(JSONToken.RBRACE); + if (lexer.token() != JSONToken.RBRACE) { + throw new JSONException("illegal ref"); + } + lexer.nextToken(JSONToken.COMMA); + + parser.setContext(context, object, fieldName); + + return (T) object; + } + + if ((typeKey != null && typeKey.equals(key)) + || JSON.DEFAULT_TYPE_KEY == key) { + lexer.nextTokenWithColon(JSONToken.LITERAL_STRING); + if (lexer.token() == JSONToken.LITERAL_STRING) { + String typeName = lexer.stringVal(); + lexer.nextToken(JSONToken.COMMA); + + if (typeName.equals(beanInfo.typeName)|| parser.isEnabled(Feature.IgnoreAutoType)) { + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + break; + } + continue; + } + + + ObjectDeserializer deserializer = getSeeAlso(config, this.beanInfo, typeName); + Class userType = null; + + if (deserializer == null) { + Class expectClass = TypeUtils.getClass(type); + userType = config.checkAutoType(typeName, expectClass, lexer.getFeatures()); + deserializer = parser.getConfig().getDeserializer(userType); + } + + Object typedObject = deserializer.deserialze(parser, userType, fieldName); + if (deserializer instanceof JavaBeanDeserializer) { + JavaBeanDeserializer javaBeanDeserializer = (JavaBeanDeserializer) deserializer; + if (typeKey != null) { + FieldDeserializer typeKeyFieldDeser = javaBeanDeserializer.getFieldDeserializer(typeKey); + typeKeyFieldDeser.setValue(typedObject, typeName); + } + } + return (T) typedObject; + } else { + throw new JSONException("syntax error"); + } + } + } + + if (object == null && fieldValues == null) { + object = createInstance(parser, type); + if (object == null) { + fieldValues = new HashMap(this.fieldDeserializers.length); + } + childContext = parser.setContext(context, object, fieldName); + if (setFlags == null) { + setFlags = new int[(this.fieldDeserializers.length / 32) + 1]; + } + } + + if (matchField) { + if (!valueParsed) { + fieldDeser.parseField(parser, object, type, fieldValues); + } else { + if (object == null) { + fieldValues.put(fieldInfo.name, fieldValue); + } else if (fieldValue == null) { + if (fieldClass != int.class // + && fieldClass != long.class // + && fieldClass != float.class // + && fieldClass != double.class // + && fieldClass != boolean.class // + ) { + fieldDeser.setValue(object, fieldValue); + } + } else { + fieldDeser.setValue(object, fieldValue); + } + + if (setFlags != null) { + int flagIndex = fieldIndex / 32; + int bitIndex = fieldIndex % 32; + setFlags[flagIndex] |= (1 >> bitIndex); + } + + if (lexer.matchStat == JSONLexer.END) { + break; + } + } + } else { + boolean match = parseField(parser, key, object, type, fieldValues, setFlags); + if (!match) { + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + break; + } + + continue; + } else if (lexer.token() == JSONToken.COLON) { + throw new JSONException("syntax error, unexpect token ':'"); + } + } + + if (lexer.token() == JSONToken.COMMA) { + continue; + } - if (key == null) { if (lexer.token() == JSONToken.RBRACE) { lexer.nextToken(JSONToken.COMMA); break; } - if (lexer.token() == JSONToken.COMMA) { - if (parser.isEnabled(Feature.AllowArbitraryCommas)) { - continue; - } + + if (lexer.token() == JSONToken.IDENTIFIER || lexer.token() == JSONToken.ERROR) { + throw new JSONException("syntax error, unexpect token " + JSONToken.name(lexer.token())); } } - boolean match = parseField(parser, key, object); - if (!match) { - if (lexer.token() == JSONToken.RBRACE) { - lexer.nextToken(); + if (object == null) { + if (fieldValues == null) { + object = createInstance(parser, type); + if (childContext == null) { + childContext = parser.setContext(context, object, fieldName); + } return (T) object; } - continue; - } + String[] paramNames = beanInfo.creatorConstructorParameters; + final Object[] params; + if (paramNames != null) { + params = new Object[paramNames.length]; + for (int i = 0; i < paramNames.length; i++) { + String paramName = paramNames[i]; - if (lexer.token() == JSONToken.COMMA) { - continue; - } + Object param = fieldValues.remove(paramName); + if (param == null) { + Type fieldType = beanInfo.creatorConstructorParameterTypes[i]; + FieldInfo fieldInfo = beanInfo.fields[i]; + if (fieldType == byte.class) { + param = (byte) 0; + } else if (fieldType == short.class) { + param = (short) 0; + } else if (fieldType == int.class) { + param = 0; + } else if (fieldType == long.class) { + param = 0L; + } else if (fieldType == float.class) { + param = 0F; + } else if (fieldType == double.class) { + param = 0D; + } else if (fieldType == boolean.class) { + param = Boolean.FALSE; + } else if (fieldType == String.class + && (fieldInfo.parserFeatures & Feature.InitStringFieldAsEmpty.mask) != 0) { + param = ""; + } + } + params[i] = param; + } + } else { + FieldInfo[] fieldInfoList = beanInfo.fields; + int size = fieldInfoList.length; + params = new Object[size]; + for (int i = 0; i < size; ++i) { + FieldInfo fieldInfo = fieldInfoList[i]; + Object param = fieldValues.get(fieldInfo.name); + if (param == null) { + Type fieldType = fieldInfo.fieldType; + if (fieldType == byte.class) { + param = (byte) 0; + } else if (fieldType == short.class) { + param = (short) 0; + } else if (fieldType == int.class) { + param = 0; + } else if (fieldType == long.class) { + param = 0L; + } else if (fieldType == float.class) { + param = 0F; + } else if (fieldType == double.class) { + param = 0D; + } else if (fieldType == boolean.class) { + param = Boolean.FALSE; + } else if (fieldType == String.class + && (fieldInfo.parserFeatures & Feature.InitStringFieldAsEmpty.mask) != 0) { + param = ""; + } + } + params[i] = param; + } + } - if (lexer.token() == JSONToken.RBRACE) { - lexer.nextToken(JSONToken.COMMA); + if (beanInfo.creatorConstructor != null) { + try { + object = beanInfo.creatorConstructor.newInstance(params); + } catch (Exception e) { + throw new JSONException("create instance error, " + paramNames + ", " + + beanInfo.creatorConstructor.toGenericString(), e); + } + + if (paramNames != null) { + for (Map.Entry entry : fieldValues.entrySet()) { + FieldDeserializer fieldDeserializer = getFieldDeserializer(entry.getKey()); + if (fieldDeserializer != null) { + fieldDeserializer.setValue(object, entry.getValue()); + } + } + } + } else if (beanInfo.factoryMethod != null) { + try { + object = beanInfo.factoryMethod.invoke(null, params); + } catch (Exception e) { + throw new JSONException("create factory method error, " + beanInfo.factoryMethod.toString(), e); + } + } + + childContext.object = object; + } + + Method buildMethod = beanInfo.buildMethod; + if (buildMethod == null) { return (T) object; } - - if (lexer.token() == JSONToken.IDENTIFIER || lexer.token() == JSONToken.ERROR) { - throw new JSONException("syntax error, unexpect token " + JSONToken.name(lexer.token())); + + + Object builtObj; + try { + builtObj = buildMethod.invoke(object); + } catch (Exception e) { + throw new JSONException("build object error", e); + } + + return (T) builtObj; + } finally { + if (childContext != null) { + childContext.object = object; } + parser.setContext(context); + } + } + protected Enum scanEnum(JSONLexerBase lexer, char[] name_chars, ObjectDeserializer fieldValueDeserilizer) { + EnumDeserializer enumDeserializer = null; + if (fieldValueDeserilizer instanceof EnumDeserializer) { + enumDeserializer = (EnumDeserializer) fieldValueDeserilizer; } - return (T) object; + if (enumDeserializer == null) { + lexer.matchStat = JSONLexer.NOT_MATCH; + return null; + } + + long enumNameHashCode = lexer.scanFieldSymbol(name_chars); + if (lexer.matchStat > 0) { + return enumDeserializer.getEnumByHashCode(enumNameHashCode); + } else { + return null; + } + } + + public boolean parseField(DefaultJSONParser parser, String key, Object object, Type objectType, + Map fieldValues) { + return parseField(parser, key, object, objectType, fieldValues, null); } + + public boolean parseField(DefaultJSONParser parser, String key, Object object, Type objectType, + Map fieldValues, int[] setFlags) { + JSONLexer lexer = parser.lexer; // xxx + + final int disableFieldSmartMatchMask = Feature.DisableFieldSmartMatch.mask; + FieldDeserializer fieldDeserializer; + if (lexer.isEnabled(disableFieldSmartMatchMask) || (this.beanInfo.parserFeatures & disableFieldSmartMatchMask) != 0) { + fieldDeserializer = getFieldDeserializer(key); + } else { + fieldDeserializer = smartMatch(key, setFlags); + } + + final int mask = Feature.SupportNonPublicField.mask; + if (fieldDeserializer == null + && (lexer.isEnabled(mask) + || (this.beanInfo.parserFeatures & mask) != 0)) { + if (this.extraFieldDeserializers == null) { + ConcurrentHashMap extraFieldDeserializers = new ConcurrentHashMap(1, 0.75f, 1); + for (Class c = this.clazz; c != null && c != Object.class; c = c.getSuperclass()) { + Field[] fields = c.getDeclaredFields(); + for (Field field : fields) { + String fieldName = field.getName(); + if (this.getFieldDeserializer(fieldName) != null) { + continue; + } + int fieldModifiers = field.getModifiers(); + if ((fieldModifiers & Modifier.FINAL) != 0 || (fieldModifiers & Modifier.STATIC) != 0) { + continue; + } + extraFieldDeserializers.put(fieldName, field); + } + } + this.extraFieldDeserializers = extraFieldDeserializers; + } - public boolean parseField(DefaultExtJSONParser parser, String key, Object object) { - JSONScanner lexer = (JSONScanner) parser.getLexer(); // xxx + Object deserOrField = extraFieldDeserializers.get(key); + if (deserOrField != null) { + if (deserOrField instanceof FieldDeserializer) { + fieldDeserializer = ((FieldDeserializer) deserOrField); + } else { + Field field = (Field) deserOrField; + field.setAccessible(true); + FieldInfo fieldInfo = new FieldInfo(key, field.getDeclaringClass(), field.getType(), field.getGenericType(), field, 0, 0, 0); + fieldDeserializer = new DefaultFieldDeserializer(parser.getConfig(), clazz, fieldInfo); + extraFieldDeserializers.put(key, fieldDeserializer); + } + } + } - FieldDeserializer fieldDeserializer = setters.get(key); if (fieldDeserializer == null) { - if (!parser.isEnabled(Feature.IgnoreNotMatch)) { + if (!lexer.isEnabled(Feature.IgnoreNotMatch)) { throw new JSONException("setter not found, class " + clazz.getName() + ", property " + key); } - lexer.nextTokenWithColon(); - parser.parse(); // skip + for (FieldDeserializer fieldDeser : this.sortedFieldDeserializers) { + FieldInfo fieldInfo = fieldDeser.fieldInfo; + if (fieldInfo.unwrapped // + && fieldDeser instanceof DefaultFieldDeserializer) { + if (fieldInfo.field != null) { + DefaultFieldDeserializer defaultFieldDeserializer = (DefaultFieldDeserializer) fieldDeser; + ObjectDeserializer fieldValueDeser = defaultFieldDeserializer.getFieldValueDeserilizer(parser.getConfig()); + if (fieldValueDeser instanceof JavaBeanDeserializer) { + JavaBeanDeserializer javaBeanFieldValueDeserializer = (JavaBeanDeserializer) fieldValueDeser; + FieldDeserializer unwrappedFieldDeser = javaBeanFieldValueDeserializer.getFieldDeserializer(key); + if (unwrappedFieldDeser != null) { + Object fieldObject; + try { + fieldObject = fieldInfo.field.get(object); + if (fieldObject == null) { + fieldObject = ((JavaBeanDeserializer) fieldValueDeser).createInstance(parser, fieldInfo.fieldType); + fieldDeser.setValue(object, fieldObject); + } + lexer.nextTokenWithColon(defaultFieldDeserializer.getFastMatchToken()); + unwrappedFieldDeser.parseField(parser, fieldObject, objectType, fieldValues); + return true; + } catch (Exception e) { + throw new JSONException("parse unwrapped field error.", e); + } + } + } else if (fieldValueDeser instanceof MapDeserializer) { + MapDeserializer javaBeanFieldValueDeserializer = (MapDeserializer) fieldValueDeser; + + Map fieldObject; + try { + fieldObject = (Map) fieldInfo.field.get(object); + if (fieldObject == null) { + fieldObject = javaBeanFieldValueDeserializer.createMap(fieldInfo.fieldType); + fieldDeser.setValue(object, fieldObject); + } + + lexer.nextTokenWithColon(); + Object fieldValue = parser.parse(key); + fieldObject.put(key, fieldValue); + } catch (Exception e) { + throw new JSONException("parse unwrapped field error.", e); + } + return true; + } + } else if (fieldInfo.method.getParameterTypes().length == 2) { + lexer.nextTokenWithColon(); + Object fieldValue = parser.parse(key); + try { + fieldInfo.method.invoke(object, key, fieldValue); + } catch (Exception e) { + throw new JSONException("parse unwrapped field error.", e); + } + return true; + } + } + } + + parser.parseExtra(object, key); return false; } + int fieldIndex = -1; + for (int i = 0; i < sortedFieldDeserializers.length; ++i) { + if (sortedFieldDeserializers[i] == fieldDeserializer) { + fieldIndex = i; + break; + } + } + if (fieldIndex != -1 && setFlags != null && key.startsWith("_")) { + if (isSetFlag(fieldIndex, setFlags)) { + parser.parseExtra(object, key); + return false; + } + } + lexer.nextTokenWithColon(fieldDeserializer.getFastMatchToken()); - fieldDeserializer.parseField(parser, object); + + fieldDeserializer.parseField(parser, object, objectType, fieldValues); + return true; } + public FieldDeserializer smartMatch(String key) { + return smartMatch(key, null); + } + + public FieldDeserializer smartMatch(String key, int[] setFlags) { + if (key == null) { + return null; + } + + FieldDeserializer fieldDeserializer = getFieldDeserializer(key, setFlags); + + if (fieldDeserializer == null) { + long smartKeyHash = TypeUtils.fnv1a_64_lower(key); + if (this.smartMatchHashArray == null) { + long[] hashArray = new long[sortedFieldDeserializers.length]; + for (int i = 0; i < sortedFieldDeserializers.length; i++) { + hashArray[i] = TypeUtils.fnv1a_64_lower(sortedFieldDeserializers[i].fieldInfo.name); + } + Arrays.sort(hashArray); + this.smartMatchHashArray = hashArray; + } + + // smartMatchHashArrayMapping + int pos = Arrays.binarySearch(smartMatchHashArray, smartKeyHash); + boolean is = false; + if (pos < 0 && (is = key.startsWith("is"))) { + smartKeyHash = TypeUtils.fnv1a_64_lower(key.substring(2)); + pos = Arrays.binarySearch(smartMatchHashArray, smartKeyHash); + } + + if (pos >= 0) { + if (smartMatchHashArrayMapping == null) { + short[] mapping = new short[smartMatchHashArray.length]; + Arrays.fill(mapping, (short) -1); + for (int i = 0; i < sortedFieldDeserializers.length; i++) { + int p = Arrays.binarySearch(smartMatchHashArray + , TypeUtils.fnv1a_64_lower(sortedFieldDeserializers[i].fieldInfo.name)); + if (p >= 0) { + mapping[p] = (short) i; + } + } + smartMatchHashArrayMapping = mapping; + } + + int deserIndex = smartMatchHashArrayMapping[pos]; + if (deserIndex != -1) { + if (!isSetFlag(deserIndex, setFlags)) { + fieldDeserializer = sortedFieldDeserializers[deserIndex]; + } + } + } + + if (fieldDeserializer != null) { + FieldInfo fieldInfo = fieldDeserializer.fieldInfo; + if ((fieldInfo.parserFeatures & Feature.DisableFieldSmartMatch.mask) != 0) { + return null; + } + + Class fieldClass = fieldInfo.fieldClass; + if (is && (fieldClass != boolean.class && fieldClass != Boolean.class)) { + fieldDeserializer = null; + } + } + } + + + return fieldDeserializer; + } + public int getFastMatchToken() { return JSONToken.LBRACE; } + + public Object createInstance(Map map, ParserConfig config) // + throws IllegalArgumentException, + IllegalAccessException, + InvocationTargetException { + Object object = null; + + if (beanInfo.creatorConstructor == null && beanInfo.factoryMethod == null) { + object = createInstance(null, clazz); + + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + FieldDeserializer fieldDeser = smartMatch(key); + if (fieldDeser == null) { + continue; + } + + final FieldInfo fieldInfo = fieldDeser.fieldInfo; + Type paramType = fieldInfo.fieldType; + String format = fieldInfo.format; + if (format != null && paramType == java.util.Date.class) { + value = TypeUtils.castToDate(value, format); + } else { + value = TypeUtils.cast(value, paramType, config); + } + + fieldDeser.setValue(object, value); + } + + if (beanInfo.buildMethod != null) { + Object builtObj; + try { + builtObj = beanInfo.buildMethod.invoke(object); + } catch (Exception e) { + throw new JSONException("build object error", e); + } + + return builtObj; + } + + return object; + } + + + FieldInfo[] fieldInfoList = beanInfo.fields; + int size = fieldInfoList.length; + Object[] params = new Object[size]; + Map missFields = null; + for (int i = 0; i < size; ++i) { + FieldInfo fieldInfo = fieldInfoList[i]; + Object param = map.get(fieldInfo.name); + + if (param == null) { + Class fieldClass = fieldInfo.fieldClass; + if (fieldClass == int.class) { + param = 0; + } else if (fieldClass == long.class) { + param = 0L; + } else if (fieldClass == short.class) { + param = Short.valueOf((short) 0); + } else if (fieldClass == byte.class) { + param = Byte.valueOf((byte) 0); + } else if (fieldClass == float.class) { + param = Float.valueOf(0); + } else if (fieldClass == double.class) { + param = Double.valueOf(0); + } else if (fieldClass == char.class) { + param = '0'; + } else if (fieldClass == boolean.class) { + param = false; + } + if (missFields == null) { + missFields = new HashMap(); + } + missFields.put(fieldInfo.name, i); + } + params[i] = param; + } + + if (missFields != null) { + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + FieldDeserializer fieldDeser = smartMatch(key); + if (fieldDeser != null) { + Integer index = missFields.get(fieldDeser.fieldInfo.name); + if (index != null) { + params[index] = value; + } + } + } + } + + if (beanInfo.creatorConstructor != null) { + try { + object = beanInfo.creatorConstructor.newInstance(params); + } catch (Exception e) { + throw new JSONException("create instance error, " + + beanInfo.creatorConstructor.toGenericString(), e); + } + } else if (beanInfo.factoryMethod != null) { + try { + object = beanInfo.factoryMethod.invoke(null, params); + } catch (Exception e) { + throw new JSONException("create factory method error, " + beanInfo.factoryMethod.toString(), e); + } + } + + return object; + } + + public Type getFieldType(int ordinal) { + return sortedFieldDeserializers[ordinal].fieldInfo.fieldType; + } + + protected Object parseRest(DefaultJSONParser parser, Type type, Object fieldName, Object instance, int features) { + return parseRest(parser, type, fieldName, instance, features, new int[0]); + } + + protected Object parseRest(DefaultJSONParser parser + , Type type + , Object fieldName + , Object instance + , int features + , int[] setFlags) { + Object value = deserialze(parser, type, fieldName, instance, features, setFlags); + + return value; + } + + protected JavaBeanDeserializer getSeeAlso(ParserConfig config, JavaBeanInfo beanInfo, String typeName) { + if (beanInfo.jsonType == null) { + return null; + } + + for (Class seeAlsoClass : beanInfo.jsonType.seeAlso()) { + ObjectDeserializer seeAlsoDeser = config.getDeserializer(seeAlsoClass); + if (seeAlsoDeser instanceof JavaBeanDeserializer) { + JavaBeanDeserializer seeAlsoJavaBeanDeser = (JavaBeanDeserializer) seeAlsoDeser; + + JavaBeanInfo subBeanInfo = seeAlsoJavaBeanDeser.beanInfo; + if (subBeanInfo.typeName.equals(typeName)) { + return seeAlsoJavaBeanDeser; + } + + JavaBeanDeserializer subSeeAlso = getSeeAlso(config, subBeanInfo, typeName); + if (subSeeAlso != null) { + return subSeeAlso; + } + } + } + return null; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + protected static void parseArray(Collection collection, // + ObjectDeserializer deser, // + DefaultJSONParser parser, // + Type type, // + Object fieldName) { + + final JSONLexerBase lexer = (JSONLexerBase) parser.lexer; + int token = lexer.token(); + if (token == JSONToken.NULL) { + lexer.nextToken(JSONToken.COMMA); + token = lexer.token(); + return; + } + + if (token != JSONToken.LBRACKET) { + parser.throwException(token); + } + char ch = lexer.getCurrent(); + if (ch == '[') { + lexer.next(); + lexer.setToken(JSONToken.LBRACKET); + } else { + lexer.nextToken(JSONToken.LBRACKET); + } + + if (lexer.token() == JSONToken.RBRACKET) { + lexer.nextToken(); + return; + } + + int index = 0; + for (;;) { + Object item = deser.deserialze(parser, type, index); + collection.add(item); + index++; + if (lexer.token() == JSONToken.COMMA) { + ch = lexer.getCurrent(); + if (ch == '[') { + lexer.next(); + lexer.setToken(JSONToken.LBRACKET); + } else { + lexer.nextToken(JSONToken.LBRACKET); + } + } else { + break; + } + } + + token = lexer.token(); + if (token != JSONToken.RBRACKET) { + parser.throwException(token); + } + + ch = lexer.getCurrent(); + if (ch == ',') { + lexer.next(); + lexer.setToken(JSONToken.COMMA); + } else { + lexer.nextToken(JSONToken.COMMA); + } +// parser.accept(JSONToken.RBRACKET, JSONToken.COMMA); + } + } diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/JavaObjectDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/JavaObjectDeserializer.java index ebc39c26b8..fbca60aea1 100644 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/JavaObjectDeserializer.java +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/JavaObjectDeserializer.java @@ -1,8 +1,14 @@ package com.alibaba.fastjson.parser.deserializer; +import java.io.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.GenericArrayType; import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.util.ArrayList; +import java.util.List; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONToken; public class JavaObjectDeserializer implements ObjectDeserializer { @@ -10,8 +16,33 @@ public class JavaObjectDeserializer implements ObjectDeserializer { public final static JavaObjectDeserializer instance = new JavaObjectDeserializer(); @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - return (T) parser.parse(); + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + if (type instanceof GenericArrayType) { + Type componentType = ((GenericArrayType) type).getGenericComponentType(); + if (componentType instanceof TypeVariable) { + TypeVariable componentVar = (TypeVariable) componentType; + componentType = componentVar.getBounds()[0]; + } + + List list = new ArrayList(); + parser.parseArray(componentType, list); + Class componentClass; + if (componentType instanceof Class) { + componentClass = (Class) componentType; + Object[] array = (Object[]) Array.newInstance(componentClass, list.size()); + list.toArray(array); + return (T) array; + } else { + return (T) list.toArray(); + } + + } + + if (type instanceof Class && type != Object.class && type != Serializable.class) { + return (T) parser.parseObject(type); + } + + return (T) parser.parse(fieldName); } public int getFastMatchToken() { diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/Jdk8DateCodec.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/Jdk8DateCodec.java new file mode 100644 index 0000000000..63b0fd204a --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/Jdk8DateCodec.java @@ -0,0 +1,419 @@ +package com.alibaba.fastjson.parser.deserializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.OffsetTime; +import java.time.Period; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.TemporalAccessor; +import java.util.Locale; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.serializer.*; + +public class Jdk8DateCodec extends ContextObjectDeserializer implements ObjectSerializer, ContextObjectSerializer, ObjectDeserializer { + + public static final Jdk8DateCodec instance = new Jdk8DateCodec(); + + private final static String defaultPatttern = "yyyy-MM-dd HH:mm:ss"; + private final static DateTimeFormatter defaultFormatter = DateTimeFormatter.ofPattern(defaultPatttern); + private final static DateTimeFormatter formatter_dt19_tw = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); + private final static DateTimeFormatter formatter_dt19_cn = DateTimeFormatter.ofPattern("yyyy年M月d日 HH:mm:ss"); + private final static DateTimeFormatter formatter_dt19_cn_1 = DateTimeFormatter.ofPattern("yyyy年M月d日 H时m分s秒"); + private final static DateTimeFormatter formatter_dt19_kr = DateTimeFormatter.ofPattern("yyyy년M월d일 HH:mm:ss"); + private final static DateTimeFormatter formatter_dt19_us = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss"); + private final static DateTimeFormatter formatter_dt19_eur = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); + private final static DateTimeFormatter formatter_dt19_de = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"); + private final static DateTimeFormatter formatter_dt19_in = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); + + private final static DateTimeFormatter formatter_d8 = DateTimeFormatter.ofPattern("yyyyMMdd"); + private final static DateTimeFormatter formatter_d10_tw = DateTimeFormatter.ofPattern("yyyy/MM/dd"); + private final static DateTimeFormatter formatter_d10_cn = DateTimeFormatter.ofPattern("yyyy年M月d日"); + private final static DateTimeFormatter formatter_d10_kr = DateTimeFormatter.ofPattern("yyyy년M월d일"); + private final static DateTimeFormatter formatter_d10_us = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + private final static DateTimeFormatter formatter_d10_eur = DateTimeFormatter.ofPattern("dd/MM/yyyy"); + private final static DateTimeFormatter formatter_d10_de = DateTimeFormatter.ofPattern("dd.MM.yyyy"); + private final static DateTimeFormatter formatter_d10_in = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + private final static DateTimeFormatter ISO_FIXED_FORMAT = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()); + + private final static String formatter_iso8601_pattern = "yyyy-MM-dd'T'HH:mm:ss"; + private final static DateTimeFormatter formatter_iso8601 = DateTimeFormatter.ofPattern(formatter_iso8601_pattern); + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName, String format, int feature) { + JSONLexer lexer = parser.lexer; + if (lexer.token() == JSONToken.NULL){ + lexer.nextToken(); + return null; + } + + if (lexer.token() == JSONToken.LITERAL_STRING) { + String text = lexer.stringVal(); + lexer.nextToken(); + + DateTimeFormatter formatter = null; + if (format != null) { + if (defaultPatttern.equals(format)) { + formatter = defaultFormatter; + } else { + formatter = DateTimeFormatter.ofPattern(format); + } + } + + if ("".equals(text)) { + return null; + } + + if (type == LocalDateTime.class) { + LocalDateTime localDateTime; + if (text.length() == 10 || text.length() == 8) { + LocalDate localDate = parseLocalDate(text, format, formatter); + localDateTime = LocalDateTime.of(localDate, LocalTime.MIN); + } else { + localDateTime = parseDateTime(text, formatter); + } + return (T) localDateTime; + } else if (type == LocalDate.class) { + LocalDate localDate; + if (text.length() == 23) { + LocalDateTime localDateTime = LocalDateTime.parse(text); + localDate = LocalDate.of(localDateTime.getYear(), localDateTime.getMonthValue(), + localDateTime.getDayOfMonth()); + } else { + localDate = parseLocalDate(text, format, formatter); + } + + return (T) localDate; + } else if (type == LocalTime.class) { + LocalTime localDate; + if (text.length() == 23) { + LocalDateTime localDateTime = LocalDateTime.parse(text); + localDate = LocalTime.of(localDateTime.getHour(), localDateTime.getMinute(), + localDateTime.getSecond(), localDateTime.getNano()); + } else { + localDate = LocalTime.parse(text); + } + return (T) localDate; + } else if (type == ZonedDateTime.class) { + if (formatter == defaultFormatter) { + formatter = ISO_FIXED_FORMAT; + } + + ZonedDateTime zonedDateTime = parseZonedDateTime(text, formatter); + + return (T) zonedDateTime; + } else if (type == OffsetDateTime.class) { + OffsetDateTime offsetDateTime = OffsetDateTime.parse(text); + + return (T) offsetDateTime; + } else if (type == OffsetTime.class) { + OffsetTime offsetTime = OffsetTime.parse(text); + + return (T) offsetTime; + } else if (type == ZoneId.class) { + ZoneId offsetTime = ZoneId.of(text); + + return (T) offsetTime; + } else if (type == Period.class) { + Period period = Period.parse(text); + + return (T) period; + } else if (type == Duration.class) { + Duration duration = Duration.parse(text); + + return (T) duration; + } else if (type == Instant.class) { + Instant instant = Instant.parse(text); + + return (T) instant; + } + } else if (lexer.token() == JSONToken.LITERAL_INT) { + long millis = lexer.longValue(); + lexer.nextToken(); + + if (type == LocalDateTime.class) { + return (T) LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), JSON.defaultTimeZone.toZoneId()); + } + if (type == LocalDate.class) { + return (T) LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), JSON.defaultTimeZone.toZoneId()).toLocalDate(); + } + if (type == LocalTime.class) { + return (T) LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), JSON.defaultTimeZone.toZoneId()).toLocalTime(); + } + + throw new UnsupportedOperationException(); + } else { + throw new UnsupportedOperationException(); + } + return null; + } + + protected LocalDateTime parseDateTime(String text, DateTimeFormatter formatter) { + if (formatter == null) { + if (text.length() == 19) { + char c4 = text.charAt(4); + char c7 = text.charAt(7); + char c10 = text.charAt(10); + char c13 = text.charAt(13); + char c16 = text.charAt(16); + if (c13 == ':' && c16 == ':') { + if (c4 == '-' && c7 == '-') { + if (c10 == 'T') { + formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; + } else if (c10 == ' ') { + formatter = defaultFormatter; + } + } else if (c4 == '-' && c7 == '-') { + formatter = defaultFormatter; + } else if (c4 == '/' && c7 == '/') { // tw yyyy/mm/dd + formatter = formatter_dt19_tw; + } else { + char c0 = text.charAt(0); + char c1 = text.charAt(1); + char c2 = text.charAt(2); + char c3 = text.charAt(3); + char c5 = text.charAt(5); + if (c2 == '/' && c5 == '/') { // mm/dd/yyyy or mm/dd/yyyy + int v0 = (c0 - '0') * 10 + (c1 - '0'); + int v1 = (c3 - '0') * 10 + (c4 - '0'); + if (v0 > 12) { + formatter = formatter_dt19_eur; + } else if (v1 > 12) { + formatter = formatter_dt19_us; + } else { + String country = Locale.getDefault().getCountry(); + + if (country.equals("US")) { + formatter = formatter_dt19_us; + } else if (country.equals("BR") // + || country.equals("AU")) { + formatter = formatter_dt19_eur; + } + } + } else if (c2 == '.' && c5 == '.') { // dd.mm.yyyy + formatter = formatter_dt19_de; + } else if (c2 == '-' && c5 == '-') { // dd-mm-yyyy + formatter = formatter_dt19_in; + } + } + } + } + + if (text.length() >= 17) { + char c4 = text.charAt(4); + if (c4 == '年') { + if (text.charAt(text.length() - 1) == '秒') { + formatter = formatter_dt19_cn_1; + } else { + formatter = formatter_dt19_cn; + } + } else if (c4 == '년') { + formatter = formatter_dt19_kr; + } + } + } + + return formatter == null ? // + LocalDateTime.parse(text) // + : LocalDateTime.parse(text, formatter); + } + + protected LocalDate parseLocalDate(String text, String format, DateTimeFormatter formatter) { + if (formatter == null) { + if (text.length() == 8) { + formatter = formatter_d8; + } + + if (text.length() == 10) { + char c4 = text.charAt(4); + char c7 = text.charAt(7); + if (c4 == '/' && c7 == '/') { // tw yyyy/mm/dd + formatter = formatter_d10_tw; + } + + char c0 = text.charAt(0); + char c1 = text.charAt(1); + char c2 = text.charAt(2); + char c3 = text.charAt(3); + char c5 = text.charAt(5); + if (c2 == '/' && c5 == '/') { // mm/dd/yyyy or mm/dd/yyyy + int v0 = (c0 - '0') * 10 + (c1 - '0'); + int v1 = (c3 - '0') * 10 + (c4 - '0'); + if (v0 > 12) { + formatter = formatter_d10_eur; + } else if (v1 > 12) { + formatter = formatter_d10_us; + } else { + String country = Locale.getDefault().getCountry(); + + if (country.equals("US")) { + formatter = formatter_d10_us; + } else if (country.equals("BR") // + || country.equals("AU")) { + formatter = formatter_d10_eur; + } + } + } else if (c2 == '.' && c5 == '.') { // dd.mm.yyyy + formatter = formatter_d10_de; + } else if (c2 == '-' && c5 == '-') { // dd-mm-yyyy + formatter = formatter_d10_in; + } + } + + if (text.length() >= 9) { + char c4 = text.charAt(4); + if (c4 == '年') { + formatter = formatter_d10_cn; + } else if (c4 == '년') { + formatter = formatter_d10_kr; + } + } + } + + return formatter == null ? // + LocalDate.parse(text) // + : LocalDate.parse(text, formatter); + } + + protected ZonedDateTime parseZonedDateTime(String text, DateTimeFormatter formatter) { + if (formatter == null) { + if (text.length() == 19) { + char c4 = text.charAt(4); + char c7 = text.charAt(7); + char c10 = text.charAt(10); + char c13 = text.charAt(13); + char c16 = text.charAt(16); + if (c13 == ':' && c16 == ':') { + if (c4 == '-' && c7 == '-') { + if (c10 == 'T') { + formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; + } else if (c10 == ' ') { + formatter = defaultFormatter; + } + } else if (c4 == '-' && c7 == '-') { + formatter = defaultFormatter; + } else if (c4 == '/' && c7 == '/') { // tw yyyy/mm/dd + formatter = formatter_dt19_tw; + } else { + char c0 = text.charAt(0); + char c1 = text.charAt(1); + char c2 = text.charAt(2); + char c3 = text.charAt(3); + char c5 = text.charAt(5); + if (c2 == '/' && c5 == '/') { // mm/dd/yyyy or mm/dd/yyyy + int v0 = (c0 - '0') * 10 + (c1 - '0'); + int v1 = (c3 - '0') * 10 + (c4 - '0'); + if (v0 > 12) { + formatter = formatter_dt19_eur; + } else if (v1 > 12) { + formatter = formatter_dt19_us; + } else { + String country = Locale.getDefault().getCountry(); + + if (country.equals("US")) { + formatter = formatter_dt19_us; + } else if (country.equals("BR") // + || country.equals("AU")) { + formatter = formatter_dt19_eur; + } + } + } else if (c2 == '.' && c5 == '.') { // dd.mm.yyyy + formatter = formatter_dt19_de; + } else if (c2 == '-' && c5 == '-') { // dd-mm-yyyy + formatter = formatter_dt19_in; + } + } + } + } + + if (text.length() >= 17) { + char c4 = text.charAt(4); + if (c4 == '年') { + if (text.charAt(text.length() - 1) == '秒') { + formatter = formatter_dt19_cn_1; + } else { + formatter = formatter_dt19_cn; + } + } else if (c4 == '년') { + formatter = formatter_dt19_kr; + } + } + } + + return formatter == null ? // + ZonedDateTime.parse(text) // + : ZonedDateTime.parse(text, formatter); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_STRING; + } + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, + int features) throws IOException { + SerializeWriter out = serializer.out; + if (object == null) { + out.writeNull(); + } else { + if (fieldType == null) { + fieldType = object.getClass(); + } + + if (fieldType == LocalDateTime.class) { + final int mask = SerializerFeature.UseISO8601DateFormat.getMask(); + LocalDateTime dateTime = (LocalDateTime) object; + String format = serializer.getDateFormatPattern(); + + if (format == null && (features & mask) != 0 || serializer.isEnabled(SerializerFeature.UseISO8601DateFormat)) { + format = formatter_iso8601_pattern; + } + + if (dateTime.getNano() == 0 || format != null) { + + if (format == null) { + format = JSON.DEFFAULT_DATE_FORMAT; + } + write(out, dateTime, format); + } else if (out.isEnabled(SerializerFeature.WriteDateUseDateFormat)) { + //使用固定格式转化时间 + write(out, dateTime, JSON.DEFFAULT_DATE_FORMAT); + } else { + out.writeLong(dateTime.atZone(JSON.defaultTimeZone.toZoneId()).toInstant().toEpochMilli()); + } + } else { + out.writeString(object.toString()); + } + } + } + + public void write(JSONSerializer serializer, Object object, BeanContext context) throws IOException { + SerializeWriter out = serializer.out; + String format = context.getFormat(); + write(out, (TemporalAccessor) object, format); + } + + private void write(SerializeWriter out, TemporalAccessor object, String format) { + DateTimeFormatter formatter; + if (format == formatter_iso8601_pattern) { + formatter = formatter_iso8601; + } else { + formatter = DateTimeFormatter.ofPattern(format); + } + + String text = formatter.format((TemporalAccessor) object); + out.writeString(text); + } +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/LinkedHashMapDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/LinkedHashMapDeserializer.java deleted file mode 100644 index a90a656600..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/LinkedHashMapDeserializer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.LinkedHashMap; -import java.util.Map; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class LinkedHashMapDeserializer implements ObjectDeserializer { - public final static LinkedHashMapDeserializer instance = new LinkedHashMapDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Map map = new LinkedHashMap(); - parser.parseObject(map); - return (T) map; - } - - public int getFastMatchToken() { - return JSONToken.LBRACE; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/LocaleDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/LocaleDeserializer.java deleted file mode 100644 index b8057a44a9..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/LocaleDeserializer.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.Locale; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class LocaleDeserializer implements ObjectDeserializer { - public final static LocaleDeserializer instance = new LocaleDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - String text = (String) parser.parse(); - - if (text == null) { - return null; - } - - String[] items = text.split("_"); - - if (items.length == 1) { - return (T) new Locale(items[0]); - } - - if (items.length == 2) { - return (T) new Locale(items[0], items[1]); - } - - return (T) new Locale(items[0], items[1], items[2]); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_STRING; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/LongDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/LongDeserializer.java deleted file mode 100644 index 55a34b2276..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/LongDeserializer.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.TypeUtils; - -public class LongDeserializer implements ObjectDeserializer { - - public final static LongDeserializer instance = new LongDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - return (T) deserialze(parser); - } - - @SuppressWarnings("unchecked") - public static T deserialze(DefaultExtJSONParser parser) { - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.LITERAL_INT) { - long longValue = lexer.longValue(); - lexer.nextToken(JSONToken.COMMA); - return (T) Long.valueOf(longValue); - } - - Object value = parser.parse(); - - if (value == null) { - return null; - } - - return (T) TypeUtils.castToLong(value); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_INT; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/LongFieldDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/LongFieldDeserializer.java deleted file mode 100644 index b2e5b23138..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/LongFieldDeserializer.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.parser.ParserConfig; -import com.alibaba.fastjson.util.FieldInfo; -import com.alibaba.fastjson.util.TypeUtils; - -public class LongFieldDeserializer extends FieldDeserializer { - - private final ObjectDeserializer fieldValueDeserilizer; - - public LongFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo){ - super(clazz, fieldInfo); - - fieldValueDeserilizer = mapping.getDeserializer(fieldInfo); - } - - @Override - public void parseField(DefaultExtJSONParser parser, Object object) { - Long value; - - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.LITERAL_INT) { - long val = lexer.longValue(); - lexer.nextToken(JSONToken.COMMA); - setValue(object, val); - return; - } else if (lexer.token() == JSONToken.NULL) { - value = null; - lexer.nextToken(JSONToken.COMMA); - - } else { - Object obj = parser.parse(); - - value = TypeUtils.castToLong(obj); - } - - if (value == null && getFieldClass() == long.class) { - // skip - return; - } - - setValue(object, value); - } - - public int getFastMatchToken() { - return fieldValueDeserilizer.getFastMatchToken(); - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/MapDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/MapDeserializer.java new file mode 100644 index 0000000000..de43c0fd3c --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/MapDeserializer.java @@ -0,0 +1,371 @@ +package com.alibaba.fastjson.parser.deserializer; + +import java.lang.reflect.Constructor; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.*; +import com.alibaba.fastjson.parser.DefaultJSONParser.ResolveTask; +import com.alibaba.fastjson.serializer.CollectionCodec; +import com.alibaba.fastjson.util.TypeUtils; + +public class MapDeserializer implements ObjectDeserializer { + public static MapDeserializer instance = new MapDeserializer(); + + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + if (type == JSONObject.class && parser.getFieldTypeResolver() == null) { + return (T) parser.parseObject(); + } + + final JSONLexer lexer = parser.lexer; + if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(JSONToken.COMMA); + return null; + } + + Map map = createMap(type); + + ParseContext context = parser.getContext(); + + try { + parser.setContext(context, map, fieldName); + return (T) deserialze(parser, type, fieldName, map); + } finally { + parser.setContext(context); + } + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected Object deserialze(DefaultJSONParser parser, Type type, Object fieldName, Map map) { + if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) type; + Type keyType = parameterizedType.getActualTypeArguments()[0]; + Type valueType = null; + if(map.getClass().getName().equals("org.springframework.util.LinkedMultiValueMap")){ + valueType = List.class; + }else{ + valueType = parameterizedType.getActualTypeArguments()[1]; + } + if (String.class == keyType) { + return parseMap(parser, (Map) map, valueType, fieldName); + } else { + return parseMap(parser, map, keyType, valueType, fieldName); + } + } else { + return parser.parseObject(map, fieldName); + } + } + + @SuppressWarnings("rawtypes") + public static Map parseMap(DefaultJSONParser parser, Map map, Type valueType, Object fieldName) { + JSONLexer lexer = parser.lexer; + + int token = lexer.token(); + if (token != JSONToken.LBRACE) { + String msg = "syntax error, expect {, actual " + lexer.tokenName(); + if (fieldName instanceof String) { + msg += ", fieldName "; + msg += fieldName; + } + msg += ", "; + msg += lexer.info(); + + if (token != JSONToken.LITERAL_STRING) { + JSONArray array = new JSONArray(); + parser.parseArray(array, fieldName); + + if (array.size() == 1) { + Object first = array.get(0); + if (first instanceof JSONObject) { + return (JSONObject) first; + } + } + } + + throw new JSONException(msg); + } + + ParseContext context = parser.getContext(); + try { + for (int i = 0;;++i) { + lexer.skipWhitespace(); + char ch = lexer.getCurrent(); + if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { + while (ch == ',') { + lexer.next(); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + } + } + + String key; + if (ch == '"') { + key = lexer.scanSymbol(parser.getSymbolTable(), '"'); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + if (ch != ':') { + throw new JSONException("expect ':' at " + lexer.pos()); + } + } else if (ch == '}') { + lexer.next(); + lexer.resetStringPosition(); + lexer.nextToken(JSONToken.COMMA); + return map; + } else if (ch == '\'') { + if (!lexer.isEnabled(Feature.AllowSingleQuotes)) { + throw new JSONException("syntax error"); + } + + key = lexer.scanSymbol(parser.getSymbolTable(), '\''); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + if (ch != ':') { + throw new JSONException("expect ':' at " + lexer.pos()); + } + } else { + if (!lexer.isEnabled(Feature.AllowUnQuotedFieldNames)) { + throw new JSONException("syntax error"); + } + + key = lexer.scanSymbolUnQuoted(parser.getSymbolTable()); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + if (ch != ':') { + throw new JSONException("expect ':' at " + lexer.pos() + ", actual " + ch); + } + } + + lexer.next(); + lexer.skipWhitespace(); + ch = lexer.getCurrent(); + + lexer.resetStringPosition(); + + if (key == JSON.DEFAULT_TYPE_KEY && !lexer.isEnabled(Feature.DisableSpecialKeyDetect)) { + String typeName = lexer.scanSymbol(parser.getSymbolTable(), '"'); + final ParserConfig config = parser.getConfig(); + + Class clazz = config.checkAutoType(typeName, null, lexer.getFeatures()); + + if (Map.class.isAssignableFrom(clazz) ) { + lexer.nextToken(JSONToken.COMMA); + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + return map; + } + continue; + } + + ObjectDeserializer deserializer = config.getDeserializer(clazz); + + lexer.nextToken(JSONToken.COMMA); + + parser.setResolveStatus(DefaultJSONParser.TypeNameRedirect); + + if (context != null && !(fieldName instanceof Integer)) { + parser.popContext(); + } + + return (Map) deserializer.deserialze(parser, clazz, fieldName); + } + + Object value; + lexer.nextToken(); + + if (i != 0) { + parser.setContext(context); + } + + if (lexer.token() == JSONToken.NULL) { + value = null; + lexer.nextToken(); + } else { + value = parser.parseObject(valueType, key); + } + + map.put(key, value); + parser.checkMapResolve(map, key); + + parser.setContext(context, value, key); + parser.setContext(context); + + final int tok = lexer.token(); + if (tok == JSONToken.EOF || tok == JSONToken.RBRACKET) { + return map; + } + + if (tok == JSONToken.RBRACE) { + lexer.nextToken(); + return map; + } + } + } finally { + parser.setContext(context); + } + + } + + public static Object parseMap(DefaultJSONParser parser, Map map, Type keyType, Type valueType, + Object fieldName) { + JSONLexer lexer = parser.lexer; + + if (lexer.token() != JSONToken.LBRACE && lexer.token() != JSONToken.COMMA) { + throw new JSONException("syntax error, expect {, actual " + lexer.tokenName()); + } + + ObjectDeserializer keyDeserializer = parser.getConfig().getDeserializer(keyType); + ObjectDeserializer valueDeserializer = parser.getConfig().getDeserializer(valueType); + lexer.nextToken(keyDeserializer.getFastMatchToken()); + + ParseContext context = parser.getContext(); + try { + for (;;) { + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + break; + } + + if (lexer.token() == JSONToken.LITERAL_STRING // + && lexer.isRef() // + && !lexer.isEnabled(Feature.DisableSpecialKeyDetect) // + ) { + Object object = null; + + lexer.nextTokenWithColon(JSONToken.LITERAL_STRING); + if (lexer.token() == JSONToken.LITERAL_STRING) { + String ref = lexer.stringVal(); + if ("..".equals(ref)) { + ParseContext parentContext = context.parent; + object = parentContext.object; + } else if ("$".equals(ref)) { + ParseContext rootContext = context; + while (rootContext.parent != null) { + rootContext = rootContext.parent; + } + + object = rootContext.object; + } else { + parser.addResolveTask(new ResolveTask(context, ref)); + parser.setResolveStatus(DefaultJSONParser.NeedToResolve); + } + } else { + throw new JSONException("illegal ref, " + JSONToken.name(lexer.token())); + } + + lexer.nextToken(JSONToken.RBRACE); + if (lexer.token() != JSONToken.RBRACE) { + throw new JSONException("illegal ref"); + } + lexer.nextToken(JSONToken.COMMA); + + // parser.setContext(context, map, fieldName); + // parser.setContext(context); + + return object; + } + + if (map.size() == 0 // + && lexer.token() == JSONToken.LITERAL_STRING // + && JSON.DEFAULT_TYPE_KEY.equals(lexer.stringVal()) // + && !lexer.isEnabled(Feature.DisableSpecialKeyDetect)) { + lexer.nextTokenWithColon(JSONToken.LITERAL_STRING); + lexer.nextToken(JSONToken.COMMA); + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + return map; + } + lexer.nextToken(keyDeserializer.getFastMatchToken()); + } + + Object key = keyDeserializer.deserialze(parser, keyType, null); + + if (lexer.token() != JSONToken.COLON) { + throw new JSONException("syntax error, expect :, actual " + lexer.token()); + } + + lexer.nextToken(valueDeserializer.getFastMatchToken()); + + Object value = valueDeserializer.deserialze(parser, valueType, key); + parser.checkMapResolve(map, key); + + map.put(key, value); + + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(keyDeserializer.getFastMatchToken()); + } + } + } finally { + parser.setContext(context); + } + + return map; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public Map createMap(Type type) { + if (type == Properties.class) { + return new Properties(); + } + + if (type == Hashtable.class) { + return new Hashtable(); + } + + if (type == IdentityHashMap.class) { + return new IdentityHashMap(); + } + + if (type == SortedMap.class || type == TreeMap.class) { + return new TreeMap(); + } + + if (type == ConcurrentMap.class || type == ConcurrentHashMap.class) { + return new ConcurrentHashMap(); + } + + if (type == Map.class || type == HashMap.class) { + return new HashMap(); + } + + if (type == LinkedHashMap.class) { + return new LinkedHashMap(); + } + + if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) type; + + Type rawType = parameterizedType.getRawType(); + if (EnumMap.class.equals(rawType)) { + Type[] actualArgs = parameterizedType.getActualTypeArguments(); + return new EnumMap((Class) actualArgs[0]); + } + + return createMap(rawType); + } + + Class clazz = (Class) type; + if (clazz.isInterface()) { + throw new JSONException("unsupport type " + type); + } + + try { + return (Map) clazz.newInstance(); + } catch (Exception e) { + throw new JSONException("unsupport type " + type, e); + } + } + + + public int getFastMatchToken() { + return JSONToken.LBRACE; + } +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/NumberDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/NumberDeserializer.java old mode 100644 new mode 100755 index c56708f02c..d23c063374 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/NumberDeserializer.java +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/NumberDeserializer.java @@ -3,7 +3,9 @@ import java.lang.reflect.Type; import java.math.BigDecimal; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONLexer; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.util.TypeUtils; @@ -13,35 +15,104 @@ public class NumberDeserializer implements ObjectDeserializer { public final static NumberDeserializer instance = new NumberDeserializer(); @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - return (T) deserialze(parser); - } - - @SuppressWarnings("unchecked") - public static T deserialze(DefaultExtJSONParser parser) { - final JSONLexer lexer = parser.getLexer(); + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + final JSONLexer lexer = parser.lexer; if (lexer.token() == JSONToken.LITERAL_INT) { + if (clazz == double.class || clazz == Double.class) { + String val = lexer.numberString(); + lexer.nextToken(JSONToken.COMMA); + return (T) Double.valueOf(Double.parseDouble(val)); + } + long val = lexer.longValue(); lexer.nextToken(JSONToken.COMMA); - + + if (clazz == short.class || clazz == Short.class) { + if (val > Short.MAX_VALUE || val < Short.MIN_VALUE) { + throw new JSONException("short overflow : " + val); + } + return (T) Short.valueOf((short) val); + } + + if (clazz == byte.class || clazz == Byte.class) { + if (val > Byte.MAX_VALUE || val < Byte.MIN_VALUE) { + throw new JSONException("short overflow : " + val); + } + + return (T) Byte.valueOf((byte) val); + } + if (val >= Integer.MIN_VALUE && val <= Integer.MAX_VALUE) { - return (T) Integer.valueOf((int) val); + return (T) Integer.valueOf((int) val); } return (T) Long.valueOf(val); } if (lexer.token() == JSONToken.LITERAL_FLOAT) { + if (clazz == double.class || clazz == Double.class) { + String val = lexer.numberString(); + lexer.nextToken(JSONToken.COMMA); + return (T) Double.valueOf(Double.parseDouble(val)); + } + BigDecimal val = lexer.decimalValue(); lexer.nextToken(JSONToken.COMMA); + + if (clazz == short.class || clazz == Short.class) { + if (val.compareTo(BigDecimal.valueOf(Short.MAX_VALUE)) > 0 || val.compareTo(BigDecimal.valueOf(Short.MIN_VALUE)) < 0) { + throw new JSONException("short overflow : " + val); + } + return (T) Short.valueOf(val.shortValue()); + } + + if (clazz == byte.class || clazz == Byte.class) { + return (T) Byte.valueOf(val.byteValue()); + } + return (T) val; } + if (lexer.token() == JSONToken.IDENTIFIER && "NaN".equals(lexer.stringVal())) { + lexer.nextToken(); + Object nan = null; + if (clazz == Double.class) { + nan = Double.NaN; + } else if (clazz == Float.class) { + nan = Float.NaN; + } + return (T) nan; + } + Object value = parser.parse(); if (value == null) { return null; } + if (clazz == double.class || clazz == Double.class) { + try { + return (T) TypeUtils.castToDouble(value); + } catch (Exception ex) { + throw new JSONException("parseDouble error, field : " + fieldName, ex); + } + } + + if (clazz == short.class || clazz == Short.class) { + try { + return (T) TypeUtils.castToShort(value); + } catch (Exception ex) { + throw new JSONException("parseShort error, field : " + fieldName, ex); + } + } + + if (clazz == byte.class || clazz == Byte.class) { + try { + return (T) TypeUtils.castToByte(value); + } catch (Exception ex) { + throw new JSONException("parseByte error, field : " + fieldName, ex); + } + } + return (T) TypeUtils.castToBigDecimal(value); } diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ObjectDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ObjectDeserializer.java old mode 100644 new mode 100755 index 1c29402d01..dfc46d3d0c --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ObjectDeserializer.java +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/ObjectDeserializer.java @@ -2,10 +2,65 @@ import java.lang.reflect.Type; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; +/** + *

Interface representing a custom deserializer for Json. You should write a custom + * deserializer, if you are not happy with the default deserialization done by Gson. You will + * also need to register this deserializer through + * {@link ParserConfig#putDeserializer(Type, ObjectDeserializer)}.

+ *
+ * public static enum OrderActionEnum {
+ *     FAIL(1), SUCC(0);
+ * 
+ *     private int code;
+ * 
+ *     OrderActionEnum(int code){
+ *         this.code = code;
+ *     }
+ * }
+ * 
+ * public static class OrderActionEnumDeser implements ObjectDeserializer {
+ *     
+ *     public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
+ *         Integer intValue = parser.parseObject(int.class);
+ *         if (intValue == 1) {
+ *             return (T) OrderActionEnum.FAIL;
+ *         } else if (intValue == 0) {
+ *             return (T) OrderActionEnum.SUCC;
+ *         }
+ *         throw new IllegalStateException();
+ *     }
+ * 
+ *     
+ *     public int getFastMatchToken() {
+ *         return JSONToken.LITERAL_INT;
+ *     }
+ * }
+ * 
+ * + *

You will also need to register {@code OrderActionEnumDeser} to ParserConfig:

+ *
+ * ParserConfig.getGlobalInstance().putDeserializer(OrderActionEnum.class, new OrderActionEnumDeser());
+ * 
+ */ public interface ObjectDeserializer { - T deserialze(DefaultExtJSONParser parser, Type type); + /** + * fastjson invokes this call-back method during deserialization when it encounters a field of the + * specified type. + *

In the implementation of this call-back method, you should consider invoking + * {@link JSON#parseObject(String, Type, Feature[])} method to create objects + * for any non-trivial field of the returned object. + * + * @param parser context DefaultJSONParser being deserialized + * @param type The type of the Object to deserialize to + * @param fieldName parent object field name + * @return a deserialized object of the specified type which is a subclass of {@code T} + */ + T deserialze(DefaultJSONParser parser, Type type, Object fieldName); int getFastMatchToken(); } diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/OptionalCodec.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/OptionalCodec.java new file mode 100644 index 0000000000..4d74def1df --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/OptionalCodec.java @@ -0,0 +1,119 @@ +package com.alibaba.fastjson.parser.deserializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; +import java.util.OptionalLong; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import com.alibaba.fastjson.util.TypeUtils; + +public class OptionalCodec implements ObjectSerializer, ObjectDeserializer { + + public static OptionalCodec instance = new OptionalCodec(); + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + + if (type == OptionalInt.class) { + Object obj = parser.parseObject(Integer.class); + Integer value = TypeUtils.castToInt(obj); + if (value == null) { + return (T) OptionalInt.empty(); + } else { + return (T) OptionalInt.of(value); + } + } + + if (type == OptionalLong.class) { + Object obj = parser.parseObject(Long.class); + Long value = TypeUtils.castToLong(obj); + if (value == null) { + return (T) OptionalLong.empty(); + } else { + return (T) OptionalLong.of(value); + } + } + + if (type == OptionalDouble.class) { + Object obj = parser.parseObject(Double.class); + Double value = TypeUtils.castToDouble(obj); + if (value == null) { + return (T) OptionalDouble.empty(); + } else { + return (T) OptionalDouble.of(value); + } + } + + type = TypeUtils.unwrapOptional(type); + Object value = parser.parseObject(type); + + if (value == null) { + return (T) Optional.empty(); + } + + return (T) Optional.of(value); + } + + public int getFastMatchToken() { + return JSONToken.LBRACE; + } + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, + int features) throws IOException { + + if (object == null) { + serializer.writeNull(); + return; + } + + if (object instanceof Optional) { + Optional optional = (Optional) object; + Object value = optional.isPresent() ? optional.get() : null; + serializer.write(value); + return; + } + + if (object instanceof OptionalDouble) { + OptionalDouble optional = (OptionalDouble) object; + if (optional.isPresent()) { + double value = optional.getAsDouble(); + serializer.write(value); + } else { + serializer.writeNull(); + } + return; + } + + if (object instanceof OptionalInt) { + OptionalInt optional = (OptionalInt) object; + if (optional.isPresent()) { + int value = optional.getAsInt(); + serializer.out.writeInt(value); + } else { + serializer.writeNull(); + } + return; + } + + if (object instanceof OptionalLong) { + OptionalLong optional = (OptionalLong) object; + if (optional.isPresent()) { + long value = optional.getAsLong(); + serializer.out.writeLong(value); + } else { + serializer.writeNull(); + } + return; + } + + throw new JSONException("not support optional : " + object.getClass()); + } + +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ParseProcess.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ParseProcess.java new file mode 100644 index 0000000000..c2273f6d0c --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/ParseProcess.java @@ -0,0 +1,6 @@ +package com.alibaba.fastjson.parser.deserializer; + + +public interface ParseProcess { + +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/PatternDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/PatternDeserializer.java deleted file mode 100644 index 61b92b8727..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/PatternDeserializer.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.regex.Pattern; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class PatternDeserializer implements ObjectDeserializer { - public final static PatternDeserializer instance = new PatternDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Object value = parser.parse(); - - if (value == null) { - return null; - } - - String pattern = (String) value; - - return (T) Pattern.compile(pattern); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_STRING; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/PropertyProcessable.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/PropertyProcessable.java new file mode 100644 index 0000000000..facad6ecf9 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/PropertyProcessable.java @@ -0,0 +1,22 @@ +package com.alibaba.fastjson.parser.deserializer; + +import java.lang.reflect.Type; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public interface PropertyProcessable extends ParseProcess { + /** + * provide property's type, {@code java.lang.Class} or {@code Type} + * @param name property name + * @return property's type + */ + Type getType(String name); + + /** + * apply property name and value + * @param name property name + * @param value property name + */ + void apply(String name, Object value); +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/PropertyProcessableDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/PropertyProcessableDeserializer.java new file mode 100644 index 0000000000..5c541a63a8 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/PropertyProcessableDeserializer.java @@ -0,0 +1,35 @@ +package com.alibaba.fastjson.parser.deserializer; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; + +import java.lang.reflect.Type; + +/** + * Created by wenshao on 15/07/2017. + */ +public class PropertyProcessableDeserializer implements ObjectDeserializer { + public final Class type; + + public PropertyProcessableDeserializer(Class type) { + this.type = type; + } + + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + PropertyProcessable processable; + try { + processable = this.type.newInstance(); + } catch (Exception e) { + throw new JSONException("craete instance error"); + } + + Object object =parser.parse(processable, fieldName); + + return (T) object; + } + + public int getFastMatchToken() { + return JSONToken.LBRACE; + } +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ResolveFieldDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ResolveFieldDeserializer.java new file mode 100644 index 0000000000..6e29c0c509 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/ResolveFieldDeserializer.java @@ -0,0 +1,101 @@ +package com.alibaba.fastjson.parser.deserializer; + +import java.lang.reflect.Array; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.util.TypeUtils; + +@SuppressWarnings("rawtypes") +public final class ResolveFieldDeserializer extends FieldDeserializer { + + private final int index; + private final List list; + private final DefaultJSONParser parser; + + private final Object key; + private final Map map; + + private final Collection collection; + + public ResolveFieldDeserializer(DefaultJSONParser parser, List list, int index){ + super(null, null); + this.parser = parser; + this.index = index; + this.list = list; + + key = null; + map = null; + + collection = null; + } + + public ResolveFieldDeserializer(Map map, Object index){ + super(null, null); + + this.parser = null; + this.index = -1; + this.list = null; + + this.key = index; + this.map = map; + + collection = null; + } + + public ResolveFieldDeserializer(Collection collection){ + super(null, null); + + this.parser = null; + this.index = -1; + this.list = null; + + key = null; + map = null; + + this.collection = collection; + } + + @SuppressWarnings("unchecked") + public void setValue(Object object, Object value) { + if (map != null) { + map.put(key, value); + return; + } + + if (collection != null) { + collection.add(value); + return; + } + + list.set(index, value); + + if (list instanceof JSONArray) { + JSONArray jsonArray = (JSONArray) list; + Object array = jsonArray.getRelatedArray(); + + if (array != null) { + int arrayLength = Array.getLength(array); + + if (arrayLength > index) { + Object item; + if (jsonArray.getComponentType() != null) { + item = TypeUtils.cast(value, jsonArray.getComponentType(), parser.getConfig()); + } else { + item = value; + } + Array.set(array, index, item); + } + } + } + } + + public void parseField(DefaultJSONParser parser, Object object, Type objectType, Map fieldValues) { + + } + +} \ No newline at end of file diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ShortDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ShortDeserializer.java deleted file mode 100644 index 76866b12a0..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ShortDeserializer.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.util.TypeUtils; - -public class ShortDeserializer implements ObjectDeserializer { - public final static ShortDeserializer instance = new ShortDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Object value = parser.parse(); - - if (value == null) { - return null; - } - - return (T) TypeUtils.castToShort(value); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_INT; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/SqlDateDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/SqlDateDeserializer.java old mode 100644 new mode 100755 index 58ed55cf02..254a36858e --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/SqlDateDeserializer.java +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/SqlDateDeserializer.java @@ -1,22 +1,40 @@ package com.alibaba.fastjson.parser.deserializer; import java.lang.reflect.Type; +import java.text.DateFormat; +import java.text.ParseException; import java.util.Date; import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONScanner; import com.alibaba.fastjson.parser.JSONToken; -public class SqlDateDeserializer implements ObjectDeserializer { +public class SqlDateDeserializer extends AbstractDateDeserializer implements ObjectDeserializer { + public final static SqlDateDeserializer instance = new SqlDateDeserializer(); + public final static SqlDateDeserializer instance_timestamp = new SqlDateDeserializer(true); + + private boolean timestamp = false; + + public SqlDateDeserializer() { + + } + + public SqlDateDeserializer(boolean timestmap) { + this.timestamp = true; + } @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Object val = parser.parse(); + protected T cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object val) { + if (timestamp) { + return castTimestamp(parser, clazz, fieldName, val); + } + if (val == null) { return null; } - + if (val instanceof java.util.Date) { val = new java.sql.Date(((Date) val).getTime()); } else if (val instanceof Number) { @@ -26,8 +44,29 @@ public T deserialze(DefaultExtJSONParser parser, Type clazz) { if (strVal.length() == 0) { return null; } - - long longVal = Long.parseLong(strVal); + + long longVal; + + JSONScanner dateLexer = new JSONScanner(strVal); + try { + if (dateLexer.scanISO8601DateIfMatch()) { + longVal = dateLexer.getCalendar().getTimeInMillis(); + } else { + + DateFormat dateFormat = parser.getDateFormat(); + try { + java.util.Date date = (java.util.Date) dateFormat.parse(strVal); + java.sql.Date sqlDate = new java.sql.Date(date.getTime()); + return (T) sqlDate; + } catch (ParseException e) { + // skip + } + + longVal = Long.parseLong(strVal); + } + } finally { + dateLexer.close(); + } return (T) new java.sql.Date(longVal); } else { throw new JSONException("parse error : " + val); @@ -35,6 +74,55 @@ public T deserialze(DefaultExtJSONParser parser, Type clazz) { return (T) val; } + + @SuppressWarnings("unchecked") + protected T castTimestamp(DefaultJSONParser parser, Type clazz, Object fieldName, Object val) { + + if (val == null) { + return null; + } + + if (val instanceof java.util.Date) { + return (T) new java.sql.Timestamp(((Date) val).getTime()); + } + + if (val instanceof Number) { + return (T) new java.sql.Timestamp(((Number) val).longValue()); + } + + if (val instanceof String) { + String strVal = (String) val; + if (strVal.length() == 0) { + return null; + } + + long longVal; + JSONScanner dateLexer = new JSONScanner(strVal); + try { + if (dateLexer.scanISO8601DateIfMatch()) { + longVal = dateLexer.getCalendar().getTimeInMillis(); + } else { + + DateFormat dateFormat = parser.getDateFormat(); + try { + java.util.Date date = (java.util.Date) dateFormat.parse(strVal); + java.sql.Timestamp sqlDate = new java.sql.Timestamp(date.getTime()); + return (T) sqlDate; + } catch (ParseException e) { + // skip + } + + longVal = Long.parseLong(strVal); + } + } finally { + dateLexer.close(); + } + + return (T) new java.sql.Timestamp(longVal); + } + + throw new JSONException("parse error"); + } public int getFastMatchToken() { return JSONToken.LITERAL_INT; diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/StackTraceElementDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/StackTraceElementDeserializer.java new file mode 100755 index 0000000000..397dd2ac87 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/StackTraceElementDeserializer.java @@ -0,0 +1,145 @@ +package com.alibaba.fastjson.parser.deserializer; + +import java.lang.reflect.Type; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; + +public class StackTraceElementDeserializer implements ObjectDeserializer { + + public final static StackTraceElementDeserializer instance = new StackTraceElementDeserializer(); + + @SuppressWarnings({ "unchecked", "unused" }) + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + JSONLexer lexer = parser.lexer; + if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(); + return null; + } + + if (lexer.token() != JSONToken.LBRACE && lexer.token() != JSONToken.COMMA) { + throw new JSONException("syntax error: " + JSONToken.name(lexer.token())); + } + + String declaringClass = null; + String methodName = null; + String fileName = null; + int lineNumber = 0; + String moduleName = null; + String moduleVersion = null; + String classLoaderName = null; + + for (;;) { + // lexer.scanSymbol + String key = lexer.scanSymbol(parser.getSymbolTable()); + + if (key == null) { + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + break; + } + if (lexer.token() == JSONToken.COMMA) { + if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { + continue; + } + } + } + + lexer.nextTokenWithColon(JSONToken.LITERAL_STRING); + if ("className".equals(key)) { + if (lexer.token() == JSONToken.NULL) { + declaringClass = null; + } else if (lexer.token() == JSONToken.LITERAL_STRING) { + declaringClass = lexer.stringVal(); + } else { + throw new JSONException("syntax error"); + } + } else if ("methodName".equals(key)) { + if (lexer.token() == JSONToken.NULL) { + methodName = null; + } else if (lexer.token() == JSONToken.LITERAL_STRING) { + methodName = lexer.stringVal(); + } else { + throw new JSONException("syntax error"); + } + } else if ("fileName".equals(key)) { + if (lexer.token() == JSONToken.NULL) { + fileName = null; + } else if (lexer.token() == JSONToken.LITERAL_STRING) { + fileName = lexer.stringVal(); + } else { + throw new JSONException("syntax error"); + } + } else if ("lineNumber".equals(key)) { + if (lexer.token() == JSONToken.NULL) { + lineNumber = 0; + } else if (lexer.token() == JSONToken.LITERAL_INT) { + lineNumber = lexer.intValue(); + } else { + throw new JSONException("syntax error"); + } + } else if ("nativeMethod".equals(key)) { + if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(JSONToken.COMMA); + } else if (lexer.token() == JSONToken.TRUE) { + lexer.nextToken(JSONToken.COMMA); + } else if (lexer.token() == JSONToken.FALSE) { + lexer.nextToken(JSONToken.COMMA); + } else { + throw new JSONException("syntax error"); + } + } else if (key == JSON.DEFAULT_TYPE_KEY) { + if (lexer.token() == JSONToken.LITERAL_STRING) { + String elementType = lexer.stringVal(); + if (!elementType.equals("java.lang.StackTraceElement")) { + throw new JSONException("syntax error : " + elementType); + } + } else { + if (lexer.token() != JSONToken.NULL) { + throw new JSONException("syntax error"); + } + } + } else if ("moduleName".equals(key)) { + if (lexer.token() == JSONToken.NULL) { + moduleName = null; + } else if (lexer.token() == JSONToken.LITERAL_STRING) { + moduleName = lexer.stringVal(); + } else { + throw new JSONException("syntax error"); + } + } else if ("moduleVersion".equals(key)) { + if (lexer.token() == JSONToken.NULL) { + moduleVersion = null; + } else if (lexer.token() == JSONToken.LITERAL_STRING) { + moduleVersion = lexer.stringVal(); + } else { + throw new JSONException("syntax error"); + } + } else if ("classLoaderName".equals(key)) { + if (lexer.token() == JSONToken.NULL) { + classLoaderName = null; + } else if (lexer.token() == JSONToken.LITERAL_STRING) { + classLoaderName = lexer.stringVal(); + } else { + throw new JSONException("syntax error"); + } + } else { + throw new JSONException("syntax error : " + key); + } + + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + break; + } + } + return (T) new StackTraceElement(declaringClass, methodName, fileName, lineNumber); + } + + public int getFastMatchToken() { + return JSONToken.LBRACE; + } +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/StringDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/StringDeserializer.java deleted file mode 100644 index 3d3be4cbfb..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/StringDeserializer.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; - -public class StringDeserializer implements ObjectDeserializer { - - public final static StringDeserializer instance = new StringDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - return (T) deserialze(parser); - } - - @SuppressWarnings("unchecked") - public static T deserialze(DefaultExtJSONParser parser) { - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.LITERAL_STRING) { - String val = lexer.stringVal(); - lexer.nextToken(JSONToken.COMMA); - return (T) val; - } - - if (lexer.token() == JSONToken.LITERAL_INT) { - String val = lexer.numberString(); - lexer.nextToken(JSONToken.COMMA); - return (T) val; - } - - Object value = parser.parse(); - - if (value == null) { - return null; - } - - return (T) value.toString(); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_STRING; - } - -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/StringFieldDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/StringFieldDeserializer.java deleted file mode 100644 index 12dec3a71a..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/StringFieldDeserializer.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONLexer; -import com.alibaba.fastjson.parser.JSONToken; -import com.alibaba.fastjson.parser.ParserConfig; -import com.alibaba.fastjson.util.FieldInfo; - -public class StringFieldDeserializer extends FieldDeserializer { - - private final ObjectDeserializer fieldValueDeserilizer; - - public StringFieldDeserializer(ParserConfig config, Class clazz, FieldInfo fieldInfo){ - super(clazz, fieldInfo); - - fieldValueDeserilizer = config.getDeserializer(fieldInfo); - } - - @Override - public void parseField(DefaultExtJSONParser parser, Object object) { - String value; - - final JSONLexer lexer = parser.getLexer(); - if (lexer.token() == JSONToken.LITERAL_STRING) { - value = lexer.stringVal(); - lexer.nextToken(JSONToken.COMMA); - } else { - - Object obj = parser.parse(); - - if (obj == null) { - value = null; - } else { - value = obj.toString(); - } - } - - setValue(object, value); - } - - public int getFastMatchToken() { - return fieldValueDeserilizer.getFastMatchToken(); - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/ThrowableDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/ThrowableDeserializer.java old mode 100644 new mode 100755 index 6ea442b326..9ac9b6b6c0 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/ThrowableDeserializer.java +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/ThrowableDeserializer.java @@ -1,22 +1,198 @@ package com.alibaba.fastjson.parser.deserializer; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.JSONLexer; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.JavaBeanSerializer; import com.alibaba.fastjson.util.TypeUtils; public class ThrowableDeserializer extends JavaBeanDeserializer { public ThrowableDeserializer(ParserConfig mapping, Class clazz){ - super(mapping, clazz); + super(mapping, clazz, clazz); } @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Object jsonValue = parser.parse(); - return (T) TypeUtils.cast(jsonValue, clazz, parser.getConfig()); + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + JSONLexer lexer = parser.lexer; + + if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(); + return null; + } + + if (parser.getResolveStatus() == DefaultJSONParser.TypeNameRedirect) { + parser.setResolveStatus(DefaultJSONParser.NONE); + } else { + if (lexer.token() != JSONToken.LBRACE) { + throw new JSONException("syntax error"); + } + } + + Throwable cause = null; + Class exClass = null; + + if (type != null && type instanceof Class) { + Class clazz = (Class) type; + if (Throwable.class.isAssignableFrom(clazz)) { + exClass = clazz; + } + } + + String message = null; + StackTraceElement[] stackTrace = null; + Map otherValues = null; + + + for (;;) { + // lexer.scanSymbol + String key = lexer.scanSymbol(parser.getSymbolTable()); + + if (key == null) { + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + break; + } + if (lexer.token() == JSONToken.COMMA) { + if (lexer.isEnabled(Feature.AllowArbitraryCommas)) { + continue; + } + } + } + + lexer.nextTokenWithColon(JSONToken.LITERAL_STRING); + + if (JSON.DEFAULT_TYPE_KEY.equals(key)) { + if (lexer.token() == JSONToken.LITERAL_STRING) { + String exClassName = lexer.stringVal(); + exClass = parser.getConfig().checkAutoType(exClassName, Throwable.class, lexer.getFeatures()); + } else { + throw new JSONException("syntax error"); + } + lexer.nextToken(JSONToken.COMMA); + } else if ("message".equals(key)) { + if (lexer.token() == JSONToken.NULL) { + message = null; + } else if (lexer.token() == JSONToken.LITERAL_STRING) { + message = lexer.stringVal(); + } else { + throw new JSONException("syntax error"); + } + lexer.nextToken(); + } else if ("cause".equals(key)) { + cause = deserialze(parser, null, "cause"); + } else if ("stackTrace".equals(key)) { + stackTrace = parser.parseObject(StackTraceElement[].class); + } else { + if (otherValues == null) { + otherValues = new HashMap(); + } + otherValues.put(key, parser.parse()); + } + + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(JSONToken.COMMA); + break; + } + } + + Throwable ex = null; + if (exClass == null) { + ex = new Exception(message, cause); + } else { + if (!Throwable.class.isAssignableFrom(exClass)) { + throw new JSONException("type not match, not Throwable. " + exClass.getName()); + } + + try { + ex = createException(message, cause, exClass); + if (ex == null) { + ex = new Exception(message, cause); + } + } catch (Exception e) { + throw new JSONException("create instance error", e); + } + } + + if (stackTrace != null) { + ex.setStackTrace(stackTrace); + } + + if (otherValues != null) { + JavaBeanDeserializer exBeanDeser = null; + + if (exClass != null) { + if (exClass == clazz) { + exBeanDeser = this; + } else { + ObjectDeserializer exDeser = parser.getConfig().getDeserializer(exClass); + if (exDeser instanceof JavaBeanDeserializer) { + exBeanDeser = (JavaBeanDeserializer) exDeser; + } + } + } + + if (exBeanDeser != null) { + for (Map.Entry entry : otherValues.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + FieldDeserializer fieldDeserializer = exBeanDeser.getFieldDeserializer(key); + if (fieldDeserializer != null) { + fieldDeserializer.setValue(ex, value); + } + } + } + } + + return (T) ex; + } + + private Throwable createException(String message, Throwable cause, Class exClass) throws Exception { + Constructor defaultConstructor = null; + Constructor messageConstructor = null; + Constructor causeConstructor = null; + for (Constructor constructor : exClass.getConstructors()) { + Class[] types = constructor.getParameterTypes(); + if (types.length == 0) { + defaultConstructor = constructor; + continue; + } + + if (types.length == 1 && types[0] == String.class) { + messageConstructor = constructor; + continue; + } + + if (types.length == 2 && types[0] == String.class && types[1] == Throwable.class) { + causeConstructor = constructor; + continue; + } + } + + if (causeConstructor != null) { + return (Throwable) causeConstructor.newInstance(message, cause); + } + + if (messageConstructor != null) { + return (Throwable) messageConstructor.newInstance(message); + } + + if (defaultConstructor != null) { + return (Throwable) defaultConstructor.newInstance(); + } + + return null; } public int getFastMatchToken() { diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/TimeDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/TimeDeserializer.java new file mode 100755 index 0000000000..e938969ee6 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/parser/deserializer/TimeDeserializer.java @@ -0,0 +1,88 @@ +package com.alibaba.fastjson.parser.deserializer; + +import java.lang.reflect.Type; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONScanner; +import com.alibaba.fastjson.parser.JSONToken; + +public class TimeDeserializer implements ObjectDeserializer { + + public final static TimeDeserializer instance = new TimeDeserializer(); + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + JSONLexer lexer = parser.lexer; + + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(JSONToken.LITERAL_STRING); + + if (lexer.token() != JSONToken.LITERAL_STRING) { + throw new JSONException("syntax error"); + } + + lexer.nextTokenWithColon(JSONToken.LITERAL_INT); + + if (lexer.token() != JSONToken.LITERAL_INT) { + throw new JSONException("syntax error"); + } + + long time = lexer.longValue(); + lexer.nextToken(JSONToken.RBRACE); + if (lexer.token() != JSONToken.RBRACE) { + throw new JSONException("syntax error"); + } + lexer.nextToken(JSONToken.COMMA); + + return (T) new java.sql.Time(time); + } + + Object val = parser.parse(); + + if (val == null) { + return null; + } + + if (val instanceof java.sql.Time) { + return (T) val; + } else if (val instanceof Number) { + return (T) new java.sql.Time(((Number) val).longValue()); + } else if (val instanceof String) { + String strVal = (String) val; + if (strVal.length() == 0) { + return null; + } + + long longVal; + JSONScanner dateLexer = new JSONScanner(strVal); + if (dateLexer.scanISO8601DateIfMatch()) { + longVal = dateLexer.getCalendar().getTimeInMillis(); + } else { + boolean isDigit = true; + for (int i = 0; i< strVal.length(); ++i) { + char ch = strVal.charAt(i); + if (ch < '0' || ch > '9') { + isDigit = false; + break; + } + } + if (!isDigit) { + dateLexer.close(); + return (T) java.sql.Time.valueOf(strVal); + } + + longVal = Long.parseLong(strVal); + } + dateLexer.close(); + return (T) new java.sql.Time(longVal); + } + + throw new JSONException("parse error"); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_INT; + } +} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/TimeZoneDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/TimeZoneDeserializer.java deleted file mode 100644 index fc6eef3ab8..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/TimeZoneDeserializer.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.TimeZone; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class TimeZoneDeserializer implements ObjectDeserializer { - public final static TimeZoneDeserializer instance = new TimeZoneDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - - String id = (String) parser.parse(); - - if (id == null) { - return null; - } - - return (T) TimeZone.getTimeZone(id); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_STRING; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/TimestampDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/TimestampDeserializer.java deleted file mode 100644 index be1170ed28..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/TimestampDeserializer.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.Date; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class TimestampDeserializer implements ObjectDeserializer { - - public final static TimestampDeserializer instance = new TimestampDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Object val = parser.parse(); - - if (val == null) { - return null; - } - - if (val instanceof java.util.Date) { - return (T) new java.sql.Timestamp(((Date) val).getTime()); - } - - if (val instanceof Number) { - return (T) new java.sql.Timestamp(((Number) val).longValue()); - } - - if (val instanceof String) { - String strVal = (String) val; - if (strVal.length() == 0) { - return null; - } - - long longVal = Long.parseLong(strVal); - return (T) new java.sql.Timestamp(longVal); - } - - throw new JSONException("parse error"); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_INT; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/TreeMapDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/TreeMapDeserializer.java deleted file mode 100644 index 6cd76753e3..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/TreeMapDeserializer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.Map; -import java.util.TreeMap; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class TreeMapDeserializer implements ObjectDeserializer { - public final static TreeMapDeserializer instance = new TreeMapDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - Map map = new TreeMap(); - parser.parseObject(map); - return (T) map; - } - - public int getFastMatchToken() { - return JSONToken.LBRACE; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/URIDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/URIDeserializer.java deleted file mode 100644 index 4beb43db28..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/URIDeserializer.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.net.URI; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class URIDeserializer implements ObjectDeserializer { - public final static URIDeserializer instance = new URIDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - - String uri = (String) parser.parse(); - - if (uri == null) { - return null; - } - - return (T) URI.create(uri); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_STRING; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/URLDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/URLDeserializer.java deleted file mode 100644 index 765e969ace..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/URLDeserializer.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.net.MalformedURLException; -import java.net.URL; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class URLDeserializer implements ObjectDeserializer { - public final static URLDeserializer instance = new URLDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - - String url = (String) parser.parse(); - - if (url == null) { - return null; - } - - try { - return (T) new URL(url); - } catch (MalformedURLException e) { - throw new JSONException("create url error", e); - } - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_STRING; - } -} diff --git a/src/main/java/com/alibaba/fastjson/parser/deserializer/UUIDDeserializer.java b/src/main/java/com/alibaba/fastjson/parser/deserializer/UUIDDeserializer.java deleted file mode 100644 index f0d610fff7..0000000000 --- a/src/main/java/com/alibaba/fastjson/parser/deserializer/UUIDDeserializer.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.alibaba.fastjson.parser.deserializer; - -import java.lang.reflect.Type; -import java.util.UUID; - -import com.alibaba.fastjson.parser.DefaultExtJSONParser; -import com.alibaba.fastjson.parser.JSONToken; - -public class UUIDDeserializer implements ObjectDeserializer { - public final static UUIDDeserializer instance = new UUIDDeserializer(); - - @SuppressWarnings("unchecked") - public T deserialze(DefaultExtJSONParser parser, Type clazz) { - - String name = (String) parser.parse(); - - if (name == null) { - return null; - } - - return (T) UUID.fromString(name); - } - - public int getFastMatchToken() { - return JSONToken.LITERAL_STRING; - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ASMSerializerFactory.java b/src/main/java/com/alibaba/fastjson/serializer/ASMSerializerFactory.java old mode 100644 new mode 100755 index 1ab39f483b..8e88be5fda --- a/src/main/java/com/alibaba/fastjson/serializer/ASMSerializerFactory.java +++ b/src/main/java/com/alibaba/fastjson/serializer/ASMSerializerFactory.java @@ -1,76 +1,74 @@ package com.alibaba.fastjson.serializer; -import static com.alibaba.fastjson.util.ASMUtils.getDesc; -import static com.alibaba.fastjson.util.ASMUtils.getType; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.asm.*; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.util.ASMClassLoader; +import com.alibaba.fastjson.util.ASMUtils; +import com.alibaba.fastjson.util.FieldInfo; +import com.alibaba.fastjson.util.TypeUtils; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; +import java.io.Serializable; +import java.lang.reflect.*; import java.lang.reflect.Type; import java.math.BigDecimal; -import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.annotation.JSONField; -import com.alibaba.fastjson.asm.ClassWriter; -import com.alibaba.fastjson.asm.Label; -import com.alibaba.fastjson.asm.MethodVisitor; -import com.alibaba.fastjson.asm.Opcodes; -import com.alibaba.fastjson.util.ASMClassLoader; -import com.alibaba.fastjson.util.FieldInfo; +import static com.alibaba.fastjson.util.ASMUtils.desc; +import static com.alibaba.fastjson.util.ASMUtils.type; public class ASMSerializerFactory implements Opcodes { - private ASMClassLoader classLoader = new ASMClassLoader(); + protected final ASMClassLoader classLoader = new ASMClassLoader(); - public ObjectSerializer createJavaBeanSerializer(Class clazz) throws Exception { - return createJavaBeanSerializer(clazz, (Map) null); - } + private final AtomicLong seed = new AtomicLong(); - private final AtomicLong seed = new AtomicLong(); - - public String getGenClassName(Class clazz) { - return "Serializer_" + seed.incrementAndGet(); - } + static final String JSONSerializer = type(JSONSerializer.class); + static final String ObjectSerializer = type(ObjectSerializer.class); + static final String ObjectSerializer_desc = "L" + ObjectSerializer + ";"; + static final String SerializeWriter = type(SerializeWriter.class); + static final String SerializeWriter_desc = "L" + SerializeWriter + ";"; + static final String JavaBeanSerializer = type(JavaBeanSerializer.class); + static final String JavaBeanSerializer_desc = "L" + type(JavaBeanSerializer.class) + ";"; + static final String SerialContext_desc = desc(SerialContext.class); + static final String SerializeFilterable_desc = desc(SerializeFilterable.class); static class Context { - public Context(){ - - } - - private int variantIndex = 6; - - private Map variants = new HashMap(); - - public int serializer() { - return 1; - } - - public int obj() { - return 2; - } - - public int fieldName() { - return 3; - } - - public int original() { - return 4; - } - - public int processValue() { - return 5; - } - - public int getVariantCount() { - return variantIndex; + static final int serializer = 1; + static final int obj = 2; + static final int paramFieldName = 3; + static final int paramFieldType = 4; + static final int features = 5; + static int fieldName = 6; + static int original = 7; + static int processValue = 8; + + private final FieldInfo[] getters; + private final String className; + private final SerializeBeanInfo beanInfo; + private final boolean writeDirect; + + private Map variants = new HashMap(); + private int variantIndex = 9; + private final boolean nonContext; + + public Context(FieldInfo[] getters, // + SerializeBeanInfo beanInfo, // + String className, // + boolean writeDirect, // + boolean nonContext){ + this.getters = getters; + this.className = className; + this.beanInfo = beanInfo; + this.writeDirect = writeDirect; + this.nonContext = nonContext || beanInfo.beanType.isEnum(); } public int var(String name) { @@ -91,123 +89,908 @@ public int var(String name, int increment) { i = variants.get(name); return i.intValue(); } + + public int getFieldOrinal(String name) { + int fieldIndex = -1; + for (int i = 0, size = getters.length; i < size; ++i) { + FieldInfo item = getters[i]; + if (item.name.equals(name)) { + fieldIndex = i; + break; + } + } + return fieldIndex; + } } - public ObjectSerializer createJavaBeanSerializer(Class clazz, Map aliasMap) throws Exception { + public JavaBeanSerializer createJavaBeanSerializer(SerializeBeanInfo beanInfo) throws Exception { + Class clazz = beanInfo.beanType; if (clazz.isPrimitive()) { throw new JSONException("unsupportd class " + clazz.getName()); } - - String className = getGenClassName(clazz); + + JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class); + + FieldInfo[] unsortedGetters = beanInfo.fields; + + for (FieldInfo fieldInfo : unsortedGetters) { + if (fieldInfo.field == null // + && fieldInfo.method != null // + && fieldInfo.method.getDeclaringClass().isInterface()) { + return new JavaBeanSerializer(beanInfo); + } + } + + FieldInfo[] getters = beanInfo.sortedFields; + + boolean nativeSorted = beanInfo.sortedFields == beanInfo.fields; + + if (getters.length > 256) { + return new JavaBeanSerializer(beanInfo); + } + + for (FieldInfo getter : getters) { + if (!ASMUtils.checkName(getter.getMember().getName())) { + return new JavaBeanSerializer(beanInfo); + } + } + + String className = "ASMSerializer_" + seed.incrementAndGet() + "_" + clazz.getSimpleName(); + String classNameType; + String classNameFull; + Package pkg = ASMSerializerFactory.class.getPackage(); + if (pkg != null) { + String packageName = pkg.getName(); + classNameType = packageName.replace('.', '/') + "/" + className; + classNameFull = packageName + "." + className; + } else { + classNameType = className; + classNameFull = className; + } + + String packageName = ASMSerializerFactory.class.getPackage().getName(); + ClassWriter cw = new ClassWriter(); - cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, className, "java/lang/Object", new String[] { "com/alibaba/fastjson/serializer/ObjectSerializer" }); + cw.visit(V1_5 // + , ACC_PUBLIC + ACC_SUPER // + , classNameType // + , JavaBeanSerializer // + , new String[] { ObjectSerializer } // + ); + + for (FieldInfo fieldInfo : getters) { + if (fieldInfo.fieldClass.isPrimitive() // + //|| fieldInfo.fieldClass.isEnum() // + || fieldInfo.fieldClass == String.class) { + continue; + } + + new FieldWriter(cw, ACC_PUBLIC, fieldInfo.name + "_asm_fieldType", "Ljava/lang/reflect/Type;") // + .visitEnd(); + + if (List.class.isAssignableFrom(fieldInfo.fieldClass)) { + new FieldWriter(cw, ACC_PUBLIC, fieldInfo.name + "_asm_list_item_ser_", + ObjectSerializer_desc) // + .visitEnd(); + } + + new FieldWriter(cw, ACC_PUBLIC, fieldInfo.name + "_asm_ser_", ObjectSerializer_desc) // + .visitEnd(); + } - MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); + MethodVisitor mw = new MethodWriter(cw, ACC_PUBLIC, "", "(" + desc(SerializeBeanInfo.class) + ")V", null, null); mw.visitVarInsn(ALOAD, 0); - mw.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V"); + mw.visitVarInsn(ALOAD, 1); + mw.visitMethodInsn(INVOKESPECIAL, JavaBeanSerializer, "", "(" + desc(SerializeBeanInfo.class) + ")V"); + + // init _asm_fieldType + for (int i = 0; i < getters.length; ++i) { + FieldInfo fieldInfo = getters[i]; + if (fieldInfo.fieldClass.isPrimitive() // +// || fieldInfo.fieldClass.isEnum() // + || fieldInfo.fieldClass == String.class) { + continue; + } + + mw.visitVarInsn(ALOAD, 0); + + if (fieldInfo.method != null) { + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldInfo.declaringClass))); + mw.visitLdcInsn(fieldInfo.method.getName()); + mw.visitMethodInsn(INVOKESTATIC, type(ASMUtils.class), "getMethodType", + "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/reflect/Type;"); + + } else { + mw.visitVarInsn(ALOAD, 0); + mw.visitLdcInsn(i); + mw.visitMethodInsn(INVOKESPECIAL, JavaBeanSerializer, "getFieldType", "(I)Ljava/lang/reflect/Type;"); + } + + mw.visitFieldInsn(PUTFIELD, classNameType, fieldInfo.name + "_asm_fieldType", "Ljava/lang/reflect/Type;"); + } + mw.visitInsn(RETURN); - mw.visitMaxs(1, 1); + mw.visitMaxs(4, 4); mw.visitEnd(); - { - Context context = new Context(); + boolean DisableCircularReferenceDetect = false; + if (jsonType != null) { + for (SerializerFeature featrues : jsonType.serialzeFeatures()) { + if (featrues == SerializerFeature.DisableCircularReferenceDetect) { + DisableCircularReferenceDetect = true; + break; + } + } + } - List getters = JavaBeanSerializer.computeGetters(clazz, aliasMap); + // 0 write + // 1 writeNormal + // 2 writeNonContext + for (int i = 0; i < 3; ++i) { + String methodName; + boolean nonContext = DisableCircularReferenceDetect; + boolean writeDirect = false; + if (i == 0) { + methodName = "write"; + writeDirect = true; + } else if (i == 1) { + methodName = "writeNormal"; + } else { + writeDirect = true; + nonContext = true; + methodName = "writeDirectNonContext"; + } - mw = cw.visitMethod(ACC_PUBLIC, "write", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;)V", null, new String[] { "java/io/IOException" }); + Context context = new Context(getters, beanInfo, classNameType, writeDirect, + nonContext); + + mw = new MethodWriter(cw, // + ACC_PUBLIC, // + methodName, // + "(L" + JSONSerializer + + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V", // + null, // + new String[] { "java/io/IOException" } // + ); + + { + Label endIf_ = new Label(); + mw.visitVarInsn(ALOAD, Context.obj); + //serializer.writeNull(); + mw.visitJumpInsn(IFNONNULL, endIf_); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, + "writeNull", "()V"); + + mw.visitInsn(RETURN); + mw.visitLabel(endIf_); + } - mw.visitVarInsn(ALOAD, context.serializer()); // serializer - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONSerializer.class), "getWriter", "()" + getDesc(SerializeWriter.class)); - mw.visitVarInsn(ASTORE, context.var("out")); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitFieldInsn(GETFIELD, JSONSerializer, "out", SerializeWriter_desc); + mw.visitVarInsn(ASTORE, context.var("out")); - Label _else = new Label(); + if ((!nativeSorted) // + && !context.writeDirect) { - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitFieldInsn(GETSTATIC, getType(SerializerFeature.class), "SortField", "L" + getType(SerializerFeature.class) + ";"); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "isEnabled", "(" + "L" + getType(SerializerFeature.class) + ";" + ")Z"); + if (jsonType == null || jsonType.alphabetic()) { + Label _else = new Label(); - mw.visitJumpInsn(IFEQ, _else); - mw.visitVarInsn(ALOAD, 0); - mw.visitVarInsn(ALOAD, 1); - mw.visitVarInsn(ALOAD, 2); - mw.visitMethodInsn(INVOKEVIRTUAL, className, "write1", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;)V"); - mw.visitInsn(RETURN); + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isSortField", "()Z"); - mw.visitLabel(_else); - mw.visitVarInsn(ALOAD, context.obj()); // obj - mw.visitTypeInsn(CHECKCAST, getType(clazz)); // serializer - mw.visitVarInsn(ASTORE, context.var("entity")); // obj + mw.visitJumpInsn(IFNE, _else); + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, 1); + mw.visitVarInsn(ALOAD, 2); + mw.visitVarInsn(ALOAD, 3); + mw.visitVarInsn(ALOAD, 4); + mw.visitVarInsn(ILOAD, 5); + mw.visitMethodInsn(INVOKEVIRTUAL, classNameType, + "writeUnsorted", "(L" + JSONSerializer + + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitInsn(RETURN); - generateWriteMethod(clazz, mw, getters, context); + mw.visitLabel(_else); + } + } + // isWriteDoubleQuoteDirect + if (context.writeDirect && !nonContext) { + Label _direct = new Label(); + Label _directElse = new Label(); + + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "writeDirect", "(L" + JSONSerializer + ";)Z"); + mw.visitJumpInsn(IFNE, _directElse); + + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, 1); + mw.visitVarInsn(ALOAD, 2); + mw.visitVarInsn(ALOAD, 3); + mw.visitVarInsn(ALOAD, 4); + mw.visitVarInsn(ILOAD, 5); + mw.visitMethodInsn(INVOKEVIRTUAL, classNameType, + "writeNormal", "(L" + JSONSerializer + + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitInsn(RETURN); + + mw.visitLabel(_directElse); + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitLdcInsn(SerializerFeature.DisableCircularReferenceDetect.mask); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isEnabled", "(I)Z"); + mw.visitJumpInsn(IFEQ, _direct); + + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, 1); + mw.visitVarInsn(ALOAD, 2); + mw.visitVarInsn(ALOAD, 3); + mw.visitVarInsn(ALOAD, 4); + mw.visitVarInsn(ILOAD, 5); + mw.visitMethodInsn(INVOKEVIRTUAL, classNameType, "writeDirectNonContext", + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitInsn(RETURN); + + mw.visitLabel(_direct); + } + + mw.visitVarInsn(ALOAD, Context.obj); // obj + mw.visitTypeInsn(CHECKCAST, type(clazz)); // serializer + mw.visitVarInsn(ASTORE, context.var("entity")); // obj + generateWriteMethod(clazz, mw, getters, context); mw.visitInsn(RETURN); - mw.visitMaxs(5, context.getVariantCount() + 1); + mw.visitMaxs(7, context.variantIndex + 2); mw.visitEnd(); } - { + if (!nativeSorted) { // sortField support - Context context = new Context(); + Context context = new Context(getters, beanInfo, classNameType, false, + DisableCircularReferenceDetect); - List getters = JavaBeanSerializer.computeGetters(clazz, aliasMap); - Collections.sort(getters); + mw = new MethodWriter(cw, ACC_PUBLIC, "writeUnsorted", + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V", + null, new String[] { "java/io/IOException" }); - mw = cw.visitMethod(ACC_PUBLIC, "write1", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;)V", null, new String[] { "java/io/IOException" }); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitFieldInsn(GETFIELD, JSONSerializer, "out", SerializeWriter_desc); + mw.visitVarInsn(ASTORE, context.var("out")); - mw.visitVarInsn(ALOAD, context.serializer()); // serializer - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONSerializer.class), "getWriter", "()" + getDesc(SerializeWriter.class)); - mw.visitVarInsn(ASTORE, context.var("out")); - - mw.visitVarInsn(ALOAD, context.obj()); // obj - mw.visitTypeInsn(CHECKCAST, getType(clazz)); // serializer + mw.visitVarInsn(ALOAD, Context.obj); // obj + mw.visitTypeInsn(CHECKCAST, type(clazz)); // serializer mw.visitVarInsn(ASTORE, context.var("entity")); // obj - generateWriteMethod(clazz, mw, getters, context); + generateWriteMethod(clazz, mw, unsortedGetters, context); mw.visitInsn(RETURN); - mw.visitMaxs(5, context.getVariantCount() + 1); + mw.visitMaxs(7, context.variantIndex + 2); + mw.visitEnd(); + } + + // 0 writeAsArray + // 1 writeAsArrayNormal + // 2 writeAsArrayNonContext + for (int i = 0; i < 3; ++i) { + String methodName; + boolean nonContext = DisableCircularReferenceDetect; + boolean writeDirect = false; + if (i == 0) { + methodName = "writeAsArray"; + writeDirect = true; + } else if (i == 1) { + methodName = "writeAsArrayNormal"; + } else { + writeDirect = true; + nonContext = true; + methodName = "writeAsArrayNonContext"; + } + + Context context = new Context(getters, beanInfo, classNameType, writeDirect, + nonContext); + + mw = new MethodWriter(cw, ACC_PUBLIC, methodName, + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V", + null, new String[] { "java/io/IOException" }); + + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitFieldInsn(GETFIELD, JSONSerializer, "out", SerializeWriter_desc); + mw.visitVarInsn(ASTORE, context.var("out")); + + mw.visitVarInsn(ALOAD, Context.obj); // obj + mw.visitTypeInsn(CHECKCAST, type(clazz)); // serializer + mw.visitVarInsn(ASTORE, context.var("entity")); // obj + generateWriteAsArray(clazz, mw, getters, context); + mw.visitInsn(RETURN); + mw.visitMaxs(7, context.variantIndex + 2); mw.visitEnd(); } byte[] code = cw.toByteArray(); - Class exampleClass = classLoader.defineClassPublic(className, code, 0, code.length); - Object instance = exampleClass.newInstance(); + Class serializerClass = classLoader.defineClassPublic(classNameFull, code, 0, code.length); + Constructor constructor = serializerClass.getConstructor(SerializeBeanInfo.class); + Object instance = constructor.newInstance(beanInfo); - return (ObjectSerializer) instance; + return (JavaBeanSerializer) instance; } - private void generateWriteMethod(Class clazz, MethodVisitor mw, List getters, Context context) throws Exception { - Label end = new Label(); + private void generateWriteAsArray(Class clazz, MethodVisitor mw, FieldInfo[] getters, + Context context) throws Exception { - int size = getters.size(); + Label nonPropertyFilters_ = new Label(); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, 0); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "hasPropertyFilters", "(" + SerializeFilterable_desc + ")Z"); + mw.visitJumpInsn(IFNE, nonPropertyFilters_); + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, 1); + mw.visitVarInsn(ALOAD, 2); + mw.visitVarInsn(ALOAD, 3); + mw.visitVarInsn(ALOAD, 4); + mw.visitVarInsn(ILOAD, 5); + mw.visitMethodInsn(INVOKESPECIAL, JavaBeanSerializer, + "writeNoneASM", "(L" + JSONSerializer + + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitInsn(RETURN); + + mw.visitLabel(nonPropertyFilters_); + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(BIPUSH, '['); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + + int size = getters.length; if (size == 0) { mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitLdcInsn("{}"); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "write", "(Ljava/lang/String;)V"); + mw.visitVarInsn(BIPUSH, ']'); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); return; } - // SEPERATOR - mw.visitVarInsn(BIPUSH, '{'); + for (int i = 0; i < size; ++i) { + final char seperator = (i == size - 1) ? ']' : ','; + + FieldInfo fieldInfo = getters[i]; + Class fieldClass = fieldInfo.fieldClass; + + mw.visitLdcInsn(fieldInfo.name); + mw.visitVarInsn(ASTORE, Context.fieldName); + + if (fieldClass == byte.class // + || fieldClass == short.class // + || fieldClass == int.class) { + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitInsn(DUP); + _get(mw, context, fieldInfo); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeInt", "(I)V"); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + } else if (fieldClass == long.class) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitInsn(DUP); + _get(mw, context, fieldInfo); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeLong", "(J)V"); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + } else if (fieldClass == float.class) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitInsn(DUP); + _get(mw, context, fieldInfo); + mw.visitInsn(ICONST_1); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFloat", "(FZ)V"); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + } else if (fieldClass == double.class) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitInsn(DUP); + _get(mw, context, fieldInfo); + mw.visitInsn(ICONST_1); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeDouble", "(DZ)V"); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + } else if (fieldClass == boolean.class) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitInsn(DUP); + _get(mw, context, fieldInfo); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(Z)V"); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + } else if (fieldClass == char.class) { + mw.visitVarInsn(ALOAD, context.var("out")); + _get(mw, context, fieldInfo); // Character.toString(value) + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "toString", "(C)Ljava/lang/String;"); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeString", "(Ljava/lang/String;C)V"); + + } else if (fieldClass == String.class) { + mw.visitVarInsn(ALOAD, context.var("out")); + _get(mw, context, fieldInfo); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeString", "(Ljava/lang/String;C)V"); + } else if (fieldClass.isEnum()) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitInsn(DUP); + _get(mw, context, fieldInfo); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeEnum", "(Ljava/lang/Enum;)V"); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + } else if (List.class.isAssignableFrom(fieldClass)) { + Type fieldType = fieldInfo.fieldType; + + Type elementType; + if (fieldType instanceof Class) { + elementType = Object.class; + } else { + elementType = ((ParameterizedType) fieldType).getActualTypeArguments()[0]; + } + + Class elementClass = null; + if (elementType instanceof Class) { + elementClass = (Class) elementType; + + if (elementClass == Object.class) { + elementClass = null; + } + } + + _get(mw, context, fieldInfo); + mw.visitTypeInsn(CHECKCAST, "java/util/List"); // cast + mw.visitVarInsn(ASTORE, context.var("list")); + + if (elementClass == String.class // + && context.writeDirect) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ALOAD, context.var("list")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(Ljava/util/List;)V"); + } else { + Label nullEnd_ = new Label(), nullElse_ = new Label(); + + mw.visitVarInsn(ALOAD, context.var("list")); + mw.visitJumpInsn(IFNONNULL, nullElse_); + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeNull", "()V"); + mw.visitJumpInsn(GOTO, nullEnd_); + + mw.visitLabel(nullElse_); + + mw.visitVarInsn(ALOAD, context.var("list")); + mw.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "size", "()I"); + mw.visitVarInsn(ISTORE, context.var("size")); + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(BIPUSH, '['); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + + Label for_ = new Label(), forFirst_ = new Label(), forEnd_ = new Label(); + + mw.visitInsn(ICONST_0); + mw.visitVarInsn(ISTORE, context.var("i")); + + // for (; i < list.size() -1; ++i) { + mw.visitLabel(for_); + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitVarInsn(ILOAD, context.var("size")); + mw.visitJumpInsn(IF_ICMPGE, forEnd_); // i < list.size - 1 + + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitJumpInsn(IFEQ, forFirst_); // i < list.size - 1 + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(BIPUSH, ','); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + + mw.visitLabel(forFirst_); + + mw.visitVarInsn(ALOAD, context.var("list")); + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "get", "(I)Ljava/lang/Object;"); + mw.visitVarInsn(ASTORE, context.var("list_item")); + + Label forItemNullEnd_ = new Label(), forItemNullElse_ = new Label(); + + mw.visitVarInsn(ALOAD, context.var("list_item")); + mw.visitJumpInsn(IFNONNULL, forItemNullElse_); + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeNull", "()V"); + mw.visitJumpInsn(GOTO, forItemNullEnd_); + + mw.visitLabel(forItemNullElse_); + + Label forItemClassIfEnd_ = new Label(), forItemClassIfElse_ = new Label(); + if (elementClass != null && Modifier.isPublic(elementClass.getModifiers())) { + mw.visitVarInsn(ALOAD, context.var("list_item")); + mw.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;"); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(elementClass))); + mw.visitJumpInsn(IF_ACMPNE, forItemClassIfElse_); + + _getListFieldItemSer(context, mw, fieldInfo, elementClass); + mw.visitVarInsn(ASTORE, context.var("list_item_desc")); + + Label instanceOfElse_ = new Label(), instanceOfEnd_ = new Label(); + + if (context.writeDirect) { + mw.visitVarInsn(ALOAD, context.var("list_item_desc")); + mw.visitTypeInsn(INSTANCEOF, JavaBeanSerializer); + mw.visitJumpInsn(IFEQ, instanceOfElse_); + + mw.visitVarInsn(ALOAD, context.var("list_item_desc")); + mw.visitTypeInsn(CHECKCAST, JavaBeanSerializer); // cast + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("list_item")); // object + if (context.nonContext) { // fieldName + mw.visitInsn(ACONST_NULL); + } else { + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", + "(I)Ljava/lang/Integer;"); + } + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(elementClass))); // fieldType + mw.visitLdcInsn(fieldInfo.serialzeFeatures); // features + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "writeAsArrayNonContext", // + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitJumpInsn(GOTO, instanceOfEnd_); + + mw.visitLabel(instanceOfElse_); + } + + mw.visitVarInsn(ALOAD, context.var("list_item_desc")); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("list_item")); // object + if (context.nonContext) { // fieldName + mw.visitInsn(ACONST_NULL); + } else { + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); + } + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(elementClass))); // fieldType + mw.visitLdcInsn(fieldInfo.serialzeFeatures); // features + mw.visitMethodInsn(INVOKEINTERFACE, ObjectSerializer, "write", // + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitLabel(instanceOfEnd_); + mw.visitJumpInsn(GOTO, forItemClassIfEnd_); + } + + mw.visitLabel(forItemClassIfElse_); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("list_item")); + if (context.nonContext) { + mw.visitInsn(ACONST_NULL); + } else { + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); + } + if (elementClass != null && Modifier.isPublic(elementClass.getModifiers())) { + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc((Class) elementType))); + mw.visitLdcInsn(fieldInfo.serialzeFeatures); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "writeWithFieldName", + "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + } else { + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "writeWithFieldName", + "(Ljava/lang/Object;Ljava/lang/Object;)V"); + } + mw.visitLabel(forItemClassIfEnd_); + mw.visitLabel(forItemNullEnd_); + + mw.visitIincInsn(context.var("i"), 1); + mw.visitJumpInsn(GOTO, for_); + + mw.visitLabel(forEnd_); + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(BIPUSH, ']'); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + + mw.visitLabel(nullEnd_); + } + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + } else { + Label notNullEnd_ = new Label(), notNullElse_ = new Label(); + + _get(mw, context, fieldInfo); + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, context.var("field_" + fieldInfo.fieldClass.getName())); + mw.visitJumpInsn(IFNONNULL, notNullElse_); + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeNull", "()V"); + mw.visitJumpInsn(GOTO, notNullEnd_); + + mw.visitLabel(notNullElse_); + + Label classIfEnd_ = new Label(), classIfElse_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("field_" + fieldInfo.fieldClass.getName())); + mw.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;"); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldClass))); + mw.visitJumpInsn(IF_ACMPNE, classIfElse_); + + _getFieldSer(context, mw, fieldInfo); + mw.visitVarInsn(ASTORE, context.var("fied_ser")); + + Label instanceOfElse_ = new Label(), instanceOfEnd_ = new Label(); + if (context.writeDirect && Modifier.isPublic(fieldClass.getModifiers())) { + mw.visitVarInsn(ALOAD, context.var("fied_ser")); + mw.visitTypeInsn(INSTANCEOF, JavaBeanSerializer); + mw.visitJumpInsn(IFEQ, instanceOfElse_); + + mw.visitVarInsn(ALOAD, context.var("fied_ser")); + mw.visitTypeInsn(CHECKCAST, JavaBeanSerializer); // cast + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("field_" + fieldInfo.fieldClass.getName())); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldClass))); // fieldType + mw.visitLdcInsn(fieldInfo.serialzeFeatures); // features + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "writeAsArrayNonContext", // + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitJumpInsn(GOTO, instanceOfEnd_); + + mw.visitLabel(instanceOfElse_); + } + mw.visitVarInsn(ALOAD, context.var("fied_ser")); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("field_" + fieldInfo.fieldClass.getName())); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldClass))); // fieldType + mw.visitLdcInsn(fieldInfo.serialzeFeatures); // features + mw.visitMethodInsn(INVOKEINTERFACE, ObjectSerializer, "write", // + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitLabel(instanceOfEnd_); + mw.visitJumpInsn(GOTO, classIfEnd_); + + mw.visitLabel(classIfElse_); + String format = fieldInfo.getFormat(); + + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("field_" + fieldInfo.fieldClass.getName())); + if (format != null) { + mw.visitLdcInsn(format); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "writeWithFormat", + "(Ljava/lang/Object;Ljava/lang/String;)V"); + } else { + mw.visitVarInsn(ALOAD, Context.fieldName); + if (fieldInfo.fieldType instanceof Class // + && ((Class) fieldInfo.fieldType).isPrimitive()) { + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "writeWithFieldName", + "(Ljava/lang/Object;Ljava/lang/Object;)V"); + } else { + mw.visitVarInsn(ALOAD, 0); // this + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_fieldType", + "Ljava/lang/reflect/Type;"); + mw.visitLdcInsn(fieldInfo.serialzeFeatures); + + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "writeWithFieldName", + "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + } + } + mw.visitLabel(classIfEnd_); + mw.visitLabel(notNullEnd_); + + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(BIPUSH, seperator); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + } + } + } + + private void generateWriteMethod(Class clazz, MethodVisitor mw, FieldInfo[] getters, + Context context) throws Exception { + + // if (serializer.containsReference(object)) { + Label end = new Label(); + + int size = getters.length; + + if (!context.writeDirect) { + // pretty format not byte code optimized + Label endSupper_ = new Label(); + Label supper_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitLdcInsn(SerializerFeature.PrettyFormat.mask); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isEnabled", "(I)Z"); + mw.visitJumpInsn(IFNE, supper_); + + boolean hasMethod = false; + for (FieldInfo getter : getters) { + if (getter.method != null) { + hasMethod = true; + } + } + + if (hasMethod) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitLdcInsn(SerializerFeature.IgnoreErrorGetter.mask); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isEnabled", "(I)Z"); + mw.visitJumpInsn(IFEQ, endSupper_); + } else { + mw.visitJumpInsn(GOTO, endSupper_); + } + + mw.visitLabel(supper_); + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, 1); + mw.visitVarInsn(ALOAD, 2); + mw.visitVarInsn(ALOAD, 3); + mw.visitVarInsn(ALOAD, 4); + mw.visitVarInsn(ILOAD, 5); + mw.visitMethodInsn(INVOKESPECIAL, JavaBeanSerializer, + "write", "(L" + JSONSerializer + + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitInsn(RETURN); + + mw.visitLabel(endSupper_); + } + + if (!context.nonContext) { + Label endRef_ = new Label(); + + // ///// + mw.visitVarInsn(ALOAD, 0); // this + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, Context.obj); + mw.visitVarInsn(ILOAD, Context.features); + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "writeReference", + "(L" + JSONSerializer + ";Ljava/lang/Object;I)Z"); + + mw.visitJumpInsn(IFEQ, endRef_); + + mw.visitInsn(RETURN); + + mw.visitLabel(endRef_); + } + + final String writeAsArrayMethodName; + + if (context.writeDirect) { + if (context.nonContext) { + writeAsArrayMethodName = "writeAsArrayNonContext"; + } else { + writeAsArrayMethodName = "writeAsArray"; + } + } else { + writeAsArrayMethodName = "writeAsArrayNormal"; + } + + if ((context.beanInfo.features & SerializerFeature.BeanToArray.mask) == 0) { + Label endWriteAsArray_ = new Label(); + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitLdcInsn(SerializerFeature.BeanToArray.mask); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isEnabled", "(I)Z"); + mw.visitJumpInsn(IFEQ, endWriteAsArray_); + + // ///// + mw.visitVarInsn(ALOAD, 0); // this + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, 2); // obj + mw.visitVarInsn(ALOAD, 3); // fieldObj + mw.visitVarInsn(ALOAD, 4); // fieldType + mw.visitVarInsn(ILOAD, 5); // features + mw.visitMethodInsn(INVOKEVIRTUAL, // + context.className, // + writeAsArrayMethodName, // + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + + mw.visitInsn(RETURN); + + mw.visitLabel(endWriteAsArray_); + } else { + mw.visitVarInsn(ALOAD, 0); // this + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, 2); // obj + mw.visitVarInsn(ALOAD, 3); // fieldObj + mw.visitVarInsn(ALOAD, 4); // fieldType + mw.visitVarInsn(ILOAD, 5); // features + mw.visitMethodInsn(INVOKEVIRTUAL, // + context.className, // + writeAsArrayMethodName, // + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitInsn(RETURN); + } + + if (!context.nonContext) { + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "getContext", "()" + SerialContext_desc); + mw.visitVarInsn(ASTORE, context.var("parent")); + + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("parent")); + mw.visitVarInsn(ALOAD, Context.obj); + mw.visitVarInsn(ALOAD, Context.paramFieldName); + mw.visitLdcInsn(context.beanInfo.features); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "setContext", + "(" + SerialContext_desc + "Ljava/lang/Object;Ljava/lang/Object;I)V"); + } + + boolean writeClasName = (context.beanInfo.features & SerializerFeature.WriteClassName.mask) != 0; + + // SEPERATO + if (writeClasName || !context.writeDirect) { + Label end_ = new Label(); + Label else_ = new Label(); + Label writeClass_ = new Label(); + + if (!writeClasName) { + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, Context.paramFieldType); + mw.visitVarInsn(ALOAD, Context.obj); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "isWriteClassName", + "(Ljava/lang/reflect/Type;Ljava/lang/Object;)Z"); + mw.visitJumpInsn(IFEQ, else_); + } + + // IFNULL + mw.visitVarInsn(ALOAD, Context.paramFieldType); + mw.visitVarInsn(ALOAD, Context.obj); + mw.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;"); + mw.visitJumpInsn(IF_ACMPEQ, else_); + + mw.visitLabel(writeClass_); + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(BIPUSH, '{'); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, Context.serializer); + if (context.beanInfo.typeKey != null) { + mw.visitLdcInsn(context.beanInfo.typeKey); + } else { + mw.visitInsn(ACONST_NULL); + } + mw.visitVarInsn(ALOAD, Context.obj); + + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "writeClassName", "(L" + JSONSerializer + ";Ljava/lang/String;Ljava/lang/Object;)V"); + mw.visitVarInsn(BIPUSH, ','); + mw.visitJumpInsn(GOTO, end_); + + mw.visitLabel(else_); + mw.visitVarInsn(BIPUSH, '{'); + + mw.visitLabel(end_); + } else { + mw.visitVarInsn(BIPUSH, '{'); + } + mw.visitVarInsn(ISTORE, context.var("seperator")); + if (!context.writeDirect) { + _before(mw, context); + } + + if (!context.writeDirect) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isNotWriteDefaultValue", "()Z"); + mw.visitVarInsn(ISTORE, context.var("notWriteDefaultValue")); + + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, 0); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "checkValue", "(" + SerializeFilterable_desc + ")Z"); + mw.visitVarInsn(ISTORE, context.var("checkValue")); + + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, 0); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "hasNameFilters", "(" + SerializeFilterable_desc + ")Z"); + mw.visitVarInsn(ISTORE, context.var("hasNameFilters")); + } + for (int i = 0; i < size; ++i) { - FieldInfo property = getters.get(i); - Method method = property.getMethod(); - Class propertyClass = method.getReturnType(); - - mw.visitLdcInsn(property.getName()); - mw.visitVarInsn(ASTORE, context.fieldName()); - - if (propertyClass == byte.class) { - _byte(clazz, mw, property, context); - } else if (propertyClass == short.class) { - _short(clazz, mw, property, context); - } else if (propertyClass == int.class) { - _int(clazz, mw, property, context); + FieldInfo property = getters[i]; + Class propertyClass = property.fieldClass; + + mw.visitLdcInsn(property.name); + mw.visitVarInsn(ASTORE, Context.fieldName); + + if (propertyClass == byte.class // + || propertyClass == short.class // + || propertyClass == int.class) { + _int(clazz, mw, property, context, context.var(propertyClass.getName()), 'I'); } else if (propertyClass == long.class) { _long(clazz, mw, property, context); } else if (propertyClass == float.class) { @@ -215,16 +998,15 @@ private void generateWriteMethod(Class clazz, MethodVisitor mw, List clazz, MethodVisitor mw, List clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - Label _end = new Label(); - _get(mw, context, method); + _nameApply(mw, property, context, _end); + _get(mw, context, property); mw.visitVarInsn(ASTORE, context.var("object")); _filters(mw, property, context, _end); @@ -274,443 +1060,484 @@ private void _object(Class clazz, MethodVisitor mw, FieldInfo property, Conte mw.visitLabel(_end); } - private void _enum(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - + private void _enum(Class clazz, MethodVisitor mw, FieldInfo fieldInfo, Context context) { Label _not_null = new Label(); Label _end_if = new Label(); Label _end = new Label(); - _get(mw, context, method); - mw.visitTypeInsn(CHECKCAST, getType(Enum.class)); // cast - mw.visitVarInsn(ASTORE, context.var("enum")); + _nameApply(mw, fieldInfo, context, _end); + _get(mw, context, fieldInfo); + mw.visitTypeInsn(CHECKCAST, "java/lang/Enum"); // cast + mw.visitVarInsn(ASTORE, context.var("enum")); - _filters(mw, property, context, _end); + _filters(mw, fieldInfo, context, _end); mw.visitVarInsn(ALOAD, context.var("enum")); mw.visitJumpInsn(IFNONNULL, _not_null); - _if_write_null(mw, property, context); + _if_write_null(mw, fieldInfo, context); mw.visitJumpInsn(GOTO, _end_if); mw.visitLabel(_not_null); - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitVarInsn(ALOAD, context.var("enum")); - - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldValue", "(CLjava/lang/String;L" + getType(Enum.class) + ";)V"); - - mw.visitLabel(_end_if); - _seperator(mw, context); - - mw.visitLabel(_end); - } - - private void _long(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - - Label _end = new Label(); - - _get(mw, context, method); - mw.visitVarInsn(LSTORE, context.var("long", 2)); - - _filters(mw, property, context, _end); - - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitVarInsn(LLOAD, context.var("long")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldValue", "(CLjava/lang/String;J)V"); - - _seperator(mw, context); - - mw.visitLabel(_end); - } - - private void _float(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - - Label _end = new Label(); - - _get(mw, context, method); - mw.visitVarInsn(FSTORE, context.var("float")); - - _filters(mw, property, context, _end); - - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitVarInsn(FLOAD, context.var("float")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldValue", "(CLjava/lang/String;F)V"); - - _seperator(mw, context); - - mw.visitLabel(_end); - } - - private void _double(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - - Label _end = new Label(); - - _get(mw, context, method); - mw.visitVarInsn(DSTORE, context.var("double")); - - _filters(mw, property, context, _end); - - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitVarInsn(DLOAD, context.var("double")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldValue", "(CLjava/lang/String;D)V"); - - _seperator(mw, context); - - mw.visitLabel(_end); - } - - private void _char(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - - Label _end = new Label(); - - _get(mw, context, method); - mw.visitVarInsn(ISTORE, context.var("char")); - - _filters(mw, property, context, _end); - - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitVarInsn(ILOAD, context.var("char")); - - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldValue", "(CLjava/lang/String;C)V"); + if (context.writeDirect) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ILOAD, context.var("seperator")); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitVarInsn(ALOAD, context.var("enum")); + mw.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Enum", "name", "()Ljava/lang/String;"); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValueStringWithDoubleQuote", + "(CLjava/lang/String;Ljava/lang/String;)V"); + } else { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ILOAD, context.var("seperator")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitInsn(ICONST_0); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldName", "(Ljava/lang/String;Z)V"); + + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("enum")); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc((Class) fieldInfo.fieldClass))); + mw.visitLdcInsn(fieldInfo.serialzeFeatures); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "writeWithFieldName", + "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + } _seperator(mw, context); + mw.visitLabel(_end_if); mw.visitLabel(_end); } + + private void _int(Class clazz, MethodVisitor mw, FieldInfo property, Context context, int var, char type) { + Label end_ = new Label(); - private void _boolean(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - - Label _end = new Label(); - - _get(mw, context, method); - mw.visitVarInsn(ISTORE, context.var("boolean")); + _nameApply(mw, property, context, end_); + _get(mw, context, property); + mw.visitVarInsn(ISTORE, var); - _filters(mw, property, context, _end); + _filters(mw, property, context, end_); - mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitVarInsn(ILOAD, context.var("boolean")); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitVarInsn(ILOAD, var); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldValue", "(CLjava/lang/String;Z)V"); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValue", "(CLjava/lang/String;" + type + ")V"); _seperator(mw, context); - mw.visitLabel(_end); - } - - private void _get(MethodVisitor mw, Context context, Method method) { - mw.visitVarInsn(ALOAD, context.var("entity")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(method.getDeclaringClass()), method.getName(), getDesc(method)); + mw.visitLabel(end_); } - private void _byte(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - - Label _end = new Label(); + private void _long(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { + Label end_ = new Label(); - _get(mw, context, method); - mw.visitVarInsn(ISTORE, context.var("byte")); + _nameApply(mw, property, context, end_); + _get(mw, context, property); + mw.visitVarInsn(LSTORE, context.var("long", 2)); - _filters(mw, property, context, _end); + _filters(mw, property, context, end_); mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitVarInsn(ILOAD, context.var("byte")); - - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldValue", "(CLjava/lang/String;I)V"); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitVarInsn(LLOAD, context.var("long", 2)); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValue", "(CLjava/lang/String;J)V"); _seperator(mw, context); - mw.visitLabel(_end); + mw.visitLabel(end_); } + + private void _float(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { + Label end_ = new Label(); - private void _short(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - - Label _end = new Label(); - - _get(mw, context, method); - mw.visitVarInsn(ISTORE, context.var("short")); + _nameApply(mw, property, context, end_); + _get(mw, context, property); + mw.visitVarInsn(FSTORE, context.var("float")); - _filters(mw, property, context, _end); + _filters(mw, property, context, end_); - mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitVarInsn(ILOAD, context.var("short")); - - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldValue", "(CLjava/lang/String;I)V"); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitVarInsn(FLOAD, context.var("float")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValue", "(CLjava/lang/String;F)V"); _seperator(mw, context); - mw.visitLabel(_end); + mw.visitLabel(end_); } - private void _int(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - - Label _end = new Label(); + private void _double(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { + Label end_ = new Label(); - _get(mw, context, method); - mw.visitVarInsn(ISTORE, context.var("int")); + _nameApply(mw, property, context, end_); + _get(mw, context, property); + mw.visitVarInsn(DSTORE, context.var("double", 2)); - _filters(mw, property, context, _end); + _filters(mw, property, context, end_); - mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitVarInsn(ILOAD, context.var("int")); - - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldValue", "(CLjava/lang/String;I)V"); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitVarInsn(DLOAD, context.var("double", 2)); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValue", "(CLjava/lang/String;D)V"); _seperator(mw, context); - mw.visitLabel(_end); + mw.visitLabel(end_); + } + + private void _get(MethodVisitor mw, Context context, FieldInfo fieldInfo) { + Method method = fieldInfo.method; + if (method != null) { + mw.visitVarInsn(ALOAD, context.var("entity")); + Class declaringClass = method.getDeclaringClass(); + mw.visitMethodInsn(declaringClass.isInterface() ? INVOKEINTERFACE : INVOKEVIRTUAL, type(declaringClass), method.getName(), desc(method)); + if (!method.getReturnType().equals(fieldInfo.fieldClass)) { + mw.visitTypeInsn(CHECKCAST, type(fieldInfo.fieldClass)); // cast + } + } else { + mw.visitVarInsn(ALOAD, context.var("entity")); + Field field = fieldInfo.field; + mw.visitFieldInsn(GETFIELD, type(fieldInfo.declaringClass), field.getName(), + desc(field.getType())); + if (!field.getType().equals(fieldInfo.fieldClass)) { + mw.visitTypeInsn(CHECKCAST, type(fieldInfo.fieldClass)); // cast + } + } } private void _decimal(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - - Label _end = new Label(); + Label end_ = new Label(); - _get(mw, context, method); + _nameApply(mw, property, context, end_); + _get(mw, context, property); mw.visitVarInsn(ASTORE, context.var("decimal")); - _filters(mw, property, context, _end); + _filters(mw, property, context, end_); - Label _if = new Label(); - Label _else = new Label(); - Label _end_if = new Label(); + Label if_ = new Label(); + Label else_ = new Label(); + Label endIf_ = new Label(); - mw.visitLabel(_if); + mw.visitLabel(if_); // if (decimalValue == null) { mw.visitVarInsn(ALOAD, context.var("decimal")); - mw.visitJumpInsn(IFNONNULL, _else); + mw.visitJumpInsn(IFNONNULL, else_); _if_write_null(mw, property, context); - mw.visitJumpInsn(GOTO, _end_if); + mw.visitJumpInsn(GOTO, endIf_); - mw.visitLabel(_else); // else { out.writeFieldValue(seperator, fieldName, fieldValue) + mw.visitLabel(else_); // else { out.writeFieldValue(seperator, fieldName, fieldValue) - mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); + mw.visitVarInsn(ALOAD, Context.fieldName); mw.visitVarInsn(ALOAD, context.var("decimal")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldValue", "(CLjava/lang/String;Ljava/math/BigDecimal;)V"); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValue", + "(CLjava/lang/String;Ljava/math/BigDecimal;)V"); _seperator(mw, context); - mw.visitJumpInsn(GOTO, _end_if); + mw.visitJumpInsn(GOTO, endIf_); - mw.visitLabel(_end_if); + mw.visitLabel(endIf_); - mw.visitLabel(_end); + mw.visitLabel(end_); } private void _string(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - - Label _end = new Label(); + Label end_ = new Label(); + + if (property.name.equals(context.beanInfo.typeKey)) { + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, Context.paramFieldType); + mw.visitVarInsn(ALOAD, Context.obj); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "isWriteClassName", + "(Ljava/lang/reflect/Type;Ljava/lang/Object;)Z"); + mw.visitJumpInsn(IFNE, end_); + } - _get(mw, context, method); + _nameApply(mw, property, context, end_); + _get(mw, context, property); mw.visitVarInsn(ASTORE, context.var("string")); - _filters(mw, property, context, _end); + _filters(mw, property, context, end_); - Label _else = new Label(); - Label _end_if = new Label(); + Label else_ = new Label(); + Label endIf_ = new Label(); // if (value == null) { mw.visitVarInsn(ALOAD, context.var("string")); - mw.visitJumpInsn(IFNONNULL, _else); + mw.visitJumpInsn(IFNONNULL, else_); _if_write_null(mw, property, context); - mw.visitJumpInsn(GOTO, _end_if); + mw.visitJumpInsn(GOTO, endIf_); - mw.visitLabel(_else); // else { out.writeFieldValue(seperator, fieldName, fieldValue) - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitVarInsn(ALOAD, context.var("string")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldValue", "(CLjava/lang/String;Ljava/lang/String;)V"); + mw.visitLabel(else_); // else { out.writeFieldValue(seperator, fieldName, fieldValue) - _seperator(mw, context); - mw.visitLabel(_end_if); + if ("trim".equals(property.format)) { + mw.visitVarInsn(ALOAD, context.var("string")); + mw.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "trim", "()Ljava/lang/String;"); + mw.visitVarInsn(ASTORE, context.var("string")); + } - mw.visitLabel(_end); - } + if (context.writeDirect) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ILOAD, context.var("seperator")); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitVarInsn(ALOAD, context.var("string")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValueStringWithDoubleQuoteCheck", + "(CLjava/lang/String;Ljava/lang/String;)V"); + } else { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ILOAD, context.var("seperator")); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitVarInsn(ALOAD, context.var("string")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValue", + "(CLjava/lang/String;Ljava/lang/String;)V"); + } + _seperator(mw, context); - private void _list(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); + mw.visitLabel(endIf_); - Type propertyType = method.getGenericReturnType(); + mw.visitLabel(end_); + } - Type elementType = ((ParameterizedType) propertyType).getActualTypeArguments()[0]; + private void _list(Class clazz, MethodVisitor mw, FieldInfo fieldInfo, Context context) { + Type propertyType = fieldInfo.fieldType; - Label _end = new Label(); + Type elementType = TypeUtils.getCollectionItemType(propertyType); - Label _if = new Label(); - Label _else = new Label(); - Label _end_if = new Label(); + Class elementClass = null; + if (elementType instanceof Class) { + elementClass = (Class) elementType; + } + + if (elementClass == Object.class // + || elementClass == Serializable.class) { + elementClass = null; + } - mw.visitLabel(_if); + Label end_ = new Label(), else_ = new Label(), endIf_ = new Label(); - _get(mw, context, method); - mw.visitTypeInsn(CHECKCAST, getType(List.class)); // cast - mw.visitVarInsn(ASTORE, context.var("list")); + _nameApply(mw, fieldInfo, context, end_); + _get(mw, context, fieldInfo); + mw.visitTypeInsn(CHECKCAST, "java/util/List"); // cast + mw.visitVarInsn(ASTORE, context.var("list")); - _filters(mw, property, context, _end); + _filters(mw, fieldInfo, context, end_); mw.visitVarInsn(ALOAD, context.var("list")); - mw.visitJumpInsn(IFNONNULL, _else); - _if_write_null(mw, property, context); - mw.visitJumpInsn(GOTO, _end_if); + mw.visitJumpInsn(IFNONNULL, else_); + _if_write_null(mw, fieldInfo, context); + mw.visitJumpInsn(GOTO, endIf_); - mw.visitLabel(_else); // else { + mw.visitLabel(else_); // else { mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "write", "(C)V"); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldName", "(Ljava/lang/String;)V"); + _writeFieldName(mw, context); // mw.visitVarInsn(ALOAD, context.var("list")); - mw.visitMethodInsn(INVOKEINTERFACE, getType(List.class), "size", "()I"); - mw.visitVarInsn(ISTORE, context.var("int")); + mw.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "size", "()I"); + mw.visitVarInsn(ISTORE, context.var("size")); - Label _if_3 = new Label(); Label _else_3 = new Label(); Label _end_if_3 = new Label(); - mw.visitLabel(_if_3); - - mw.visitVarInsn(ILOAD, context.var("int")); + mw.visitVarInsn(ILOAD, context.var("size")); mw.visitInsn(ICONST_0); mw.visitJumpInsn(IF_ICMPNE, _else_3); - mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ALOAD, context.var("out")); mw.visitLdcInsn("[]"); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "write", "(Ljava/lang/String;)V"); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(Ljava/lang/String;)V"); mw.visitJumpInsn(GOTO, _end_if_3); mw.visitLabel(_else_3); - { + if (!context.nonContext) { + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("list")); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "setContext", "(Ljava/lang/Object;Ljava/lang/Object;)V"); + } + + if (elementType == String.class // + && context.writeDirect) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ALOAD, context.var("list")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(Ljava/util/List;)V"); + } else { mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(BIPUSH, '['); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "write", "(C)V"); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); - // list_serializer = null - mw.visitInsn(ACONST_NULL); - mw.visitTypeInsn(CHECKCAST, getType(ObjectSerializer.class)); // cast to string - mw.visitVarInsn(ASTORE, context.var("list_ser")); - - Label _for = new Label(); - Label _end_for = new Label(); + Label for_ = new Label(), forFirst_ = new Label(), forEnd_ = new Label(); mw.visitInsn(ICONST_0); - mw.visitVarInsn(ISTORE, context.var("i")); + mw.visitVarInsn(ISTORE, context.var("i")); // for (; i < list.size() -1; ++i) { - mw.visitLabel(_for); + mw.visitLabel(for_); mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitVarInsn(ILOAD, context.var("size")); + mw.visitJumpInsn(IF_ICMPGE, forEnd_); // i < list.size - 1 - mw.visitVarInsn(ILOAD, context.var("int")); - mw.visitInsn(ICONST_1); - mw.visitInsn(ISUB); - - mw.visitJumpInsn(IF_ICMPGE, _end_for); // i < list.size - 1 - - if (elementType == String.class) { - // out.write((String)list.get(i)); - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(ALOAD, context.var("list")); - mw.visitVarInsn(ILOAD, context.var("i")); - mw.visitMethodInsn(INVOKEINTERFACE, getType(List.class), "get", "(I)Ljava/lang/Object;"); - mw.visitTypeInsn(CHECKCAST, getType(String.class)); // cast to string - mw.visitVarInsn(BIPUSH, ','); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeString", "(Ljava/lang/String;C)V"); - } else { - mw.visitVarInsn(ALOAD, context.serializer()); - mw.visitVarInsn(ALOAD, context.var("list")); - mw.visitVarInsn(ILOAD, context.var("i")); - mw.visitMethodInsn(INVOKEINTERFACE, getType(List.class), "get", "(I)Ljava/lang/Object;"); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONSerializer.class), "write", "(Ljava/lang/Object;)V"); + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitJumpInsn(IFEQ, forFirst_); // i < list.size - 1 - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(BIPUSH, ','); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "write", "(C)V"); - } + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(BIPUSH, ','); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); - mw.visitIincInsn(context.var("i"), 1); - mw.visitJumpInsn(GOTO, _for); + mw.visitLabel(forFirst_); - mw.visitLabel(_end_for); + mw.visitVarInsn(ALOAD, context.var("list")); + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "get", "(I)Ljava/lang/Object;"); + mw.visitVarInsn(ASTORE, context.var("list_item")); - if (elementType == String.class) { - // out.write((String)list.get(size - 1)); - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(ALOAD, context.var("list")); - mw.visitVarInsn(ILOAD, context.var("int")); - mw.visitInsn(ICONST_1); - mw.visitInsn(ISUB); - mw.visitMethodInsn(INVOKEINTERFACE, getType(List.class), "get", "(I)Ljava/lang/Object;"); - mw.visitTypeInsn(CHECKCAST, getType(String.class)); // cast to string - mw.visitVarInsn(BIPUSH, ']'); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeString", "(Ljava/lang/String;C)V"); + Label forItemNullEnd_ = new Label(), forItemNullElse_ = new Label(); + + mw.visitVarInsn(ALOAD, context.var("list_item")); + mw.visitJumpInsn(IFNONNULL, forItemNullElse_); + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeNull", "()V"); + mw.visitJumpInsn(GOTO, forItemNullEnd_); + + mw.visitLabel(forItemNullElse_); + + Label forItemClassIfEnd_ = new Label(), forItemClassIfElse_ = new Label(); + if (elementClass != null && Modifier.isPublic(elementClass.getModifiers())) { + mw.visitVarInsn(ALOAD, context.var("list_item")); + mw.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;"); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(elementClass))); + mw.visitJumpInsn(IF_ACMPNE, forItemClassIfElse_); + + _getListFieldItemSer(context, mw, fieldInfo, elementClass); + // mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, context.var("list_item_desc")); + + Label instanceOfElse_ = new Label(), instanceOfEnd_ = new Label(); + + if (context.writeDirect) { + String writeMethodName = context.nonContext && context.writeDirect ? // + "writeDirectNonContext" // + : "write"; + mw.visitVarInsn(ALOAD, context.var("list_item_desc")); + mw.visitTypeInsn(INSTANCEOF, JavaBeanSerializer); + mw.visitJumpInsn(IFEQ, instanceOfElse_); + + mw.visitVarInsn(ALOAD, context.var("list_item_desc")); + mw.visitTypeInsn(CHECKCAST, JavaBeanSerializer); // cast + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("list_item")); // object + if (context.nonContext) { // fieldName + mw.visitInsn(ACONST_NULL); + } else { + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); + } + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(elementClass))); // fieldType + mw.visitLdcInsn(fieldInfo.serialzeFeatures); // features + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, writeMethodName, // + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitJumpInsn(GOTO, instanceOfEnd_); + + mw.visitLabel(instanceOfElse_); + } + mw.visitVarInsn(ALOAD, context.var("list_item_desc")); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("list_item")); // object + if (context.nonContext) { // fieldName + mw.visitInsn(ACONST_NULL); + } else { + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); + } + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(elementClass))); // fieldType + mw.visitLdcInsn(fieldInfo.serialzeFeatures); // features + mw.visitMethodInsn(INVOKEINTERFACE, ObjectSerializer, "write", // + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + + mw.visitLabel(instanceOfEnd_); + mw.visitJumpInsn(GOTO, forItemClassIfEnd_); + } + + mw.visitLabel(forItemClassIfElse_); + + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("list_item")); + if (context.nonContext) { + mw.visitInsn(ACONST_NULL); } else { - mw.visitVarInsn(ALOAD, context.serializer()); - mw.visitVarInsn(ALOAD, context.var("list")); - mw.visitVarInsn(ILOAD, context.var("i")); - mw.visitMethodInsn(INVOKEINTERFACE, getType(List.class), "get", "(I)Ljava/lang/Object;"); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONSerializer.class), "write", "(Ljava/lang/Object;)V"); + mw.visitVarInsn(ILOAD, context.var("i")); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); + } - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(BIPUSH, ']'); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "write", "(C)V"); + if (elementClass != null && Modifier.isPublic(elementClass.getModifiers())) { + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc((Class) elementType))); + mw.visitLdcInsn(fieldInfo.serialzeFeatures); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "writeWithFieldName", + "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + } else { + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "writeWithFieldName", + "(Ljava/lang/Object;Ljava/lang/Object;)V"); } + + mw.visitLabel(forItemClassIfEnd_); + mw.visitLabel(forItemNullEnd_); + + mw.visitIincInsn(context.var("i"), 1); + mw.visitJumpInsn(GOTO, for_); + + mw.visitLabel(forEnd_); + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(BIPUSH, ']'); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); } + + { + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "popContext", "()V"); + } + mw.visitLabel(_end_if_3); _seperator(mw, context); - mw.visitLabel(_end_if); + mw.visitLabel(endIf_); - mw.visitLabel(_end); + mw.visitLabel(end_); } private void _filters(MethodVisitor mw, FieldInfo property, Context context, Label _end) { - if (property.getField() != null) { - if (Modifier.isTransient(property.getField().getModifiers())) { - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitFieldInsn(GETSTATIC, getType(SerializerFeature.class), "SkipTransientField", "L" + getType(SerializerFeature.class) + ";"); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "isEnabled", "(" + "L" + getType(SerializerFeature.class) + ";" + ")Z"); + if (property.fieldTransient) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitLdcInsn(SerializerFeature.SkipTransientField.mask); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isEnabled", "(I)Z"); + mw.visitJumpInsn(IFNE, _end); + } - // if true - mw.visitJumpInsn(IFNE, _end); - } + _notWriteDefault(mw, property, context, _end); + + if (context.writeDirect) { + return; } _apply(mw, property, context); @@ -718,219 +1545,438 @@ private void _filters(MethodVisitor mw, FieldInfo property, Context context, Lab _processKey(mw, property, context); - Label _else_processKey = new Label(); - _processValue(mw, property, context); + _processValue(mw, property, context, _end); + } - mw.visitVarInsn(ALOAD, context.original()); - mw.visitVarInsn(ALOAD, context.processValue()); - mw.visitJumpInsn(IF_ACMPEQ, _else_processKey); - _writeObject(mw, property, context, _end); - mw.visitJumpInsn(GOTO, _end); + private void _nameApply(MethodVisitor mw, FieldInfo property, Context context, Label _end) { + if (!context.writeDirect) { + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, Context.obj); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "applyName", + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/String;)Z"); + mw.visitJumpInsn(IFEQ, _end); + + _labelApply(mw, property, context, _end); + } - mw.visitLabel(_else_processKey); + if (property.field == null) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitLdcInsn(SerializerFeature.IgnoreNonFieldGetter.mask); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isEnabled", "(I)Z"); + + // if true + mw.visitJumpInsn(IFNE, _end); + } + } + + private void _labelApply(MethodVisitor mw, FieldInfo property, Context context, Label _end) { + mw.visitVarInsn(ALOAD, 0); // this + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitLdcInsn(property.label); + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "applyLabel", + "(L" + JSONSerializer + ";Ljava/lang/String;)Z"); + mw.visitJumpInsn(IFEQ, _end); } private void _writeObject(MethodVisitor mw, FieldInfo fieldInfo, Context context, Label _end) { - String format = null; - JSONField annotation = fieldInfo.getAnnotation(JSONField.class); + String format = fieldInfo.getFormat(); + Class fieldClass = fieldInfo.fieldClass; - if (annotation != null) { - format = annotation.format(); + Label notNull_ = new Label(); - if (format.trim().length() == 0) { - format = null; - } + // if (obj == null) + if (context.writeDirect) { + mw.visitVarInsn(ALOAD, context.var("object")); + } else { + mw.visitVarInsn(ALOAD, Context.processValue); } - - Label _not_null = new Label(); - - mw.visitVarInsn(ALOAD, context.processValue()); - mw.visitJumpInsn(IFNONNULL, _not_null); // if (obj == null) + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, context.var("object")); + mw.visitJumpInsn(IFNONNULL, notNull_); _if_write_null(mw, fieldInfo, context); mw.visitJumpInsn(GOTO, _end); - mw.visitLabel(_not_null); - // writeFieldNullNumber + mw.visitLabel(notNull_); + mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "write", "(C)V"); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); - // out.writeFieldName("fieldName") - mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitVarInsn(ALOAD, context.fieldName()); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldName", "(Ljava/lang/String;)V"); + _writeFieldName(mw, context); + + Label classIfEnd_ = new Label(), classIfElse_ = new Label(); + if (Modifier.isPublic(fieldClass.getModifiers()) // + && !ParserConfig.isPrimitive2(fieldClass) // + ) { + mw.visitVarInsn(ALOAD, context.var("object")); + mw.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;"); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldClass))); + mw.visitJumpInsn(IF_ACMPNE, classIfElse_); + + _getFieldSer(context, mw, fieldInfo); + mw.visitVarInsn(ASTORE, context.var("fied_ser")); + + Label instanceOfElse_ = new Label(), instanceOfEnd_ = new Label(); + mw.visitVarInsn(ALOAD, context.var("fied_ser")); + mw.visitTypeInsn(INSTANCEOF, JavaBeanSerializer); + mw.visitJumpInsn(IFEQ, instanceOfElse_); + + boolean disableCircularReferenceDetect = (fieldInfo.serialzeFeatures & SerializerFeature.DisableCircularReferenceDetect.mask) != 0; + boolean fieldBeanToArray = (fieldInfo.serialzeFeatures & SerializerFeature.BeanToArray.mask) != 0; + String writeMethodName; + if (disableCircularReferenceDetect || (context.nonContext && context.writeDirect)) { + writeMethodName = fieldBeanToArray ? "writeAsArrayNonContext" : "writeDirectNonContext"; + } else { + writeMethodName = fieldBeanToArray ? "writeAsArray" : "write"; + } + + mw.visitVarInsn(ALOAD, context.var("fied_ser")); + mw.visitTypeInsn(CHECKCAST, JavaBeanSerializer); // cast + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("object")); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_fieldType", + "Ljava/lang/reflect/Type;"); + mw.visitLdcInsn(fieldInfo.serialzeFeatures); // features + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, writeMethodName, // + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + mw.visitJumpInsn(GOTO, instanceOfEnd_); + + mw.visitLabel(instanceOfElse_); + + mw.visitVarInsn(ALOAD, context.var("fied_ser")); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, context.var("object")); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_fieldType", + "Ljava/lang/reflect/Type;"); + mw.visitLdcInsn(fieldInfo.serialzeFeatures); // features + mw.visitMethodInsn(INVOKEINTERFACE, ObjectSerializer, "write", // + "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + + mw.visitLabel(instanceOfEnd_); + mw.visitJumpInsn(GOTO, classIfEnd_); + } + + mw.visitLabel(classIfElse_); - // serializer.write(obj) - mw.visitVarInsn(ALOAD, context.serializer()); // serializer - mw.visitVarInsn(ALOAD, context.processValue()); + mw.visitVarInsn(ALOAD, Context.serializer); + if (context.writeDirect) { + mw.visitVarInsn(ALOAD, context.var("object")); + } else { + mw.visitVarInsn(ALOAD, Context.processValue); + } if (format != null) { mw.visitLdcInsn(format); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONSerializer.class), "writeWithFormat", "(Ljava/lang/Object;Ljava/lang/String;)V"); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "writeWithFormat", + "(Ljava/lang/Object;Ljava/lang/String;)V"); } else { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONSerializer.class), "write", "(Ljava/lang/Object;)V"); + mw.visitVarInsn(ALOAD, Context.fieldName); + if (fieldInfo.fieldType instanceof Class // + && ((Class) fieldInfo.fieldType).isPrimitive()) { + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "writeWithFieldName", + "(Ljava/lang/Object;Ljava/lang/Object;)V"); + } else { + if (fieldInfo.fieldClass == String.class) { + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(String.class))); + } else { + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_fieldType", + "Ljava/lang/reflect/Type;"); + } + mw.visitLdcInsn(fieldInfo.serialzeFeatures); + + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "writeWithFieldName", + "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;I)V"); + } } + mw.visitLabel(classIfEnd_); _seperator(mw, context); } + private void _before(MethodVisitor mw, Context context) { + mw.visitVarInsn(ALOAD, 0); // this + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, Context.obj); + mw.visitVarInsn(ILOAD, context.var("seperator")); + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "writeBefore", + "(L" + JSONSerializer + ";Ljava/lang/Object;C)C"); + mw.visitVarInsn(ISTORE, context.var("seperator")); + } + + private void _after(MethodVisitor mw, Context context) { + mw.visitVarInsn(ALOAD, 0); // this + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, 2); // obj + mw.visitVarInsn(ILOAD, context.var("seperator")); + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "writeAfter", + "(L" + JSONSerializer + ";Ljava/lang/Object;C)C"); + mw.visitVarInsn(ISTORE, context.var("seperator")); + } + + private void _notWriteDefault(MethodVisitor mw, FieldInfo property, Context context, Label _end) { + if (context.writeDirect) { + return; + } + + Label elseLabel = new Label(); + + mw.visitVarInsn(ILOAD, context.var("notWriteDefaultValue")); + mw.visitJumpInsn(IFEQ, elseLabel); + + Class propertyClass = property.fieldClass; + if (propertyClass == boolean.class) { + mw.visitVarInsn(ILOAD, context.var("boolean")); + mw.visitJumpInsn(IFEQ, _end); + } else if (propertyClass == byte.class) { + mw.visitVarInsn(ILOAD, context.var("byte")); + mw.visitJumpInsn(IFEQ, _end); + } else if (propertyClass == short.class) { + mw.visitVarInsn(ILOAD, context.var("short")); + mw.visitJumpInsn(IFEQ, _end); + } else if (propertyClass == int.class) { + mw.visitVarInsn(ILOAD, context.var("int")); + mw.visitJumpInsn(IFEQ, _end); + } else if (propertyClass == long.class) { + mw.visitVarInsn(LLOAD, context.var("long")); + mw.visitInsn(LCONST_0); + mw.visitInsn(LCMP); + mw.visitJumpInsn(IFEQ, _end); + } else if (propertyClass == float.class) { + mw.visitVarInsn(FLOAD, context.var("float")); + mw.visitInsn(FCONST_0); + mw.visitInsn(FCMPL); + mw.visitJumpInsn(IFEQ, _end); + } else if (propertyClass == double.class) { + mw.visitVarInsn(DLOAD, context.var("double")); + mw.visitInsn(DCONST_0); + mw.visitInsn(DCMPL); + mw.visitJumpInsn(IFEQ, _end); + } + + mw.visitLabel(elseLabel); + } + private void _apply(MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - Class propertyClass = method.getReturnType(); + Class propertyClass = property.fieldClass; - mw.visitVarInsn(ALOAD, context.serializer()); - mw.visitVarInsn(ALOAD, context.obj()); - mw.visitVarInsn(ALOAD, context.fieldName()); + mw.visitVarInsn(ALOAD, 0); // this + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, Context.obj); + mw.visitVarInsn(ALOAD, Context.fieldName); if (propertyClass == byte.class) { mw.visitVarInsn(ILOAD, context.var("byte")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;B)Z"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); } else if (propertyClass == short.class) { mw.visitVarInsn(ILOAD, context.var("short")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;S)Z"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;"); } else if (propertyClass == int.class) { mw.visitVarInsn(ILOAD, context.var("int")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;I)Z"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); } else if (propertyClass == char.class) { mw.visitVarInsn(ILOAD, context.var("char")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;C)Z"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;"); } else if (propertyClass == long.class) { - mw.visitVarInsn(LLOAD, context.var("long")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;J)Z"); + mw.visitVarInsn(LLOAD, context.var("long", 2)); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"); } else if (propertyClass == float.class) { mw.visitVarInsn(FLOAD, context.var("float")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;F)Z"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); } else if (propertyClass == double.class) { - mw.visitVarInsn(DLOAD, context.var("double")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;D)Z"); + mw.visitVarInsn(DLOAD, context.var("double", 2)); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"); } else if (propertyClass == boolean.class) { mw.visitVarInsn(ILOAD, context.var("boolean")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;B)Z"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"); } else if (propertyClass == BigDecimal.class) { mw.visitVarInsn(ALOAD, context.var("decimal")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Z"); } else if (propertyClass == String.class) { mw.visitVarInsn(ALOAD, context.var("string")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Z"); } else if (propertyClass.isEnum()) { mw.visitVarInsn(ALOAD, context.var("enum")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Z"); - } else if (propertyClass == List.class) { + } else if (List.class.isAssignableFrom(propertyClass)) { mw.visitVarInsn(ALOAD, context.var("list")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Z"); } else { mw.visitVarInsn(ALOAD, context.var("object")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "apply", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Z"); } + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, + "apply", "(L" + JSONSerializer + + ";Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Z"); } - private void _processValue(MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - Class propertyClass = method.getReturnType(); + private void _processValue(MethodVisitor mw, FieldInfo fieldInfo, Context context, Label _end) { + Label processKeyElse_ = new Label(); - mw.visitVarInsn(ALOAD, context.serializer()); - mw.visitVarInsn(ALOAD, context.obj()); - mw.visitVarInsn(ALOAD, context.fieldName()); + Class fieldClass = fieldInfo.fieldClass; - if (propertyClass == byte.class) { + if (fieldClass.isPrimitive()) { + Label checkValueEnd_ = new Label(); + mw.visitVarInsn(ILOAD, context.var("checkValue")); + mw.visitJumpInsn(IFNE, checkValueEnd_); + + mw.visitInsn(ACONST_NULL); + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, Context.original); + mw.visitVarInsn(ASTORE, Context.processValue); + mw.visitJumpInsn(GOTO, processKeyElse_); + + mw.visitLabel(checkValueEnd_); + } + + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, 0); + mw.visitLdcInsn(context.getFieldOrinal(fieldInfo.name)); + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "getBeanContext", "(I)" + desc(BeanContext.class)); + mw.visitVarInsn(ALOAD, Context.obj); + mw.visitVarInsn(ALOAD, Context.fieldName); + + String valueDesc = "Ljava/lang/Object;"; + if (fieldClass == byte.class) { mw.visitVarInsn(ILOAD, context.var("byte")); - mw.visitMethodInsn(INVOKESTATIC, getType(Byte.class), "valueOf", "(B)Ljava/lang/Byte;"); - } else if (propertyClass == short.class) { + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, Context.original); + } else if (fieldClass == short.class) { mw.visitVarInsn(ILOAD, context.var("short")); - mw.visitMethodInsn(INVOKESTATIC, getType(Short.class), "valueOf", "(S)Ljava/lang/Short;"); - } else if (propertyClass == int.class) { + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;"); + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, Context.original); + } else if (fieldClass == int.class) { mw.visitVarInsn(ILOAD, context.var("int")); - mw.visitMethodInsn(INVOKESTATIC, getType(Integer.class), "valueOf", "(I)Ljava/lang/Integer;"); - } else if (propertyClass == char.class) { + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, Context.original); + } else if (fieldClass == char.class) { mw.visitVarInsn(ILOAD, context.var("char")); - mw.visitMethodInsn(INVOKESTATIC, getType(Character.class), "valueOf", "(C)Ljava/lang/Character;"); - } else if (propertyClass == long.class) { - mw.visitVarInsn(LLOAD, context.var("long")); - mw.visitMethodInsn(INVOKESTATIC, getType(Long.class), "valueOf", "(J)Ljava/lang/Long;"); - } else if (propertyClass == float.class) { + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;"); + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, Context.original); + } else if (fieldClass == long.class) { + mw.visitVarInsn(LLOAD, context.var("long", 2)); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"); + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, Context.original); + } else if (fieldClass == float.class) { mw.visitVarInsn(FLOAD, context.var("float")); - mw.visitMethodInsn(INVOKESTATIC, getType(Float.class), "valueOf", "(F)Ljava/lang/Float;"); - } else if (propertyClass == double.class) { - mw.visitVarInsn(DLOAD, context.var("double")); - mw.visitMethodInsn(INVOKESTATIC, getType(Double.class), "valueOf", "(D)Ljava/lang/Double;"); - } else if (propertyClass == boolean.class) { + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, Context.original); + } else if (fieldClass == double.class) { + mw.visitVarInsn(DLOAD, context.var("double", 2)); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"); + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, Context.original); + } else if (fieldClass == boolean.class) { mw.visitVarInsn(ILOAD, context.var("boolean")); - mw.visitMethodInsn(INVOKESTATIC, getType(Boolean.class), "valueOf", "(Z)Ljava/lang/Boolean;"); - } else if (propertyClass == BigDecimal.class) { + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"); + mw.visitInsn(DUP); + mw.visitVarInsn(ASTORE, Context.original); + } else if (fieldClass == BigDecimal.class) { mw.visitVarInsn(ALOAD, context.var("decimal")); - } else if (propertyClass == String.class) { + mw.visitVarInsn(ASTORE, Context.original); + mw.visitVarInsn(ALOAD, Context.original); + } else if (fieldClass == String.class) { mw.visitVarInsn(ALOAD, context.var("string")); - } else if (propertyClass.isEnum()) { + mw.visitVarInsn(ASTORE, Context.original); + mw.visitVarInsn(ALOAD, Context.original); + } else if (fieldClass.isEnum()) { mw.visitVarInsn(ALOAD, context.var("enum")); - } else if (propertyClass == List.class) { + mw.visitVarInsn(ASTORE, Context.original); + mw.visitVarInsn(ALOAD, Context.original); + } else if (List.class.isAssignableFrom(fieldClass)) { mw.visitVarInsn(ALOAD, context.var("list")); + mw.visitVarInsn(ASTORE, Context.original); + mw.visitVarInsn(ALOAD, Context.original); } else { mw.visitVarInsn(ALOAD, context.var("object")); + mw.visitVarInsn(ASTORE, Context.original); + mw.visitVarInsn(ALOAD, Context.original); } - mw.visitVarInsn(ASTORE, context.original()); - mw.visitVarInsn(ALOAD, context.original()); + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "processValue", + "(L" + JSONSerializer + ";" // + + desc(BeanContext.class) // + + "Ljava/lang/Object;Ljava/lang/String;" // + + valueDesc + ")Ljava/lang/Object;"); + + mw.visitVarInsn(ASTORE, Context.processValue); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processValue", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;"); + mw.visitVarInsn(ALOAD, Context.original); + mw.visitVarInsn(ALOAD, Context.processValue); + mw.visitJumpInsn(IF_ACMPEQ, processKeyElse_); + _writeObject(mw, fieldInfo, context, _end); + mw.visitJumpInsn(GOTO, _end); - mw.visitVarInsn(ASTORE, context.processValue()); + mw.visitLabel(processKeyElse_); } private void _processKey(MethodVisitor mw, FieldInfo property, Context context) { - Method method = property.getMethod(); - Class propertyClass = method.getReturnType(); + Label _else_processKey = new Label(); + + mw.visitVarInsn(ILOAD, context.var("hasNameFilters")); + mw.visitJumpInsn(IFEQ, _else_processKey); + + Class propertyClass = property.fieldClass; - mw.visitVarInsn(ALOAD, context.serializer()); - mw.visitVarInsn(ALOAD, context.obj()); - mw.visitVarInsn(ALOAD, context.fieldName()); + mw.visitVarInsn(ALOAD, 0); + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitVarInsn(ALOAD, Context.obj); + mw.visitVarInsn(ALOAD, Context.fieldName); if (propertyClass == byte.class) { mw.visitVarInsn(ILOAD, context.var("byte")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;B)Ljava/lang/String;"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); } else if (propertyClass == short.class) { mw.visitVarInsn(ILOAD, context.var("short")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;S)Ljava/lang/String;"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;"); } else if (propertyClass == int.class) { mw.visitVarInsn(ILOAD, context.var("int")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;I)Ljava/lang/String;"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); } else if (propertyClass == char.class) { mw.visitVarInsn(ILOAD, context.var("char")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;C)Ljava/lang/String;"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;"); } else if (propertyClass == long.class) { - mw.visitVarInsn(LLOAD, context.var("long")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;J)Ljava/lang/String;"); + mw.visitVarInsn(LLOAD, context.var("long", 2)); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"); } else if (propertyClass == float.class) { mw.visitVarInsn(FLOAD, context.var("float")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;F)Ljava/lang/String;"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); } else if (propertyClass == double.class) { - mw.visitVarInsn(DLOAD, context.var("double")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;D)Ljava/lang/String;"); + mw.visitVarInsn(DLOAD, context.var("double", 2)); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"); } else if (propertyClass == boolean.class) { mw.visitVarInsn(ILOAD, context.var("boolean")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Z)Ljava/lang/String;"); + mw.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"); } else if (propertyClass == BigDecimal.class) { mw.visitVarInsn(ALOAD, context.var("decimal")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;"); } else if (propertyClass == String.class) { mw.visitVarInsn(ALOAD, context.var("string")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;"); } else if (propertyClass.isEnum()) { mw.visitVarInsn(ALOAD, context.var("enum")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;"); - } else if (propertyClass == List.class) { + } else if (List.class.isAssignableFrom(propertyClass)) { mw.visitVarInsn(ALOAD, context.var("list")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;"); } else { mw.visitVarInsn(ALOAD, context.var("object")); - mw.visitMethodInsn(INVOKESTATIC, getType(FilterUtils.class), "processKey", "(Lcom/alibaba/fastjson/serializer/JSONSerializer;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;"); } - mw.visitVarInsn(ASTORE, context.fieldName()); + mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, + "processKey", "(L" + JSONSerializer + + ";Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;"); + + mw.visitVarInsn(ASTORE, Context.fieldName); + + mw.visitLabel(_else_processKey); } private void _if_write_null(MethodVisitor mw, FieldInfo fieldInfo, Context context) { - Method method = fieldInfo.getMethod(); - - Class propertyClass = method.getReturnType(); + Class propertyClass = fieldInfo.fieldClass; Label _if = new Label(); Label _else = new Label(); @@ -939,41 +1985,64 @@ private void _if_write_null(MethodVisitor mw, FieldInfo fieldInfo, Context conte mw.visitLabel(_if); - // out.isEnabled(Serializer.WriteMapNullValue) - boolean writeNull = false; - JSONField annotation = fieldInfo.getAnnotation(JSONField.class); + JSONField annotation = fieldInfo.getAnnotation(); + int features = 0; if (annotation != null) { - for (SerializerFeature feature : annotation.serialzeFeatures()) { - if (feature == SerializerFeature.WriteMapNullValue) { - writeNull = true; - } - } + features = SerializerFeature.of(annotation.serialzeFeatures()); } - - if (!writeNull) { + JSONType jsonType = context.beanInfo.jsonType; + if (jsonType != null) { + features |= SerializerFeature.of(jsonType.serialzeFeatures()); + } + + int writeNullFeatures; + if (propertyClass == String.class) { + writeNullFeatures = SerializerFeature.WriteMapNullValue.getMask() + | SerializerFeature.WriteNullStringAsEmpty.getMask(); + } else if (Number.class.isAssignableFrom(propertyClass)) { + writeNullFeatures = SerializerFeature.WriteMapNullValue.getMask() + | SerializerFeature.WriteNullNumberAsZero.getMask(); + } else if (Collection.class.isAssignableFrom(propertyClass)) { + writeNullFeatures = SerializerFeature.WriteMapNullValue.getMask() + | SerializerFeature.WriteNullListAsEmpty.getMask(); + } else if (Boolean.class == propertyClass) { + writeNullFeatures = SerializerFeature.WriteMapNullValue.getMask() + | SerializerFeature.WriteNullBooleanAsFalse.getMask(); + } else { + writeNullFeatures = SerializerFeature.WriteMapNullValue.getMask(); + } + + if ((features & writeNullFeatures) == 0) { mw.visitVarInsn(ALOAD, context.var("out")); - mw.visitFieldInsn(GETSTATIC, getType(SerializerFeature.class), "WriteMapNullValue", "L" + getType(SerializerFeature.class) + ";"); - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "isEnabled", "(" + "L" + getType(SerializerFeature.class) + ";" + ")Z"); + mw.visitLdcInsn(writeNullFeatures); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isEnabled", "(I)Z"); mw.visitJumpInsn(IFEQ, _else); } - + mw.visitLabel(_write_null); - // out.writeFieldNull(seperator, 'fieldName') + mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(ILOAD, context.var("seperator")); - mw.visitVarInsn(ALOAD, context.fieldName()); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); + + _writeFieldName(mw, context); + + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitLdcInsn(features); + // features if (propertyClass == String.class || propertyClass == Character.class) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldNullString", "(CLjava/lang/String;)V"); + mw.visitLdcInsn(SerializerFeature.WriteNullStringAsEmpty.mask); } else if (Number.class.isAssignableFrom(propertyClass)) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldNullNumber", "(CLjava/lang/String;)V"); + mw.visitLdcInsn(SerializerFeature.WriteNullNumberAsZero.mask); } else if (propertyClass == Boolean.class) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldNullBoolean", "(CLjava/lang/String;)V"); + mw.visitLdcInsn(SerializerFeature.WriteNullBooleanAsFalse.mask); } else if (Collection.class.isAssignableFrom(propertyClass) || propertyClass.isArray()) { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldNullList", "(CLjava/lang/String;)V"); + mw.visitLdcInsn(SerializerFeature.WriteNullListAsEmpty.mask); } else { - mw.visitMethodInsn(INVOKEVIRTUAL, getType(SerializeWriter.class), "writeFieldNull", "(CLjava/lang/String;)V"); + mw.visitLdcInsn(0); } + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeNull", "(II)V"); // seperator = ','; _seperator(mw, context); @@ -985,9 +2054,64 @@ private void _if_write_null(MethodVisitor mw, FieldInfo fieldInfo, Context conte mw.visitLabel(_end_if); } + private void _writeFieldName(MethodVisitor mw, Context context) { + if (context.writeDirect) { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldNameDirect", "(Ljava/lang/String;)V"); + } else { + mw.visitVarInsn(ALOAD, context.var("out")); + mw.visitVarInsn(ALOAD, Context.fieldName); + mw.visitInsn(ICONST_0); + mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldName", "(Ljava/lang/String;Z)V"); + } + } + private void _seperator(MethodVisitor mw, Context context) { mw.visitVarInsn(BIPUSH, ','); mw.visitVarInsn(ISTORE, context.var("seperator")); } + private void _getListFieldItemSer(Context context, MethodVisitor mw, FieldInfo fieldInfo, Class itemType) { + Label notNull_ = new Label(); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_list_item_ser_", + ObjectSerializer_desc); + mw.visitJumpInsn(IFNONNULL, notNull_); + + mw.visitVarInsn(ALOAD, 0); // this + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(itemType))); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "getObjectWriter", + "(Ljava/lang/Class;)" + ObjectSerializer_desc); + + mw.visitFieldInsn(PUTFIELD, context.className, fieldInfo.name + "_asm_list_item_ser_", + ObjectSerializer_desc); + + mw.visitLabel(notNull_); + + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_list_item_ser_", + ObjectSerializer_desc); + } + + private void _getFieldSer(Context context, MethodVisitor mw, FieldInfo fieldInfo) { + Label notNull_ = new Label(); + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_ser_", ObjectSerializer_desc); + mw.visitJumpInsn(IFNONNULL, notNull_); + + mw.visitVarInsn(ALOAD, 0); // this + mw.visitVarInsn(ALOAD, Context.serializer); + mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldInfo.fieldClass))); + mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "getObjectWriter", + "(Ljava/lang/Class;)" + ObjectSerializer_desc); + + mw.visitFieldInsn(PUTFIELD, context.className, fieldInfo.name + "_asm_ser_", ObjectSerializer_desc); + + mw.visitLabel(notNull_); + + mw.visitVarInsn(ALOAD, 0); + mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_ser_", ObjectSerializer_desc); + } } diff --git a/src/main/java/com/alibaba/fastjson/serializer/AdderSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/AdderSerializer.java new file mode 100644 index 0000000000..ecd09566fc --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/AdderSerializer.java @@ -0,0 +1,24 @@ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.concurrent.atomic.DoubleAdder; +import java.util.concurrent.atomic.LongAdder; + +/** + * Created by wenshao on 14/03/2017. + */ +public class AdderSerializer implements ObjectSerializer { + public static final AdderSerializer instance = new AdderSerializer(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + if (object instanceof LongAdder) { + out.writeFieldValue('{', "value", ((LongAdder) object).longValue()); + out.write('}'); + } else if (object instanceof DoubleAdder) { + out.writeFieldValue('{', "value", ((DoubleAdder) object).doubleValue()); + out.write('}'); + } + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/AfterFilter.java b/src/main/java/com/alibaba/fastjson/serializer/AfterFilter.java new file mode 100644 index 0000000000..0c032fcf6d --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/AfterFilter.java @@ -0,0 +1,31 @@ +package com.alibaba.fastjson.serializer; + +/** + * @since 1.1.35 + */ +public abstract class AfterFilter implements SerializeFilter { + + private static final ThreadLocal serializerLocal = new ThreadLocal(); + private static final ThreadLocal seperatorLocal = new ThreadLocal(); + + private final static Character COMMA = Character.valueOf(','); + + final char writeAfter(JSONSerializer serializer, Object object, char seperator) { + serializerLocal.set(serializer); + seperatorLocal.set(seperator); + writeAfter(object); + serializerLocal.set(null); + return seperatorLocal.get(); + } + + protected final void writeKeyValue(String key, Object value) { + JSONSerializer serializer = serializerLocal.get(); + char seperator = seperatorLocal.get(); + serializer.writeKeyValue(seperator, key, value); + if (seperator != ',') { + seperatorLocal.set(COMMA); + } + } + + public abstract void writeAfter(Object object); +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/AnnotationSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/AnnotationSerializer.java new file mode 100644 index 0000000000..66689cdc9e --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/AnnotationSerializer.java @@ -0,0 +1,46 @@ +package com.alibaba.fastjson.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import sun.reflect.annotation.AnnotationType; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.Iterator; +import java.util.Map; + +/** + * Created by wenshao on 10/05/2017. + */ +public class AnnotationSerializer implements ObjectSerializer { + public static AnnotationSerializer instance = new AnnotationSerializer(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + Class objClass = object.getClass(); + Class[] interfaces = objClass.getInterfaces(); + if (interfaces.length == 1 && interfaces[0].isAnnotation()) { + Class annotationClass = interfaces[0]; + AnnotationType type = AnnotationType.getInstance(annotationClass); + Map members = type.members(); + JSONObject json = new JSONObject(members.size()); + Iterator> iterator = members.entrySet().iterator(); + Map.Entry entry; + Object val = null; + while (iterator.hasNext()) { + entry = iterator.next(); + try { + val = entry.getValue().invoke(object); + } catch (IllegalAccessException e) { + // skip + } catch (InvocationTargetException e) { + // skip + } + json.put(entry.getKey(), JSON.toJSON(val)); + } + serializer.write(json); + return; + } + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/AppendableSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/AppendableSerializer.java old mode 100644 new mode 100755 index 202fafefca..7e291acc30 --- a/src/main/java/com/alibaba/fastjson/serializer/AppendableSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/AppendableSerializer.java @@ -1,19 +1,16 @@ package com.alibaba.fastjson.serializer; import java.io.IOException; +import java.lang.reflect.Type; public class AppendableSerializer implements ObjectSerializer { public final static AppendableSerializer instance = new AppendableSerializer(); - public void write(JSONSerializer serializer, Object object) throws IOException { + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { if (object == null) { - SerializeWriter out = serializer.getWriter(); - if (out.isEnabled(SerializerFeature.WriteNullStringAsEmpty)) { - out.writeString(""); - } else { - out.writeNull(); - } + SerializeWriter out = serializer.out; + out.writeNull(SerializerFeature.WriteNullStringAsEmpty); return; } diff --git a/src/main/java/com/alibaba/fastjson/serializer/ArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ArraySerializer.java old mode 100644 new mode 100755 index cc503bae83..dedad4d4d1 --- a/src/main/java/com/alibaba/fastjson/serializer/ArraySerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/ArraySerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,60 +16,60 @@ package com.alibaba.fastjson.serializer; import java.io.IOException; +import java.lang.reflect.Type; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public class ArraySerializer implements ObjectSerializer { + private final Class componentType; private final ObjectSerializer compObjectSerializer; - public ArraySerializer(ObjectSerializer compObjectSerializer){ - super(); + public ArraySerializer(Class componentType, ObjectSerializer compObjectSerializer){ + this.componentType = componentType; this.compObjectSerializer = compObjectSerializer; } - public final void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - + public final void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) + throws IOException { + SerializeWriter out = serializer.out; + if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } + out.writeNull(SerializerFeature.WriteNullListAsEmpty); return; } Object[] array = (Object[]) object; int size = array.length; - int end = size - 1; - - if (end == -1) { - out.append("[]"); - return; - } + SerialContext context = serializer.context; + serializer.setContext(context, object, fieldName, 0); - out.append('['); - for (int i = 0; i < end; ++i) { - Object item = array[i]; + try { + out.append('['); + for (int i = 0; i < size; ++i) { + if (i != 0) { + out.append(','); + } + Object item = array[i]; - if (item == null) { - out.append("null,"); - } else { - compObjectSerializer.write(serializer, item); - out.append(','); + if (item == null) { + if (out.isEnabled(SerializerFeature.WriteNullStringAsEmpty) && object instanceof String[]) { + out.writeString(""); + } else { + out.append("null"); + } + } else if (item.getClass() == componentType) { + compObjectSerializer.write(serializer, item, i, null, 0); + } else { + ObjectSerializer itemSerializer = serializer.getObjectWriter(item.getClass()); + itemSerializer.write(serializer, item, i, null, 0); + } } - } - - Object item = array[end]; - - if (item == null) { - out.append("null]"); - } else { - compObjectSerializer.write(serializer, item); out.append(']'); + } finally { + serializer.context = context; } } } diff --git a/src/main/java/com/alibaba/fastjson/serializer/AtomicBooleanSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/AtomicBooleanSerializer.java deleted file mode 100644 index 6ed688c260..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/AtomicBooleanSerializer.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * @author wenshao - */ -public class AtomicBooleanSerializer implements ObjectSerializer { - - public final static AtomicBooleanSerializer instance = new AtomicBooleanSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - AtomicBoolean val = (AtomicBoolean) object; - if (val.get()) { - out.append("true"); - } else { - out.append("false"); - } - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/AtomicCodec.java b/src/main/java/com/alibaba/fastjson/serializer/AtomicCodec.java new file mode 100755 index 0000000000..1b309cfafc --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/AtomicCodec.java @@ -0,0 +1,123 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicIntegerArray; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicLongArray; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class AtomicCodec implements ObjectSerializer, ObjectDeserializer { + + public final static AtomicCodec instance = new AtomicCodec(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object instanceof AtomicInteger) { + AtomicInteger val = (AtomicInteger) object; + out.writeInt(val.get()); + return; + } + + if (object instanceof AtomicLong) { + AtomicLong val = (AtomicLong) object; + out.writeLong(val.get()); + return; + } + + if (object instanceof AtomicBoolean) { + AtomicBoolean val = (AtomicBoolean) object; + out.append(val.get() ? "true" : "false"); + return; + } + + if (object == null) { + out.writeNull(SerializerFeature.WriteNullListAsEmpty); + return; + } + + if (object instanceof AtomicIntegerArray) { + AtomicIntegerArray array = (AtomicIntegerArray) object; + int len = array.length(); + out.write('['); + for (int i = 0; i < len; ++i) { + int val = array.get(i); + if (i != 0) { + out.write(','); + } + out.writeInt(val); + } + out.write(']'); + + return; + } + + AtomicLongArray array = (AtomicLongArray) object; + int len = array.length(); + out.write('['); + for (int i = 0; i < len; ++i) { + long val = array.get(i); + if (i != 0) { + out.write(','); + } + out.writeLong(val); + } + out.write(']'); + } + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + if (parser.lexer.token() == JSONToken.NULL) { + parser.lexer.nextToken(JSONToken.COMMA); + return null; + } + + JSONArray array = new JSONArray(); + parser.parseArray(array); + + if (clazz == AtomicIntegerArray.class) { + AtomicIntegerArray atomicArray = new AtomicIntegerArray(array.size()); + for (int i = 0; i < array.size(); ++i) { + atomicArray.set(i, array.getInteger(i)); + } + + return (T) atomicArray; + } + + AtomicLongArray atomicArray = new AtomicLongArray(array.size()); + for (int i = 0; i < array.size(); ++i) { + atomicArray.set(i, array.getLong(i)); + } + + return (T) atomicArray; + } + + public int getFastMatchToken() { + return JSONToken.LBRACKET; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/AtomicIntegerArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/AtomicIntegerArraySerializer.java deleted file mode 100644 index eb36d9c785..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/AtomicIntegerArraySerializer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicIntegerArray; - -/** - * @author wenshao - */ -public class AtomicIntegerArraySerializer implements ObjectSerializer { - - public final static AtomicIntegerArraySerializer instance = new AtomicIntegerArraySerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } - return; - } - - AtomicIntegerArray array = (AtomicIntegerArray) object; - int len = array.length(); - out.append('['); - for (int i = 0; i < len; ++i) { - int val = array.get(i); - if (i != 0) { - out.write(','); - } - out.writeInt(val); - } - out.append(']'); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/AtomicIntegerSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/AtomicIntegerSerializer.java deleted file mode 100644 index 67948a3324..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/AtomicIntegerSerializer.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @author wenshao - */ -public class AtomicIntegerSerializer implements ObjectSerializer { - - public final static AtomicIntegerSerializer instance = new AtomicIntegerSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - AtomicInteger val = (AtomicInteger) object; - out.writeInt(val.get()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/AtomicLongArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/AtomicLongArraySerializer.java deleted file mode 100644 index ee4d61093e..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/AtomicLongArraySerializer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicLongArray; - -/** - * @author wenshao - */ -public class AtomicLongArraySerializer implements ObjectSerializer { - - public final static AtomicLongArraySerializer instance = new AtomicLongArraySerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } - return; - } - - AtomicLongArray array = (AtomicLongArray) object; - int len = array.length(); - out.append('['); - for (int i = 0; i < len; ++i) { - long val = array.get(i); - if (i != 0) { - out.write(','); - } - out.writeLong(val); - } - out.append(']'); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/AtomicLongSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/AtomicLongSerializer.java deleted file mode 100644 index e70df156af..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/AtomicLongSerializer.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicLong; - -/** - * @author wenshao - */ -public class AtomicLongSerializer implements ObjectSerializer { - - public final static AtomicLongSerializer instance = new AtomicLongSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - AtomicLong val = (AtomicLong) object; - out.writeLong(val.get()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/AtomicReferenceSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/AtomicReferenceSerializer.java deleted file mode 100644 index 1af821bc36..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/AtomicReferenceSerializer.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicReference; - -/** - * @author wenshao - */ -public class AtomicReferenceSerializer implements ObjectSerializer { - - public final static AtomicReferenceSerializer instance = new AtomicReferenceSerializer(); - - @SuppressWarnings("rawtypes") - public void write(JSONSerializer serializer, Object object) throws IOException { - AtomicReference val = (AtomicReference) object; - serializer.write(val.get()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/AutowiredObjectSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/AutowiredObjectSerializer.java old mode 100644 new mode 100755 index 32e85e84c4..7bc3e1db7f --- a/src/main/java/com/alibaba/fastjson/serializer/AutowiredObjectSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/AutowiredObjectSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ import java.util.Set; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public interface AutowiredObjectSerializer extends ObjectSerializer { Set getAutowiredFor(); diff --git a/src/main/java/com/alibaba/fastjson/serializer/AwtCodec.java b/src/main/java/com/alibaba/fastjson/serializer/AwtCodec.java new file mode 100644 index 0000000000..5556e38f31 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/AwtCodec.java @@ -0,0 +1,350 @@ +package com.alibaba.fastjson.serializer; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Point; +import java.awt.Rectangle; +import java.io.IOException; +import java.lang.reflect.Type; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParseContext; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +public class AwtCodec implements ObjectSerializer, ObjectDeserializer { + + public final static AwtCodec instance = new AwtCodec(); + + public static boolean support(Class clazz) { + return clazz == Point.class // + || clazz == Rectangle.class // + || clazz == Font.class // + || clazz == Color.class // + ; + } + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, + int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(); + return; + } + + char sep = '{'; + + if (object instanceof Point) { + Point font = (Point) object; + + sep = writeClassName(out, Point.class, sep); + + out.writeFieldValue(sep, "x", font.x); + out.writeFieldValue(',', "y", font.y); + } else if (object instanceof Font) { + Font font = (Font) object; + + sep = writeClassName(out, Font.class, sep); + + out.writeFieldValue(sep, "name", font.getName()); + out.writeFieldValue(',', "style", font.getStyle()); + out.writeFieldValue(',', "size", font.getSize()); + } else if (object instanceof Rectangle) { + Rectangle rectangle = (Rectangle) object; + + sep = writeClassName(out, Rectangle.class, sep); + + out.writeFieldValue(sep, "x", rectangle.x); + out.writeFieldValue(',', "y", rectangle.y); + out.writeFieldValue(',', "width", rectangle.width); + out.writeFieldValue(',', "height", rectangle.height); + } else if (object instanceof Color) { + Color color = (Color) object; + + sep = writeClassName(out, Color.class, sep); + + out.writeFieldValue(sep, "r", color.getRed()); + out.writeFieldValue(',', "g", color.getGreen()); + out.writeFieldValue(',', "b", color.getBlue()); + if (color.getAlpha() > 0) { + out.writeFieldValue(',', "alpha", color.getAlpha()); + } + } else { + throw new JSONException("not support awt class : " + object.getClass().getName()); + } + + out.write('}'); + + } + + protected char writeClassName(SerializeWriter out, Class clazz, char sep) { + if (out.isEnabled(SerializerFeature.WriteClassName)) { + out.write('{'); + out.writeFieldName(JSON.DEFAULT_TYPE_KEY); + out.writeString(clazz.getName()); + sep = ','; + } + return sep; + } + + @SuppressWarnings("unchecked") + + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + JSONLexer lexer = parser.lexer; + + if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(JSONToken.COMMA); + return null; + } + + if (lexer.token() != JSONToken.LBRACE && lexer.token() != JSONToken.COMMA) { + throw new JSONException("syntax error"); + } + lexer.nextToken(); + + T obj; + if (type == Point.class) { + obj = (T) parsePoint(parser, fieldName); + } else if (type == Rectangle.class) { + obj = (T) parseRectangle(parser); + } else if (type == Color.class) { + obj = (T) parseColor(parser); + } else if (type == Font.class) { + obj = (T) parseFont(parser); + } else { + throw new JSONException("not support awt class : " + type); + } + + ParseContext context = parser.getContext(); + parser.setContext(obj, fieldName); + parser.setContext(context); + + return obj; + } + + protected Font parseFont(DefaultJSONParser parser) { + JSONLexer lexer = parser.lexer; + + int size = 0, style = 0; + String name = null; + for (;;) { + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + break; + } + + String key; + if (lexer.token() == JSONToken.LITERAL_STRING) { + key = lexer.stringVal(); + lexer.nextTokenWithColon(JSONToken.LITERAL_INT); + } else { + throw new JSONException("syntax error"); + } + + + if (key.equalsIgnoreCase("name")) { + if (lexer.token() == JSONToken.LITERAL_STRING) { + name = lexer.stringVal(); + lexer.nextToken(); + } else { + throw new JSONException("syntax error"); + } + } else if (key.equalsIgnoreCase("style")) { + if (lexer.token() == JSONToken.LITERAL_INT) { + style = lexer.intValue(); + lexer.nextToken(); + } else { + throw new JSONException("syntax error"); + } + } else if (key.equalsIgnoreCase("size")) { + if (lexer.token() == JSONToken.LITERAL_INT) { + size = lexer.intValue(); + lexer.nextToken(); + } else { + throw new JSONException("syntax error"); + } + } else { + throw new JSONException("syntax error, " + key); + } + + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(JSONToken.LITERAL_STRING); + } + } + + return new Font(name, style, size); + } + + protected Color parseColor(DefaultJSONParser parser) { + JSONLexer lexer = parser.lexer; + + int r = 0, g = 0, b = 0, alpha = 0; + for (;;) { + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + break; + } + + String key; + if (lexer.token() == JSONToken.LITERAL_STRING) { + key = lexer.stringVal(); + lexer.nextTokenWithColon(JSONToken.LITERAL_INT); + } else { + throw new JSONException("syntax error"); + } + + int val; + if (lexer.token() == JSONToken.LITERAL_INT) { + val = lexer.intValue(); + lexer.nextToken(); + } else { + throw new JSONException("syntax error"); + } + + if (key.equalsIgnoreCase("r")) { + r = val; + } else if (key.equalsIgnoreCase("g")) { + g = val; + } else if (key.equalsIgnoreCase("b")) { + b = val; + } else if (key.equalsIgnoreCase("alpha")) { + alpha = val; + } else { + throw new JSONException("syntax error, " + key); + } + + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(JSONToken.LITERAL_STRING); + } + } + + return new Color(r, g, b, alpha); + } + + protected Rectangle parseRectangle(DefaultJSONParser parser) { + JSONLexer lexer = parser.lexer; + + int x = 0, y = 0, width = 0, height = 0; + for (;;) { + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + break; + } + + String key; + if (lexer.token() == JSONToken.LITERAL_STRING) { + key = lexer.stringVal(); + lexer.nextTokenWithColon(JSONToken.LITERAL_INT); + } else { + throw new JSONException("syntax error"); + } + + int val; + int token = lexer.token(); + if (token == JSONToken.LITERAL_INT) { + val = lexer.intValue(); + lexer.nextToken(); + } else if (token == JSONToken.LITERAL_FLOAT) { + val = (int) lexer.floatValue(); + lexer.nextToken(); + } else { + throw new JSONException("syntax error"); + } + + if (key.equalsIgnoreCase("x")) { + x = val; + } else if (key.equalsIgnoreCase("y")) { + y = val; + } else if (key.equalsIgnoreCase("width")) { + width = val; + } else if (key.equalsIgnoreCase("height")) { + height = val; + } else { + throw new JSONException("syntax error, " + key); + } + + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(JSONToken.LITERAL_STRING); + } + } + + return new Rectangle(x, y, width, height); + } + + protected Point parsePoint(DefaultJSONParser parser, Object fieldName) { + JSONLexer lexer = parser.lexer; + + int x = 0, y = 0; + for (;;) { + if (lexer.token() == JSONToken.RBRACE) { + lexer.nextToken(); + break; + } + + String key; + if (lexer.token() == JSONToken.LITERAL_STRING) { + key = lexer.stringVal(); + + if (JSON.DEFAULT_TYPE_KEY.equals(key)) { + parser.acceptType("java.awt.Point"); + continue; + } + + if ("$ref".equals(key)) { + return (Point) parseRef(parser, fieldName); + } + + lexer.nextTokenWithColon(JSONToken.LITERAL_INT); + } else { + throw new JSONException("syntax error"); + } + + int token = lexer.token(); + int val; + if (token == JSONToken.LITERAL_INT) { + val = lexer.intValue(); + lexer.nextToken(); + } else if(token == JSONToken.LITERAL_FLOAT) { + val = (int) lexer.floatValue(); + lexer.nextToken(); + } else { + throw new JSONException("syntax error : " + lexer.tokenName()); + } + + if (key.equalsIgnoreCase("x")) { + x = val; + } else if (key.equalsIgnoreCase("y")) { + y = val; + } else { + throw new JSONException("syntax error, " + key); + } + + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(JSONToken.LITERAL_STRING); + } + } + + return new Point(x, y); + } + + private Object parseRef(DefaultJSONParser parser, Object fieldName) { + JSONLexer lexer = parser.getLexer(); + lexer.nextTokenWithColon(JSONToken.LITERAL_STRING); + String ref = lexer.stringVal(); + parser.setContext(parser.getContext(), fieldName); + parser.addResolveTask(new DefaultJSONParser.ResolveTask(parser.getContext(), ref)); + parser.popContext(); + parser.setResolveStatus(DefaultJSONParser.NeedToResolve); + lexer.nextToken(JSONToken.RBRACE); + parser.accept(JSONToken.RBRACE); + return null; + } + + public int getFastMatchToken() { + return JSONToken.LBRACE; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/BeanContext.java b/src/main/java/com/alibaba/fastjson/serializer/BeanContext.java new file mode 100644 index 0000000000..8513476d6e --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/BeanContext.java @@ -0,0 +1,69 @@ +package com.alibaba.fastjson.serializer; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Type; + +import com.alibaba.fastjson.util.FieldInfo; + +/** + * @since 1.2.9 + * + */ +public final class BeanContext { + + private final Class beanClass; + private final FieldInfo fieldInfo; + private final String format; + + public BeanContext(Class beanClass, FieldInfo fieldInfo){ + this.beanClass = beanClass; + this.fieldInfo = fieldInfo; + this.format = fieldInfo.getFormat(); + } + + public Class getBeanClass() { + return beanClass; + } + + public Method getMethod() { + return fieldInfo.method; + } + + public Field getField() { + return fieldInfo.field; + } + + public String getName() { + return fieldInfo.name; + } + + public String getLabel() { + return fieldInfo.label; + } + + public Class getFieldClass() { + return fieldInfo.fieldClass; + } + + public Type getFieldType() { + return fieldInfo.fieldType; + } + + public int getFeatures() { + return fieldInfo.serialzeFeatures; + } + + public boolean isJsonDirect() { + return this.fieldInfo.jsonDirect; + } + + public T getAnnation(Class annotationClass) { + return fieldInfo.getAnnation(annotationClass); + } + + public String getFormat() { + return format; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/BeforeFilter.java b/src/main/java/com/alibaba/fastjson/serializer/BeforeFilter.java new file mode 100644 index 0000000000..34ed06041d --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/BeforeFilter.java @@ -0,0 +1,28 @@ +package com.alibaba.fastjson.serializer; + +public abstract class BeforeFilter implements SerializeFilter { + + private static final ThreadLocal serializerLocal = new ThreadLocal(); + private static final ThreadLocal seperatorLocal = new ThreadLocal(); + + private final static Character COMMA = Character.valueOf(','); + + final char writeBefore(JSONSerializer serializer, Object object, char seperator) { + serializerLocal.set(serializer); + seperatorLocal.set(seperator); + writeBefore(object); + serializerLocal.set(null); + return seperatorLocal.get(); + } + + protected final void writeKeyValue(String key, Object value) { + JSONSerializer serializer = serializerLocal.get(); + char seperator = seperatorLocal.get(); + serializer.writeKeyValue(seperator, key, value); + if (seperator != ',') { + seperatorLocal.set(COMMA); + } + } + + public abstract void writeBefore(Object object); +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/BigDecimalCodec.java b/src/main/java/com/alibaba/fastjson/serializer/BigDecimalCodec.java new file mode 100755 index 0000000000..e8ed25cd4c --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/BigDecimalCodec.java @@ -0,0 +1,91 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.math.BigDecimal; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class BigDecimalCodec implements ObjectSerializer, ObjectDeserializer { + + public final static BigDecimalCodec instance = new BigDecimalCodec(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(SerializerFeature.WriteNullNumberAsZero); + } else { + BigDecimal val = (BigDecimal) object; + + String outText; + if (out.isEnabled(SerializerFeature.WriteBigDecimalAsPlain)) { + outText = val.toPlainString(); + } else { + outText = val.toString(); + } + out.write(outText); + + if (out.isEnabled(SerializerFeature.WriteClassName) && fieldType != BigDecimal.class && val.scale() == 0) { + out.write('.'); + } + } + } + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + try { + return (T) deserialze(parser); + } catch (Exception ex) { + throw new JSONException("parseDecimal error, field : " + fieldName, ex); + } + } + + @SuppressWarnings("unchecked") + public static T deserialze(DefaultJSONParser parser) { + final JSONLexer lexer = parser.lexer; + if (lexer.token() == JSONToken.LITERAL_INT) { + BigDecimal decimalValue = lexer.decimalValue(); + lexer.nextToken(JSONToken.COMMA); + return (T) decimalValue; + } + + if (lexer.token() == JSONToken.LITERAL_FLOAT) { + BigDecimal val = lexer.decimalValue(); + lexer.nextToken(JSONToken.COMMA); + return (T) val; + } + + Object value = parser.parse(); + return value == null // + ? null // + : (T) TypeUtils.castToBigDecimal(value); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_INT; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/BigDecimalSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/BigDecimalSerializer.java deleted file mode 100644 index 18ffdce003..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/BigDecimalSerializer.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.math.BigDecimal; - -/** - * @author wenshao - */ -public class BigDecimalSerializer implements ObjectSerializer { - - public final static BigDecimalSerializer instance = new BigDecimalSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullNumberAsZero)) { - out.write('0'); - } else { - out.writeNull(); - } - return; - } - - BigDecimal val = (BigDecimal) object; - out.write(val.toString()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/BigIntegerCodec.java b/src/main/java/com/alibaba/fastjson/serializer/BigIntegerCodec.java new file mode 100755 index 0000000000..7bfa5d6c68 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/BigIntegerCodec.java @@ -0,0 +1,70 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.math.BigInteger; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class BigIntegerCodec implements ObjectSerializer, ObjectDeserializer { + + public final static BigIntegerCodec instance = new BigIntegerCodec(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(SerializerFeature.WriteNullNumberAsZero); + return; + } + + BigInteger val = (BigInteger) object; + out.write(val.toString()); + } + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + return (T) deserialze(parser); + } + + @SuppressWarnings("unchecked") + public static T deserialze(DefaultJSONParser parser) { + final JSONLexer lexer = parser.lexer; + if (lexer.token() == JSONToken.LITERAL_INT) { + String val = lexer.numberString(); + lexer.nextToken(JSONToken.COMMA); + return (T) new BigInteger(val); + } + + Object value = parser.parse(); + return value == null // + ? null // + : (T) TypeUtils.castToBigInteger(value); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_INT; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/BigIntegerSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/BigIntegerSerializer.java deleted file mode 100644 index c414ce345e..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/BigIntegerSerializer.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.math.BigInteger; - -/** - * @author wenshao - */ -public class BigIntegerSerializer implements ObjectSerializer { - - public final static BigIntegerSerializer instance = new BigIntegerSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullNumberAsZero)) { - out.write('0'); - } else { - out.writeNull(); - } - return; - } - - BigInteger val = (BigInteger) object; - out.write(val.toString()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/BooleanArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/BooleanArraySerializer.java deleted file mode 100644 index 9720c6fae6..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/BooleanArraySerializer.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class BooleanArraySerializer implements ObjectSerializer { - - public static BooleanArraySerializer instance = new BooleanArraySerializer(); - - public final void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } - return; - } - - out.writeBooleanArray((boolean[]) object); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/BooleanCodec.java b/src/main/java/com/alibaba/fastjson/serializer/BooleanCodec.java new file mode 100755 index 0000000000..c485172eb0 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/BooleanCodec.java @@ -0,0 +1,97 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.concurrent.atomic.AtomicBoolean; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class BooleanCodec implements ObjectSerializer, ObjectDeserializer { + + public final static BooleanCodec instance = new BooleanCodec(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + Boolean value = (Boolean) object; + if (value == null) { + out.writeNull(SerializerFeature.WriteNullBooleanAsFalse); + return; + } + + if (value.booleanValue()) { + out.write("true"); + } else { + out.write("false"); + } + } + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + final JSONLexer lexer = parser.lexer; + + Boolean boolObj; + + try { + if (lexer.token() == JSONToken.TRUE) { + lexer.nextToken(JSONToken.COMMA); + boolObj = Boolean.TRUE; + } else if (lexer.token() == JSONToken.FALSE) { + lexer.nextToken(JSONToken.COMMA); + boolObj = Boolean.FALSE; + } else if (lexer.token() == JSONToken.LITERAL_INT) { + int intValue = lexer.intValue(); + lexer.nextToken(JSONToken.COMMA); + + if (intValue == 1) { + boolObj = Boolean.TRUE; + } else { + boolObj = Boolean.FALSE; + } + } else { + Object value = parser.parse(); + + if (value == null) { + return null; + } + + boolObj = TypeUtils.castToBoolean(value); + } + } catch (Exception ex) { + throw new JSONException("parseBoolean error, field : " + fieldName, ex); + } + + if (clazz == AtomicBoolean.class) { + return (T) new AtomicBoolean(boolObj.booleanValue()); + } + + return (T) boolObj; + } + + public int getFastMatchToken() { + return JSONToken.TRUE; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/BooleanSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/BooleanSerializer.java deleted file mode 100644 index 01798cdb5e..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/BooleanSerializer.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class BooleanSerializer implements ObjectSerializer { - - public final static BooleanSerializer instance = new BooleanSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - Boolean value = (Boolean) object; - if (value == null) { - if (out.isEnabled(SerializerFeature.WriteNullBooleanAsFalse)) { - out.write("false"); - } else { - out.writeNull(); - } - return; - } - - if (value.booleanValue()) { - out.write("true"); - } else { - out.write("false"); - } - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ByteArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ByteArraySerializer.java deleted file mode 100644 index 9fb65cc291..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/ByteArraySerializer.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class ByteArraySerializer implements ObjectSerializer { - - public static ByteArraySerializer instance = new ByteArraySerializer(); - - public final void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } - return; - } - - byte[] array = (byte[]) object; - out.writeByteArray(array); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/CalendarCodec.java b/src/main/java/com/alibaba/fastjson/serializer/CalendarCodec.java new file mode 100755 index 0000000000..a29a1666a0 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/CalendarCodec.java @@ -0,0 +1,139 @@ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.IOUtils; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; + +public class CalendarCodec implements ObjectSerializer, ObjectDeserializer { + + public final static CalendarCodec instance = new CalendarCodec(); + + private DatatypeFactory dateFactory; + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) + throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(); + return; + } + + Calendar calendar; + if (object instanceof XMLGregorianCalendar) { + calendar = ((XMLGregorianCalendar) object).toGregorianCalendar(); + } else { + calendar = (Calendar) object; + } + + if (out.isEnabled(SerializerFeature.UseISO8601DateFormat)) { + final char quote = out.isEnabled(SerializerFeature.UseSingleQuotes) // + ? '\'' // + : '\"'; + out.append(quote); + + int year = calendar.get(Calendar.YEAR); + int month = calendar.get(Calendar.MONTH) + 1; + int day = calendar.get(Calendar.DAY_OF_MONTH); + int hour = calendar.get(Calendar.HOUR_OF_DAY); + int minute = calendar.get(Calendar.MINUTE); + int second = calendar.get(Calendar.SECOND); + int millis = calendar.get(Calendar.MILLISECOND); + + char[] buf; + if (millis != 0) { + buf = "0000-00-00T00:00:00.000".toCharArray(); + IOUtils.getChars(millis, 23, buf); + IOUtils.getChars(second, 19, buf); + IOUtils.getChars(minute, 16, buf); + IOUtils.getChars(hour, 13, buf); + IOUtils.getChars(day, 10, buf); + IOUtils.getChars(month, 7, buf); + IOUtils.getChars(year, 4, buf); + + } else { + if (second == 0 && minute == 0 && hour == 0) { + buf = "0000-00-00".toCharArray(); + IOUtils.getChars(day, 10, buf); + IOUtils.getChars(month, 7, buf); + IOUtils.getChars(year, 4, buf); + } else { + buf = "0000-00-00T00:00:00".toCharArray(); + IOUtils.getChars(second, 19, buf); + IOUtils.getChars(minute, 16, buf); + IOUtils.getChars(hour, 13, buf); + IOUtils.getChars(day, 10, buf); + IOUtils.getChars(month, 7, buf); + IOUtils.getChars(year, 4, buf); + } + } + + out.write(buf); + + int timeZone = calendar.getTimeZone().getRawOffset() / (3600 * 1000); + if (timeZone == 0) { + out.append("Z"); + } else if (timeZone > 0) { + out.append("+").append(String.format("%02d", timeZone)).append(":00"); + } else { + out.append("-").append(String.format("%02d", -timeZone)).append(":00"); + } + + out.append(quote); + } else { + Date date = calendar.getTime(); + serializer.write(date); + } + } + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + Object value = DateCodec.instance.deserialze(parser, type, fieldName); + + if (value instanceof Calendar) { + return (T) value; + } + + Date date = (Date) value; + if (date == null) { + return null; + } + + JSONLexer lexer = parser.lexer; + Calendar calendar = Calendar.getInstance(lexer.getTimeZone(), lexer.getLocale()); + calendar.setTime(date); + + if (type == XMLGregorianCalendar.class) { + return (T) createXMLGregorianCalendar((GregorianCalendar) calendar); + } + + return (T) calendar; + } + + public XMLGregorianCalendar createXMLGregorianCalendar(Calendar calendar) { + if (dateFactory == null) { + try { + dateFactory = DatatypeFactory.newInstance(); + } catch (DatatypeConfigurationException e) { + throw new IllegalStateException("Could not obtain an instance of DatatypeFactory.", e); + } + } + return dateFactory.newXMLGregorianCalendar((GregorianCalendar) calendar); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_INT; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/CharArrayCodec.java b/src/main/java/com/alibaba/fastjson/serializer/CharArrayCodec.java new file mode 100755 index 0000000000..afafcc1eab --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/CharArrayCodec.java @@ -0,0 +1,77 @@ +package com.alibaba.fastjson.serializer; + +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.List; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + + +public class CharArrayCodec implements ObjectDeserializer { + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + return (T) deserialze(parser); + } + + @SuppressWarnings("unchecked") + public static T deserialze(DefaultJSONParser parser) { + final JSONLexer lexer = parser.lexer; + if (lexer.token() == JSONToken.LITERAL_STRING) { + String val = lexer.stringVal(); + lexer.nextToken(JSONToken.COMMA); + return (T) val.toCharArray(); + } + + if (lexer.token() == JSONToken.LITERAL_INT) { + Number val = lexer.integerValue(); + lexer.nextToken(JSONToken.COMMA); + return (T) val.toString().toCharArray(); + } + + Object value = parser.parse(); + + if (value instanceof String) { + return (T) ((String) value).toCharArray(); + } + + if (value instanceof Collection) { + Collection collection = (Collection) value; + + boolean accept = true; + for (Object item : collection) { + if (item instanceof String) { + int itemLength = ((String) item).length(); + if (itemLength != 1) { + accept = false; + break; + } + } + } + + if (!accept) { + throw new JSONException("can not cast to char[]"); + } + + char[] chars = new char[collection.size()]; + int pos = 0; + for (Object item : collection) { + chars[pos++] = ((String) item).charAt(0); + } + return (T) chars; + } + + return value == null // + ? null // + : (T) JSON.toJSONString(value).toCharArray(); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_STRING; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/CharacterCodec.java b/src/main/java/com/alibaba/fastjson/serializer/CharacterCodec.java new file mode 100755 index 0000000000..6f82c4f2ca --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/CharacterCodec.java @@ -0,0 +1,61 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class CharacterCodec implements ObjectSerializer, ObjectDeserializer { + + public final static CharacterCodec instance = new CharacterCodec(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + Character value = (Character) object; + if (value == null) { + out.writeString(""); + return; + } + + char c = value.charValue(); + if (c == 0) { + out.writeString("\u0000"); + } else { + out.writeString(value.toString()); + } + } + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + Object value = parser.parse(); + return value == null // + ? null // + : (T) TypeUtils.castToChar(value); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_STRING; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/CharacterSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/CharacterSerializer.java deleted file mode 100644 index 5d6493c591..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/CharacterSerializer.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class CharacterSerializer implements ObjectSerializer { - - public final static CharacterSerializer instance = new CharacterSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - Character value = (Character) object; - if (value == null) { - out.writeString(""); - return; - } - - char c = value.charValue(); - if (c == 0) { - out.writeString("\u0000"); - } else { - out.writeString(value.toString()); - } - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/CharsetSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/CharsetSerializer.java deleted file mode 100644 index 3eaab7ab54..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/CharsetSerializer.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.nio.charset.Charset; - - -public class CharsetSerializer implements ObjectSerializer { - - public final static CharsetSerializer instance = new CharsetSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - if (object == null) { - serializer.writeNull(); - return; - } - - Charset charset = (Charset) object; - serializer.write(charset.toString()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ClassSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ClassSerializer.java deleted file mode 100644 index fa00439a83..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/ClassSerializer.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class ClassSerializer implements ObjectSerializer { - - public final static ClassSerializer instance = new ClassSerializer(); - - @SuppressWarnings("rawtypes") - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - Class clazz = (Class) object; - out.writeString(clazz.getName()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ClobSeriliazer.java b/src/main/java/com/alibaba/fastjson/serializer/ClobSeriliazer.java new file mode 100755 index 0000000000..0605dd6600 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/ClobSeriliazer.java @@ -0,0 +1,48 @@ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.io.Reader; +import java.lang.reflect.Type; +import java.sql.Clob; +import java.sql.SQLException; + +import com.alibaba.fastjson.JSONException; + +public class ClobSeriliazer implements ObjectSerializer { + + public final static ClobSeriliazer instance = new ClobSeriliazer(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + try { + if (object == null) { + serializer.writeNull(); + return; + } + + Clob clob = (Clob) object; + Reader reader = clob.getCharacterStream(); + + StringBuilder buf = new StringBuilder(); + + try { + char[] chars = new char[2048]; + for (;;) { + int len = reader.read(chars, 0, chars.length); + if (len < 0) { + break; + } + buf.append(chars, 0, len); + } + } catch(Exception ex) { + throw new JSONException("read string from reader error", ex); + } + + String text = buf.toString(); + reader.close(); + serializer.write(text); + } catch (SQLException e) { + throw new IOException("write clob error", e); + } + } + +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/CollectionCodec.java b/src/main/java/com/alibaba/fastjson/serializer/CollectionCodec.java new file mode 100755 index 0000000000..b559356af0 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/CollectionCodec.java @@ -0,0 +1,139 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.TreeSet; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class CollectionCodec implements ObjectSerializer, ObjectDeserializer { + + public final static CollectionCodec instance = new CollectionCodec(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(SerializerFeature.WriteNullListAsEmpty); + return; + } + + Type elementType = null; + if (out.isEnabled(SerializerFeature.WriteClassName) + || SerializerFeature.isEnabled(features, SerializerFeature.WriteClassName)) + { + elementType = TypeUtils.getCollectionItemType(fieldType); + } + + Collection collection = (Collection) object; + + SerialContext context = serializer.context; + serializer.setContext(context, object, fieldName, 0); + + if (out.isEnabled(SerializerFeature.WriteClassName)) { + if (HashSet.class == collection.getClass()) { + out.append("Set"); + } else if (TreeSet.class == collection.getClass()) { + out.append("TreeSet"); + } + } + + try { + int i = 0; + out.append('['); + for (Object item : collection) { + + if (i++ != 0) { + out.append(','); + } + + if (item == null) { + out.writeNull(); + continue; + } + + Class clazz = item.getClass(); + + if (clazz == Integer.class) { + out.writeInt(((Integer) item).intValue()); + continue; + } + + if (clazz == Long.class) { + out.writeLong(((Long) item).longValue()); + + if (out.isEnabled(SerializerFeature.WriteClassName)) { + out.write('L'); + } + continue; + } + + ObjectSerializer itemSerializer = serializer.getObjectWriter(clazz); + if (SerializerFeature.isEnabled(features, SerializerFeature.WriteClassName) + && itemSerializer instanceof JavaBeanSerializer) { + JavaBeanSerializer javaBeanSerializer = (JavaBeanSerializer) itemSerializer; + javaBeanSerializer.writeNoneASM(serializer, item, i - 1, elementType, features); + } else { + itemSerializer.write(serializer, item, i - 1, elementType, features); + } + } + out.append(']'); + } finally { + serializer.context = context; + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + if (parser.lexer.token() == JSONToken.NULL) { + parser.lexer.nextToken(JSONToken.COMMA); + return null; + } + + if (type == JSONArray.class) { + JSONArray array = new JSONArray(); + parser.parseArray(array); + return (T) array; + } + + Collection list = TypeUtils.createCollection(type); + + Type itemType = TypeUtils.getCollectionItemType(type); + parser.parseArray(itemType, list, fieldName); + + return (T) list; + } + + + + public int getFastMatchToken() { + return JSONToken.LBRACKET; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/CollectionSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/CollectionSerializer.java deleted file mode 100644 index feae5169da..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/CollectionSerializer.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.Collection; - -/** - * @author wenshao - */ -public class CollectionSerializer implements ObjectSerializer { - - public final static CollectionSerializer instance = new CollectionSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } - return; - } - - Collection collection = (Collection) object; - - out.append('['); - boolean first = true; - for (Object item : collection) { - if (!first) { - out.append(','); - } - first = false; - - if (item == null) { - out.writeNull(); - continue; - } - - Class clazz = item.getClass(); - - if (clazz == Integer.class) { - out.writeInt(((Integer) item).intValue()); - continue; - } - - if (clazz == Long.class) { - out.writeLong(((Long) item).longValue()); - continue; - } - - serializer.write(item); - } - out.append(']'); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ContextObjectSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ContextObjectSerializer.java new file mode 100644 index 0000000000..c6865e1010 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/ContextObjectSerializer.java @@ -0,0 +1,9 @@ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; + +public interface ContextObjectSerializer extends ObjectSerializer { + void write(JSONSerializer serializer, // + Object object, // + BeanContext context) throws IOException; +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ContextValueFilter.java b/src/main/java/com/alibaba/fastjson/serializer/ContextValueFilter.java new file mode 100644 index 0000000000..22d0ff846c --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/ContextValueFilter.java @@ -0,0 +1,9 @@ +package com.alibaba.fastjson.serializer; + +/** + * @since 1.2.9 + * + */ +public interface ContextValueFilter extends SerializeFilter { + Object process(BeanContext context, Object object, String name, Object value); +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/DateCodec.java b/src/main/java/com/alibaba/fastjson/serializer/DateCodec.java new file mode 100644 index 0000000000..90e428d671 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/DateCodec.java @@ -0,0 +1,255 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONScanner; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.AbstractDateDeserializer; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.IOUtils; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class DateCodec extends AbstractDateDeserializer implements ObjectSerializer, ObjectDeserializer { + + public final static DateCodec instance = new DateCodec(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(); + return; + } + + Date date; + if (object instanceof Date) { + date = (Date) object; + } else { + date = TypeUtils.castToDate(object); + } + + if (out.isEnabled(SerializerFeature.WriteDateUseDateFormat)) { + DateFormat format = serializer.getDateFormat(); + if (format == null) { + format = new SimpleDateFormat(JSON.DEFFAULT_DATE_FORMAT, serializer.locale); + format.setTimeZone(serializer.timeZone); + } + String text = format.format(date); + out.writeString(text); + return; + } + + if (out.isEnabled(SerializerFeature.WriteClassName)) { + if (object.getClass() != fieldType) { + if (object.getClass() == java.util.Date.class) { + out.write("new Date("); + out.writeLong(((Date) object).getTime()); + out.write(')'); + } else { + out.write('{'); + out.writeFieldName(JSON.DEFAULT_TYPE_KEY); + serializer.write(object.getClass().getName()); + out.writeFieldValue(',', "val", ((Date) object).getTime()); + out.write('}'); + } + return; + } + } + + long time = date.getTime(); + if (out.isEnabled(SerializerFeature.UseISO8601DateFormat)) { + char quote = out.isEnabled(SerializerFeature.UseSingleQuotes) ? '\'' : '\"'; + out.write(quote); + + Calendar calendar = Calendar.getInstance(serializer.timeZone, serializer.locale); + calendar.setTimeInMillis(time); + + int year = calendar.get(Calendar.YEAR); + int month = calendar.get(Calendar.MONTH) + 1; + int day = calendar.get(Calendar.DAY_OF_MONTH); + int hour = calendar.get(Calendar.HOUR_OF_DAY); + int minute = calendar.get(Calendar.MINUTE); + int second = calendar.get(Calendar.SECOND); + int millis = calendar.get(Calendar.MILLISECOND); + + char[] buf; + if (millis != 0) { + buf = "0000-00-00T00:00:00.000".toCharArray(); + IOUtils.getChars(millis, 23, buf); + IOUtils.getChars(second, 19, buf); + IOUtils.getChars(minute, 16, buf); + IOUtils.getChars(hour, 13, buf); + IOUtils.getChars(day, 10, buf); + IOUtils.getChars(month, 7, buf); + IOUtils.getChars(year, 4, buf); + + } else { + if (second == 0 && minute == 0 && hour == 0) { + buf = "0000-00-00".toCharArray(); + IOUtils.getChars(day, 10, buf); + IOUtils.getChars(month, 7, buf); + IOUtils.getChars(year, 4, buf); + } else { + buf = "0000-00-00T00:00:00".toCharArray(); + IOUtils.getChars(second, 19, buf); + IOUtils.getChars(minute, 16, buf); + IOUtils.getChars(hour, 13, buf); + IOUtils.getChars(day, 10, buf); + IOUtils.getChars(month, 7, buf); + IOUtils.getChars(year, 4, buf); + } + } + + out.write(buf); + + int timeZone = calendar.getTimeZone().getRawOffset()/(3600*1000); + if (timeZone == 0) { + out.write('Z'); + } else { + if (timeZone > 9) { + out.write('+'); + out.writeInt(timeZone); + } else if (timeZone > 0) { + out.write('+'); + out.write('0'); + out.writeInt(timeZone); + } else if (timeZone < -9) { + out.write('-'); + out.writeInt(timeZone); + } else if (timeZone < 0) { + out.write('-'); + out.write('0'); + out.writeInt(timeZone); + } + + out.append(":00"); + } + + out.write(quote); + } else { + out.writeLong(time); + } + } + + @SuppressWarnings("unchecked") + public T cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object val) { + + if (val == null) { + return null; + } + + if (val instanceof java.util.Date) { + return (T) val; + } else if (val instanceof Number) { + return (T) new java.util.Date(((Number) val).longValue()); + } else if (val instanceof String) { + String strVal = (String) val; + if (strVal.length() == 0) { + return null; + } + + { + JSONScanner dateLexer = new JSONScanner(strVal); + try { + if (dateLexer.scanISO8601DateIfMatch(false)) { + Calendar calendar = dateLexer.getCalendar(); + + if (clazz == Calendar.class) { + return (T) calendar; + } + + return (T) calendar.getTime(); + } + } finally { + dateLexer.close(); + } + } + + if (strVal.length() == parser.getDateFomartPattern().length() + || (strVal.length() == 22 && parser.getDateFomartPattern().equals("yyyyMMddHHmmssSSSZ"))) { + DateFormat dateFormat = parser.getDateFormat(); + try { + return (T) dateFormat.parse(strVal); + } catch (ParseException e) { + // skip + } + } + + if (strVal.startsWith("/Date(") && strVal.endsWith(")/")) { + String dotnetDateStr = strVal.substring(6, strVal.length() - 2); + strVal = dotnetDateStr; + } + + if ("0000-00-00".equals(strVal) + || "0000-00-00T00:00:00".equalsIgnoreCase(strVal) + || "0001-01-01T00:00:00+08:00".equalsIgnoreCase(strVal)) { + return null; + } + + int index = strVal.lastIndexOf('|'); + if (index > 20) { + String tzStr = strVal.substring(index + 1); + TimeZone timeZone = TimeZone.getTimeZone(tzStr); + if (!"GMT".equals(timeZone.getID())) { + String subStr = strVal.substring(0, index); + JSONScanner dateLexer = new JSONScanner(subStr); + try { + if (dateLexer.scanISO8601DateIfMatch(false)) { + Calendar calendar = dateLexer.getCalendar(); + + calendar.setTimeZone(timeZone); + + if (clazz == Calendar.class) { + return (T) calendar; + } + + return (T) calendar.getTime(); + } + } finally { + dateLexer.close(); + } + } + } + + // 2017-08-14 19:05:30.000|America/Los_Angeles +// + long longVal = Long.parseLong(strVal); + return (T) new java.util.Date(longVal); + } + + throw new JSONException("parse error"); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_INT; + } + +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/DateSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/DateSerializer.java deleted file mode 100644 index d0a0978eb4..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/DateSerializer.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.Calendar; -import java.util.Date; - -import com.alibaba.fastjson.util.IOUtils; - -/** - * @author wenshao - */ -public class DateSerializer implements ObjectSerializer { - - public final static DateSerializer instance = new DateSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - out.writeNull(); - return; - } - - Date date = (Date) object; - long time = date.getTime(); - if (serializer.isEnabled(SerializerFeature.UseISO8601DateFormat)) { - if (serializer.isEnabled(SerializerFeature.UseSingleQuotes)) { - out.append('\''); - } else { - out.append('\"'); - } - - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(time); - - int year = calendar.get(Calendar.YEAR); - int month = calendar.get(Calendar.MONTH) + 1; - int day = calendar.get(Calendar.DAY_OF_MONTH); - int hour = calendar.get(Calendar.HOUR_OF_DAY); - int minute = calendar.get(Calendar.MINUTE); - int second = calendar.get(Calendar.SECOND); - int millis = calendar.get(Calendar.MILLISECOND); - - char[] buf; - if (millis != 0) { - buf = "0000-00-00T00:00:00.000".toCharArray(); - IOUtils.getChars(millis, 23, buf); - IOUtils.getChars(second, 19, buf); - IOUtils.getChars(minute, 16, buf); - IOUtils.getChars(hour, 13, buf); - IOUtils.getChars(day, 10, buf); - IOUtils.getChars(month, 7, buf); - IOUtils.getChars(year, 4, buf); - - } else { - if (second == 0 && minute == 0 && hour == 0) { - buf = "0000-00-00".toCharArray(); - IOUtils.getChars(day, 10, buf); - IOUtils.getChars(month, 7, buf); - IOUtils.getChars(year, 4, buf); - } else { - buf = "0000-00-00T00:00:00".toCharArray(); - IOUtils.getChars(second, 19, buf); - IOUtils.getChars(minute, 16, buf); - IOUtils.getChars(hour, 13, buf); - IOUtils.getChars(day, 10, buf); - IOUtils.getChars(month, 7, buf); - IOUtils.getChars(year, 4, buf); - } - } - - out.write(buf); - - if (serializer.isEnabled(SerializerFeature.UseSingleQuotes)) { - out.append('\''); - } else { - out.append('\"'); - } - } else { - out.writeLong(time); - } - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/DoubleArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/DoubleArraySerializer.java deleted file mode 100644 index f60cd64e1c..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/DoubleArraySerializer.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class DoubleArraySerializer implements ObjectSerializer { - - public static final DoubleArraySerializer instance = new DoubleArraySerializer(); - - public DoubleArraySerializer(){ - } - - public final void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } - return; - } - - double[] array = (double[]) object; - int size = array.length; - - int end = size - 1; - - if (end == -1) { - out.append("[]"); - return; - } - - out.append('['); - for (int i = 0; i < end; ++i) { - double item = array[i]; - - if (Double.isNaN(item)) { - out.writeNull(); - } else { - out.append(Double.toString(item)); - } - - out.append(','); - } - - double item = array[end]; - - if (Double.isNaN(item)) { - out.writeNull(); - } else { - out.append(Double.toString(item)); - } - - out.append(']'); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/DoubleSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/DoubleSerializer.java old mode 100644 new mode 100755 index 481af43da6..d7c05699e1 --- a/src/main/java/com/alibaba/fastjson/serializer/DoubleSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/DoubleSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,38 +16,50 @@ package com.alibaba.fastjson.serializer; import java.io.IOException; +import java.lang.reflect.Type; +import java.text.DecimalFormat; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public class DoubleSerializer implements ObjectSerializer { - public final static DoubleSerializer instance = new DoubleSerializer(); + public final static DoubleSerializer instance = new DoubleSerializer(); - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); + private DecimalFormat decimalFormat = null; + + public DoubleSerializer(){ + + } + + public DoubleSerializer(DecimalFormat decimalFormat){ + this.decimalFormat = decimalFormat; + } + + public DoubleSerializer(String decimalFormat){ + this(new DecimalFormat(decimalFormat)); + } + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; if (object == null) { - if (serializer.isEnabled(SerializerFeature.WriteNullNumberAsZero)) { - out.write('0'); - } else { - out.writeNull(); - } + out.writeNull(SerializerFeature.WriteNullNumberAsZero); return; } - double doubleValue = ((Double) object).doubleValue(); - - if (Double.isNaN(doubleValue)) { - out.writeNull(); - } else if (Double.isInfinite(doubleValue)) { + double doubleValue = ((Double) object).doubleValue(); + + if (Double.isNaN(doubleValue) // + || Double.isInfinite(doubleValue)) { out.writeNull(); } else { - String doubleText = Double.toString(doubleValue); - if (doubleText.endsWith(".0")) { - doubleText = doubleText.substring(0, doubleText.length() - 2); + if (decimalFormat == null) { + out.writeDouble(doubleValue, true); + } else { + String doubleText = decimalFormat.format(doubleValue); + out.write(doubleText); } - out.append(doubleText); } } } diff --git a/src/main/java/com/alibaba/fastjson/serializer/EnumSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/EnumSerializer.java old mode 100644 new mode 100755 index 6f609e1559..2cb942a7ec --- a/src/main/java/com/alibaba/fastjson/serializer/EnumSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/EnumSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,23 +16,17 @@ package com.alibaba.fastjson.serializer; import java.io.IOException; +import java.lang.reflect.Type; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public class EnumSerializer implements ObjectSerializer { public final static EnumSerializer instance = new EnumSerializer(); - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (serializer.isEnabled(SerializerFeature.WriteEnumUsingToString)) { - Enum e = (Enum) object; - serializer.write(e.name()); - } else { - Enum e = (Enum) object; - out.writeInt(e.ordinal()); - } + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + out.writeEnum((Enum) object); } } diff --git a/src/main/java/com/alibaba/fastjson/serializer/EnumerationSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/EnumerationSerializer.java new file mode 100755 index 0000000000..38468ad174 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/EnumerationSerializer.java @@ -0,0 +1,55 @@ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Enumeration; + + +public class EnumerationSerializer implements ObjectSerializer { + public static EnumerationSerializer instance = new EnumerationSerializer(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(SerializerFeature.WriteNullListAsEmpty); + return; + } + + Type elementType = null; + if (out.isEnabled(SerializerFeature.WriteClassName)) { + if (fieldType instanceof ParameterizedType) { + ParameterizedType param = (ParameterizedType) fieldType; + elementType = param.getActualTypeArguments()[0]; + } + } + + Enumeration e = (Enumeration) object; + + SerialContext context = serializer.context; + serializer.setContext(context, object, fieldName, 0); + + try { + int i = 0; + out.append('['); + while (e.hasMoreElements()) { + Object item = e.nextElement(); + if (i++ != 0) { + out.append(','); + } + + if (item == null) { + out.writeNull(); + continue; + } + + ObjectSerializer itemSerializer = serializer.getObjectWriter(item.getClass()); + itemSerializer.write(serializer, item, i - 1, elementType, 0); + } + out.append(']'); + } finally { + serializer.context = context; + } + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ExceptionSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ExceptionSerializer.java deleted file mode 100644 index 449e8d68d3..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/ExceptionSerializer.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.alibaba.fastjson.serializer; - -public class ExceptionSerializer extends JavaBeanSerializer { - - public ExceptionSerializer(Class clazz){ - super(clazz); - } - - protected boolean isWriteClassName(JSONSerializer serializer) { - return true; - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/FieldSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/FieldSerializer.java old mode 100644 new mode 100755 index 25143d2c18..60c5100e3f --- a/src/main/java/com/alibaba/fastjson/serializer/FieldSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/FieldSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,83 +15,296 @@ */ package com.alibaba.fastjson.serializer; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Method; - +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.util.FieldInfo; +import com.alibaba.fastjson.util.TypeUtils; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.text.SimpleDateFormat; +import java.util.Collection; +import java.util.Date; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ -public abstract class FieldSerializer implements Comparable { +public class FieldSerializer implements Comparable { - protected final FieldInfo fieldInfo; - private final String double_quoted_fieldPrefix; - private final String single_quoted_fieldPrefix; - private final String un_quoted_fieldPrefix; - private boolean writeNull = false; + public final FieldInfo fieldInfo; + protected final boolean writeNull; + protected int features; - public FieldSerializer(FieldInfo fieldInfo){ - super(); - this.fieldInfo = fieldInfo; - fieldInfo.getMethod().setAccessible(true); + private final String double_quoted_fieldPrefix; + private String single_quoted_fieldPrefix; + private String un_quoted_fieldPrefix; - this.double_quoted_fieldPrefix = '"' + fieldInfo.getName() + "\":"; + protected BeanContext fieldContext; + + private String format; + protected boolean writeEnumUsingToString = false; + protected boolean writeEnumUsingName = false; + protected boolean disableCircularReferenceDetect = false; + + protected boolean serializeUsing = false; + + protected boolean persistenceXToMany = false; // OneToMany or ManyToMany + protected boolean browserCompatible; + + private RuntimeSerializerInfo runtimeInfo; + + public FieldSerializer(Class beanType, FieldInfo fieldInfo) { + this.fieldInfo = fieldInfo; + this.fieldContext = new BeanContext(beanType, fieldInfo); - this.single_quoted_fieldPrefix = '\'' + fieldInfo.getName() + "\':"; + if (beanType != null && (fieldInfo.isEnum || fieldInfo.fieldClass == long.class || fieldInfo.fieldClass == Long.class)) { + JSONType jsonType = TypeUtils.getAnnotation(beanType,JSONType.class); + if (jsonType != null) { + for (SerializerFeature feature : jsonType.serialzeFeatures()) { + if (feature == SerializerFeature.WriteEnumUsingToString) { + writeEnumUsingToString = true; + } else if(feature == SerializerFeature.WriteEnumUsingName){ + writeEnumUsingName = true; + } else if(feature == SerializerFeature.DisableCircularReferenceDetect){ + disableCircularReferenceDetect = true; + } else if(feature == SerializerFeature.BrowserCompatible){ + browserCompatible = true; + } + } + } + } + + fieldInfo.setAccessible(); - this.un_quoted_fieldPrefix = fieldInfo.getName() + ":"; + this.double_quoted_fieldPrefix = '"' + fieldInfo.name + "\":"; - JSONField annotation = fieldInfo.getAnnotation(JSONField.class); + boolean writeNull = false; + JSONField annotation = fieldInfo.getAnnotation(); if (annotation != null) { for (SerializerFeature feature : annotation.serialzeFeatures()) { - if (feature == SerializerFeature.WriteMapNullValue) { + if ((feature.getMask() & SerializerFeature.WRITE_BEAN_NULL_FEATURES) != 0) { writeNull = true; + break; } } - } - } - public boolean isWriteNull() { - return writeNull; - } + format = annotation.format(); - public Field getField() { - return fieldInfo.getField(); - } + if (format.trim().length() == 0) { + format = null; + } - public String getName() { - return fieldInfo.getName(); - } + for (SerializerFeature feature : annotation.serialzeFeatures()) { + if (feature == SerializerFeature.WriteEnumUsingToString) { + writeEnumUsingToString = true; + } else if(feature == SerializerFeature.WriteEnumUsingName){ + writeEnumUsingName = true; + } else if(feature == SerializerFeature.DisableCircularReferenceDetect){ + disableCircularReferenceDetect = true; + } else if(feature == SerializerFeature.BrowserCompatible){ + browserCompatible = true; + } + } + + features = SerializerFeature.of(annotation.serialzeFeatures()); + } + + this.writeNull = writeNull; - public Method getMethod() { - return fieldInfo.getMethod(); + persistenceXToMany = TypeUtils.isAnnotationPresentOneToMany(fieldInfo.method) + || TypeUtils.isAnnotationPresentManyToMany(fieldInfo.method); } public void writePrefix(JSONSerializer serializer) throws IOException { - SerializeWriter out = serializer.getWriter(); + SerializeWriter out = serializer.out; - if (serializer.isEnabled(SerializerFeature.QuoteFieldNames)) { - if (serializer.isEnabled(SerializerFeature.UseSingleQuotes)) { + if (out.quoteFieldNames) { + if (out.useSingleQuotes) { + if (single_quoted_fieldPrefix == null) { + single_quoted_fieldPrefix = '\'' + fieldInfo.name + "\':"; + } out.write(single_quoted_fieldPrefix); } else { out.write(double_quoted_fieldPrefix); } } else { + if (un_quoted_fieldPrefix == null) { + this.un_quoted_fieldPrefix = fieldInfo.name + ":"; + } out.write(un_quoted_fieldPrefix); } } + public Object getPropertyValueDirect(Object object) throws InvocationTargetException, IllegalAccessException { + Object fieldValue = fieldInfo.get(object); + if (persistenceXToMany && !TypeUtils.isHibernateInitialized(fieldValue)) { + return null; + } + return fieldValue; + } + + public Object getPropertyValue(Object object) throws InvocationTargetException, IllegalAccessException { + Object propertyValue = fieldInfo.get(object); + if (format != null && propertyValue != null) { + if (fieldInfo.fieldClass == Date.class) { + SimpleDateFormat dateFormat = new SimpleDateFormat(format); + dateFormat.setTimeZone(JSON.defaultTimeZone); + return dateFormat.format(propertyValue); + } + } + return propertyValue; + } + public int compareTo(FieldSerializer o) { - return this.getName().compareTo(o.getName()); + return this.fieldInfo.compareTo(o.fieldInfo); } + + + public void writeValue(JSONSerializer serializer, Object propertyValue) throws Exception { + if (runtimeInfo == null) { + + Class runtimeFieldClass; + if (propertyValue == null) { + runtimeFieldClass = this.fieldInfo.fieldClass; + } else { + runtimeFieldClass = propertyValue.getClass(); + } + + ObjectSerializer fieldSerializer = null; + JSONField fieldAnnotation = fieldInfo.getAnnotation(); + + if (fieldAnnotation != null && fieldAnnotation.serializeUsing() != Void.class) { + fieldSerializer = (ObjectSerializer) fieldAnnotation.serializeUsing().newInstance(); + serializeUsing = true; + } else { + if (format != null) { + if (runtimeFieldClass == double.class || runtimeFieldClass == Double.class) { + fieldSerializer = new DoubleSerializer(format); + } else if (runtimeFieldClass == float.class || runtimeFieldClass == Float.class) { + fieldSerializer = new FloatCodec(format); + } + } - public Object getPropertyValue(Object object) throws Exception { - return getMethod().invoke(object); + if (fieldSerializer == null) { + fieldSerializer = serializer.getObjectWriter(runtimeFieldClass); + } + } + + runtimeInfo = new RuntimeSerializerInfo(fieldSerializer, runtimeFieldClass); + } + + final RuntimeSerializerInfo runtimeInfo = this.runtimeInfo; + + final int fieldFeatures = disableCircularReferenceDetect? + (fieldInfo.serialzeFeatures|SerializerFeature.DisableCircularReferenceDetect.getMask()):fieldInfo.serialzeFeatures; + + if (propertyValue == null) { + SerializeWriter out = serializer.out; + + if (fieldInfo.fieldClass == Object.class + && out.isEnabled(SerializerFeature.WRITE_BEAN_NULL_FEATURES)) { + out.writeNull(); + return; + } + + Class runtimeFieldClass = runtimeInfo.runtimeFieldClass; + + if (Number.class.isAssignableFrom(runtimeFieldClass)) { + out.writeNull(features, SerializerFeature.WriteNullNumberAsZero.mask); + return; + } else if (String.class == runtimeFieldClass) { + out.writeNull(features, SerializerFeature.WriteNullStringAsEmpty.mask); + return; + } else if (Boolean.class == runtimeFieldClass) { + out.writeNull(features, SerializerFeature.WriteNullBooleanAsFalse.mask); + return; + } else if (Collection.class.isAssignableFrom(runtimeFieldClass)) { + out.writeNull(features, SerializerFeature.WriteNullListAsEmpty.mask); + return; + } + + ObjectSerializer fieldSerializer = runtimeInfo.fieldSerializer; + + if ((out.isEnabled(SerializerFeature.WRITE_BEAN_NULL_FEATURES)) + && fieldSerializer instanceof JavaBeanSerializer) { + out.writeNull(); + return; + } + + fieldSerializer.write(serializer, null, fieldInfo.name, fieldInfo.fieldType, fieldFeatures); + return; + } + + if (fieldInfo.isEnum) { + if (writeEnumUsingName) { + serializer.out.writeString(((Enum) propertyValue).name()); + return; + } + + if (writeEnumUsingToString) { + serializer.out.writeString(((Enum) propertyValue).toString()); + return; + } + } + + Class valueClass = propertyValue.getClass(); + ObjectSerializer valueSerializer; + if (valueClass == runtimeInfo.runtimeFieldClass || serializeUsing) { + valueSerializer = runtimeInfo.fieldSerializer; + } else { + valueSerializer = serializer.getObjectWriter(valueClass); + } + + if (format != null && !(valueSerializer instanceof DoubleSerializer || valueSerializer instanceof FloatCodec)) { + if (valueSerializer instanceof ContextObjectSerializer) { + ((ContextObjectSerializer) valueSerializer).write(serializer, propertyValue, this.fieldContext); + } else { + serializer.writeWithFormat(propertyValue, format); + } + return; + } + + if (fieldInfo.unwrapped) { + if (valueSerializer instanceof JavaBeanSerializer) { + JavaBeanSerializer javaBeanSerializer = (JavaBeanSerializer) valueSerializer; + javaBeanSerializer.write(serializer, propertyValue, fieldInfo.name, fieldInfo.fieldType, fieldFeatures, true); + return; + } + + if (valueSerializer instanceof MapSerializer) { + MapSerializer mapSerializer = (MapSerializer) valueSerializer; + mapSerializer.write(serializer, propertyValue, fieldInfo.name, fieldInfo.fieldType, fieldFeatures, true); + return; + } + } + + if ((features & SerializerFeature.WriteClassName.mask) != 0 + && valueClass != fieldInfo.fieldClass + && JavaBeanSerializer.class.isInstance(valueSerializer)) { + ((JavaBeanSerializer) valueSerializer).write(serializer, propertyValue, fieldInfo.name, fieldInfo.fieldType, fieldFeatures, false); + return; + } + + if (browserCompatible && propertyValue != null + && (fieldInfo.fieldClass == long.class || fieldInfo.fieldClass == Long.class)) { + long value = (Long) propertyValue; + if (value > 9007199254740991L || value < -9007199254740991L) { + serializer.getWriter().writeString(Long.toString(value)); + return; + } + } + + valueSerializer.write(serializer, propertyValue, fieldInfo.name, fieldInfo.fieldType, fieldFeatures); } - public abstract void writeProperty(JSONSerializer serializer, Object propertyValue) throws Exception; + static class RuntimeSerializerInfo { + final ObjectSerializer fieldSerializer; + final Class runtimeFieldClass; + public RuntimeSerializerInfo(ObjectSerializer fieldSerializer, Class runtimeFieldClass){ + this.fieldSerializer = fieldSerializer; + this.runtimeFieldClass = runtimeFieldClass; + } + } } diff --git a/src/main/java/com/alibaba/fastjson/serializer/FileSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/FileSerializer.java deleted file mode 100644 index f433454428..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/FileSerializer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.alibaba.fastjson.serializer; - -import java.io.File; -import java.io.IOException; - -public class FileSerializer implements ObjectSerializer { - - public static FileSerializer instance = new FileSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - out.writeNull(); - return; - } - - File file = (File) object; - - serializer.write(file.getPath()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/FilterUtils.java b/src/main/java/com/alibaba/fastjson/serializer/FilterUtils.java deleted file mode 100644 index eaa21fc962..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/FilterUtils.java +++ /dev/null @@ -1,281 +0,0 @@ -package com.alibaba.fastjson.serializer; - -import java.util.List; - -public class FilterUtils { - public static Object processValue(JSONSerializer serializer, Object object, String key, Object propertyValue) { - List valueFilters = serializer.getValueFiltersDirect(); - if (valueFilters != null) { - for (ValueFilter valueFilter : valueFilters) { - propertyValue = valueFilter.process(object, key, propertyValue); - } - } - - return propertyValue; - } - - public static String processKey(JSONSerializer serializer, Object object, String key, Object propertyValue) { - List nameFilters = serializer.getNameFiltersDirect(); - if (nameFilters != null) { - for (NameFilter nameFilter : nameFilters) { - key = nameFilter.process(object, key, propertyValue); - } - } - - return key; - } - - public static String processKey(JSONSerializer serializer, Object object, String key, byte intValue) { - List nameFilters = serializer.getNameFiltersDirect(); - if (nameFilters != null) { - Object propertyValue = Byte.valueOf(intValue); - - for (NameFilter nameFilter : nameFilters) { - key = nameFilter.process(object, key, propertyValue); - } - } - - return key; - } - - public static String processKey(JSONSerializer serializer, Object object, String key, short intValue) { - List nameFilters = serializer.getNameFiltersDirect(); - if (nameFilters != null) { - Object propertyValue = Short.valueOf(intValue); - - for (NameFilter nameFilter : nameFilters) { - key = nameFilter.process(object, key, propertyValue); - } - } - - return key; - } - - public static String processKey(JSONSerializer serializer, Object object, String key, int intValue) { - List nameFilters = serializer.getNameFiltersDirect(); - if (nameFilters != null) { - Object propertyValue = Integer.valueOf(intValue); - - for (NameFilter nameFilter : nameFilters) { - key = nameFilter.process(object, key, propertyValue); - } - } - - return key; - } - - public static String processKey(JSONSerializer serializer, Object object, String key, long intValue) { - List nameFilters = serializer.getNameFiltersDirect(); - if (nameFilters != null) { - Object propertyValue = Long.valueOf(intValue); - - for (NameFilter nameFilter : nameFilters) { - key = nameFilter.process(object, key, propertyValue); - } - } - - return key; - } - - public static String processKey(JSONSerializer serializer, Object object, String key, float intValue) { - List nameFilters = serializer.getNameFiltersDirect(); - if (nameFilters != null) { - Object propertyValue = Float.valueOf(intValue); - - for (NameFilter nameFilter : nameFilters) { - key = nameFilter.process(object, key, propertyValue); - } - } - - return key; - } - - public static String processKey(JSONSerializer serializer, Object object, String key, double intValue) { - List nameFilters = serializer.getNameFiltersDirect(); - if (nameFilters != null) { - Object propertyValue = Double.valueOf(intValue); - - for (NameFilter nameFilter : nameFilters) { - key = nameFilter.process(object, key, propertyValue); - } - } - - return key; - } - - public static String processKey(JSONSerializer serializer, Object object, String key, boolean intValue) { - List nameFilters = serializer.getNameFiltersDirect(); - if (nameFilters != null) { - Object propertyValue = Boolean.valueOf(intValue); - - for (NameFilter nameFilter : nameFilters) { - key = nameFilter.process(object, key, propertyValue); - } - } - - return key; - } - - public static String processKey(JSONSerializer serializer, Object object, String key, char intValue) { - List nameFilters = serializer.getNameFiltersDirect(); - if (nameFilters != null) { - Object propertyValue = Character.valueOf(intValue); - - for (NameFilter nameFilter : nameFilters) { - key = nameFilter.process(object, key, propertyValue); - } - } - - return key; - } - - public static boolean apply(JSONSerializer serializer, Object object, String key, Object propertyValue) { - List propertyFilters = serializer.getPropertyFiltersDirect(); - - if (propertyFilters != null) { - boolean apply = true; - for (PropertyFilter propertyFilter : propertyFilters) { - if (!propertyFilter.apply(object, key, propertyValue)) { - return false; - } - } - - return apply; - } - - return true; - } - - public static boolean apply(JSONSerializer serializer, Object object, String key, byte value) { - List propertyFilters = serializer.getPropertyFiltersDirect(); - - if (propertyFilters != null) { - boolean apply = true; - - Object propertyValue = Byte.valueOf(value); - for (PropertyFilter propertyFilter : propertyFilters) { - if (!propertyFilter.apply(object, key, propertyValue)) { - return false; - } - } - - return apply; - } - - return true; - } - - public static boolean apply(JSONSerializer serializer, Object object, String key, short value) { - List propertyFilters = serializer.getPropertyFiltersDirect(); - - if (propertyFilters != null) { - boolean apply = true; - - Object propertyValue = Short.valueOf(value); - for (PropertyFilter propertyFilter : propertyFilters) { - if (!propertyFilter.apply(object, key, propertyValue)) { - return false; - } - } - - return apply; - } - - return true; - } - - public static boolean apply(JSONSerializer serializer, Object object, String key, int value) { - List propertyFilters = serializer.getPropertyFiltersDirect(); - - if (propertyFilters != null) { - boolean apply = true; - - Object propertyValue = Integer.valueOf(value); - for (PropertyFilter propertyFilter : propertyFilters) { - if (!propertyFilter.apply(object, key, propertyValue)) { - return false; - } - } - - return apply; - } - - return true; - } - - public static boolean apply(JSONSerializer serializer, Object object, String key, char value) { - List propertyFilters = serializer.getPropertyFiltersDirect(); - - if (propertyFilters != null) { - boolean apply = true; - - Object propertyValue = Character.valueOf(value); - for (PropertyFilter propertyFilter : propertyFilters) { - if (!propertyFilter.apply(object, key, propertyValue)) { - return false; - } - } - - return apply; - } - - return true; - } - - public static boolean apply(JSONSerializer serializer, Object object, String key, long value) { - List propertyFilters = serializer.getPropertyFiltersDirect(); - - if (propertyFilters != null) { - boolean apply = true; - - Object propertyValue = Long.valueOf(value); - for (PropertyFilter propertyFilter : propertyFilters) { - if (!propertyFilter.apply(object, key, propertyValue)) { - return false; - } - } - - return apply; - } - - return true; - } - - public static boolean apply(JSONSerializer serializer, Object object, String key, float value) { - List propertyFilters = serializer.getPropertyFiltersDirect(); - - if (propertyFilters != null) { - boolean apply = true; - - Object propertyValue = Float.valueOf(value); - for (PropertyFilter propertyFilter : propertyFilters) { - if (!propertyFilter.apply(object, key, propertyValue)) { - return false; - } - } - - return apply; - } - - return true; - } - - public static boolean apply(JSONSerializer serializer, Object object, String key, double value) { - List propertyFilters = serializer.getPropertyFiltersDirect(); - - if (propertyFilters != null) { - boolean apply = true; - - Object propertyValue = Double.valueOf(value); - for (PropertyFilter propertyFilter : propertyFilters) { - if (!propertyFilter.apply(object, key, propertyValue)) { - return false; - } - } - - return apply; - } - - return true; - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/FloatArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/FloatArraySerializer.java deleted file mode 100644 index 1b1d8beb79..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/FloatArraySerializer.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class FloatArraySerializer implements ObjectSerializer { - - public static final FloatArraySerializer instance = new FloatArraySerializer(); - - public FloatArraySerializer(){ - } - - public final void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } - return; - } - - float[] array = (float[]) object; - int size = array.length; - - int end = size - 1; - - if (end == -1) { - out.append("[]"); - return; - } - - out.append('['); - for (int i = 0; i < end; ++i) { - float item = array[i]; - - if (Float.isNaN(item)) { - out.writeNull(); - } else { - out.append(Float.toString(item)); - } - - out.append(','); - } - - float item = array[end]; - - if (Float.isNaN(item)) { - out.writeNull(); - } else { - out.append(Float.toString(item)); - } - - out.append(']'); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/FloatCodec.java b/src/main/java/com/alibaba/fastjson/serializer/FloatCodec.java new file mode 100755 index 0000000000..5f80019b13 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/FloatCodec.java @@ -0,0 +1,104 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.text.DecimalFormat; +import java.text.NumberFormat; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class FloatCodec implements ObjectSerializer, ObjectDeserializer { + private NumberFormat decimalFormat; + + public static FloatCodec instance = new FloatCodec(); + + public FloatCodec(){ + + } + + public FloatCodec(DecimalFormat decimalFormat){ + this.decimalFormat = decimalFormat; + } + + public FloatCodec(String decimalFormat){ + this(new DecimalFormat(decimalFormat)); + } + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(SerializerFeature.WriteNullNumberAsZero); + return; + } + + float floatValue = ((Float) object).floatValue(); + if (decimalFormat != null) { + String floatText = decimalFormat.format(floatValue); + out.write(floatText); + } else { + out.writeFloat(floatValue, true); + } + } + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + try { + return (T) deserialze(parser); + } catch (Exception ex) { + throw new JSONException("parseLong error, field : " + fieldName, ex); + } + } + + @SuppressWarnings("unchecked") + public static T deserialze(DefaultJSONParser parser) { + final JSONLexer lexer = parser.lexer; + + if (lexer.token() == JSONToken.LITERAL_INT) { + String val = lexer.numberString(); + lexer.nextToken(JSONToken.COMMA); + return (T) Float.valueOf(Float.parseFloat(val)); + } + + if (lexer.token() == JSONToken.LITERAL_FLOAT) { + float val = lexer.floatValue(); + lexer.nextToken(JSONToken.COMMA); + return (T) Float.valueOf(val); + } + + Object value = parser.parse(); + + if (value == null) { + return null; + } + + return (T) TypeUtils.castToFloat(value); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_INT; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/FloatSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/FloatSerializer.java deleted file mode 100644 index d552ef432b..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/FloatSerializer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class FloatSerializer implements ObjectSerializer { - - public static FloatSerializer instance = new FloatSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (serializer.isEnabled(SerializerFeature.WriteNullNumberAsZero)) { - out.write('0'); - } else { - out.writeNull(); - } - return; - } - - float floatValue = ((Float) object).floatValue(); - - if (Float.isNaN(floatValue)) { - out.writeNull(); - } else if (Float.isInfinite(floatValue)) { - out.writeNull(); - } else { - String floatText= Float.toString(floatValue); - if (floatText.endsWith(".0")) { - floatText = floatText.substring(0, floatText.length() - 2); - } - out.write(floatText); - } - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/GuavaCodec.java b/src/main/java/com/alibaba/fastjson/serializer/GuavaCodec.java new file mode 100644 index 0000000000..45c21f0492 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/GuavaCodec.java @@ -0,0 +1,23 @@ +package com.alibaba.fastjson.serializer; + +import com.google.common.collect.Multimap; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.Map; + +/** + * Created by wenshao on 15/01/2017. + */ +public class GuavaCodec implements ObjectSerializer { + public static GuavaCodec instance = new GuavaCodec(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + if (object instanceof Multimap) { + Multimap multimap = (Multimap) object; + serializer.write(multimap.asMap()); + } + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/InetAddressSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/InetAddressSerializer.java deleted file mode 100644 index d5c4929f7b..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/InetAddressSerializer.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.net.InetAddress; - -public class InetAddressSerializer implements ObjectSerializer { - - public static InetAddressSerializer instance = new InetAddressSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - if (object == null) { - serializer.writeNull(); - return; - } - - InetAddress address = (InetAddress) object; - - serializer.write(address.getHostAddress()); - } -} - diff --git a/src/main/java/com/alibaba/fastjson/serializer/InetSocketAddressSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/InetSocketAddressSerializer.java deleted file mode 100644 index 3c19b80ffc..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/InetSocketAddressSerializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; - -public class InetSocketAddressSerializer implements ObjectSerializer { - - public static InetSocketAddressSerializer instance = new InetSocketAddressSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - if (object == null) { - serializer.writeNull(); - return; - } - - SerializeWriter out = serializer.getWriter(); - InetSocketAddress address = (InetSocketAddress) object; - - InetAddress inetAddress = address.getAddress(); - - out.write('{'); - if (inetAddress != null) { - out.writeFieldName("address"); - serializer.write(inetAddress); - out.write(','); - } - out.writeFieldName("port"); - out.writeInt(address.getPort()); - out.write('}'); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/IntArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/IntArraySerializer.java deleted file mode 100644 index 6be09eeea3..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/IntArraySerializer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class IntArraySerializer implements ObjectSerializer { - - public static IntArraySerializer instance = new IntArraySerializer(); - - public final void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } - return; - } - - int[] array = (int[]) object; - - out.writeIntArray(array); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/IntegerCodec.java b/src/main/java/com/alibaba/fastjson/serializer/IntegerCodec.java new file mode 100755 index 0000000000..502b4831b9 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/IntegerCodec.java @@ -0,0 +1,113 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.util.Iterator; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class IntegerCodec implements ObjectSerializer, ObjectDeserializer { + + public static IntegerCodec instance = new IntegerCodec(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + Number value = (Number) object; + + if (value == null) { + out.writeNull(SerializerFeature.WriteNullNumberAsZero); + return; + } + + if (object instanceof Long) { + out.writeLong(value.longValue()); + } else { + out.writeInt(value.intValue()); + } + + if (out.isEnabled(SerializerFeature.WriteClassName)) { + Class clazz = value.getClass(); + if (clazz == Byte.class) { + out.write('B'); + } else if (clazz == Short.class) { + out.write('S'); + } + } + } + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + final JSONLexer lexer = parser.lexer; + + final int token = lexer.token(); + + if (token == JSONToken.NULL) { + lexer.nextToken(JSONToken.COMMA); + return null; + } + + + Integer intObj; + try { + if (token == JSONToken.LITERAL_INT) { + int val = lexer.intValue(); + lexer.nextToken(JSONToken.COMMA); + intObj = Integer.valueOf(val); + } else if (token == JSONToken.LITERAL_FLOAT) { + BigDecimal decimalValue = lexer.decimalValue(); + lexer.nextToken(JSONToken.COMMA); + intObj = Integer.valueOf(decimalValue.intValue()); + } else { + if (token == JSONToken.LBRACE) { + JSONObject jsonObject = new JSONObject(true); + parser.parseObject(jsonObject); + intObj = TypeUtils.castToInt(jsonObject); + } else { + Object value = parser.parse(); + intObj = TypeUtils.castToInt(value); + } + } + } catch (Exception ex) { + throw new JSONException("parseInt error, field : " + fieldName, ex); + } + + + if (clazz == AtomicInteger.class) { + return (T) new AtomicInteger(intObj.intValue()); + } + + return (T) intObj; + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_INT; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/IntegerSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/IntegerSerializer.java deleted file mode 100644 index 2ad6c96832..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/IntegerSerializer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class IntegerSerializer implements ObjectSerializer { - - public static IntegerSerializer instance = new IntegerSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - Number value = (Number) object; - - if (value == null) { - if (out.isEnabled(SerializerFeature.WriteNullNumberAsZero)) { - out.write('0'); - } else { - out.writeNull(); - } - return; - } - - out.writeInt(value.intValue()); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/JSONAwareSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/JSONAwareSerializer.java old mode 100644 new mode 100755 index 8aab28f26a..64c9e1e005 --- a/src/main/java/com/alibaba/fastjson/serializer/JSONAwareSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/JSONAwareSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,24 @@ package com.alibaba.fastjson.serializer; import java.io.IOException; +import java.lang.reflect.Type; import com.alibaba.fastjson.JSONAware; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public class JSONAwareSerializer implements ObjectSerializer { public static JSONAwareSerializer instance = new JSONAwareSerializer(); - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(); + return; + } JSONAware aware = (JSONAware) object; out.write(aware.toJSONString()); diff --git a/src/main/java/com/alibaba/fastjson/serializer/JSONLibDataFormatSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/JSONLibDataFormatSerializer.java old mode 100644 new mode 100755 index 7cb12da4bd..dfa68dfd15 --- a/src/main/java/com/alibaba/fastjson/serializer/JSONLibDataFormatSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/JSONLibDataFormatSerializer.java @@ -1,6 +1,7 @@ package com.alibaba.fastjson.serializer; import java.io.IOException; +import java.lang.reflect.Type; import java.util.Date; import com.alibaba.fastjson.JSONObject; @@ -11,9 +12,9 @@ public JSONLibDataFormatSerializer(){ } @SuppressWarnings("deprecation") - public void write(JSONSerializer serializer, Object object) throws IOException { + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { if (object == null) { - serializer.getWriter().writeNull(); + serializer.out.writeNull(); return; } diff --git a/src/main/java/com/alibaba/fastjson/serializer/JSONSerializable.java b/src/main/java/com/alibaba/fastjson/serializer/JSONSerializable.java new file mode 100644 index 0000000000..a19adfebf4 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/JSONSerializable.java @@ -0,0 +1,39 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public interface JSONSerializable { + + /** + * write to json + * @param serializer json seriliazer + * @param fieldName field name + * @param fieldType field type + * @param features field features + * @throws IOException + */ + void write(JSONSerializer serializer, // + Object fieldName, // + Type fieldType, // + int features // + ) throws IOException; +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/JSONSerializableSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/JSONSerializableSerializer.java new file mode 100644 index 0000000000..68db068cbd --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/JSONSerializableSerializer.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class JSONSerializableSerializer implements ObjectSerializer { + + public static JSONSerializableSerializer instance = new JSONSerializableSerializer(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + JSONSerializable jsonSerializable = ((JSONSerializable) object); + jsonSerializable.write(serializer, fieldName, fieldType, features); + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/JSONSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/JSONSerializer.java old mode 100644 new mode 100755 index 6b292c733c..e3fa96ad06 --- a/src/main/java/com/alibaba/fastjson/serializer/JSONSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/JSONSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,109 +15,215 @@ */ package com.alibaba.fastjson.serializer; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Type; -import java.nio.charset.Charset; +import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - -import com.alibaba.fastjson.JSONAware; +import java.util.*; +import java.util.zip.GZIPOutputStream; + +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.JSONStreamAware; -import com.alibaba.fastjson.util.ServiceLoader; +import com.alibaba.fastjson.util.IOUtils; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ -public class JSONSerializer { +public class JSONSerializer extends SerializeFilterable { + + protected final SerializeConfig config; + public final SerializeWriter out; - private final SerializeConfig config; + private int indentCount = 0; + private String indent = "\t"; - private final SerializeWriter out; + private String dateFormatPattern; + private DateFormat dateFormat; - private List propertyFilters = null; - private List valueFilters = null; - private List nameFilters = null; + protected IdentityHashMap references = null; + protected SerialContext context; - private int indentCount = 0; - private String indent = "\t"; + protected TimeZone timeZone = JSON.defaultTimeZone; + protected Locale locale = JSON.defaultLocale; + + public JSONSerializer(){ + this(new SerializeWriter(), SerializeConfig.getGlobalInstance()); + } - public List getValueFilters() { - if (valueFilters == null) { - valueFilters = new ArrayList(); + public JSONSerializer(SerializeWriter out){ + this(out, SerializeConfig.getGlobalInstance()); + } + + public JSONSerializer(SerializeConfig config){ + this(new SerializeWriter(), config); + } + + public JSONSerializer(SerializeWriter out, SerializeConfig config){ + this.out = out; + this.config = config; + } + + public String getDateFormatPattern() { + if (dateFormat instanceof SimpleDateFormat) { + return ((SimpleDateFormat) dateFormat).toPattern(); } + return dateFormatPattern; + } - return valueFilters; + public DateFormat getDateFormat() { + if (dateFormat == null) { + if (dateFormatPattern != null) { + dateFormat = new SimpleDateFormat(dateFormatPattern, locale); + dateFormat.setTimeZone(timeZone); + } + } + + return dateFormat; } - public List getValueFiltersDirect() { - return valueFilters; + public void setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + if (dateFormatPattern != null) { + dateFormatPattern = null; + } } - public int getIndentCount() { - return indentCount; + public void setDateFormat(String dateFormat) { + this.dateFormatPattern = dateFormat; + if (this.dateFormat != null) { + this.dateFormat = null; + } } - public void incrementIndent() { - indentCount++; + public SerialContext getContext() { + return context; } - public void decrementIdent() { - indentCount--; + public void setContext(SerialContext context) { + this.context = context; } - public void println() { - out.write('\n'); - for (int i = 0; i < indentCount; ++i) { - out.write(indent); + public void setContext(SerialContext parent, Object object, Object fieldName, int features) { + this.setContext(parent, object, fieldName, features, 0); + } + + public void setContext(SerialContext parent, Object object, Object fieldName, int features, int fieldFeatures) { + if (out.disableCircularReferenceDetect) { + return; } + + this.context = new SerialContext(parent, object, fieldName, features, fieldFeatures); + if (references == null) { + references = new IdentityHashMap(); + } + this.references.put(object, context); + } + + public void setContext(Object object, Object fieldName) { + this.setContext(context, object, fieldName, 0); } - public List getNameFilters() { - if (nameFilters == null) { - nameFilters = new ArrayList(); + public void popContext() { + if (context != null) { + this.context = this.context.parent; } + } - return nameFilters; + public final boolean isWriteClassName(Type fieldType, Object obj) { + return out.isEnabled(SerializerFeature.WriteClassName) // + && (fieldType != null // + || (!out.isEnabled(SerializerFeature.NotWriteRootClassName)) // + || (context != null && (context.parent != null))); } - public List getNameFiltersDirect() { - return nameFilters; + public boolean containsReference(Object value) { + if (references == null) { + return false; + } + + SerialContext refContext = references.get(value); + if (refContext == null) { + return false; + } + + Object fieldName = refContext.fieldName; + + return fieldName == null || fieldName instanceof Integer || fieldName instanceof String; } - public List getPropertyFilters() { - if (propertyFilters == null) { - propertyFilters = new ArrayList(); + public void writeReference(Object object) { + SerialContext context = this.context; + Object current = context.object; + + if (object == current) { + out.write("{\"$ref\":\"@\"}"); + return; + } + + SerialContext parentContext = context.parent; + + if (parentContext != null) { + if (object == parentContext.object) { + out.write("{\"$ref\":\"..\"}"); + return; + } } - return propertyFilters; + SerialContext rootContext = context; + for (;;) { + if (rootContext.parent == null) { + break; + } + rootContext = rootContext.parent; + } + + if (object == rootContext.object) { + out.write("{\"$ref\":\"$\"}"); + } else { + out.write("{\"$ref\":\""); + String path = references.get(object).toString(); + out.write(path); + out.write("\"}"); + } } - public List getPropertyFiltersDirect() { - return propertyFilters; + public boolean checkValue(SerializeFilterable filterable) { + return (valueFilters != null && valueFilters.size() > 0) // + || (contextValueFilters != null && contextValueFilters.size() > 0) // + || (filterable.valueFilters != null && filterable.valueFilters.size() > 0) + || (filterable.contextValueFilters != null && filterable.contextValueFilters.size() > 0) + || out.writeNonStringValueAsString; + } + + public boolean hasNameFilters(SerializeFilterable filterable) { + return (nameFilters != null && nameFilters.size() > 0) // + || (filterable.nameFilters != null && filterable.nameFilters.size() > 0); } - public JSONSerializer(){ - this(new SerializeWriter(), SerializeConfig.getGlobalInstance()); + public boolean hasPropertyFilters(SerializeFilterable filterable) { + return (propertyFilters != null && propertyFilters.size() > 0) // + || (filterable.propertyFilters != null && filterable.propertyFilters.size() > 0); } - public JSONSerializer(SerializeWriter out){ - this(out, SerializeConfig.getGlobalInstance()); + public int getIndentCount() { + return indentCount; } - public JSONSerializer(SerializeConfig mapping){ - this(new SerializeWriter(), mapping); + public void incrementIndent() { + indentCount++; } - public JSONSerializer(SerializeWriter out, SerializeConfig config){ - this.out = out; - this.config = config; + public void decrementIdent() { + indentCount--; + } + + public void println() { + out.write('\n'); + for (int i = 0; i < indentCount; ++i) { + out.write(indent); + } } public SerializeWriter getWriter() { @@ -144,7 +250,7 @@ public SerializeConfig getMapping() { return config; } - public static final void write(Writer out, Object object) { + public static void write(Writer out, Object object) { SerializeWriter writer = new SerializeWriter(); try { JSONSerializer serializer = new JSONSerializer(writer); @@ -157,12 +263,40 @@ public static final void write(Writer out, Object object) { } } - public static final void write(SerializeWriter out, Object object) { + public static void write(SerializeWriter out, Object object) { JSONSerializer serializer = new JSONSerializer(out); serializer.write(object); } public final void write(Object object) { + if (object == null) { + out.writeNull(); + return; + } + + Class clazz = object.getClass(); + ObjectSerializer writer = getObjectWriter(clazz); + + try { + writer.write(this, object, null, null, 0); + } catch (IOException e) { + throw new JSONException(e.getMessage(), e); + } + } + + public final void writeWithFieldName(Object object, Object fieldName) { + writeWithFieldName(object, fieldName, null, 0); + } + + protected final void writeKeyValue(char seperator, String key, Object value) { + if (seperator != '\0') { + out.write(seperator); + } + out.writeFieldName(key); + write(value); + } + + public final void writeWithFieldName(Object object, Object fieldName, Type fieldType, int fieldFeatures) { try { if (object == null) { out.writeNull(); @@ -173,7 +307,7 @@ public final void write(Object object) { ObjectSerializer writer = getObjectWriter(clazz); - writer.write(this, object); + writer.write(this, object, fieldName, fieldType, fieldFeatures); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } @@ -181,65 +315,70 @@ public final void write(Object object) { public final void writeWithFormat(Object object, String format) { if (object instanceof Date) { - String text = new SimpleDateFormat(format).format((Date) object); + DateFormat dateFormat = this.getDateFormat(); + if (dateFormat == null) { + dateFormat = new SimpleDateFormat(format, locale); + dateFormat.setTimeZone(timeZone); + } + String text = dateFormat.format((Date) object); out.writeString(text); return; } + + if (object instanceof byte[]) { + byte[] bytes = (byte[]) object; + if ("gzip".equals(format) || "gzip,base64".equals(format)) { + GZIPOutputStream gzipOut = null; + try { + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + if (bytes.length < 512) { + gzipOut = new GZIPOutputStream(byteOut, bytes.length); + } else { + gzipOut = new GZIPOutputStream(byteOut); + } + gzipOut.write(bytes); + gzipOut.finish(); + out.writeByteArray(byteOut.toByteArray()); + } catch (IOException ex) { + throw new JSONException("write gzipBytes error", ex); + } finally { + IOUtils.close(gzipOut); + } + } else if ("hex".equals(format)) { + out.writeHex(bytes); + } else { + out.writeByteArray(bytes); + } + return; + } + + if (object instanceof Collection) { + Collection collection = (Collection) object; + Iterator iterator = collection.iterator(); + out.write('['); + for (int i = 0; i < collection.size(); i++) { + Object item = iterator.next(); + if (i != 0) { + out.write(','); + } + writeWithFormat(item, format); + } + out.write(']'); + return; + } write(object); } public final void write(String text) { - StringSerializer.instance.write(this, text); + StringCodec.instance.write(this, text); } public ObjectSerializer getObjectWriter(Class clazz) { - ObjectSerializer writer = config.get(clazz); - - if (writer == null) { - final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - for (AutowiredObjectSerializer autowired : ServiceLoader.load(AutowiredObjectSerializer.class, classLoader)) { - for (Type forType : autowired.getAutowiredFor()) { - config.put(forType, autowired); - } - } - - writer = config.get(clazz); - } - - if (writer == null) { - if (Map.class.isAssignableFrom(clazz)) { - config.put(clazz, MapSerializer.instance); - } else if (List.class.isAssignableFrom(clazz)) { - config.put(clazz, ListSerializer.instance); - } else if (Collection.class.isAssignableFrom(clazz)) { - config.put(clazz, CollectionSerializer.instance); - } else if (Date.class.isAssignableFrom(clazz)) { - config.put(clazz, DateSerializer.instance); - } else if (JSONAware.class.isAssignableFrom(clazz)) { - config.put(clazz, JSONAwareSerializer.instance); - } else if (JSONStreamAware.class.isAssignableFrom(clazz)) { - config.put(clazz, JSONStreamAwareSerializer.instance); - } else if (clazz.isEnum()) { - config.put(clazz, EnumSerializer.instance); - } else if (clazz.isArray()) { - Class componentType = clazz.getComponentType(); - ObjectSerializer compObjectSerializer = getObjectWriter(componentType); - config.put(clazz, new ArraySerializer(compObjectSerializer)); - } else if (Throwable.class.isAssignableFrom(clazz)) { - config.put(clazz, new ExceptionSerializer(clazz)); - } else if (TimeZone.class.isAssignableFrom(clazz)) { - config.put(clazz, TimeZoneSerializer.instance); - } else if (Appendable.class.isAssignableFrom(clazz)) { - config.put(clazz, AppendableSerializer.instance); - } else if (Charset.class.isAssignableFrom(clazz)) { - config.put(clazz, CharsetSerializer.instance); - } else { - config.put(clazz, config.createJavaBeanSerializer(clazz)); - } - - writer = config.get(clazz); - } - return writer; + return config.getObjectWriter(clazz); } + public void close() { + this.out.close(); + } + } diff --git a/src/main/java/com/alibaba/fastjson/serializer/JSONSerializerContext.java b/src/main/java/com/alibaba/fastjson/serializer/JSONSerializerContext.java deleted file mode 100644 index 10f1955327..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/JSONSerializerContext.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -/** - * circular references detect - * - * @author wenshao - */ -public final class JSONSerializerContext { - - public static final int DEFAULT_TABLE_SIZE = 128; - - private final Entry[] buckets; - private final int indexMask; - - public JSONSerializerContext(){ - this(DEFAULT_TABLE_SIZE); - } - - public JSONSerializerContext(int tableSize){ - this.indexMask = tableSize - 1; - this.buckets = new Entry[tableSize]; - } - - public final boolean put(Object o) { - final int hash = System.identityHashCode(o); - final int bucket = hash & indexMask; - - for (Entry entry = buckets[bucket]; entry != null; entry = entry.next) { - if (o == entry.object) { - return true; - } - } - - Entry entry = new Entry(o, hash, buckets[bucket]); - buckets[bucket] = entry; - - return false; - } - - protected static final class Entry { - - public final int hashCode; - public final Object object; - - public Entry next; - - public Entry(Object object, int hash, Entry next){ - this.object = object; - this.next = next; - this.hashCode = hash; - } - - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/JSONSerializerMap.java b/src/main/java/com/alibaba/fastjson/serializer/JSONSerializerMap.java old mode 100644 new mode 100755 index 42d2a4296e..6b56a825c4 --- a/src/main/java/com/alibaba/fastjson/serializer/JSONSerializerMap.java +++ b/src/main/java/com/alibaba/fastjson/serializer/JSONSerializerMap.java @@ -1,6 +1,9 @@ package com.alibaba.fastjson.serializer; + @Deprecated public class JSONSerializerMap extends SerializeConfig { - + public final boolean put(Class clazz, ObjectSerializer serializer) { + return super.put(clazz, serializer); + } } diff --git a/src/main/java/com/alibaba/fastjson/serializer/JSONStreamAwareSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/JSONStreamAwareSerializer.java deleted file mode 100644 index 5fbe2ff656..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/JSONStreamAwareSerializer.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -import com.alibaba.fastjson.JSONStreamAware; - -/** - * @author wenshao - */ -public class JSONStreamAwareSerializer implements ObjectSerializer { - - public static JSONStreamAwareSerializer instance = new JSONStreamAwareSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - JSONStreamAware aware = (JSONStreamAware) object; - aware.writeJSONString(out); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java index 7d55ae5876..f307e97a36 100644 --- a/src/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,37 +17,37 @@ import java.io.IOException; import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; +import java.util.*; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.PropertyNamingStrategy; import com.alibaba.fastjson.annotation.JSONField; -import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.util.FieldInfo; +import com.alibaba.fastjson.util.TypeUtils; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ -public class JavaBeanSerializer implements ObjectSerializer { - +public class JavaBeanSerializer extends SerializeFilterable implements ObjectSerializer { // serializers - private final FieldSerializer[] getters; - - public FieldSerializer[] getGetters() { - return getters; - } - - public JavaBeanSerializer(Class clazz){ - this(clazz, (Map) null); + protected final FieldSerializer[] getters; + protected final FieldSerializer[] sortedGetters; + + protected SerializeBeanInfo beanInfo; + + private transient volatile long[] hashArray; + private transient volatile short[] hashArrayMapping; + + public JavaBeanSerializer(Class beanType){ + this(beanType, (Map) null); } - public JavaBeanSerializer(Class clazz, String... aliasList){ - this(clazz, createAliasMap(aliasList)); + public JavaBeanSerializer(Class beanType, String... aliasList){ + this(beanType, createAliasMap(aliasList)); } static Map createAliasMap(String... aliasList) { @@ -59,229 +59,696 @@ static Map createAliasMap(String... aliasList) { return aliasMap; } - public JavaBeanSerializer(Class clazz, Map aliasMap){ - List getterList = new ArrayList(); - - List fieldInfoList = computeGetters(clazz, aliasMap); + /** + * @since 1.2.42 + */ + public Class getType() { + return beanInfo.beanType; + } - for (FieldInfo fieldInfo : fieldInfoList) { - getterList.add(createFieldSerializer(fieldInfo)); + public JavaBeanSerializer(Class beanType, Map aliasMap){ + this(TypeUtils.buildBeanInfo(beanType, aliasMap, null)); + } + + public JavaBeanSerializer(SerializeBeanInfo beanInfo) { + this.beanInfo = beanInfo; + + sortedGetters = new FieldSerializer[beanInfo.sortedFields.length]; + for (int i = 0; i < sortedGetters.length; ++i) { + sortedGetters[i] = new FieldSerializer(beanInfo.beanType, beanInfo.sortedFields[i]); } + + if (beanInfo.fields == beanInfo.sortedFields) { + getters = sortedGetters; + } else { + getters = new FieldSerializer[beanInfo.fields.length]; + for (int i = 0; i < getters.length; ++i) { + getters[i] = getFieldSerializer(beanInfo.fields[i].name); + } + } + } - // - getters = getterList.toArray(new FieldSerializer[getterList.size()]); + public void writeDirectNonContext(JSONSerializer serializer, // + Object object, // + Object fieldName, // + Type fieldType, // + int features) throws IOException { + write(serializer, object, fieldName, fieldType, features); + } + + public void writeAsArray(JSONSerializer serializer, // + Object object, // + Object fieldName, // + Type fieldType, // + int features) throws IOException { + write(serializer, object, fieldName, fieldType, features); + } + + public void writeAsArrayNonContext(JSONSerializer serializer, // + Object object, // + Object fieldName, // + Type fieldType, // + int features) throws IOException { + write(serializer, object, fieldName, fieldType, features); } - protected boolean isWriteClassName(JSONSerializer serializer) { - return serializer.isEnabled(SerializerFeature.WriteClassName); + public void write(JSONSerializer serializer, // + Object object, // + Object fieldName, // + Type fieldType, // + int features) throws IOException { + write(serializer, object, fieldName, fieldType, features, false); } - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); + public void writeNoneASM(JSONSerializer serializer, // + Object object, // + Object fieldName, // + Type fieldType, // + int features) throws IOException { + write(serializer, object, fieldName, fieldType, features, false); + } + + protected void write(JSONSerializer serializer, // + Object object, // + Object fieldName, // + Type fieldType, // + int features, + boolean unwrapped + ) throws IOException { + SerializeWriter out = serializer.out; if (object == null) { out.writeNull(); return; } - FieldSerializer[] getters = this.getters; + if (writeReference(serializer, object, features)) { + return; + } + + final FieldSerializer[] getters; + + if (out.sortField) { + getters = this.sortedGetters; + } else { + getters = this.getters; + } - if (out.isEnabled(SerializerFeature.SortField)) { - Arrays.sort(getters); + SerialContext parent = serializer.context; + if (!this.beanInfo.beanType.isEnum()) { + serializer.setContext(parent, object, fieldName, this.beanInfo.features, features); } + final boolean writeAsArray = isWriteAsArray(serializer, features); + try { - out.append('{'); + final char startSeperator = writeAsArray ? '[' : '{'; + final char endSeperator = writeAsArray ? ']' : '}'; + if (!unwrapped) { + out.append(startSeperator); + } + + if (getters.length > 0 && out.isEnabled(SerializerFeature.PrettyFormat)) { + serializer.incrementIndent(); + serializer.println(); + } boolean commaFlag = false; - if (isWriteClassName(serializer)) { - out.writeFieldName("class"); - serializer.write(object.getClass()); - commaFlag = true; + if ((this.beanInfo.features & SerializerFeature.WriteClassName.mask) != 0 + ||(features & SerializerFeature.WriteClassName.mask) != 0 + || serializer.isWriteClassName(fieldType, object)) { + Class objClass = object.getClass(); + + final Type type; + if (objClass != fieldType && fieldType instanceof WildcardType) { + type = TypeUtils.getClass(fieldType); + } else { + type = fieldType; + } + + if (objClass != type) { + writeClassName(serializer, beanInfo.typeKey, object); + commaFlag = true; + } } + char seperator = commaFlag ? ',' : '\0'; + + final boolean directWritePrefix = out.quoteFieldNames && !out.useSingleQuotes; + char newSeperator = this.writeBefore(serializer, object, seperator); + commaFlag = newSeperator == ','; + + final boolean skipTransient = out.isEnabled(SerializerFeature.SkipTransientField); + final boolean ignoreNonFieldGetter = out.isEnabled(SerializerFeature.IgnoreNonFieldGetter); + for (int i = 0; i < getters.length; ++i) { FieldSerializer fieldSerializer = getters[i]; - if (serializer.isEnabled(SerializerFeature.SkipTransientField)) { - Field field = fieldSerializer.getField(); + Field field = fieldSerializer.fieldInfo.field; + FieldInfo fieldInfo = fieldSerializer.fieldInfo; + String fieldInfoName = fieldInfo.name; + Class fieldClass = fieldInfo.fieldClass; + + if (skipTransient) { if (field != null) { - if (Modifier.isTransient(field.getModifiers())) { + if (fieldInfo.fieldTransient) { continue; } } } - Object propertyValue = fieldSerializer.getPropertyValue(object); + if (ignoreNonFieldGetter) { + if (field == null) { + continue; + } + } - if (!FilterUtils.apply(serializer, object, fieldSerializer.getName(), propertyValue)) { + boolean notApply = false; + if ((!this.applyName(serializer, object, fieldInfoName)) // + || !this.applyLabel(serializer, fieldInfo.label)) { + if (writeAsArray) { + notApply = true; + } else { + continue; + } + } + + if (beanInfo.typeKey != null + && fieldInfoName.equals(beanInfo.typeKey) + && serializer.isWriteClassName(fieldType, object)) { + continue; + } + + Object propertyValue; + + if (notApply) { + propertyValue = null; + } else { + try { + propertyValue = fieldSerializer.getPropertyValueDirect(object); + } catch (InvocationTargetException ex) { + if (out.isEnabled(SerializerFeature.IgnoreErrorGetter)) { + propertyValue = null; + } else { + throw ex; + } + } + } + + if (!this.apply(serializer, object, fieldInfoName, propertyValue)) { continue; } - String key = FilterUtils.processKey(serializer, object, fieldSerializer.getName(), propertyValue); + if (fieldClass == String.class && "trim".equals(fieldInfo.format)) { + if (propertyValue != null) { + propertyValue = ((String) propertyValue).trim(); + } + } + + String key = fieldInfoName; + key = this.processKey(serializer, object, key, propertyValue); Object originalValue = propertyValue; - propertyValue = FilterUtils.processValue(serializer, object, fieldSerializer.getName(), propertyValue); + propertyValue = this.processValue(serializer, fieldSerializer.fieldContext, object, fieldInfoName, + propertyValue); if (propertyValue == null) { - if ((!fieldSerializer.isWriteNull()) && (!serializer.isEnabled(SerializerFeature.WriteMapNullValue))) { + int serialzeFeatures = fieldInfo.serialzeFeatures; + if (beanInfo.jsonType != null) { + serialzeFeatures |= SerializerFeature.of(beanInfo.jsonType.serialzeFeatures()); + } + // beanInfo.jsonType + if (fieldClass == Boolean.class) { + int defaultMask = SerializerFeature.WriteNullBooleanAsFalse.mask; + final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask; + if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) { + continue; + } else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) { + propertyValue = false; + } + } else if (fieldClass == String.class) { + int defaultMask = SerializerFeature.WriteNullStringAsEmpty.mask; + final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask; + if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) { + continue; + } else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) { + propertyValue = ""; + } + } else if (Number.class.isAssignableFrom(fieldClass)) { + int defaultMask = SerializerFeature.WriteNullNumberAsZero.mask; + final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask; + if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) { + continue; + } else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) { + propertyValue = 0; + } + } else if (Collection.class.isAssignableFrom(fieldClass)) { + int defaultMask = SerializerFeature.WriteNullListAsEmpty.mask; + final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask; + if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) { + continue; + } else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) { + propertyValue = Collections.emptyList(); + } + } else if ((!writeAsArray) && (!fieldSerializer.writeNull) && !out.isEnabled(SerializerFeature.WriteMapNullValue.mask)){ + continue; + } + } + + if (propertyValue != null // + && (out.notWriteDefaultValue // + || (fieldInfo.serialzeFeatures & SerializerFeature.NotWriteDefaultValue.mask) != 0 // + || (beanInfo.features & SerializerFeature.NotWriteDefaultValue.mask) != 0 // + )) { + Class fieldCLass = fieldInfo.fieldClass; + if (fieldCLass == byte.class && propertyValue instanceof Byte + && ((Byte) propertyValue).byteValue() == 0) { + continue; + } else if (fieldCLass == short.class && propertyValue instanceof Short + && ((Short) propertyValue).shortValue() == 0) { + continue; + } else if (fieldCLass == int.class && propertyValue instanceof Integer + && ((Integer) propertyValue).intValue() == 0) { + continue; + } else if (fieldCLass == long.class && propertyValue instanceof Long + && ((Long) propertyValue).longValue() == 0L) { + continue; + } else if (fieldCLass == float.class && propertyValue instanceof Float + && ((Float) propertyValue).floatValue() == 0F) { + continue; + } else if (fieldCLass == double.class && propertyValue instanceof Double + && ((Double) propertyValue).doubleValue() == 0D) { + continue; + } else if (fieldCLass == boolean.class && propertyValue instanceof Boolean + && !((Boolean) propertyValue).booleanValue()) { continue; } } if (commaFlag) { - out.append(','); + if (fieldInfo.unwrapped + && propertyValue instanceof Map + && ((Map) propertyValue).size() == 0) { + continue; + } + + out.write(','); + if (out.isEnabled(SerializerFeature.PrettyFormat)) { + serializer.println(); + } } - if (key != fieldSerializer.getName()) { - out.writeFieldName(key); + if (key != fieldInfoName) { + if (!writeAsArray) { + out.writeFieldName(key, true); + } + serializer.write(propertyValue); } else if (originalValue != propertyValue) { - fieldSerializer.writePrefix(serializer); + if (!writeAsArray) { + fieldSerializer.writePrefix(serializer); + } serializer.write(propertyValue); } else { - fieldSerializer.writeProperty(serializer, propertyValue); + if (!writeAsArray) { + if (!fieldInfo.unwrapped) { + if (directWritePrefix) { + out.write(fieldInfo.name_chars, 0, fieldInfo.name_chars.length); + } else { + fieldSerializer.writePrefix(serializer); + } + } + } + + if (!writeAsArray) { + JSONField fieldAnnotation = fieldInfo.getAnnotation(); + if (fieldClass == String.class && (fieldAnnotation == null || fieldAnnotation.serializeUsing() == Void.class)) { + if (propertyValue == null) { + if ((out.features & SerializerFeature.WriteNullStringAsEmpty.mask) != 0 + || (fieldSerializer.features & SerializerFeature.WriteNullStringAsEmpty.mask) != 0) { + out.writeString(""); + } else { + out.writeNull(); + } + } else { + String propertyValueString = (String) propertyValue; + + if (out.useSingleQuotes) { + out.writeStringWithSingleQuote(propertyValueString); + } else { + out.writeStringWithDoubleQuote(propertyValueString, (char) 0); + } + } + } else { + if (fieldInfo.unwrapped + && propertyValue instanceof Map + && ((Map) propertyValue).size() == 0) { + commaFlag = false; + continue; + } + + fieldSerializer.writeValue(serializer, propertyValue); + } + } else { + fieldSerializer.writeValue(serializer, propertyValue); + } } - commaFlag = true; + boolean fieldUnwrappedNull = false; + if (fieldInfo.unwrapped + && propertyValue instanceof Map) { + Map map = ((Map) propertyValue); + if (map.size() == 0) { + fieldUnwrappedNull = true; + } else if (!serializer.isEnabled(SerializerFeature.WriteMapNullValue)){ + boolean hasNotNull = false; + for (Object value : map.values()) { + if (value != null) { + hasNotNull = true; + break; + } + } + if (!hasNotNull) { + fieldUnwrappedNull = true; + } + } + } + + if (!fieldUnwrappedNull) { + commaFlag = true; + } + } + + this.writeAfter(serializer, object, commaFlag ? ',' : '\0'); + + if (getters.length > 0 && out.isEnabled(SerializerFeature.PrettyFormat)) { + serializer.decrementIdent(); + serializer.println(); } - out.append('}'); + if (!unwrapped) { + out.append(endSeperator); + } } catch (Exception e) { - throw new JSONException("write javaBean error", e); + String errorMessage = "write javaBean error, fastjson version " + JSON.VERSION; + if (object != null) { + errorMessage += ", class " + object.getClass().getName(); + } + if (fieldName != null) { + errorMessage += ", fieldName : " + fieldName; + } + if (e.getMessage() != null) { + errorMessage += (", " + e.getMessage()); + } + + throw new JSONException(errorMessage, e); + } finally { + serializer.context = parent; } } - public FieldSerializer createFieldSerializer(FieldInfo fieldInfo) { - Class clazz = fieldInfo.getMethod().getReturnType(); - - if (clazz == Number.class) { - return new NumberFieldSerializer(fieldInfo); + protected void writeClassName(JSONSerializer serializer, String typeKey, Object object) { + if (typeKey == null) { + typeKey = serializer.config.typeKey; } + serializer.out.writeFieldName(typeKey, false); + String typeName = this.beanInfo.typeName; + if (typeName == null) { + Class clazz = object.getClass(); - return new ObjectFieldSerializer(fieldInfo); + if (TypeUtils.isProxy(clazz)) { + clazz = clazz.getSuperclass(); + } + + typeName = clazz.getName(); + } + serializer.write(typeName); } - public static List computeGetters(Class clazz, Map aliasMap) { - List getters = new ArrayList(); + public boolean writeReference(JSONSerializer serializer, Object object, int fieldFeatures) { + SerialContext context = serializer.context; + int mask = SerializerFeature.DisableCircularReferenceDetect.mask; + if (context == null || (context.features & mask) != 0 || (fieldFeatures & mask) != 0) { + return false; + } - for (Method method : clazz.getMethods()) { - String methodName = method.getName(); + if (serializer.references != null && serializer.references.containsKey(object)) { + serializer.writeReference(object); + return true; + } else { + return false; + } + } + + protected boolean isWriteAsArray(JSONSerializer serializer) { + return isWriteAsArray(serializer, 0); + } - if (Modifier.isStatic(method.getModifiers())) { - continue; - } + protected boolean isWriteAsArray(JSONSerializer serializer, int fieldFeatrues) { + final int mask = SerializerFeature.BeanToArray.mask; + return (beanInfo.features & mask) != 0 // + || serializer.out.beanToArray // + || (fieldFeatrues & mask) != 0; + } + + public Object getFieldValue(Object object, String key) { + FieldSerializer fieldDeser = getFieldSerializer(key); + if (fieldDeser == null) { + throw new JSONException("field not found. " + key); + } + + try { + return fieldDeser.getPropertyValue(object); + } catch (InvocationTargetException ex) { + throw new JSONException("getFieldValue error." + key, ex); + } catch (IllegalAccessException ex) { + throw new JSONException("getFieldValue error." + key, ex); + } + } - if (method.getReturnType().equals(Void.TYPE)) { - continue; + public Object getFieldValue(Object object, String key, long keyHash, boolean throwFieldNotFoundException) { + FieldSerializer fieldDeser = getFieldSerializer(keyHash); + if (fieldDeser == null) { + if (throwFieldNotFoundException) { + throw new JSONException("field not found. " + key); } + return null; + } - if (method.getParameterTypes().length != 0) { - continue; - } + try { + return fieldDeser.getPropertyValue(object); + } catch (InvocationTargetException ex) { + throw new JSONException("getFieldValue error." + key, ex); + } catch (IllegalAccessException ex) { + throw new JSONException("getFieldValue error." + key, ex); + } + } - JSONField annotation = method.getAnnotation(JSONField.class); + public FieldSerializer getFieldSerializer(String key) { + if (key == null) { + return null; + } - if (annotation != null) { - if (!annotation.serialize()) { - continue; - } + int low = 0; + int high = sortedGetters.length - 1; - if (annotation.name().length() != 0) { - String propertyName = annotation.name(); + while (low <= high) { + int mid = (low + high) >>> 1; - if (aliasMap != null) { - propertyName = aliasMap.get(propertyName); - if (propertyName == null) { - continue; - } - } + String fieldName = sortedGetters[mid].fieldInfo.name; - getters.add(new FieldInfo(propertyName, method, null)); - continue; - } + int cmp = fieldName.compareTo(key); + + if (cmp < 0) { + low = mid + 1; + } else if (cmp > 0) { + high = mid - 1; + } else { + return sortedGetters[mid]; // key found } + } - if (methodName.startsWith("get")) { - if (methodName.length() < 4) { - continue; - } + return null; // key not found. + } - if (methodName.equals("getClass")) { - continue; - } + public FieldSerializer getFieldSerializer(long hash) { + PropertyNamingStrategy[] namingStrategies = null; + if (this.hashArray == null) { + namingStrategies = PropertyNamingStrategy.values(); - if (!Character.isUpperCase(methodName.charAt(3))) { - continue; + long[] hashArray = new long[sortedGetters.length * namingStrategies.length]; + int index = 0; + for (int i = 0; i < sortedGetters.length; i++) { + String name = sortedGetters[i].fieldInfo.name; + hashArray[index++] = TypeUtils.fnv1a_64(name); + + for (int j = 0; j < namingStrategies.length; j++) { + String name_t = namingStrategies[j].translate(name); + if (name.equals(name_t)) { + continue; + } + hashArray[index++] = TypeUtils.fnv1a_64(name_t); } + } + Arrays.sort(hashArray, 0, index); - String propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); + this.hashArray = new long[index]; + System.arraycopy(hashArray, 0, this.hashArray, 0, index); + } - Field field = ParserConfig.getField(clazz, propertyName); - if (field != null) { - JSONField fieldAnnotation = field.getAnnotation(JSONField.class); + int pos = Arrays.binarySearch(hashArray, hash); + if (pos < 0) { + return null; + } - if (fieldAnnotation != null && fieldAnnotation.name().length() != 0) { - propertyName = fieldAnnotation.name(); + if (hashArrayMapping == null) { + if (namingStrategies == null) { + namingStrategies = PropertyNamingStrategy.values(); + } - if (aliasMap != null) { - propertyName = aliasMap.get(propertyName); - if (propertyName == null) { - continue; - } - } - } + short[] mapping = new short[hashArray.length]; + Arrays.fill(mapping, (short) -1); + for (int i = 0; i < sortedGetters.length; i++) { + String name = sortedGetters[i].fieldInfo.name; + + int p = Arrays.binarySearch(hashArray + , TypeUtils.fnv1a_64(name)); + if (p >= 0) { + mapping[p] = (short) i; } - if (aliasMap != null) { - propertyName = aliasMap.get(propertyName); - if (propertyName == null) { + for (int j = 0; j < namingStrategies.length; j++) { + String name_t = namingStrategies[j].translate(name); + if (name.equals(name_t)) { continue; } - } - getters.add(new FieldInfo(propertyName, method, field)); + int p_t = Arrays.binarySearch(hashArray + , TypeUtils.fnv1a_64(name_t)); + if (p_t >= 0) { + mapping[p_t] = (short) i; + } + } } + hashArrayMapping = mapping; + } - if (methodName.startsWith("is")) { - if (methodName.length() < 3) { - continue; - } + int getterIndex = hashArrayMapping[pos]; + if (getterIndex != -1) { + return sortedGetters[getterIndex]; + } - if (!Character.isUpperCase(methodName.charAt(2))) { - continue; - } + return null; // key not found. + } - String propertyName = Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3); + public List getFieldValues(Object object) throws Exception { + List fieldValues = new ArrayList(sortedGetters.length); + for (FieldSerializer getter : sortedGetters) { + fieldValues.add(getter.getPropertyValue(object)); + } - Field field = ParserConfig.getField(clazz, propertyName); - if (field != null) { - JSONField fieldAnnotation = field.getAnnotation(JSONField.class); + return fieldValues; + } - if (fieldAnnotation != null && fieldAnnotation.name().length() != 0) { - propertyName = fieldAnnotation.name(); + // for jsonpath deepSet + public List getObjectFieldValues(Object object) throws Exception { + List fieldValues = new ArrayList(sortedGetters.length); + for (FieldSerializer getter : sortedGetters) { + Class fieldClass = getter.fieldInfo.fieldClass; + if (fieldClass.isPrimitive()) { + continue; + } + if (fieldClass.getName().startsWith("java.lang.")) { + continue; + } + fieldValues.add(getter.getPropertyValue(object)); + } - if (aliasMap != null) { - propertyName = aliasMap.get(propertyName); - if (propertyName == null) { - continue; - } - } - } - } + return fieldValues; + } + + public int getSize(Object object) throws Exception { + int size = 0; + for (FieldSerializer getter : sortedGetters) { + Object value = getter.getPropertyValueDirect(object); + if (value != null) { + size ++; + } + } + return size; + } + + public Map getFieldValuesMap(Object object) throws Exception { + Map map = new LinkedHashMap(sortedGetters.length); + + for (FieldSerializer getter : sortedGetters) { + map.put(getter.fieldInfo.name, getter.getPropertyValue(object)); + } + + return map; + } - if (aliasMap != null) { - propertyName = aliasMap.get(propertyName); - if (propertyName == null) { - continue; - } + protected BeanContext getBeanContext(int orinal) { + return sortedGetters[orinal].fieldContext; + } + + protected Type getFieldType(int ordinal) { + return sortedGetters[ordinal].fieldInfo.fieldType; + } + + protected char writeBefore(JSONSerializer jsonBeanDeser, // + Object object, char seperator) { + + if (jsonBeanDeser.beforeFilters != null) { + for (BeforeFilter beforeFilter : jsonBeanDeser.beforeFilters) { + seperator = beforeFilter.writeBefore(jsonBeanDeser, object, seperator); + } + } + + if (this.beforeFilters != null) { + for (BeforeFilter beforeFilter : this.beforeFilters) { + seperator = beforeFilter.writeBefore(jsonBeanDeser, object, seperator); + } + } + + return seperator; + } + + protected char writeAfter(JSONSerializer jsonBeanDeser, // + Object object, char seperator) { + if (jsonBeanDeser.afterFilters != null) { + for (AfterFilter afterFilter : jsonBeanDeser.afterFilters) { + seperator = afterFilter.writeAfter(jsonBeanDeser, object, seperator); + } + } + + if (this.afterFilters != null) { + for (AfterFilter afterFilter : this.afterFilters) { + seperator = afterFilter.writeAfter(jsonBeanDeser, object, seperator); + } + } + + return seperator; + } + + protected boolean applyLabel(JSONSerializer jsonBeanDeser, String label) { + if (jsonBeanDeser.labelFilters != null) { + for (LabelFilter propertyFilter : jsonBeanDeser.labelFilters) { + if (!propertyFilter.apply(label)) { + return false; } - - getters.add(new FieldInfo(propertyName, method, field)); } } - - return getters; + + if (this.labelFilters != null) { + for (LabelFilter propertyFilter : this.labelFilters) { + if (!propertyFilter.apply(label)) { + return false; + } + } + } + + return true; } } diff --git a/src/main/java/com/alibaba/fastjson/serializer/LabelFilter.java b/src/main/java/com/alibaba/fastjson/serializer/LabelFilter.java new file mode 100644 index 0000000000..744eeb416f --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/LabelFilter.java @@ -0,0 +1,24 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +/** + * @author wenshao[szujobs@hotmail.com] + * @since 1.2.7 + */ +public interface LabelFilter extends SerializeFilter { + boolean apply(String label); +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/Labels.java b/src/main/java/com/alibaba/fastjson/serializer/Labels.java new file mode 100644 index 0000000000..b5fc52788c --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/Labels.java @@ -0,0 +1,60 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.util.Arrays; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class Labels { + + private static class DefaultLabelFilter implements LabelFilter { + + private String[] includes; + private String[] excludes; + + public DefaultLabelFilter(String[] includes, String[] excludes){ + if (includes != null) { + this.includes = new String[includes.length]; + System.arraycopy(includes, 0, this.includes, 0, includes.length); + Arrays.sort(this.includes); + } + if (excludes != null) { + this.excludes = new String[excludes.length]; + System.arraycopy(excludes, 0, this.excludes, 0, excludes.length); + Arrays.sort(this.excludes); + } + } + + public boolean apply(String label) { + if (excludes != null) { + return Arrays.binarySearch(excludes, label) == -1; + } + + return includes != null // + && Arrays.binarySearch(includes, label) >= 0; + } + } + + public static LabelFilter includes(String... views) { + return new DefaultLabelFilter(views, null); + } + + public static LabelFilter excludes(String... views) { + return new DefaultLabelFilter(null, views); + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ListSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ListSerializer.java index 0191d61cf0..c1638504f1 100644 --- a/src/main/java/com/alibaba/fastjson/serializer/ListSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/ListSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,74 +15,136 @@ */ package com.alibaba.fastjson.serializer; +import com.alibaba.fastjson.util.TypeUtils; + import java.io.IOException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; import java.util.List; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public final class ListSerializer implements ObjectSerializer { public static final ListSerializer instance = new ListSerializer(); - public final void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); + public final void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) + throws IOException { + + boolean writeClassName = serializer.out.isEnabled(SerializerFeature.WriteClassName) + || SerializerFeature.isEnabled(features, SerializerFeature.WriteClassName); + + SerializeWriter out = serializer.out; + + Type elementType = null; + if (writeClassName) { + elementType = TypeUtils.getCollectionItemType(fieldType); + } if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } + out.writeNull(SerializerFeature.WriteNullListAsEmpty); return; } List list = (List) object; - final int size = list.size(); - int end = size - 1; - - if (end == -1) { + if (list.size() == 0) { out.append("[]"); return; } - out.append('['); - for (int i = 0; i < end; ++i) { - Object item = list.get(i); + SerialContext context = serializer.context; + serializer.setContext(context, object, fieldName, 0); - if (item == null) { - out.append("null,"); - } else { - Class clazz = item.getClass(); + ObjectSerializer itemSerializer = null; + try { + if (out.isEnabled(SerializerFeature.PrettyFormat)) { + out.append('['); + serializer.incrementIndent(); - if (clazz == Integer.class) { - out.writeIntAndChar(((Integer) item).intValue(), ','); - } else if (clazz == Long.class) { - long val = ((Long) item).longValue(); - out.writeLongAndChar(val, ','); - } else { - serializer.write(item); - out.append(','); + int i = 0; + for (Object item : list) { + if (i != 0) { + out.append(','); + } + + serializer.println(); + if (item != null) { + if (serializer.containsReference(item)) { + serializer.writeReference(item); + } else { + itemSerializer = serializer.getObjectWriter(item.getClass()); + SerialContext itemContext = new SerialContext(context, object, fieldName, 0, 0); + serializer.context = itemContext; + itemSerializer.write(serializer, item, i, elementType, features); + } + } else { + serializer.out.writeNull(); + } + i++; } + + serializer.decrementIdent(); + serializer.println(); + out.append(']'); + return; } - } - Object item = list.get(end); + out.append('['); + for (int i = 0, size = list.size(); i < size; ++i) { + Object item = list.get(i); + if (i != 0) { + out.append(','); + } + + if (item == null) { + out.append("null"); + } else { + Class clazz = item.getClass(); - if (item == null) { - out.append("null]"); - } else { - Class clazz = item.getClass(); + if (clazz == Integer.class) { + out.writeInt(((Integer) item).intValue()); + } else if (clazz == Long.class) { + long val = ((Long) item).longValue(); + if (writeClassName) { + out.writeLong(val); + out.write('L'); + } else { + out.writeLong(val); + } + } else { + if ((SerializerFeature.DisableCircularReferenceDetect.mask & features) != 0){ + itemSerializer = serializer.getObjectWriter(item.getClass()); + itemSerializer.write(serializer, item, i, elementType, features); + }else { + if (!out.disableCircularReferenceDetect) { + SerialContext itemContext = new SerialContext(context, object, fieldName, 0, 0); + serializer.context = itemContext; + } - if (clazz == Integer.class) { - out.writeIntAndChar(((Integer) item).intValue(), ']'); - } else if (clazz == Long.class) { - out.writeLongAndChar(((Long) item).longValue(), ']'); - } else { - serializer.write(item); - out.append(']'); + if (serializer.containsReference(item)) { + serializer.writeReference(item); + } else { + itemSerializer = serializer.getObjectWriter(item.getClass()); + if ((SerializerFeature.WriteClassName.mask & features) != 0 + && itemSerializer instanceof JavaBeanSerializer) + { + JavaBeanSerializer javaBeanSerializer = (JavaBeanSerializer) itemSerializer; + javaBeanSerializer.writeNoneASM(serializer, item, i, elementType, features); + } else { + itemSerializer.write(serializer, item, i, elementType, features); + } + } + } + } + } } + out.append(']'); + } finally { + serializer.context = context; } } + } diff --git a/src/main/java/com/alibaba/fastjson/serializer/LocaleSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/LocaleSerializer.java deleted file mode 100644 index 0bcbd86da6..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/LocaleSerializer.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.Locale; - -public class LocaleSerializer implements ObjectSerializer { - - public final static LocaleSerializer instance = new LocaleSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - if (object == null) { - serializer.writeNull(); - return; - } - - Locale locale = (Locale) object; - serializer.write(locale.toString()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/LongArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/LongArraySerializer.java deleted file mode 100644 index c47b6ea90c..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/LongArraySerializer.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class LongArraySerializer implements ObjectSerializer { - - public static LongArraySerializer instance = new LongArraySerializer(); - - public final void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } - return; - } - - long[] array = (long[]) object; - - out.writeLongArray(array); - } - - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/LongCodec.java b/src/main/java/com/alibaba/fastjson/serializer/LongCodec.java new file mode 100755 index 0000000000..a878ecfd6d --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/LongCodec.java @@ -0,0 +1,93 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class LongCodec implements ObjectSerializer, ObjectDeserializer { + + public static LongCodec instance = new LongCodec(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(SerializerFeature.WriteNullNumberAsZero); + } else { + long value = ((Long) object).longValue(); + out.writeLong(value); + + if (out.isEnabled(SerializerFeature.WriteClassName) // + && value <= Integer.MAX_VALUE && value >= Integer.MIN_VALUE // + && fieldType != Long.class + && fieldType != long.class) { + out.write('L'); + } + } + } + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + final JSONLexer lexer = parser.lexer; + + Long longObject; + try { + final int token = lexer.token(); + if (token == JSONToken.LITERAL_INT) { + long longValue = lexer.longValue(); + lexer.nextToken(JSONToken.COMMA); + longObject = Long.valueOf(longValue); + } else { + if (token == JSONToken.LBRACE) { + JSONObject jsonObject = new JSONObject(true); + parser.parseObject(jsonObject); + longObject = TypeUtils.castToLong(jsonObject); + } else { + Object value = parser.parse(); + + longObject = TypeUtils.castToLong(value); + } + if (longObject == null) { + return null; + } + } + } catch (Exception ex) { + throw new JSONException("parseLong error, field : " + fieldName, ex); + } + + return clazz == AtomicLong.class // + ? (T) new AtomicLong(longObject.longValue()) // + : (T) longObject; + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_INT; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/LongSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/LongSerializer.java deleted file mode 100644 index ff56dab957..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/LongSerializer.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class LongSerializer implements ObjectSerializer { - - public static LongSerializer instance = new LongSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullNumberAsZero)) { - out.write('0'); - } else { - out.writeNull(); - } - return; - } - - Long value = (Long) object; - out.writeLong(value.longValue()); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/MapSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/MapSerializer.java old mode 100644 new mode 100755 index b0eb97c31f..b620a566b1 --- a/src/main/java/com/alibaba/fastjson/serializer/MapSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/MapSerializer.java @@ -1,117 +1,287 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * @author wenshao - */ -public class MapSerializer implements ObjectSerializer { - - public static MapSerializer instance = new MapSerializer(); - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - out.writeNull(); - return; - } - - Map map = (Map) object; - - if (out.isEnabled(SerializerFeature.SortField)) { - map = new TreeMap(map); - } - - out.write('{'); - - Class preClazz = null; - ObjectSerializer preWriter = null; - - boolean first = true; - for (Map.Entry entry : map.entrySet()) { - Object value = entry.getValue(); - - Object entryKey = entry.getKey(); - String key = entryKey == null ? "null" : entryKey.toString(); - - List propertyFilters = serializer.getPropertyFiltersDirect(); - if (propertyFilters != null) { - boolean apply = true; - for (PropertyFilter propertyFilter : propertyFilters) { - if (!propertyFilter.apply(object, key, value)) { - apply = false; - break; - } - } - - if (!apply) { - continue; - } - } - - List nameFilters = serializer.getNameFiltersDirect(); - if (nameFilters != null) { - for (NameFilter nameFilter : nameFilters) { - key = nameFilter.process(object, key, value); - } - } - - List valueFilters = serializer.getValueFiltersDirect(); - if (valueFilters != null) { - for (ValueFilter valueFilter : valueFilters) { - value = valueFilter.process(object, key, value); - } - } - - if (value == null) { - if (!serializer.isEnabled(SerializerFeature.WriteMapNullValue)) { - continue; - } - } - - if (!first) { - out.write(','); - } - - out.writeFieldName(key); - first = false; - - if (value == null) { - out.writeNull(); - continue; - } - - Class clazz = value.getClass(); - - if (clazz == preClazz) { - preWriter.write(serializer, value); - } else { - preClazz = clazz; - preWriter = serializer.getObjectWriter(clazz); - - preWriter.write(serializer, value); - } - } - out.write('}'); - } -} +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.*; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class MapSerializer extends SerializeFilterable implements ObjectSerializer { + + public static MapSerializer instance = new MapSerializer(); + + private static final int NON_STRINGKEY_AS_STRING = SerializerFeature.of( + new SerializerFeature[] { + SerializerFeature.BrowserCompatible, + SerializerFeature.WriteNonStringKeyAsString, + SerializerFeature.BrowserSecure}); + + public void write(JSONSerializer serializer + , Object object + , Object fieldName + , Type fieldType + , int features) throws IOException { + write(serializer, object, fieldName, fieldType, features, false); + } + + @SuppressWarnings({ "rawtypes"}) + public void write(JSONSerializer serializer + , Object object + , Object fieldName + , Type fieldType + , int features // + , boolean unwrapped) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(); + return; + } + + Map map = (Map) object; + final int mapSortFieldMask = SerializerFeature.MapSortField.mask; + if ((out.features & mapSortFieldMask) != 0 || (features & mapSortFieldMask) != 0) { + if (map instanceof JSONObject) { + map = ((JSONObject) map).getInnerMap(); + } + + if ((!(map instanceof SortedMap)) && !(map instanceof LinkedHashMap)) { + try { + map = new TreeMap(map); + } catch (Exception ex) { + // skip + } + } + } + + if (serializer.containsReference(object)) { + serializer.writeReference(object); + return; + } + + SerialContext parent = serializer.context; + serializer.setContext(parent, object, fieldName, 0); + try { + if (!unwrapped) { + out.write('{'); + } + + serializer.incrementIndent(); + + Class preClazz = null; + ObjectSerializer preWriter = null; + + boolean first = true; + + if (out.isEnabled(SerializerFeature.WriteClassName)) { + String typeKey = serializer.config.typeKey; + Class mapClass = map.getClass(); + boolean containsKey = (mapClass == JSONObject.class || mapClass == HashMap.class || mapClass == LinkedHashMap.class) + && map.containsKey(typeKey); + if (!containsKey) { + out.writeFieldName(typeKey); + out.writeString(object.getClass().getName()); + first = false; + } + } + + for (Map.Entry entry : map.entrySet()) { + Object value = entry.getValue(); + + Object entryKey = entry.getKey(); + + { + List preFilters = serializer.propertyPreFilters; + if (preFilters != null && preFilters.size() > 0) { + if (entryKey == null || entryKey instanceof String) { + if (!this.applyName(serializer, object, (String) entryKey)) { + continue; + } + } else if (entryKey.getClass().isPrimitive() || entryKey instanceof Number) { + String strKey = JSON.toJSONString(entryKey); + if (!this.applyName(serializer, object, strKey)) { + continue; + } + } + } + } + { + List preFilters = this.propertyPreFilters; + if (preFilters != null && preFilters.size() > 0) { + if (entryKey == null || entryKey instanceof String) { + if (!this.applyName(serializer, object, (String) entryKey)) { + continue; + } + } else if (entryKey.getClass().isPrimitive() || entryKey instanceof Number) { + String strKey = JSON.toJSONString(entryKey); + if (!this.applyName(serializer, object, strKey)) { + continue; + } + } + } + } + + { + List propertyFilters = serializer.propertyFilters; + if (propertyFilters != null && propertyFilters.size() > 0) { + if (entryKey == null || entryKey instanceof String) { + if (!this.apply(serializer, object, (String) entryKey, value)) { + continue; + } + } else if (entryKey.getClass().isPrimitive() || entryKey instanceof Number) { + String strKey = JSON.toJSONString(entryKey); + if (!this.apply(serializer, object, strKey, value)) { + continue; + } + } + } + } + { + List propertyFilters = this.propertyFilters; + if (propertyFilters != null && propertyFilters.size() > 0) { + if (entryKey == null || entryKey instanceof String) { + if (!this.apply(serializer, object, (String) entryKey, value)) { + continue; + } + } else if (entryKey.getClass().isPrimitive() || entryKey instanceof Number) { + String strKey = JSON.toJSONString(entryKey); + if (!this.apply(serializer, object, strKey, value)) { + continue; + } + } + } + } + + { + List nameFilters = serializer.nameFilters; + if (nameFilters != null && nameFilters.size() > 0) { + if (entryKey == null || entryKey instanceof String) { + entryKey = this.processKey(serializer, object, (String) entryKey, value); + } else if (entryKey.getClass().isPrimitive() || entryKey instanceof Number) { + String strKey = JSON.toJSONString(entryKey); + entryKey = this.processKey(serializer, object, strKey, value); + } + } + } + { + List nameFilters = this.nameFilters; + if (nameFilters != null && nameFilters.size() > 0) { + if (entryKey == null || entryKey instanceof String) { + entryKey = this.processKey(serializer, object, (String) entryKey, value); + } else if (entryKey.getClass().isPrimitive() || entryKey instanceof Number) { + String strKey = JSON.toJSONString(entryKey); + entryKey = this.processKey(serializer, object, strKey, value); + } + } + } + + { + if (entryKey == null || entryKey instanceof String) { + value = this.processValue(serializer, null, object, (String) entryKey, value); + } else { + boolean objectOrArray = entryKey instanceof Map || entryKey instanceof Collection; + if (!objectOrArray) { + String strKey = JSON.toJSONString(entryKey); + value = this.processValue(serializer, null, object, strKey, value); + } + } + } + + if (value == null) { + if (!out.isEnabled(SerializerFeature.WriteMapNullValue)) { + continue; + } + } + + if (entryKey instanceof String) { + String key = (String) entryKey; + + if (!first) { + out.write(','); + } + + if (out.isEnabled(SerializerFeature.PrettyFormat)) { + serializer.println(); + } + out.writeFieldName(key, true); + } else { + if (!first) { + out.write(','); + } + + if (out.isEnabled(NON_STRINGKEY_AS_STRING) && !(entryKey instanceof Enum)) { + String strEntryKey = JSON.toJSONString(entryKey); + serializer.write(strEntryKey); + } else { + serializer.write(entryKey); + } + + out.write(':'); + } + + first = false; + + if (value == null) { + out.writeNull(); + continue; + } + + Class clazz = value.getClass(); + + if (clazz != preClazz) { + preClazz = clazz; + preWriter = serializer.getObjectWriter(clazz); + } + + if (SerializerFeature.isEnabled(features, SerializerFeature.WriteClassName) + && preWriter instanceof JavaBeanSerializer) { + Type valueType = null; + if (fieldType instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) fieldType; + Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); + if (actualTypeArguments.length == 2) { + valueType = actualTypeArguments[1]; + } + } + + JavaBeanSerializer javaBeanSerializer = (JavaBeanSerializer) preWriter; + javaBeanSerializer.writeNoneASM(serializer, value, entryKey, valueType, features); + } else { + preWriter.write(serializer, value, entryKey, null, features); + } + } + } finally { + serializer.context = parent; + } + + serializer.decrementIdent(); + if (out.isEnabled(SerializerFeature.PrettyFormat) && map.size() > 0) { + serializer.println(); + } + + if (!unwrapped) { + out.write('}'); + } + } + +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/MiscCodec.java b/src/main/java/com/alibaba/fastjson/serializer/MiscCodec.java new file mode 100755 index 0000000000..a17f0cee09 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/MiscCodec.java @@ -0,0 +1,384 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.net.UnknownHostException; +import java.nio.charset.Charset; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.regex.Pattern; + +import com.alibaba.fastjson.*; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.IOUtils; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class MiscCodec implements ObjectSerializer, ObjectDeserializer { + private static boolean FILE_RELATIVE_PATH_SUPPORT = false; + public final static MiscCodec instance = new MiscCodec(); + private static Method method_paths_get; + private static boolean method_paths_get_error = false; + + static { + FILE_RELATIVE_PATH_SUPPORT = "true".equals(IOUtils.getStringProperty("fastjson.deserializer.fileRelativePathSupport")); + } + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, + int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(); + return; + } + + Class objClass = object.getClass(); + + String strVal; + if (objClass == SimpleDateFormat.class) { + String pattern = ((SimpleDateFormat) object).toPattern(); + + if (out.isEnabled(SerializerFeature.WriteClassName)) { + if (object.getClass() != fieldType) { + out.write('{'); + out.writeFieldName(JSON.DEFAULT_TYPE_KEY); + serializer.write(object.getClass().getName()); + out.writeFieldValue(',', "val", pattern); + out.write('}'); + return; + } + } + + strVal = pattern; + } else if (objClass == Class.class) { + Class clazz = (Class) object; + strVal = clazz.getName(); + } else if (objClass == InetSocketAddress.class) { + InetSocketAddress address = (InetSocketAddress) object; + + InetAddress inetAddress = address.getAddress(); + + out.write('{'); + if (inetAddress != null) { + out.writeFieldName("address"); + serializer.write(inetAddress); + out.write(','); + } + out.writeFieldName("port"); + out.writeInt(address.getPort()); + out.write('}'); + return; + } else if (object instanceof File) { + strVal = ((File) object).getPath(); + } else if (object instanceof InetAddress) { + strVal = ((InetAddress) object).getHostAddress(); + } else if (object instanceof TimeZone) { + TimeZone timeZone = (TimeZone) object; + strVal = timeZone.getID(); + } else if (object instanceof Currency) { + Currency currency = (Currency) object; + strVal = currency.getCurrencyCode(); + } else if (object instanceof JSONStreamAware) { + JSONStreamAware aware = (JSONStreamAware) object; + aware.writeJSONString(out); + return; + } else if (object instanceof Iterator) { + Iterator it = ((Iterator) object); + writeIterator(serializer, out, it); + return; + } else if (object instanceof Iterable) { + Iterator it = ((Iterable) object).iterator(); + writeIterator(serializer, out, it); + return; + } else if (object instanceof Map.Entry) { + Map.Entry entry = (Map.Entry) object; + Object objKey = entry.getKey(); + Object objVal = entry.getValue(); + + if (objKey instanceof String) { + String key = (String) objKey; + + if (objVal instanceof String) { + String value = (String) objVal; + out.writeFieldValueStringWithDoubleQuoteCheck('{', key, value); + } else { + out.write('{'); + out.writeFieldName(key); + serializer.write(objVal); + } + } else { + out.write('{'); + serializer.write(objKey); + out.write(':'); + serializer.write(objVal); + } + out.write('}'); + return; + } else if (object.getClass().getName().equals("net.sf.json.JSONNull")) { + out.writeNull(); + return; + } else { + throw new JSONException("not support class : " + objClass); + } + + out.writeString(strVal); + } + + protected void writeIterator(JSONSerializer serializer, SerializeWriter out, Iterator it) { + int i = 0; + out.write('['); + while (it.hasNext()) { + if (i != 0) { + out.write(','); + } + Object item = it.next(); + serializer.write(item); + ++i; + } + out.write(']'); + return; + } + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + JSONLexer lexer = parser.lexer; + + if (clazz == InetSocketAddress.class) { + if (lexer.token() == JSONToken.NULL) { + lexer.nextToken(); + return null; + } + + parser.accept(JSONToken.LBRACE); + + InetAddress address = null; + int port = 0; + for (;;) { + String key = lexer.stringVal(); + lexer.nextToken(JSONToken.COLON); + + if (key.equals("address")) { + parser.accept(JSONToken.COLON); + address = parser.parseObject(InetAddress.class); + } else if (key.equals("port")) { + parser.accept(JSONToken.COLON); + if (lexer.token() != JSONToken.LITERAL_INT) { + throw new JSONException("port is not int"); + } + port = lexer.intValue(); + lexer.nextToken(); + } else { + parser.accept(JSONToken.COLON); + parser.parse(); + } + + if (lexer.token() == JSONToken.COMMA) { + lexer.nextToken(); + continue; + } + + break; + } + + parser.accept(JSONToken.RBRACE); + + return (T) new InetSocketAddress(address, port); + } + + Object objVal; + + if (parser.resolveStatus == DefaultJSONParser.TypeNameRedirect) { + parser.resolveStatus = DefaultJSONParser.NONE; + parser.accept(JSONToken.COMMA); + + if (lexer.token() == JSONToken.LITERAL_STRING) { + if (!"val".equals(lexer.stringVal())) { + throw new JSONException("syntax error"); + } + lexer.nextToken(); + } else { + throw new JSONException("syntax error"); + } + + parser.accept(JSONToken.COLON); + + objVal = parser.parse(); + + parser.accept(JSONToken.RBRACE); + } else { + objVal = parser.parse(); + } + + String strVal; + + if (objVal == null) { + strVal = null; + } else if (objVal instanceof String) { + strVal = (String) objVal; + } else { + if (objVal instanceof JSONObject) { + JSONObject jsonObject = (JSONObject) objVal; + + if (clazz == Currency.class) { + String currency = jsonObject.getString("currency"); + if (currency != null) { + return (T) Currency.getInstance(currency); + } + + String symbol = jsonObject.getString("currencyCode"); + if (symbol != null) { + return (T) Currency.getInstance(symbol); + } + } + + if (clazz == Map.Entry.class) { + return (T) jsonObject.entrySet().iterator().next(); + } + + return jsonObject.toJavaObject(clazz); + } + throw new JSONException("expect string"); + } + + if (strVal == null || strVal.length() == 0) { + return null; + } + + if (clazz == UUID.class) { + return (T) UUID.fromString(strVal); + } + + if (clazz == URI.class) { + return (T) URI.create(strVal); + } + + if (clazz == URL.class) { + try { + return (T) new URL(strVal); + } catch (MalformedURLException e) { + throw new JSONException("create url error", e); + } + } + + if (clazz == Pattern.class) { + return (T) Pattern.compile(strVal); + } + + if (clazz == Locale.class) { + return (T) TypeUtils.toLocale(strVal); + } + + if (clazz == SimpleDateFormat.class) { + SimpleDateFormat dateFormat = new SimpleDateFormat(strVal, lexer.getLocale()); + dateFormat.setTimeZone(lexer.getTimeZone()); + return (T) dateFormat; + } + + if (clazz == InetAddress.class || clazz == Inet4Address.class || clazz == Inet6Address.class) { + try { + return (T) InetAddress.getByName(strVal); + } catch (UnknownHostException e) { + throw new JSONException("deserialize inet adress error", e); + } + } + + if (clazz == File.class) { + if (strVal.indexOf("..") >= 0 && !FILE_RELATIVE_PATH_SUPPORT) { + throw new JSONException("file relative path not support."); + } + + return (T) new File(strVal); + } + + if (clazz == TimeZone.class) { + return (T) TimeZone.getTimeZone(strVal); + } + + if (clazz instanceof ParameterizedType) { + ParameterizedType parmeterizedType = (ParameterizedType) clazz; + clazz = parmeterizedType.getRawType(); + } + + if (clazz == Class.class) { + return (T) TypeUtils.loadClass(strVal, parser.getConfig().getDefaultClassLoader()); + } + + if (clazz == Charset.class) { + return (T) Charset.forName(strVal); + } + + if (clazz == Currency.class) { + return (T) Currency.getInstance(strVal); + } + + if (clazz == JSONPath.class) { + return (T) new JSONPath(strVal); + } + + + + if (clazz instanceof Class) { + String className = ((Class) clazz).getName(); + + if (className.equals("java.nio.file.Path")) { + try { + if (method_paths_get == null && !method_paths_get_error) { + Class paths = TypeUtils.loadClass("java.nio.file.Paths"); + method_paths_get = paths.getMethod("get", String.class, String[].class); + } + if (method_paths_get != null) { + return (T) method_paths_get.invoke(null, strVal, new String[0]); + } + + throw new JSONException("Path deserialize erorr"); + } catch (NoSuchMethodException ex) { + method_paths_get_error = true; + } catch (IllegalAccessException ex) { + throw new JSONException("Path deserialize erorr", ex); + } catch (InvocationTargetException ex) { + throw new JSONException("Path deserialize erorr", ex); + } + } + + throw new JSONException("MiscCodec not support " + className); + } + + throw new JSONException("MiscCodec not support " + clazz.toString()); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_STRING; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/NameFilter.java b/src/main/java/com/alibaba/fastjson/serializer/NameFilter.java old mode 100644 new mode 100755 index 810b876716..265e082794 --- a/src/main/java/com/alibaba/fastjson/serializer/NameFilter.java +++ b/src/main/java/com/alibaba/fastjson/serializer/NameFilter.java @@ -1,6 +1,20 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.fastjson.serializer; -public interface NameFilter { - - String process(Object source, String name, Object value); +public interface NameFilter extends SerializeFilter { + String process(Object object, String name, Object value); } diff --git a/src/main/java/com/alibaba/fastjson/serializer/NumberFieldSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/NumberFieldSerializer.java deleted file mode 100644 index 7abc97db9d..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/NumberFieldSerializer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import com.alibaba.fastjson.util.FieldInfo; - - -/** - * @author wenshao - */ -class NumberFieldSerializer extends FieldSerializer { - - public NumberFieldSerializer(FieldInfo fieldInfo){ - super(fieldInfo); - } - - @Override - public void writeProperty(JSONSerializer serializer, Object propertyValue) throws Exception { - SerializeWriter out = serializer.getWriter(); - - writePrefix(serializer); - - Object value = propertyValue; - - if (value == null) { - if (out.isEnabled(SerializerFeature.WriteNullNumberAsZero)) { - out.write('0'); - } else { - out.writeNull(); - } - return; - } - - out.append(value.toString()); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ObjectArrayCodec.java b/src/main/java/com/alibaba/fastjson/serializer/ObjectArrayCodec.java new file mode 100755 index 0000000000..f36da63730 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/ObjectArrayCodec.java @@ -0,0 +1,248 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Array; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.util.TypeUtils; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class ObjectArrayCodec implements ObjectSerializer, ObjectDeserializer { + + public static final ObjectArrayCodec instance = new ObjectArrayCodec(); + + public ObjectArrayCodec(){ + } + + public final void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) + throws IOException { + SerializeWriter out = serializer.out; + + Object[] array = (Object[]) object; + + if (object == null) { + out.writeNull(SerializerFeature.WriteNullListAsEmpty); + return; + } + + int size = array.length; + + int end = size - 1; + + if (end == -1) { + out.append("[]"); + return; + } + + SerialContext context = serializer.context; + serializer.setContext(context, object, fieldName, 0); + + try { + Class preClazz = null; + ObjectSerializer preWriter = null; + out.append('['); + + if (out.isEnabled(SerializerFeature.PrettyFormat)) { + serializer.incrementIndent(); + serializer.println(); + for (int i = 0; i < size; ++i) { + if (i != 0) { + out.write(','); + serializer.println(); + } + serializer.write(array[i]); + } + serializer.decrementIdent(); + serializer.println(); + out.write(']'); + return; + } + + for (int i = 0; i < end; ++i) { + Object item = array[i]; + + if (item == null) { + out.append("null,"); + } else { + if (serializer.containsReference(item)) { + serializer.writeReference(item); + } else { + Class clazz = item.getClass(); + + if (clazz == preClazz) { + preWriter.write(serializer, item, null, null, 0); + } else { + preClazz = clazz; + preWriter = serializer.getObjectWriter(clazz); + + preWriter.write(serializer, item, null, null, 0); + } + } + out.append(','); + } + } + + Object item = array[end]; + + if (item == null) { + out.append("null]"); + } else { + if (serializer.containsReference(item)) { + serializer.writeReference(item); + } else { + serializer.writeWithFieldName(item, end); + } + out.append(']'); + } + } finally { + serializer.context = context; + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + final JSONLexer lexer = parser.lexer; + int token = lexer.token(); + if (token == JSONToken.NULL) { + lexer.nextToken(JSONToken.COMMA); + return null; + } + + if (token == JSONToken.LITERAL_STRING || token == JSONToken.HEX) { + byte[] bytes = lexer.bytesValue(); + lexer.nextToken(JSONToken.COMMA); + + if (bytes.length == 0 && type != byte[].class) { + return null; + } + + return (T) bytes; + } + + Class componentClass; + Type componentType; + if (type instanceof GenericArrayType) { + GenericArrayType clazz = (GenericArrayType) type; + componentType = clazz.getGenericComponentType(); + if (componentType instanceof TypeVariable) { + TypeVariable typeVar = (TypeVariable) componentType; + Type objType = parser.getContext().type; + if (objType instanceof ParameterizedType) { + ParameterizedType objParamType = (ParameterizedType) objType; + Type objRawType = objParamType.getRawType(); + Type actualType = null; + if (objRawType instanceof Class) { + TypeVariable[] objTypeParams = ((Class) objRawType).getTypeParameters(); + for (int i = 0; i < objTypeParams.length; ++i) { + if (objTypeParams[i].getName().equals(typeVar.getName())) { + actualType = objParamType.getActualTypeArguments()[i]; + } + } + } + if (actualType instanceof Class) { + componentClass = (Class) actualType; + } else { + componentClass = Object.class; + } + } else { + componentClass = TypeUtils.getClass(typeVar.getBounds()[0]); + } + } else { + componentClass = TypeUtils.getClass(componentType); + } + } else { + Class clazz = (Class) type; + componentType = componentClass = clazz.getComponentType(); + } + JSONArray array = new JSONArray(); + parser.parseArray(componentType, array, fieldName); + + return (T) toObjectArray(parser, componentClass, array); + } + + @SuppressWarnings("unchecked") + private T toObjectArray(DefaultJSONParser parser, Class componentType, JSONArray array) { + if (array == null) { + return null; + } + + int size = array.size(); + + Object objArray = Array.newInstance(componentType, size); + for (int i = 0; i < size; ++i) { + Object value = array.get(i); + + if (value == array) { + Array.set(objArray, i, objArray); + continue; + } + + if (componentType.isArray()) { + Object element; + if (componentType.isInstance(value)) { + element = value; + } else { + element = toObjectArray(parser, componentType, (JSONArray) value); + } + + Array.set(objArray, i, element); + } else { + Object element = null; + if (value instanceof JSONArray) { + boolean contains = false; + JSONArray valueArray = (JSONArray) value; + int valueArraySize = valueArray.size(); + for (int y = 0; y < valueArraySize; ++y) { + Object valueItem = valueArray.get(y); + if (valueItem == array) { + valueArray.set(i, objArray); + contains = true; + } + } + if (contains) { + element = valueArray.toArray(); + } + } + + if (element == null) { + element = TypeUtils.cast(value, componentType, parser.getConfig()); + } + Array.set(objArray, i, element); + + } + } + + array.setRelatedArray(objArray); + array.setComponentType(componentType); + return (T) objArray; // TODO + } + + public int getFastMatchToken() { + return JSONToken.LBRACKET; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ObjectArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ObjectArraySerializer.java deleted file mode 100644 index 20ef7e4942..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/ObjectArraySerializer.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class ObjectArraySerializer implements ObjectSerializer { - - public static final ObjectArraySerializer instance = new ObjectArraySerializer(); - - public ObjectArraySerializer(){ - } - - public final void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - Object[] array = (Object[]) object; - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } - return; - } - - int size = array.length; - - int end = size - 1; - - if (end == -1) { - out.append("[]"); - return; - } - - Class preClazz = null; - ObjectSerializer preWriter = null; - out.append('['); - - if (out.isEnabled(SerializerFeature.PrettyFormat)) { - serializer.incrementIndent(); - serializer.println(); - for (int i = 0; i < size; ++i) { - if (i != 0) { - out.write(','); - serializer.println(); - } - serializer.write(array[i]); - } - serializer.decrementIdent(); - serializer.println(); - out.write(']'); - return; - } - - for (int i = 0; i < end; ++i) { - Object item = array[i]; - - if (item == null) { - out.append("null,"); - } else { - Class clazz = item.getClass(); - - if (clazz == preClazz) { - preWriter.write(serializer, item); - } else { - preClazz = clazz; - preWriter = serializer.getObjectWriter(clazz); - - preWriter.write(serializer, item); - } - - out.append(','); - } - } - - Object item = array[end]; - - if (item == null) { - out.append("null]"); - } else { - serializer.write(item); - out.append(']'); - } - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ObjectFieldSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ObjectFieldSerializer.java deleted file mode 100644 index 5609d4364b..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/ObjectFieldSerializer.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import com.alibaba.fastjson.annotation.JSONField; -import com.alibaba.fastjson.util.FieldInfo; - -/** - * @author wenshao - */ -public class ObjectFieldSerializer extends FieldSerializer { - - private ObjectSerializer fieldSerializer; - private Class runtimeFieldClass; - private String format; - - public ObjectFieldSerializer(FieldInfo fieldInfo) { - super(fieldInfo); - - JSONField annotation = fieldInfo.getAnnotation(JSONField.class); - - if (annotation != null) { - format = annotation.format(); - - if (format.trim().length() == 0) { - format = null; - } - } - } - - @Override - public void writeProperty(JSONSerializer serializer, Object propertyValue) - throws Exception { - writePrefix(serializer); - - if (format != null) { - serializer.writeWithFormat(propertyValue, format); - return; - } - - if (fieldSerializer == null) { - - if (propertyValue == null) { - runtimeFieldClass = this.getMethod().getReturnType(); - } else { - runtimeFieldClass = propertyValue.getClass(); - } - - fieldSerializer = serializer.getObjectWriter(runtimeFieldClass); - } - - if (propertyValue == null) { - fieldSerializer.write(serializer, null); - return; - } - - if (propertyValue.getClass() == runtimeFieldClass) { - fieldSerializer.write(serializer, propertyValue); - return; - } - - serializer.write(propertyValue); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ObjectNameSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ObjectNameSerializer.java deleted file mode 100644 index f85da2fa6d..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/ObjectNameSerializer.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -import javax.management.ObjectName; - -public class ObjectNameSerializer implements ObjectSerializer { - - public final static ObjectNameSerializer instance = new ObjectNameSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - serializer.write(((ObjectName) object).toString()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ObjectSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ObjectSerializer.java old mode 100644 new mode 100755 index 717051bee9..97af830a0a --- a/src/main/java/com/alibaba/fastjson/serializer/ObjectSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/ObjectSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,60 @@ package com.alibaba.fastjson.serializer; import java.io.IOException; +import java.lang.reflect.Type; /** - * @author wenshao + * Interface representing a custom serializer for fastjson. You should write a custom serializer, if + * you are not happy with the default serialization done by fastjson. You will also need to register + * this serializer through {@link com.alibaba.fastjson.serializer.SerializeConfig#put(Type, ObjectSerializer)}. + * + *
+ * public static class Result {
+ *     public ResultCode code;
+ * }
+ * 
+ * public static enum ResultCode {
+ *     LOGIN_FAILURE(8), INVALID_ARGUMENT(0), SIGN_ERROR(17);
+ *     public final int value;
+ *     ResultCode(int value){
+ *         this.value = value;
+ *     }
+ * }
+ * 
+ * public static class ResultCodeSerilaizer implements ObjectSerializer {
+ *     public void write(JSONSerializer serializer, 
+ *                       Object object, 
+ *                       Object fieldName, 
+ *                       Type fieldType,
+ *                       int features) throws IOException {
+ *         serializer.write(((ResultCode) object).value);
+ *     }
+ * }
+ * 
+ * SerializeConfig.getGlobalInstance().put(ResultCode.class, new ResultCodeSerilaizer());
+ * 
+ * Result result = new Result();
+ * result.code = ResultCode.SIGN_ERROR;
+ * String json = JSON.toJSONString(result, config); // {"code":17}
+ * Assert.assertEquals("{\"code\":17}", json);
+ * 
+ * @author wenshao[szujobs@hotmail.com] */ public interface ObjectSerializer { - - abstract void write(JSONSerializer serializer, Object object) throws IOException; + + /** + * fastjson invokes this call-back method during serialization when it encounters a field of the + * specified type. + * @param serializer + * @param object src the object that needs to be converted to Json. + * @param fieldName parent object field name + * @param fieldType parent object field type + * @param features parent object field serializer features + * @throws IOException + */ + void write(JSONSerializer serializer, // + Object object, // + Object fieldName, // + Type fieldType, // + int features) throws IOException; } diff --git a/src/main/java/com/alibaba/fastjson/serializer/PascalNameFilter.java b/src/main/java/com/alibaba/fastjson/serializer/PascalNameFilter.java new file mode 100755 index 0000000000..624f368bab --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/PascalNameFilter.java @@ -0,0 +1,16 @@ +package com.alibaba.fastjson.serializer; + +public class PascalNameFilter implements NameFilter { + + public String process(Object source, String name, Object value) { + if (name == null || name.length() == 0) { + return name; + } + + char[] chars = name.toCharArray(); + chars[0]= Character.toUpperCase(chars[0]); + + String pascalName = new String(chars); + return pascalName; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/PatternSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/PatternSerializer.java deleted file mode 100644 index db56805f57..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/PatternSerializer.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.regex.Pattern; - -/** - * @author wenshao - */ -public class PatternSerializer implements ObjectSerializer { - - public final static PatternSerializer instance = new PatternSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - if (object == null) { - serializer.writeNull(); - return; - } - - Pattern p = (Pattern) object; - serializer.write(p.pattern()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/PrimitiveArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/PrimitiveArraySerializer.java new file mode 100755 index 0000000000..9d08875e00 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/PrimitiveArraySerializer.java @@ -0,0 +1,136 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class PrimitiveArraySerializer implements ObjectSerializer { + + public static PrimitiveArraySerializer instance = new PrimitiveArraySerializer(); + + public final void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(SerializerFeature.WriteNullListAsEmpty); + return; + } + + if (object instanceof int[]) { + int[] array = (int[]) object; + out.write('['); + for (int i = 0; i < array.length; ++i) { + if (i != 0) { + out.write(','); + } + out.writeInt(array[i]); + } + out.write(']'); + return; + } + + if (object instanceof short[]) { + short[] array = (short[]) object; + out.write('['); + for (int i = 0; i < array.length; ++i) { + if (i != 0) { + out.write(','); + } + out.writeInt(array[i]); + } + out.write(']'); + return; + } + + if (object instanceof long[]) { + long[] array = (long[]) object; + + out.write('['); + for (int i = 0; i < array.length; ++i) { + if (i != 0) { + out.write(','); + } + out.writeLong(array[i]); + } + out.write(']'); + return; + } + + if (object instanceof boolean[]) { + boolean[] array = (boolean[]) object; + out.write('['); + for (int i = 0; i < array.length; ++i) { + if (i != 0) { + out.write(','); + } + out.write(array[i]); + } + out.write(']'); + return; + } + + if (object instanceof float[]) { + float[] array = (float[]) object; + out.write('['); + for (int i = 0; i < array.length; ++i) { + if (i != 0) { + out.write(','); + } + + float item = array[i]; + if (Float.isNaN(item)) { + out.writeNull(); + } else { + out.append(Float.toString(item)); + } + } + out.write(']'); + return; + } + + if (object instanceof double[]) { + double[] array = (double[]) object; + out.write('['); + for (int i = 0; i < array.length; ++i) { + if (i != 0) { + out.write(','); + } + + double item = array[i]; + if (Double.isNaN(item)) { + out.writeNull(); + } else { + out.append(Double.toString(item)); + } + } + out.write(']'); + return; + } + + if (object instanceof byte[]) { + byte[] array = (byte[]) object; + out.writeByteArray(array); + return; + } + + char[] chars = (char[]) object; + out.writeString(chars); + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/PropertyFilter.java b/src/main/java/com/alibaba/fastjson/serializer/PropertyFilter.java old mode 100644 new mode 100755 index 3298c5a216..d920fccf43 --- a/src/main/java/com/alibaba/fastjson/serializer/PropertyFilter.java +++ b/src/main/java/com/alibaba/fastjson/serializer/PropertyFilter.java @@ -1,30 +1,30 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -/** - * @author wenshao - */ -public interface PropertyFilter { - - /** - * @param source the owner of the property - * @param name the name of the property - * @param value the value of the property - * @return true if the property will be filtered out, false otherwise - */ - boolean apply(Object source, String name, Object value); -} +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public interface PropertyFilter extends SerializeFilter { + + /** + * @param object the owner of the property + * @param name the name of the property + * @param value the value of the property + * @return true if the property will be included, false if to be filtered out + */ + boolean apply(Object object, String name, Object value); +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/PropertyPreFilter.java b/src/main/java/com/alibaba/fastjson/serializer/PropertyPreFilter.java new file mode 100755 index 0000000000..c4019f8df3 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/PropertyPreFilter.java @@ -0,0 +1,21 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +public interface PropertyPreFilter extends SerializeFilter { + + boolean apply(JSONSerializer serializer, Object object, String name); +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ReferenceCodec.java b/src/main/java/com/alibaba/fastjson/serializer/ReferenceCodec.java new file mode 100644 index 0000000000..2e71967cb6 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/ReferenceCodec.java @@ -0,0 +1,75 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.ref.Reference; +import java.lang.ref.SoftReference; +import java.lang.ref.WeakReference; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.concurrent.atomic.AtomicReference; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class ReferenceCodec implements ObjectSerializer, ObjectDeserializer { + + public final static ReferenceCodec instance = new ReferenceCodec(); + + @SuppressWarnings("rawtypes") + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + Object item; + if (object instanceof AtomicReference) { + AtomicReference val = (AtomicReference) object; + item = val.get(); + } else { + item = ((Reference) object).get(); + } + serializer.write(item); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + ParameterizedType paramType = (ParameterizedType) type; + Type itemType = paramType.getActualTypeArguments()[0]; + + Object itemObject = parser.parseObject(itemType); + + Type rawType = paramType.getRawType(); + if (rawType == AtomicReference.class) { + return (T) new AtomicReference(itemObject); + } + + if (rawType == WeakReference.class) { + return (T) new WeakReference(itemObject); + } + + if (rawType == SoftReference.class) { + return (T) new SoftReference(itemObject); + } + + throw new UnsupportedOperationException(rawType.toString()); + } + + public int getFastMatchToken() { + return JSONToken.LBRACE; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/SerialContext.java b/src/main/java/com/alibaba/fastjson/serializer/SerialContext.java new file mode 100755 index 0000000000..b4ca48ad80 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/SerialContext.java @@ -0,0 +1,97 @@ +package com.alibaba.fastjson.serializer; + +public class SerialContext { + + public final SerialContext parent; + public final Object object; + public final Object fieldName; + public final int features; + + public SerialContext(SerialContext parent, Object object, Object fieldName, int features, int fieldFeatures){ + this.parent = parent; + this.object = object; + this.fieldName = fieldName; + this.features = features; + } + + public String toString() { + if (parent == null) { + return "$"; + } else { + StringBuilder buf = new StringBuilder(); + toString(buf); + return buf.toString(); + } + } + + protected void toString(StringBuilder buf) { + if (parent == null) { + buf.append('$'); + } else { + parent.toString(buf); + if (fieldName == null) { + buf.append(".null"); + } else if (fieldName instanceof Integer) { + buf.append('['); + buf.append(((Integer)fieldName).intValue()); + buf.append(']'); + } else { + buf.append('.'); + + String fieldName = this.fieldName.toString(); + boolean special = false; + for (int i = 0; i < fieldName.length(); ++i) { + char ch = fieldName.charAt(i); + if (ch == '.' || ch == '@' || ch == '(' || ch == '\\') { + special = true; + } + } + + if (special) { + for (int i = 0; i < fieldName.length(); ++i) { + char ch = fieldName.charAt(i); + if (ch == '.' || ch == '@' || ch == '(') { + buf.append('\\'); + buf.append('\\'); + } else if (ch == '\\') { + buf.append('\\'); + buf.append('\\'); + buf.append('\\'); + } + buf.append(ch); + } + } else { + buf.append(fieldName); + } + } + } + } + + /** + * @deprecated + */ + public SerialContext getParent() { + return parent; + } + + /** + * @deprecated + */ + public Object getObject() { + return object; + } + + /** + * @deprecated + */ + public Object getFieldName() { + return fieldName; + } + + /** + * @deprecated + */ + public String getPath() { + return toString(); + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/SerialWriterStringEncoder.java b/src/main/java/com/alibaba/fastjson/serializer/SerialWriterStringEncoder.java deleted file mode 100644 index a0ecdd5e25..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/SerialWriterStringEncoder.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.alibaba.fastjson.serializer; - -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CoderResult; -import java.nio.charset.CodingErrorAction; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.util.ThreadLocalCache; - -public class SerialWriterStringEncoder { - - private final CharsetEncoder encoder; - - public SerialWriterStringEncoder(Charset cs) { - this(cs.newEncoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE)); - } - - public SerialWriterStringEncoder(CharsetEncoder encoder) { - this.encoder = encoder; - } - - public byte[] encode(char[] chars, int off, int len) { - if (len == 0) { - return new byte[0]; - } - - encoder.reset(); - - int bytesLength = scale(len, encoder.maxBytesPerChar()); - - byte[] bytes = ThreadLocalCache.getBytes(bytesLength); - - return encode(chars, off, len, bytes); - } - - public CharsetEncoder getEncoder() { - return encoder; - } - - public byte[] encode(char[] chars, int off, int len, byte[] bytes) { - ByteBuffer byteBuf = ByteBuffer.wrap(bytes); - - CharBuffer charBuf = CharBuffer.wrap(chars, off, len); - try { - CoderResult cr = encoder.encode(charBuf, byteBuf, true); - if (!cr.isUnderflow()) { - cr.throwException(); - } - cr = encoder.flush(byteBuf); - if (!cr.isUnderflow()) { - cr.throwException(); - } - } catch (CharacterCodingException x) { - // Substitution is always enabled, - // so this shouldn't happen - throw new JSONException(x.getMessage(), x); - } - - int bytesLength = byteBuf.position(); - byte[] copy = new byte[bytesLength]; - System.arraycopy(bytes, 0, copy, 0, bytesLength); - return copy; - } - - private static int scale(int len, float expansionFactor) { - // We need to perform double, not float, arithmetic; otherwise - // we lose low order bits when len is larger than 2**24. - return (int) (len * (double) expansionFactor); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/SerializeBeanInfo.java b/src/main/java/com/alibaba/fastjson/serializer/SerializeBeanInfo.java new file mode 100644 index 0000000000..e5efc3e4a8 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/SerializeBeanInfo.java @@ -0,0 +1,35 @@ +package com.alibaba.fastjson.serializer; + +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.util.FieldInfo; + +public class SerializeBeanInfo { + + protected final Class beanType; + protected final String typeName; + protected final String typeKey; + protected final JSONType jsonType; + + protected final FieldInfo[] fields; + protected final FieldInfo[] sortedFields; + + protected int features; + + public SerializeBeanInfo(Class beanType, // + JSONType jsonType, // + String typeName, // + String typeKey, + int features, + FieldInfo[] fields, // + FieldInfo[] sortedFields + ){ + this.beanType = beanType; + this.jsonType = jsonType; + this.typeName = typeName; + this.typeKey = typeKey; + this.features = features; + this.fields = fields; + this.sortedFields = sortedFields; + } + +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/SerializeConfig.java b/src/main/java/com/alibaba/fastjson/serializer/SerializeConfig.java index 024fded50d..1747c28849 100644 --- a/src/main/java/com/alibaba/fastjson/serializer/SerializeConfig.java +++ b/src/main/java/com/alibaba/fastjson/serializer/SerializeConfig.java @@ -1,148 +1,742 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.File; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.URI; -import java.net.URL; -import java.nio.charset.Charset; -import java.util.Locale; -import java.util.TimeZone; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicIntegerArray; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicLongArray; -import java.util.concurrent.atomic.AtomicReference; -import java.util.regex.Pattern; - -import javax.management.ObjectName; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.util.IdentityHashMap; - -/** - * circular references detect - * - * @author wenshao - */ -public class SerializeConfig extends IdentityHashMap { - - private final static SerializeConfig globalInstance = new SerializeConfig(); - - private boolean asm = true; - - private final ASMSerializerFactory asmFactory = new ASMSerializerFactory(); - - public final ObjectSerializer createASMSerializer(Class clazz) throws Exception { - return asmFactory.createJavaBeanSerializer(clazz); - } - - public ObjectSerializer createJavaBeanSerializer(Class clazz) { - if (!Modifier.isPublic(clazz.getModifiers())) { - return new JavaBeanSerializer(clazz); - } - - if (asm) { - try { - return createASMSerializer(clazz); - } catch (Throwable e) { - throw new JSONException("create asm serilizer error, class " + clazz, e); - } - } - - return new JavaBeanSerializer(clazz); - } - - public boolean isAsmEnable() { - return asm; - } - - public void setAsmEnable(boolean asmEnable) { - this.asm = asmEnable; - } - - public final static SerializeConfig getGlobalInstance() { - return globalInstance; - } - - public SerializeConfig(){ - this(DEFAULT_TABLE_SIZE); - } - - public SerializeConfig(int tableSize){ - super(tableSize); - - put(Boolean.class, BooleanSerializer.instance); - put(Character.class, CharacterSerializer.instance); - put(Byte.class, IntegerSerializer.instance); - put(Short.class, IntegerSerializer.instance); - put(Integer.class, IntegerSerializer.instance); - put(Long.class, LongSerializer.instance); - put(Float.class, FloatSerializer.instance); - put(Double.class, DoubleSerializer.instance); - put(BigDecimal.class, BigDecimalSerializer.instance); - put(BigInteger.class, BigIntegerSerializer.instance); - put(String.class, StringSerializer.instance); - put(byte[].class, ByteArraySerializer.instance); - put(short[].class, ShortArraySerializer.instance); - put(int[].class, IntArraySerializer.instance); - put(long[].class, LongArraySerializer.instance); - put(float[].class, FloatArraySerializer.instance); - put(double[].class, DoubleArraySerializer.instance); - put(boolean[].class, BooleanArraySerializer.instance); - put(Object[].class, ObjectArraySerializer.instance); - put(Class.class, ClassSerializer.instance); - - put(Locale.class, LocaleSerializer.instance); - put(TimeZone.class, TimeZoneSerializer.instance); - put(UUID.class, UUIDSerializer.instance); - put(InetAddress.class, InetAddressSerializer.instance); - put(Inet4Address.class, InetAddressSerializer.instance); - put(Inet6Address.class, InetAddressSerializer.instance); - put(InetSocketAddress.class, InetSocketAddressSerializer.instance); - put(File.class, FileSerializer.instance); - put(URI.class, URISerializer.instance); - put(URL.class, URLSerializer.instance); - put(Appendable.class, AppendableSerializer.instance); - put(StringBuffer.class, AppendableSerializer.instance); - put(StringBuilder.class, AppendableSerializer.instance); - put(Pattern.class, PatternSerializer.instance); - put(Charset.class, CharsetSerializer.instance); - - // atomic - put(AtomicBoolean.class, AtomicBooleanSerializer.instance); - put(AtomicInteger.class, AtomicIntegerSerializer.instance); - put(AtomicLong.class, AtomicLongSerializer.instance); - put(AtomicReference.class, AtomicReferenceSerializer.instance); - put(AtomicIntegerArray.class, AtomicIntegerArraySerializer.instance); - put(AtomicLongArray.class, AtomicLongArraySerializer.instance); - - // jmx - put(ObjectName.class, ObjectNameSerializer.instance); - - } - -} +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import com.alibaba.fastjson.*; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.deserializer.Jdk8DateCodec; +import com.alibaba.fastjson.parser.deserializer.OptionalCodec; +import com.alibaba.fastjson.support.springfox.SwaggerJsonSerializer; +import com.alibaba.fastjson.util.*; +import com.alibaba.fastjson.util.IdentityHashMap; +import com.alibaba.fastjson.util.ServiceLoader; + +import javax.xml.datatype.XMLGregorianCalendar; +import java.io.File; +import java.io.Serializable; +import java.lang.ref.SoftReference; +import java.lang.ref.WeakReference; +import java.lang.reflect.*; +import java.lang.reflect.Proxy; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.*; +import java.nio.charset.Charset; +import java.sql.Clob; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.atomic.*; +import java.util.regex.Pattern; + +/** + * circular references detect + * + * @author wenshao[szujobs@hotmail.com] + */ +public class SerializeConfig { + + public final static SerializeConfig globalInstance = new SerializeConfig(); + + private static boolean awtError = false; + private static boolean jdk8Error = false; + private static boolean oracleJdbcError = false; + private static boolean springfoxError = false; + private static boolean guavaError = false; + private static boolean jsonnullError = false; + + private boolean asm = !ASMUtils.IS_ANDROID; + private ASMSerializerFactory asmFactory; + protected String typeKey = JSON.DEFAULT_TYPE_KEY; + public PropertyNamingStrategy propertyNamingStrategy; + + private final IdentityHashMap serializers; + + private final boolean fieldBased; + + public String getTypeKey() { + return typeKey; + } + + public void setTypeKey(String typeKey) { + this.typeKey = typeKey; + } + + private final JavaBeanSerializer createASMSerializer(SerializeBeanInfo beanInfo) throws Exception { + JavaBeanSerializer serializer = asmFactory.createJavaBeanSerializer(beanInfo); + + for (int i = 0; i < serializer.sortedGetters.length; ++i) { + FieldSerializer fieldDeser = serializer.sortedGetters[i]; + Class fieldClass = fieldDeser.fieldInfo.fieldClass; + if (fieldClass.isEnum()) { + ObjectSerializer fieldSer = this.getObjectWriter(fieldClass); + if (!(fieldSer instanceof EnumSerializer)) { + serializer.writeDirect = false; + } + } + } + + return serializer; + } + + public final ObjectSerializer createJavaBeanSerializer(Class clazz) { + SerializeBeanInfo beanInfo = TypeUtils.buildBeanInfo(clazz, null, propertyNamingStrategy, fieldBased); + if (beanInfo.fields.length == 0 && Iterable.class.isAssignableFrom(clazz)) { + return MiscCodec.instance; + } + + return createJavaBeanSerializer(beanInfo); + } + + public ObjectSerializer createJavaBeanSerializer(SerializeBeanInfo beanInfo) { + JSONType jsonType = beanInfo.jsonType; + + boolean asm = this.asm && !fieldBased; + + if (jsonType != null) { + Class serializerClass = jsonType.serializer(); + if (serializerClass != Void.class) { + try { + Object seralizer = serializerClass.newInstance(); + if (seralizer instanceof ObjectSerializer) { + return (ObjectSerializer) seralizer; + } + } catch (Throwable e) { + // skip + } + } + + if (jsonType.asm() == false) { + asm = false; + } + + for (SerializerFeature feature : jsonType.serialzeFeatures()) { + if (SerializerFeature.WriteNonStringValueAsString == feature // + || SerializerFeature.WriteEnumUsingToString == feature // + || SerializerFeature.NotWriteDefaultValue == feature + || SerializerFeature.BrowserCompatible == feature) { + asm = false; + break; + } + } + } + + Class clazz = beanInfo.beanType; + if (!Modifier.isPublic(beanInfo.beanType.getModifiers())) { + return new JavaBeanSerializer(beanInfo); + } + + + + if (asm && asmFactory.classLoader.isExternalClass(clazz) + || clazz == Serializable.class || clazz == Object.class) { + asm = false; + } + + if (asm && !ASMUtils.checkName(clazz.getSimpleName())) { + asm = false; + } + + if (asm && beanInfo.beanType.isInterface()) { + asm = false; + } + + if (asm) { + for(FieldInfo fieldInfo : beanInfo.fields){ + Field field = fieldInfo.field; + if (field != null && !field.getType().equals(fieldInfo.fieldClass)) { + asm = false; + break; + } + + Method method = fieldInfo.method; + if (method != null && !method.getReturnType().equals(fieldInfo.fieldClass)) { + asm = false; + break; + } + + JSONField annotation = fieldInfo.getAnnotation(); + + if (annotation == null) { + continue; + } + + String format = annotation.format(); + if (format.length() != 0) { + if (fieldInfo.fieldClass == String.class && "trim".equals(format)) { + + } else { + asm = false; + break; + } + } + + if ((!ASMUtils.checkName(annotation.name())) // + || annotation.jsonDirect() + || annotation.serializeUsing() != Void.class + || annotation.unwrapped() + ) { + asm = false; + break; + } + + for (SerializerFeature feature : annotation.serialzeFeatures()) { + if (SerializerFeature.WriteNonStringValueAsString == feature // + || SerializerFeature.WriteEnumUsingToString == feature // + || SerializerFeature.NotWriteDefaultValue == feature + || SerializerFeature.BrowserCompatible == feature + || SerializerFeature.WriteClassName == feature) { + asm = false; + break; + } + } + + if (TypeUtils.isAnnotationPresentOneToMany(method) || TypeUtils.isAnnotationPresentManyToMany(method)) { + asm = true; + break; + } + } + } + + if (asm) { + try { + ObjectSerializer asmSerializer = createASMSerializer(beanInfo); + if (asmSerializer != null) { + return asmSerializer; + } + } catch (ClassNotFoundException ex) { + // skip + } catch (ClassFormatError e) { + // skip + } catch (ClassCastException e) { + // skip + } catch (Throwable e) { + throw new JSONException("create asm serializer error, class " + + clazz, e); + } + } + + return new JavaBeanSerializer(beanInfo); + } + + public boolean isAsmEnable() { + return asm; + } + + public void setAsmEnable(boolean asmEnable) { + if (ASMUtils.IS_ANDROID) { + return; + } + this.asm = asmEnable; + } + + public static SerializeConfig getGlobalInstance() { + return globalInstance; + } + + public SerializeConfig() { + this(IdentityHashMap.DEFAULT_SIZE); + } + + public SerializeConfig(boolean fieldBase) { + this(IdentityHashMap.DEFAULT_SIZE, fieldBase); + } + + public SerializeConfig(int tableSize) { + this(tableSize, false); + } + + public SerializeConfig(int tableSize, boolean fieldBase) { + this.fieldBased = fieldBase; + serializers = new IdentityHashMap(tableSize); + + try { + if (asm) { + asmFactory = new ASMSerializerFactory(); + } + } catch (Throwable eror) { + asm = false; + } + + initSerializers(); + } + + private void initSerializers() { + put(Boolean.class, BooleanCodec.instance); + put(Character.class, CharacterCodec.instance); + put(Byte.class, IntegerCodec.instance); + put(Short.class, IntegerCodec.instance); + put(Integer.class, IntegerCodec.instance); + put(Long.class, LongCodec.instance); + put(Float.class, FloatCodec.instance); + put(Double.class, DoubleSerializer.instance); + put(BigDecimal.class, BigDecimalCodec.instance); + put(BigInteger.class, BigIntegerCodec.instance); + put(String.class, StringCodec.instance); + put(byte[].class, PrimitiveArraySerializer.instance); + put(short[].class, PrimitiveArraySerializer.instance); + put(int[].class, PrimitiveArraySerializer.instance); + put(long[].class, PrimitiveArraySerializer.instance); + put(float[].class, PrimitiveArraySerializer.instance); + put(double[].class, PrimitiveArraySerializer.instance); + put(boolean[].class, PrimitiveArraySerializer.instance); + put(char[].class, PrimitiveArraySerializer.instance); + put(Object[].class, ObjectArrayCodec.instance); + put(Class.class, MiscCodec.instance); + + put(SimpleDateFormat.class, MiscCodec.instance); + put(Currency.class, new MiscCodec()); + put(TimeZone.class, MiscCodec.instance); + put(InetAddress.class, MiscCodec.instance); + put(Inet4Address.class, MiscCodec.instance); + put(Inet6Address.class, MiscCodec.instance); + put(InetSocketAddress.class, MiscCodec.instance); + put(File.class, MiscCodec.instance); + put(Appendable.class, AppendableSerializer.instance); + put(StringBuffer.class, AppendableSerializer.instance); + put(StringBuilder.class, AppendableSerializer.instance); + put(Charset.class, ToStringSerializer.instance); + put(Pattern.class, ToStringSerializer.instance); + put(Locale.class, ToStringSerializer.instance); + put(URI.class, ToStringSerializer.instance); + put(URL.class, ToStringSerializer.instance); + put(UUID.class, ToStringSerializer.instance); + + // atomic + put(AtomicBoolean.class, AtomicCodec.instance); + put(AtomicInteger.class, AtomicCodec.instance); + put(AtomicLong.class, AtomicCodec.instance); + put(AtomicReference.class, ReferenceCodec.instance); + put(AtomicIntegerArray.class, AtomicCodec.instance); + put(AtomicLongArray.class, AtomicCodec.instance); + + put(WeakReference.class, ReferenceCodec.instance); + put(SoftReference.class, ReferenceCodec.instance); + + put(LinkedList.class, CollectionCodec.instance); + } + + /** + * add class level serialize filter + * @since 1.2.10 + */ + public void addFilter(Class clazz, SerializeFilter filter) { + ObjectSerializer serializer = getObjectWriter(clazz); + + if (serializer instanceof SerializeFilterable) { + SerializeFilterable filterable = (SerializeFilterable) serializer; + + if (this != SerializeConfig.globalInstance) { + if (filterable == MapSerializer.instance) { + MapSerializer newMapSer = new MapSerializer(); + this.put(clazz, newMapSer); + newMapSer.addFilter(filter); + return; + } + } + + filterable.addFilter(filter); + } + } + + /** class level serializer feature config + * @since 1.2.12 + */ + public void config(Class clazz, SerializerFeature feature, boolean value) { + ObjectSerializer serializer = getObjectWriter(clazz, false); + + if (serializer == null) { + SerializeBeanInfo beanInfo = TypeUtils.buildBeanInfo(clazz, null, propertyNamingStrategy); + + if (value) { + beanInfo.features |= feature.mask; + } else { + beanInfo.features &= ~feature.mask; + } + + serializer = this.createJavaBeanSerializer(beanInfo); + + put(clazz, serializer); + return; + } + + if (serializer instanceof JavaBeanSerializer) { + JavaBeanSerializer javaBeanSerializer = (JavaBeanSerializer) serializer; + SerializeBeanInfo beanInfo = javaBeanSerializer.beanInfo; + + int originalFeaturs = beanInfo.features; + if (value) { + beanInfo.features |= feature.mask; + } else { + beanInfo.features &= ~feature.mask; + } + + if (originalFeaturs == beanInfo.features) { + return; + } + + Class serializerClass = serializer.getClass(); + if (serializerClass != JavaBeanSerializer.class) { + ObjectSerializer newSerializer = this.createJavaBeanSerializer(beanInfo); + this.put(clazz, newSerializer); + } + } + } + + public ObjectSerializer getObjectWriter(Class clazz) { + return getObjectWriter(clazz, true); + } + + private ObjectSerializer getObjectWriter(Class clazz, boolean create) { + ObjectSerializer writer = serializers.get(clazz); + + if (writer == null) { + try { + final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + for (Object o : ServiceLoader.load(AutowiredObjectSerializer.class, classLoader)) { + if (!(o instanceof AutowiredObjectSerializer)) { + continue; + } + + AutowiredObjectSerializer autowired = (AutowiredObjectSerializer) o; + for (Type forType : autowired.getAutowiredFor()) { + put(forType, autowired); + } + } + } catch (ClassCastException ex) { + // skip + } + + writer = serializers.get(clazz); + } + + if (writer == null) { + final ClassLoader classLoader = JSON.class.getClassLoader(); + if (classLoader != Thread.currentThread().getContextClassLoader()) { + try { + for (Object o : ServiceLoader.load(AutowiredObjectSerializer.class, classLoader)) { + + if (!(o instanceof AutowiredObjectSerializer)) { + continue; + } + + AutowiredObjectSerializer autowired = (AutowiredObjectSerializer) o; + for (Type forType : autowired.getAutowiredFor()) { + put(forType, autowired); + } + } + } catch (ClassCastException ex) { + // skip + } + + writer = serializers.get(clazz); + } + } + + if (writer == null) { + String className = clazz.getName(); + Class superClass; + + if (Map.class.isAssignableFrom(clazz)) { + put(clazz, writer = MapSerializer.instance); + } else if (List.class.isAssignableFrom(clazz)) { + put(clazz, writer = ListSerializer.instance); + } else if (Collection.class.isAssignableFrom(clazz)) { + put(clazz, writer = CollectionCodec.instance); + } else if (Date.class.isAssignableFrom(clazz)) { + put(clazz, writer = DateCodec.instance); + } else if (JSONAware.class.isAssignableFrom(clazz)) { + put(clazz, writer = JSONAwareSerializer.instance); + } else if (JSONSerializable.class.isAssignableFrom(clazz)) { + put(clazz, writer = JSONSerializableSerializer.instance); + } else if (JSONStreamAware.class.isAssignableFrom(clazz)) { + put(clazz, writer = MiscCodec.instance); + } else if (clazz.isEnum()) { + JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class); + if (jsonType != null && jsonType.serializeEnumAsJavaBean()) { + put(clazz, writer = createJavaBeanSerializer(clazz)); + } else { + put(clazz, writer = EnumSerializer.instance); + } + } else if ((superClass = clazz.getSuperclass()) != null && superClass.isEnum()) { + JSONType jsonType = TypeUtils.getAnnotation(superClass, JSONType.class); + if (jsonType != null && jsonType.serializeEnumAsJavaBean()) { + put(clazz, writer = createJavaBeanSerializer(clazz)); + } else { + put(clazz, writer = EnumSerializer.instance); + } + } else if (clazz.isArray()) { + Class componentType = clazz.getComponentType(); + ObjectSerializer compObjectSerializer = getObjectWriter(componentType); + put(clazz, writer = new ArraySerializer(componentType, compObjectSerializer)); + } else if (Throwable.class.isAssignableFrom(clazz)) { + SerializeBeanInfo beanInfo = TypeUtils.buildBeanInfo(clazz, null, propertyNamingStrategy); + beanInfo.features |= SerializerFeature.WriteClassName.mask; + put(clazz, writer = new JavaBeanSerializer(beanInfo)); + } else if (TimeZone.class.isAssignableFrom(clazz) || Map.Entry.class.isAssignableFrom(clazz)) { + put(clazz, writer = MiscCodec.instance); + } else if (Appendable.class.isAssignableFrom(clazz)) { + put(clazz, writer = AppendableSerializer.instance); + } else if (Charset.class.isAssignableFrom(clazz)) { + put(clazz, writer = ToStringSerializer.instance); + } else if (Enumeration.class.isAssignableFrom(clazz)) { + put(clazz, writer = EnumerationSerializer.instance); + } else if (Calendar.class.isAssignableFrom(clazz) // + || XMLGregorianCalendar.class.isAssignableFrom(clazz)) { + put(clazz, writer = CalendarCodec.instance); + } else if (Clob.class.isAssignableFrom(clazz)) { + put(clazz, writer = ClobSeriliazer.instance); + } else if (TypeUtils.isPath(clazz)) { + put(clazz, writer = ToStringSerializer.instance); + } else if (Iterator.class.isAssignableFrom(clazz)) { + put(clazz, writer = MiscCodec.instance); + } else { + if (className.startsWith("java.awt.") // + && AwtCodec.support(clazz) // + ) { + // awt + if (!awtError) { + try { + String[] names = new String[]{ + "java.awt.Color", + "java.awt.Font", + "java.awt.Point", + "java.awt.Rectangle" + }; + for (String name : names) { + if (name.equals(className)) { + put(Class.forName(name), writer = AwtCodec.instance); + return writer; + } + } + } catch (Throwable e) { + awtError = true; + // skip + } + } + } + + // jdk8 + if ((!jdk8Error) // + && (className.startsWith("java.time.") // + || className.startsWith("java.util.Optional") // + || className.equals("java.util.concurrent.atomic.LongAdder") + || className.equals("java.util.concurrent.atomic.DoubleAdder") + )) { + try { + { + String[] names = new String[]{ + "java.time.LocalDateTime", + "java.time.LocalDate", + "java.time.LocalTime", + "java.time.ZonedDateTime", + "java.time.OffsetDateTime", + "java.time.OffsetTime", + "java.time.ZoneOffset", + "java.time.ZoneRegion", + "java.time.Period", + "java.time.Duration", + "java.time.Instant" + }; + for (String name : names) { + if (name.equals(className)) { + put(Class.forName(name), writer = Jdk8DateCodec.instance); + return writer; + } + } + } + { + String[] names = new String[]{ + "java.util.Optional", + "java.util.OptionalDouble", + "java.util.OptionalInt", + "java.util.OptionalLong" + }; + for (String name : names) { + if (name.equals(className)) { + put(Class.forName(name), writer = OptionalCodec.instance); + return writer; + } + } + } + { + String[] names = new String[]{ + "java.util.concurrent.atomic.LongAdder", + "java.util.concurrent.atomic.DoubleAdder" + }; + for (String name : names) { + if (name.equals(className)) { + put(Class.forName(name), writer = AdderSerializer.instance); + return writer; + } + } + } + } catch (Throwable e) { + // skip + jdk8Error = true; + } + } + + if ((!oracleJdbcError) // + && className.startsWith("oracle.sql.")) { + try { + String[] names = new String[] { + "oracle.sql.DATE", + "oracle.sql.TIMESTAMP" + }; + + for (String name : names) { + if (name.equals(className)) { + put(Class.forName(name), writer = DateCodec.instance); + return writer; + } + } + } catch (Throwable e) { + // skip + oracleJdbcError = true; + } + } + + if ((!springfoxError) // + && className.equals("springfox.documentation.spring.web.json.Json")) { + try { + put(Class.forName("springfox.documentation.spring.web.json.Json"), // + writer = SwaggerJsonSerializer.instance); + return writer; + } catch (ClassNotFoundException e) { + // skip + springfoxError = true; + } + } + + if ((!guavaError) // + && className.startsWith("com.google.common.collect.")) { + try { + String[] names = new String[] { + "com.google.common.collect.HashMultimap", + "com.google.common.collect.LinkedListMultimap", + "com.google.common.collect.ArrayListMultimap", + "com.google.common.collect.TreeMultimap" + }; + + for (String name : names) { + if (name.equals(className)) { + put(Class.forName(name), writer = GuavaCodec.instance); + return writer; + } + } + } catch (ClassNotFoundException e) { + // skip + guavaError = true; + } + } + + if ((!jsonnullError) && className.equals("net.sf.json.JSONNull")) { + try { + put(Class.forName("net.sf.json.JSONNull"), writer = MiscCodec.instance); + return writer; + } catch (ClassNotFoundException e) { + // skip + jsonnullError = true; + } + } + + Class[] interfaces = clazz.getInterfaces(); + if (interfaces.length == 1 && interfaces[0].isAnnotation()) { + return AnnotationSerializer.instance; + } + + if (TypeUtils.isProxy(clazz)) { + Class superClazz = clazz.getSuperclass(); + + ObjectSerializer superWriter = getObjectWriter(superClazz); + put(clazz, superWriter); + return superWriter; + } + + if (Proxy.isProxyClass(clazz)) { + Class handlerClass = null; + + if (interfaces.length == 2) { + handlerClass = interfaces[1]; + } else { + for (Class proxiedInterface : interfaces) { + if (proxiedInterface.getName().startsWith("org.springframework.aop.")) { + continue; + } + if (handlerClass != null) { + handlerClass = null; // multi-matched + break; + } + handlerClass = proxiedInterface; + } + } + + if (handlerClass != null) { + ObjectSerializer superWriter = getObjectWriter(handlerClass); + put(clazz, superWriter); + return superWriter; + } + } + + if (create) { + writer = createJavaBeanSerializer(clazz); + put(clazz, writer); + } + } + + if (writer == null) { + writer = serializers.get(clazz); + } + } + return writer; + } + + public final ObjectSerializer get(Type key) { + return this.serializers.get(key); + } + + public boolean put(Object type, Object value) { + return put((Type)type, (ObjectSerializer)value); + } + + public boolean put(Type type, ObjectSerializer value) { + return this.serializers.put(type, value); + } + + /** + * 1.2.24 + * @param enumClasses + */ + public void configEnumAsJavaBean(Class... enumClasses) { + for (Class enumClass : enumClasses) { + put(enumClass, createJavaBeanSerializer(enumClass)); + } + } + + /** + * for spring config support + * @param propertyNamingStrategy + */ + public void setPropertyNamingStrategy(PropertyNamingStrategy propertyNamingStrategy) { + this.propertyNamingStrategy = propertyNamingStrategy; + } + + public void clearSerializers() { + this.serializers.clear(); + this.initSerializers(); + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/SerializeFilter.java b/src/main/java/com/alibaba/fastjson/serializer/SerializeFilter.java new file mode 100755 index 0000000000..73dc2cbe86 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/SerializeFilter.java @@ -0,0 +1,6 @@ +package com.alibaba.fastjson.serializer; + + +public interface SerializeFilter { + +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/SerializeFilterable.java b/src/main/java/com/alibaba/fastjson/serializer/SerializeFilterable.java new file mode 100644 index 0000000000..efe60a5aee --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/SerializeFilterable.java @@ -0,0 +1,263 @@ +package com.alibaba.fastjson.serializer; + +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.JSON; + +public abstract class SerializeFilterable { + + protected List beforeFilters = null; + protected List afterFilters = null; + protected List propertyFilters = null; + protected List valueFilters = null; + protected List nameFilters = null; + protected List propertyPreFilters = null; + protected List labelFilters = null; + protected List contextValueFilters = null; + + protected boolean writeDirect = true; + + public List getBeforeFilters() { + if (beforeFilters == null) { + beforeFilters = new ArrayList(); + writeDirect = false; + } + + return beforeFilters; + } + + public List getAfterFilters() { + if (afterFilters == null) { + afterFilters = new ArrayList(); + writeDirect = false; + } + + return afterFilters; + } + + public List getNameFilters() { + if (nameFilters == null) { + nameFilters = new ArrayList(); + writeDirect = false; + } + + return nameFilters; + } + + public List getPropertyPreFilters() { + if (propertyPreFilters == null) { + propertyPreFilters = new ArrayList(); + writeDirect = false; + } + + return propertyPreFilters; + } + + public List getLabelFilters() { + if (labelFilters == null) { + labelFilters = new ArrayList(); + writeDirect = false; + } + + return labelFilters; + } + + public List getPropertyFilters() { + if (propertyFilters == null) { + propertyFilters = new ArrayList(); + writeDirect = false; + } + + return propertyFilters; + } + + public List getContextValueFilters() { + if (contextValueFilters == null) { + contextValueFilters = new ArrayList(); + writeDirect = false; + } + + return contextValueFilters; + } + + public List getValueFilters() { + if (valueFilters == null) { + valueFilters = new ArrayList(); + writeDirect = false; + } + + return valueFilters; + } + + public void addFilter(SerializeFilter filter) { + if (filter == null) { + return; + } + + if (filter instanceof PropertyPreFilter) { + this.getPropertyPreFilters().add((PropertyPreFilter) filter); + } + + if (filter instanceof NameFilter) { + this.getNameFilters().add((NameFilter) filter); + } + + if (filter instanceof ValueFilter) { + this.getValueFilters().add((ValueFilter) filter); + } + + if (filter instanceof ContextValueFilter) { + this.getContextValueFilters().add((ContextValueFilter) filter); + } + + if (filter instanceof PropertyFilter) { + this.getPropertyFilters().add((PropertyFilter) filter); + } + + if (filter instanceof BeforeFilter) { + this.getBeforeFilters().add((BeforeFilter) filter); + } + + if (filter instanceof AfterFilter) { + this.getAfterFilters().add((AfterFilter) filter); + } + + if (filter instanceof LabelFilter) { + this.getLabelFilters().add((LabelFilter) filter); + } + } + + public boolean applyName(JSONSerializer jsonBeanDeser, // + Object object, String key) { + + if (jsonBeanDeser.propertyPreFilters != null) { + for (PropertyPreFilter filter : jsonBeanDeser.propertyPreFilters) { + if (!filter.apply(jsonBeanDeser, object, key)) { + return false; + } + } + } + + if (this.propertyPreFilters != null) { + for (PropertyPreFilter filter : this.propertyPreFilters) { + if (!filter.apply(jsonBeanDeser, object, key)) { + return false; + } + } + } + + return true; + } + + public boolean apply(JSONSerializer jsonBeanDeser, // + Object object, // + String key, Object propertyValue) { + + if (jsonBeanDeser.propertyFilters != null) { + for (PropertyFilter propertyFilter : jsonBeanDeser.propertyFilters) { + if (!propertyFilter.apply(object, key, propertyValue)) { + return false; + } + } + } + + if (this.propertyFilters != null) { + for (PropertyFilter propertyFilter : this.propertyFilters) { + if (!propertyFilter.apply(object, key, propertyValue)) { + return false; + } + } + } + + return true; + } + + protected String processKey(JSONSerializer jsonBeanDeser, // + Object object, // + String key, // + Object propertyValue) { + + if (jsonBeanDeser.nameFilters != null) { + for (NameFilter nameFilter : jsonBeanDeser.nameFilters) { + key = nameFilter.process(object, key, propertyValue); + } + } + + if (this.nameFilters != null) { + for (NameFilter nameFilter : this.nameFilters) { + key = nameFilter.process(object, key, propertyValue); + } + } + + return key; + } + + protected Object processValue(JSONSerializer jsonBeanDeser, // + BeanContext beanContext, + Object object, // + String key, // + Object propertyValue) { + + if (propertyValue != null) { + if ((jsonBeanDeser.out.writeNonStringValueAsString // + || (beanContext != null && (beanContext.getFeatures() & SerializerFeature.WriteNonStringValueAsString.mask) != 0)) + && (propertyValue instanceof Number || propertyValue instanceof Boolean)) { + String format = null; + if (propertyValue instanceof Number + && beanContext != null) { + format = beanContext.getFormat(); + } + + if (format != null) { + propertyValue = new DecimalFormat(format).format(propertyValue); + } else { + propertyValue = propertyValue.toString(); + } + } else if (beanContext != null && beanContext.isJsonDirect()) { + String jsonStr = (String) propertyValue; + propertyValue = JSON.parse(jsonStr); + } + } + + if (jsonBeanDeser.valueFilters != null) { + for (ValueFilter valueFilter : jsonBeanDeser.valueFilters) { + propertyValue = valueFilter.process(object, key, propertyValue); + } + } + + List valueFilters = this.valueFilters; + if (valueFilters != null) { + for (ValueFilter valueFilter : valueFilters) { + propertyValue = valueFilter.process(object, key, propertyValue); + } + } + + if (jsonBeanDeser.contextValueFilters != null) { + for (ContextValueFilter valueFilter : jsonBeanDeser.contextValueFilters) { + propertyValue = valueFilter.process(beanContext, object, key, propertyValue); + } + } + + if (this.contextValueFilters != null) { + for (ContextValueFilter valueFilter : this.contextValueFilters) { + propertyValue = valueFilter.process(beanContext, object, key, propertyValue); + } + } + + return propertyValue; + } + + /** + * only invoke by asm byte + * + * @return + */ + protected boolean writeDirect(JSONSerializer jsonBeanDeser) { + return jsonBeanDeser.out.writeDirect // + && this.writeDirect // + && jsonBeanDeser.writeDirect; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/SerializeWriter.java b/src/main/java/com/alibaba/fastjson/serializer/SerializeWriter.java old mode 100644 new mode 100755 index 2217256f47..750c7a04ef --- a/src/main/java/com/alibaba/fastjson/serializer/SerializeWriter.java +++ b/src/main/java/com/alibaba/fastjson/serializer/SerializeWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,1302 +15,2435 @@ */ package com.alibaba.fastjson.serializer; -import static com.alibaba.fastjson.parser.CharTypes.replaceChars; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.util.IOUtils; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.math.BigDecimal; import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.List; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.parser.CharTypes; -import com.alibaba.fastjson.util.IOUtils; +import static com.alibaba.fastjson.util.IOUtils.replaceChars; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public final class SerializeWriter extends Writer { + private final static ThreadLocal bufLocal = new ThreadLocal(); + private final static ThreadLocal bytesBufLocal = new ThreadLocal(); + + protected char buf[]; + + /** + * The number of chars in the buffer. + */ + protected int count; + + protected int features; + + private final Writer writer; + + protected boolean useSingleQuotes; + protected boolean quoteFieldNames; + protected boolean sortField; + protected boolean disableCircularReferenceDetect; + protected boolean beanToArray; + protected boolean writeNonStringValueAsString; + protected boolean notWriteDefaultValue; + protected boolean writeEnumUsingName; + protected boolean writeEnumUsingToString; + protected boolean writeDirect; + + protected char keySeperator; + + protected int maxBufSize = -1; + + protected boolean browserSecure; + protected long sepcialBits; + + public SerializeWriter(){ + this((Writer) null); + } + + public SerializeWriter(Writer writer){ + this(writer, JSON.DEFAULT_GENERATE_FEATURE, SerializerFeature.EMPTY); + } + + public SerializeWriter(SerializerFeature... features){ + this(null, features); + } + + public SerializeWriter(Writer writer, SerializerFeature... features){ + this(writer, 0, features); + } + + /** + * @since 1.2.9 + * @param writer + * @param defaultFeatures + * @param features + */ + public SerializeWriter(Writer writer, int defaultFeatures, SerializerFeature... features){ + this.writer = writer; + + buf = bufLocal.get(); + + if (buf != null) { + bufLocal.set(null); + } else { + buf = new char[2048]; + } + + int featuresValue = defaultFeatures; + for (SerializerFeature feature : features) { + featuresValue |= feature.getMask(); + } + this.features = featuresValue; + + computeFeatures(); + } + + public int getMaxBufSize() { + return maxBufSize; + } + + public void setMaxBufSize(int maxBufSize) { + if (maxBufSize < this.buf.length) { + throw new JSONException("must > " + buf.length); + } + + this.maxBufSize = maxBufSize; + } + + public int getBufferLength() { + return this.buf.length; + } + + public SerializeWriter(int initialSize){ + this(null, initialSize); + } + + public SerializeWriter(Writer writer, int initialSize){ + this.writer = writer; + + if (initialSize <= 0) { + throw new IllegalArgumentException("Negative initial size: " + initialSize); + } + buf = new char[initialSize]; + + computeFeatures(); + } + + public void config(SerializerFeature feature, boolean state) { + if (state) { + features |= feature.getMask(); + // 由于枚举序列化特性WriteEnumUsingToString和WriteEnumUsingName不能共存,需要检查 + if (feature == SerializerFeature.WriteEnumUsingToString) { + features &= ~SerializerFeature.WriteEnumUsingName.getMask(); + } else if (feature == SerializerFeature.WriteEnumUsingName) { + features &= ~SerializerFeature.WriteEnumUsingToString.getMask(); + } + } else { + features &= ~feature.getMask(); + } + + computeFeatures(); + } + + final static int nonDirectFeatures = 0 // + | SerializerFeature.UseSingleQuotes.mask // + | SerializerFeature.BrowserCompatible.mask // + | SerializerFeature.PrettyFormat.mask // + | SerializerFeature.WriteEnumUsingToString.mask + | SerializerFeature.WriteNonStringValueAsString.mask + | SerializerFeature.WriteSlashAsSpecial.mask + | SerializerFeature.IgnoreErrorGetter.mask + | SerializerFeature.WriteClassName.mask + | SerializerFeature.NotWriteDefaultValue.mask + ; + protected void computeFeatures() { + quoteFieldNames = (this.features & SerializerFeature.QuoteFieldNames.mask) != 0; + useSingleQuotes = (this.features & SerializerFeature.UseSingleQuotes.mask) != 0; + sortField = (this.features & SerializerFeature.SortField.mask) != 0; + disableCircularReferenceDetect = (this.features & SerializerFeature.DisableCircularReferenceDetect.mask) != 0; + beanToArray = (this.features & SerializerFeature.BeanToArray.mask) != 0; + writeNonStringValueAsString = (this.features & SerializerFeature.WriteNonStringValueAsString.mask) != 0; + notWriteDefaultValue = (this.features & SerializerFeature.NotWriteDefaultValue.mask) != 0; + writeEnumUsingName = (this.features & SerializerFeature.WriteEnumUsingName.mask) != 0; + writeEnumUsingToString = (this.features & SerializerFeature.WriteEnumUsingToString.mask) != 0; + + writeDirect = quoteFieldNames // + && (this.features & nonDirectFeatures) == 0 // + && (beanToArray || writeEnumUsingName) + ; + + keySeperator = useSingleQuotes ? '\'' : '"'; + + browserSecure = (this.features & SerializerFeature.BrowserSecure.mask) != 0; + + final long S0 = 0x4FFFFFFFFL, S1 = 0x8004FFFFFFFFL, S2 = 0x50000304ffffffffL; +// long s = 0; +// for (int i = 0; i <= 31; ++i) { +// s |= (1L << i); +// } +// s |= (1L << '"'); +// +// //S0 = s; +// //S1 = s | (1L << '/'); +// +// s |= (1L << '('); // 41 +// s |= (1L << ')'); // 42 +// s |= (1L << '<'); // 60 +// s |= (1L << '>'); // 62 +// S2 = s; + sepcialBits = browserSecure + ? S2 + : (features & SerializerFeature.WriteSlashAsSpecial.mask) != 0 ? S1 : S0; + } + + public boolean isSortField() { + return sortField; + } + + public boolean isNotWriteDefaultValue() { + return notWriteDefaultValue; + } + + public boolean isEnabled(SerializerFeature feature) { + return (this.features & feature.mask) != 0; + } + + public boolean isEnabled(int feature) { + return (this.features & feature) != 0; + } + + /** + * Writes a character to the buffer. + */ + public void write(int c) { + int newcount = count + 1; + if (newcount > buf.length) { + if (writer == null) { + expandCapacity(newcount); + } else { + flush(); + newcount = 1; + } + } + buf[count] = (char) c; + count = newcount; + } + + /** + * Writes characters to the buffer. + * + * @param c the data to be written + * @param off the start offset in the data + * @param len the number of chars that are written + */ + public void write(char c[], int off, int len) { + if (off < 0 // + || off > c.length // + || len < 0 // + || off + len > c.length // + || off + len < 0) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return; + } + + int newcount = count + len; + if (newcount > buf.length) { + if (writer == null) { + expandCapacity(newcount); + } else { + do { + int rest = buf.length - count; + System.arraycopy(c, off, buf, count, rest); + count = buf.length; + flush(); + len -= rest; + off += rest; + } while (len > buf.length); + newcount = len; + } + } + System.arraycopy(c, off, buf, count, len); + count = newcount; + + } + + public void expandCapacity(int minimumCapacity) { + if (maxBufSize != -1 && minimumCapacity >= maxBufSize) { + throw new JSONException("serialize exceeded MAX_OUTPUT_LENGTH=" + maxBufSize + ", minimumCapacity=" + minimumCapacity); + } + + int newCapacity = buf.length + (buf.length >> 1) + 1; + + if (newCapacity < minimumCapacity) { + newCapacity = minimumCapacity; + } + char newValue[] = new char[newCapacity]; + System.arraycopy(buf, 0, newValue, 0, count); + buf = newValue; + } + + public SerializeWriter append(CharSequence csq) { + String s = (csq == null ? "null" : csq.toString()); + write(s, 0, s.length()); + return this; + } + + public SerializeWriter append(CharSequence csq, int start, int end) { + String s = (csq == null ? "null" : csq).subSequence(start, end).toString(); + write(s, 0, s.length()); + return this; + } + + public SerializeWriter append(char c) { + write(c); + return this; + } + + /** + * Write a portion of a string to the buffer. + * + * @param str String to be written from + * @param off Offset from which to start reading characters + * @param len Number of characters to be written + */ + public void write(String str, int off, int len) { + int newcount = count + len; + if (newcount > buf.length) { + if (writer == null) { + expandCapacity(newcount); + } else { + do { + int rest = buf.length - count; + str.getChars(off, off + rest, buf, count); + count = buf.length; + flush(); + len -= rest; + off += rest; + } while (len > buf.length); + newcount = len; + } + } + str.getChars(off, off + len, buf, count); + count = newcount; + } + + /** + * Writes the contents of the buffer to another character stream. + * + * @param out the output stream to write to + * @throws IOException If an I/O error occurs. + */ + public void writeTo(Writer out) throws IOException { + if (this.writer != null) { + throw new UnsupportedOperationException("writer not null"); + } + out.write(buf, 0, count); + } + + public void writeTo(OutputStream out, String charsetName) throws IOException { + writeTo(out, Charset.forName(charsetName)); + } + + public void writeTo(OutputStream out, Charset charset) throws IOException { + writeToEx(out, charset); + } + + public int writeToEx(OutputStream out, Charset charset) throws IOException { + if (this.writer != null) { + throw new UnsupportedOperationException("writer not null"); + } + + if (charset == IOUtils.UTF8) { + return encodeToUTF8(out); + } else { + byte[] bytes = new String(buf, 0, count).getBytes(charset); + out.write(bytes); + return bytes.length; + } + } + + /** + * Returns a copy of the input data. + * + * @return an array of chars copied from the input data. + */ + public char[] toCharArray() { + if (this.writer != null) { + throw new UnsupportedOperationException("writer not null"); + } + + char[] newValue = new char[count]; + System.arraycopy(buf, 0, newValue, 0, count); + return newValue; + } + + /** + * only for springwebsocket + * @return + */ + public char[] toCharArrayForSpringWebSocket() { + if (this.writer != null) { + throw new UnsupportedOperationException("writer not null"); + } + + char[] newValue = new char[count - 2]; + System.arraycopy(buf, 1, newValue, 0, count - 2); + return newValue; + } + + public byte[] toBytes(String charsetName) { + return toBytes(charsetName == null || "UTF-8".equals(charsetName) // + ? IOUtils.UTF8 // + : Charset.forName(charsetName)); + } + + public byte[] toBytes(Charset charset) { + if (this.writer != null) { + throw new UnsupportedOperationException("writer not null"); + } + + if (charset == IOUtils.UTF8) { + return encodeToUTF8Bytes(); + } else { + return new String(buf, 0, count).getBytes(charset); + } + } + + private int encodeToUTF8(OutputStream out) throws IOException { + + int bytesLength = (int) (count * (double) 3); + byte[] bytes = bytesBufLocal.get(); + + if (bytes == null) { + bytes = new byte[1024 * 8]; + bytesBufLocal.set(bytes); + } + + if (bytes.length < bytesLength) { + bytes = new byte[bytesLength]; + } + + int position = IOUtils.encodeUTF8(buf, 0, count, bytes); + out.write(bytes, 0, position); + return position; + } + + private byte[] encodeToUTF8Bytes() { + int bytesLength = (int) (count * (double) 3); + byte[] bytes = bytesBufLocal.get(); + + if (bytes == null) { + bytes = new byte[1024 * 8]; + bytesBufLocal.set(bytes); + } + + if (bytes.length < bytesLength) { + bytes = new byte[bytesLength]; + } + + int position = IOUtils.encodeUTF8(buf, 0, count, bytes); + byte[] copy = new byte[position]; + System.arraycopy(bytes, 0, copy, 0, position); + return copy; + } + + public int size() { + return count; + } + + public String toString() { + return new String(buf, 0, count); + } + + /** + * Close the stream. This method does not release the buffer, since its contents might still be required. Note: + * Invoking this method in this class will have no effect. + */ + public void close() { + if (writer != null && count > 0) { + flush(); + } + if (buf.length <= 1024 * 128) { + bufLocal.set(buf); + } + + this.buf = null; + } + + public void write(String text) { + if (text == null) { + writeNull(); + return; + } + + write(text, 0, text.length()); + } + + public void writeInt(int i) { + if (i == Integer.MIN_VALUE) { + write("-2147483648"); + return; + } + + int size = (i < 0) ? IOUtils.stringSize(-i) + 1 : IOUtils.stringSize(i); + + int newcount = count + size; + if (newcount > buf.length) { + if (writer == null) { + expandCapacity(newcount); + } else { + char[] chars = new char[size]; + IOUtils.getChars(i, size, chars); + write(chars, 0, chars.length); + return; + } + } + + IOUtils.getChars(i, newcount, buf); + + count = newcount; + } + + public void writeByteArray(byte[] bytes) { + if (isEnabled(SerializerFeature.WriteClassName.mask)) { + writeHex(bytes); + return; + } + + int bytesLen = bytes.length; + final char quote = useSingleQuotes ? '\'' : '"'; + if (bytesLen == 0) { + String emptyString = useSingleQuotes ? "''" : "\"\""; + write(emptyString); + return; + } + + final char[] CA = IOUtils.CA; + + int eLen = (bytesLen / 3) * 3; // Length of even 24-bits. + int charsLen = ((bytesLen - 1) / 3 + 1) << 2; // base64 character count + // char[] chars = new char[charsLen]; + int offset = count; + int newcount = count + charsLen + 2; + if (newcount > buf.length) { + if (writer != null) { + write(quote); + + for (int s = 0; s < eLen;) { + // Copy next three bytes into lower 24 bits of int, paying attension to sign. + int i = (bytes[s++] & 0xff) << 16 | (bytes[s++] & 0xff) << 8 | (bytes[s++] & 0xff); + + // Encode the int into four chars + write(CA[(i >>> 18) & 0x3f]); + write(CA[(i >>> 12) & 0x3f]); + write(CA[(i >>> 6) & 0x3f]); + write(CA[i & 0x3f]); + } + + // Pad and encode last bits if source isn't even 24 bits. + int left = bytesLen - eLen; // 0 - 2. + if (left > 0) { + // Prepare the int + int i = ((bytes[eLen] & 0xff) << 10) | (left == 2 ? ((bytes[bytesLen - 1] & 0xff) << 2) : 0); + + // Set last four chars + write(CA[i >> 12]); + write(CA[(i >>> 6) & 0x3f]); + write(left == 2 ? CA[i & 0x3f] : '='); + write('='); + } + + write(quote); + return; + } + expandCapacity(newcount); + } + count = newcount; + buf[offset++] = quote; + + // Encode even 24-bits + for (int s = 0, d = offset; s < eLen;) { + // Copy next three bytes into lower 24 bits of int, paying attension to sign. + int i = (bytes[s++] & 0xff) << 16 | (bytes[s++] & 0xff) << 8 | (bytes[s++] & 0xff); + + // Encode the int into four chars + buf[d++] = CA[(i >>> 18) & 0x3f]; + buf[d++] = CA[(i >>> 12) & 0x3f]; + buf[d++] = CA[(i >>> 6) & 0x3f]; + buf[d++] = CA[i & 0x3f]; + } + + // Pad and encode last bits if source isn't even 24 bits. + int left = bytesLen - eLen; // 0 - 2. + if (left > 0) { + // Prepare the int + int i = ((bytes[eLen] & 0xff) << 10) | (left == 2 ? ((bytes[bytesLen - 1] & 0xff) << 2) : 0); + + // Set last four chars + buf[newcount - 5] = CA[i >> 12]; + buf[newcount - 4] = CA[(i >>> 6) & 0x3f]; + buf[newcount - 3] = left == 2 ? CA[i & 0x3f] : '='; + buf[newcount - 2] = '='; + } + buf[newcount - 1] = quote; + } + + public void writeHex(byte[] bytes) { + int newcount = count + bytes.length * 2 + 3; + if (newcount > buf.length) { + if (writer != null) { + char[] chars = new char[bytes.length + 3]; + int pos = 0; + chars[pos++] = 'x'; + chars[pos++] = '\''; + + for (int i = 0; i < bytes.length; ++i) { + byte b = bytes[i]; + + int a = b & 0xFF; + int b0 = a >> 4; + int b1 = a & 0xf; + + chars[pos++] = (char) (b0 + (b0 < 10 ? 48 : 55)); + chars[pos++] = (char) (b1 + (b1 < 10 ? 48 : 55)); + } + chars[pos++] = '\''; + try { + writer.write(chars); + } catch (IOException ex) { + throw new JSONException("writeBytes error.", ex); + } + return; + } + expandCapacity(newcount); + } + + buf[count++] = 'x'; + buf[count++] = '\''; + + for (int i = 0; i < bytes.length; ++i) { + byte b = bytes[i]; + + int a = b & 0xFF; + int b0 = a >> 4; + int b1 = a & 0xf; + + buf[count++] = (char) (b0 + (b0 < 10 ? 48 : 55)); + buf[count++] = (char) (b1 + (b1 < 10 ? 48 : 55)); + } + buf[count++] = '\''; + } + + public void writeFloat(float value, boolean checkWriteClassName) { + if (Float.isNaN(value) // + || Float.isInfinite(value)) { + writeNull(); + } else { + String floatText= Float.toString(value); + if (isEnabled(SerializerFeature.WriteNullNumberAsZero) && floatText.endsWith(".0")) { + floatText = floatText.substring(0, floatText.length() - 2); + } + write(floatText); + + if (checkWriteClassName && isEnabled(SerializerFeature.WriteClassName)) { + write('F'); + } + } + } + + public void writeDouble(double doubleValue, boolean checkWriteClassName) { + if (Double.isNaN(doubleValue) // + || Double.isInfinite(doubleValue)) { + writeNull(); + } else { + String doubleText = Double.toString(doubleValue); + if (isEnabled(SerializerFeature.WriteNullNumberAsZero) && doubleText.endsWith(".0")) { + doubleText = doubleText.substring(0, doubleText.length() - 2); + } + + write(doubleText); + + if (checkWriteClassName && isEnabled(SerializerFeature.WriteClassName)) { + write('D'); + } + } + } + + public void writeEnum(Enum value) { + if (value == null) { + writeNull(); + return; + } + + String strVal = null; + if (writeEnumUsingName && !writeEnumUsingToString) { + strVal = value.name(); + } else if (writeEnumUsingToString) { + strVal = value.toString();; + } + + if (strVal != null) { + char quote = isEnabled(SerializerFeature.UseSingleQuotes) ? '\'' : '"'; + write(quote); + write(strVal); + write(quote); + } else { + writeInt(value.ordinal()); + } + } + + public void writeLong(long i) { + boolean needQuotationMark = isEnabled(SerializerFeature.BrowserCompatible) // + && (!isEnabled(SerializerFeature.WriteClassName)) // + && (i > 9007199254740991L || i < -9007199254740991L); + + if (i == Long.MIN_VALUE) { + if (needQuotationMark) write("\"-9223372036854775808\""); + else write("-9223372036854775808"); + return; + } + + int size = (i < 0) ? IOUtils.stringSize(-i) + 1 : IOUtils.stringSize(i); + + int newcount = count + size; + if (needQuotationMark) newcount += 2; + if (newcount > buf.length) { + if (writer == null) { + expandCapacity(newcount); + } else { + char[] chars = new char[size]; + IOUtils.getChars(i, size, chars); + if (needQuotationMark) { + write('"'); + write(chars, 0, chars.length); + write('"'); + } else { + write(chars, 0, chars.length); + } + return; + } + } + + if (needQuotationMark) { + buf[count] = '"'; + IOUtils.getChars(i, newcount - 1, buf); + buf[newcount - 1] = '"'; + } else { + IOUtils.getChars(i, newcount, buf); + } + + count = newcount; + } + + public void writeNull() { + write("null"); + } + + public void writeNull(SerializerFeature feature) { + writeNull(0, feature.mask); + } + + public void writeNull(int beanFeatures , int feature) { + if ((beanFeatures & feature) == 0 // + && (this.features & feature) == 0) { + writeNull(); + return; + } + + if (feature == SerializerFeature.WriteNullListAsEmpty.mask) { + write("[]"); + } else if (feature == SerializerFeature.WriteNullStringAsEmpty.mask) { + writeString(""); + } else if (feature == SerializerFeature.WriteNullBooleanAsFalse.mask) { + write("false"); + } else if (feature == SerializerFeature.WriteNullNumberAsZero.mask) { + write('0'); + } else { + writeNull(); + } + } + + public void writeStringWithDoubleQuote(String text, final char seperator) { + if (text == null) { + writeNull(); + if (seperator != 0) { + write(seperator); + } + return; + } + + int len = text.length(); + int newcount = count + len + 2; + if (seperator != 0) { + newcount++; + } + + if (newcount > buf.length) { + if (writer != null) { + write('"'); + + for (int i = 0; i < text.length(); ++i) { + char ch = text.charAt(i); + + if (isEnabled(SerializerFeature.BrowserSecure)) { + if (ch == '(' || ch == ')' || ch == '<' || ch == '>') { + write('\\'); + write('u'); + write(IOUtils.DIGITS[(ch >>> 12) & 15]); + write(IOUtils.DIGITS[(ch >>> 8) & 15]); + write(IOUtils.DIGITS[(ch >>> 4) & 15]); + write(IOUtils.DIGITS[ch & 15]); + continue; + } + } + + if (isEnabled(SerializerFeature.BrowserCompatible)) { + if (ch == '\b' // + || ch == '\f' // + || ch == '\n' // + || ch == '\r' // + || ch == '\t' // + || ch == '"' // + || ch == '/' // + || ch == '\\') { + write('\\'); + write(replaceChars[(int) ch]); + continue; + } + + if (ch < 32) { + write('\\'); + write('u'); + write('0'); + write('0'); + write(IOUtils.ASCII_CHARS[ch * 2]); + write(IOUtils.ASCII_CHARS[ch * 2 + 1]); + continue; + } + + if (ch >= 127) { + write('\\'); + write('u'); + write(IOUtils.DIGITS[(ch >>> 12) & 15]); + write(IOUtils.DIGITS[(ch >>> 8) & 15]); + write(IOUtils.DIGITS[(ch >>> 4) & 15]); + write(IOUtils.DIGITS[ch & 15]); + continue; + } + } else { + if (ch < IOUtils.specicalFlags_doubleQuotes.length + && IOUtils.specicalFlags_doubleQuotes[ch] != 0 // + || (ch == '/' && isEnabled(SerializerFeature.WriteSlashAsSpecial))) { + write('\\'); + if (IOUtils.specicalFlags_doubleQuotes[ch] == 4) { + write('u'); + write(IOUtils.DIGITS[ch >>> 12 & 15]); + write(IOUtils.DIGITS[ch >>> 8 & 15]); + write(IOUtils.DIGITS[ch >>> 4 & 15]); + write(IOUtils.DIGITS[ch & 15]); + } else { + write(IOUtils.replaceChars[ch]); + } + continue; + } + } + + write(ch); + } + + write('"'); + if (seperator != 0) { + write(seperator); + } + return; + } + expandCapacity(newcount); + } + + int start = count + 1; + int end = start + len; + + buf[count] = '\"'; + text.getChars(0, len, buf, start); + + count = newcount; + + if (isEnabled(SerializerFeature.BrowserCompatible)) { + int lastSpecialIndex = -1; + + for (int i = start; i < end; ++i) { + char ch = buf[i]; + + if (ch == '"' // + || ch == '/' // + || ch == '\\') { + lastSpecialIndex = i; + newcount += 1; + continue; + } + + if (ch == '\b' // + || ch == '\f' // + || ch == '\n' // + || ch == '\r' // + || ch == '\t') { + lastSpecialIndex = i; + newcount += 1; + continue; + } + + if (ch < 32) { + lastSpecialIndex = i; + newcount += 5; + continue; + } + + if (ch >= 127) { + lastSpecialIndex = i; + newcount += 5; + continue; + } + } + + if (newcount > buf.length) { + expandCapacity(newcount); + } + count = newcount; + + for (int i = lastSpecialIndex; i >= start; --i) { + char ch = buf[i]; + + if (ch == '\b' // + || ch == '\f'// + || ch == '\n' // + || ch == '\r' // + || ch == '\t') { + System.arraycopy(buf, i + 1, buf, i + 2, end - i - 1); + buf[i] = '\\'; + buf[i + 1] = replaceChars[(int) ch]; + end += 1; + continue; + } + + if (ch == '"' // + || ch == '/' // + || ch == '\\') { + System.arraycopy(buf, i + 1, buf, i + 2, end - i - 1); + buf[i] = '\\'; + buf[i + 1] = ch; + end += 1; + continue; + } + + if (ch < 32) { + System.arraycopy(buf, i + 1, buf, i + 6, end - i - 1); + buf[i] = '\\'; + buf[i + 1] = 'u'; + buf[i + 2] = '0'; + buf[i + 3] = '0'; + buf[i + 4] = IOUtils.ASCII_CHARS[ch * 2]; + buf[i + 5] = IOUtils.ASCII_CHARS[ch * 2 + 1]; + end += 5; + continue; + } + + if (ch >= 127) { + System.arraycopy(buf, i + 1, buf, i + 6, end - i - 1); + buf[i] = '\\'; + buf[i + 1] = 'u'; + buf[i + 2] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[i + 3] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[i + 4] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[i + 5] = IOUtils.DIGITS[ch & 15]; + end += 5; + } + } + + if (seperator != 0) { + buf[count - 2] = '\"'; + buf[count - 1] = seperator; + } else { + buf[count - 1] = '\"'; + } + + return; + } + + int specialCount = 0; + int lastSpecialIndex = -1; + int firstSpecialIndex = -1; + char lastSpecial = '\0'; + + for (int i = start; i < end; ++i) { + char ch = buf[i]; + + if (ch >= ']') { // 93 + if (ch >= 0x7F // + && (ch == '\u2028' // + || ch == '\u2029' // + || ch < 0xA0)) { + if (firstSpecialIndex == -1) { + firstSpecialIndex = i; + } + + specialCount++; + lastSpecialIndex = i; + lastSpecial = ch; + newcount += 4; + } + continue; + } + + boolean special = (ch < 64 && (sepcialBits & (1L << ch)) != 0) || ch == '\\'; + if (special) { + specialCount++; + lastSpecialIndex = i; + lastSpecial = ch; + + if (ch == '(' + || ch == ')' + || ch == '<' + || ch == '>' + || (ch < IOUtils.specicalFlags_doubleQuotes.length // + && IOUtils.specicalFlags_doubleQuotes[ch] == 4) // + ) { + newcount += 4; + } + + if (firstSpecialIndex == -1) { + firstSpecialIndex = i; + } + } + } + + if (specialCount > 0) { + newcount += specialCount; + if (newcount > buf.length) { + expandCapacity(newcount); + } + count = newcount; + + if (specialCount == 1) { + if (lastSpecial == '\u2028') { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = end - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = 'u'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '0'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '8'; + } else if (lastSpecial == '\u2029') { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = end - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = 'u'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '0'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '9'; + } else if (lastSpecial == '(' || lastSpecial == ')' || lastSpecial == '<' || lastSpecial == '>') { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = end - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = 'u'; + + final char ch = lastSpecial; + buf[++lastSpecialIndex] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[++lastSpecialIndex] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[++lastSpecialIndex] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[++lastSpecialIndex] = IOUtils.DIGITS[ch & 15]; + } else { + final char ch = lastSpecial; + if (ch < IOUtils.specicalFlags_doubleQuotes.length // + && IOUtils.specicalFlags_doubleQuotes[ch] == 4) { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = end - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + + int bufIndex = lastSpecialIndex; + buf[bufIndex++] = '\\'; + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + } else { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 2; + int LengthOfCopy = end - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = replaceChars[(int) ch]; + } + } + } else if (specialCount > 1) { + int textIndex = firstSpecialIndex - start; + int bufIndex = firstSpecialIndex; + for (int i = textIndex; i < text.length(); ++i) { + char ch = text.charAt(i); + + if (browserSecure && (ch == '(' + || ch == ')' + || ch == '<' + || ch == '>')) { + buf[bufIndex++] = '\\'; + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + end += 5; + } else if (ch < IOUtils.specicalFlags_doubleQuotes.length // + && IOUtils.specicalFlags_doubleQuotes[ch] != 0 // + || (ch == '/' && isEnabled(SerializerFeature.WriteSlashAsSpecial))) { + buf[bufIndex++] = '\\'; + if (IOUtils.specicalFlags_doubleQuotes[ch] == 4) { + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + end += 5; + } else { + buf[bufIndex++] = replaceChars[(int) ch]; + end++; + } + } else { + if (ch == '\u2028' || ch == '\u2029') { + buf[bufIndex++] = '\\'; + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + end += 5; + } else { + buf[bufIndex++] = ch; + } + } + } + } + } + + if (seperator != 0) { + buf[count - 2] = '\"'; + buf[count - 1] = seperator; + } else { + buf[count - 1] = '\"'; + } + } + + public void writeStringWithDoubleQuote(char[] text, final char seperator) { + if (text == null) { + writeNull(); + if (seperator != 0) { + write(seperator); + } + return; + } + + int len = text.length; + int newcount = count + len + 2; + if (seperator != 0) { + newcount++; + } + + if (newcount > buf.length) { + if (writer != null) { + write('"'); + + for (int i = 0; i < text.length; ++i) { + char ch = text[i]; + + if (isEnabled(SerializerFeature.BrowserSecure)) { + if (ch == '(' || ch == ')' || ch == '<' || ch == '>') { + write('\\'); + write('u'); + write(IOUtils.DIGITS[(ch >>> 12) & 15]); + write(IOUtils.DIGITS[(ch >>> 8) & 15]); + write(IOUtils.DIGITS[(ch >>> 4) & 15]); + write(IOUtils.DIGITS[ch & 15]); + continue; + } + } + + if (isEnabled(SerializerFeature.BrowserCompatible)) { + if (ch == '\b' // + || ch == '\f' // + || ch == '\n' // + || ch == '\r' // + || ch == '\t' // + || ch == '"' // + || ch == '/' // + || ch == '\\') { + write('\\'); + write(replaceChars[(int) ch]); + continue; + } + + if (ch < 32) { + write('\\'); + write('u'); + write('0'); + write('0'); + write(IOUtils.ASCII_CHARS[ch * 2]); + write(IOUtils.ASCII_CHARS[ch * 2 + 1]); + continue; + } + + if (ch >= 127) { + write('\\'); + write('u'); + write(IOUtils.DIGITS[(ch >>> 12) & 15]); + write(IOUtils.DIGITS[(ch >>> 8) & 15]); + write(IOUtils.DIGITS[(ch >>> 4) & 15]); + write(IOUtils.DIGITS[ch & 15]); + continue; + } + } else { + if (ch < IOUtils.specicalFlags_doubleQuotes.length + && IOUtils.specicalFlags_doubleQuotes[ch] != 0 // + || (ch == '/' && isEnabled(SerializerFeature.WriteSlashAsSpecial))) { + write('\\'); + if (IOUtils.specicalFlags_doubleQuotes[ch] == 4) { + write('u'); + write(IOUtils.DIGITS[ch >>> 12 & 15]); + write(IOUtils.DIGITS[ch >>> 8 & 15]); + write(IOUtils.DIGITS[ch >>> 4 & 15]); + write(IOUtils.DIGITS[ch & 15]); + } else { + write(IOUtils.replaceChars[ch]); + } + continue; + } + } + + write(ch); + } + + write('"'); + if (seperator != 0) { + write(seperator); + } + return; + } + expandCapacity(newcount); + } + + int start = count + 1; + int end = start + len; + + buf[count] = '\"'; +// text.getChars(0, len, buf, start); + System.arraycopy(text, 0, buf, start, text.length); + + count = newcount; + + if (isEnabled(SerializerFeature.BrowserCompatible)) { + int lastSpecialIndex = -1; + + for (int i = start; i < end; ++i) { + char ch = buf[i]; + + if (ch == '"' // + || ch == '/' // + || ch == '\\') { + lastSpecialIndex = i; + newcount += 1; + continue; + } + + if (ch == '\b' // + || ch == '\f' // + || ch == '\n' // + || ch == '\r' // + || ch == '\t') { + lastSpecialIndex = i; + newcount += 1; + continue; + } + + if (ch < 32) { + lastSpecialIndex = i; + newcount += 5; + continue; + } + + if (ch >= 127) { + lastSpecialIndex = i; + newcount += 5; + continue; + } + } + + if (newcount > buf.length) { + expandCapacity(newcount); + } + count = newcount; + + for (int i = lastSpecialIndex; i >= start; --i) { + char ch = buf[i]; + + if (ch == '\b' // + || ch == '\f'// + || ch == '\n' // + || ch == '\r' // + || ch == '\t') { + System.arraycopy(buf, i + 1, buf, i + 2, end - i - 1); + buf[i] = '\\'; + buf[i + 1] = replaceChars[(int) ch]; + end += 1; + continue; + } + + if (ch == '"' // + || ch == '/' // + || ch == '\\') { + System.arraycopy(buf, i + 1, buf, i + 2, end - i - 1); + buf[i] = '\\'; + buf[i + 1] = ch; + end += 1; + continue; + } + + if (ch < 32) { + System.arraycopy(buf, i + 1, buf, i + 6, end - i - 1); + buf[i] = '\\'; + buf[i + 1] = 'u'; + buf[i + 2] = '0'; + buf[i + 3] = '0'; + buf[i + 4] = IOUtils.ASCII_CHARS[ch * 2]; + buf[i + 5] = IOUtils.ASCII_CHARS[ch * 2 + 1]; + end += 5; + continue; + } + + if (ch >= 127) { + System.arraycopy(buf, i + 1, buf, i + 6, end - i - 1); + buf[i] = '\\'; + buf[i + 1] = 'u'; + buf[i + 2] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[i + 3] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[i + 4] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[i + 5] = IOUtils.DIGITS[ch & 15]; + end += 5; + } + } + + if (seperator != 0) { + buf[count - 2] = '\"'; + buf[count - 1] = seperator; + } else { + buf[count - 1] = '\"'; + } + + return; + } + + int specialCount = 0; + int lastSpecialIndex = -1; + int firstSpecialIndex = -1; + char lastSpecial = '\0'; + + for (int i = start; i < end; ++i) { + char ch = buf[i]; + + if (ch >= ']') { // 93 + if (ch >= 0x7F // + && (ch == '\u2028' // + || ch == '\u2029' // + || ch < 0xA0)) { + if (firstSpecialIndex == -1) { + firstSpecialIndex = i; + } + + specialCount++; + lastSpecialIndex = i; + lastSpecial = ch; + newcount += 4; + } + continue; + } + + boolean special = (ch < 64 && (sepcialBits & (1L << ch)) != 0) || ch == '\\'; + if (special) { + specialCount++; + lastSpecialIndex = i; + lastSpecial = ch; + + if (ch == '(' + || ch == ')' + || ch == '<' + || ch == '>' + || (ch < IOUtils.specicalFlags_doubleQuotes.length // + && IOUtils.specicalFlags_doubleQuotes[ch] == 4) // + ) { + newcount += 4; + } + + if (firstSpecialIndex == -1) { + firstSpecialIndex = i; + } + } + } + + if (specialCount > 0) { + newcount += specialCount; + if (newcount > buf.length) { + expandCapacity(newcount); + } + count = newcount; + + if (specialCount == 1) { + if (lastSpecial == '\u2028') { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = end - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = 'u'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '0'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '8'; + } else if (lastSpecial == '\u2029') { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = end - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = 'u'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '0'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '9'; + } else if (lastSpecial == '(' || lastSpecial == ')' || lastSpecial == '<' || lastSpecial == '>') { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = end - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = 'u'; + + final char ch = lastSpecial; + buf[++lastSpecialIndex] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[++lastSpecialIndex] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[++lastSpecialIndex] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[++lastSpecialIndex] = IOUtils.DIGITS[ch & 15]; + } else { + final char ch = lastSpecial; + if (ch < IOUtils.specicalFlags_doubleQuotes.length // + && IOUtils.specicalFlags_doubleQuotes[ch] == 4) { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = end - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + + int bufIndex = lastSpecialIndex; + buf[bufIndex++] = '\\'; + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + } else { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 2; + int LengthOfCopy = end - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = replaceChars[(int) ch]; + } + } + } else if (specialCount > 1) { + int textIndex = firstSpecialIndex - start; + int bufIndex = firstSpecialIndex; + for (int i = textIndex; i < text.length; ++i) { + char ch = text[i]; + + if (browserSecure && (ch == '(' + || ch == ')' + || ch == '<' + || ch == '>')) { + buf[bufIndex++] = '\\'; + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + end += 5; + } else if (ch < IOUtils.specicalFlags_doubleQuotes.length // + && IOUtils.specicalFlags_doubleQuotes[ch] != 0 // + || (ch == '/' && isEnabled(SerializerFeature.WriteSlashAsSpecial))) { + buf[bufIndex++] = '\\'; + if (IOUtils.specicalFlags_doubleQuotes[ch] == 4) { + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + end += 5; + } else { + buf[bufIndex++] = replaceChars[(int) ch]; + end++; + } + } else { + if (ch == '\u2028' || ch == '\u2029') { + buf[bufIndex++] = '\\'; + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + end += 5; + } else { + buf[bufIndex++] = ch; + } + } + } + } + } + + if (seperator != 0) { + buf[count - 2] = '\"'; + buf[count - 1] = seperator; + } else { + buf[count - 1] = '\"'; + } + } + + public void writeFieldNameDirect(String text) { + int len = text.length(); + int newcount = count + len + 3; + + if (newcount > buf.length) { + expandCapacity(newcount); + } + + int start = count + 1; + + buf[count] = '\"'; + text.getChars(0, len, buf, start); + + count = newcount; + buf[count - 2] = '\"'; + buf[count - 1] = ':'; + } + + public void write(List list) { + if (list.isEmpty()) { + write("[]"); + return; + } + + int offset = count; + final int initOffset = offset; + for (int i = 0, list_size = list.size(); i < list_size; ++i) { + String text = list.get(i); + + boolean hasSpecial = false; + if (text == null) { + hasSpecial = true; + } else { + for (int j = 0, len = text.length(); j < len; ++j) { + char ch = text.charAt(j); + if (hasSpecial = (ch < ' ' // + || ch > '~' // + || ch == '"' // + || ch == '\\')) { + break; + } + } + } + + if (hasSpecial) { + count = initOffset; + write('['); + for (int j = 0; j < list.size(); ++j) { + text = list.get(j); + if (j != 0) { + write(','); + } + + if (text == null) { + write("null"); + } else { + writeStringWithDoubleQuote(text, (char) 0); + } + } + write(']'); + return; + } + + int newcount = offset + text.length() + 3; + if (i == list.size() - 1) { + newcount++; + } + if (newcount > buf.length) { + count = offset; + expandCapacity(newcount); + } + + if (i == 0) { + buf[offset++] = '['; + } else { + buf[offset++] = ','; + } + buf[offset++] = '"'; + text.getChars(0, text.length(), buf, offset); + offset += text.length(); + buf[offset++] = '"'; + } + buf[offset++] = ']'; + count = offset; + } + + + public void writeFieldValue(char seperator, String name, char value) { + write(seperator); + writeFieldName(name); + if (value == 0) { + writeString("\u0000"); + } else { + writeString(Character.toString(value)); + } + } + + public void writeFieldValue(char seperator, String name, boolean value) { + if (!quoteFieldNames) { + write(seperator); + writeFieldName(name); + write(value); + return; + } + int intSize = value ? 4 : 5; + + int nameLen = name.length(); + int newcount = count + nameLen + 4 + intSize; + if (newcount > buf.length) { + if (writer != null) { + write(seperator); + writeString(name); + write(':'); + write(value); + return; + } + expandCapacity(newcount); + } + + int start = count; + count = newcount; + + buf[start] = seperator; + + int nameEnd = start + nameLen + 1; + + buf[start + 1] = keySeperator; + + name.getChars(0, nameLen, buf, start + 2); + + buf[nameEnd + 1] = keySeperator; + + if (value) { + System.arraycopy(":true".toCharArray(), 0, buf, nameEnd + 2, 5); + } else { + System.arraycopy(":false".toCharArray(), 0, buf, nameEnd + 2, 6); + } + } + + public void write(boolean value) { + if (value) { + write("true"); + } else { + write("false"); + } + } + + public void writeFieldValue(char seperator, String name, int value) { + if (value == Integer.MIN_VALUE || !quoteFieldNames) { + write(seperator); + writeFieldName(name); + writeInt(value); + return; + } + + int intSize = (value < 0) ? IOUtils.stringSize(-value) + 1 : IOUtils.stringSize(value); + + int nameLen = name.length(); + int newcount = count + nameLen + 4 + intSize; + if (newcount > buf.length) { + if (writer != null) { + write(seperator); + writeFieldName(name); + writeInt(value); + return; + } + expandCapacity(newcount); + } + + int start = count; + count = newcount; + + buf[start] = seperator; + + int nameEnd = start + nameLen + 1; + + buf[start + 1] = keySeperator; + + name.getChars(0, nameLen, buf, start + 2); + + buf[nameEnd + 1] = keySeperator; + buf[nameEnd + 2] = ':'; + + IOUtils.getChars(value, count, buf); + } + + public void writeFieldValue(char seperator, String name, long value) { + if (value == Long.MIN_VALUE || !quoteFieldNames) { + write(seperator); + writeFieldName(name); + writeLong(value); + return; + } + + int intSize = (value < 0) ? IOUtils.stringSize(-value) + 1 : IOUtils.stringSize(value); + + int nameLen = name.length(); + int newcount = count + nameLen + 4 + intSize; + if (newcount > buf.length) { + if (writer != null) { + write(seperator); + writeFieldName(name); + writeLong(value); + return; + } + expandCapacity(newcount); + } + + int start = count; + count = newcount; + + buf[start] = seperator; + + int nameEnd = start + nameLen + 1; + + buf[start + 1] = keySeperator; + + name.getChars(0, nameLen, buf, start + 2); + + buf[nameEnd + 1] = keySeperator; + buf[nameEnd + 2] = ':'; + + IOUtils.getChars(value, count, buf); + } + + public void writeFieldValue(char seperator, String name, float value) { + write(seperator); + writeFieldName(name); + writeFloat(value, false); + } + + public void writeFieldValue(char seperator, String name, double value) { + write(seperator); + writeFieldName(name); + writeDouble(value, false); + } + + public void writeFieldValue(char seperator, String name, String value) { + if (quoteFieldNames) { + if (useSingleQuotes) { + write(seperator); + writeFieldName(name); + if (value == null) { + writeNull(); + } else { + writeString(value); + } + } else { + if (isEnabled(SerializerFeature.BrowserCompatible)) { + write(seperator); + writeStringWithDoubleQuote(name, ':'); + writeStringWithDoubleQuote(value, (char) 0); + } else { + writeFieldValueStringWithDoubleQuoteCheck(seperator, name, value); + } + } + } else { + write(seperator); + writeFieldName(name); + if (value == null) { + writeNull(); + } else { + writeString(value); + } + } + } + + public void writeFieldValueStringWithDoubleQuoteCheck(char seperator, String name, String value) { + int nameLen = name.length(); + int valueLen; + + int newcount = count; + + if (value == null) { + valueLen = 4; + newcount += nameLen + 8; + } else { + valueLen = value.length(); + newcount += nameLen + valueLen + 6; + } + + if (newcount > buf.length) { + if (writer != null) { + write(seperator); + writeStringWithDoubleQuote(name, ':'); + writeStringWithDoubleQuote(value, (char) 0); + return; + } + expandCapacity(newcount); + } + + buf[count] = seperator; + + int nameStart = count + 2; + int nameEnd = nameStart + nameLen; + + buf[count + 1] = '\"'; + name.getChars(0, nameLen, buf, nameStart); + + count = newcount; + + buf[nameEnd] = '\"'; + + int index = nameEnd + 1; + buf[index++] = ':'; + + if (value == null) { + buf[index++] = 'n'; + buf[index++] = 'u'; + buf[index++] = 'l'; + buf[index++] = 'l'; + return; + } + + buf[index++] = '"'; + + int valueStart = index; + int valueEnd = valueStart + valueLen; + + value.getChars(0, valueLen, buf, valueStart); + + int specialCount = 0; + int lastSpecialIndex = -1; + int firstSpecialIndex = -1; + char lastSpecial = '\0'; + + for (int i = valueStart; i < valueEnd; ++i) { + char ch = buf[i]; + + if (ch >= ']') { + if (ch >= 0x7F // + && (ch == '\u2028' // + || ch == '\u2029' // + || ch < 0xA0)) { + if (firstSpecialIndex == -1) { + firstSpecialIndex = i; + } + + specialCount++; + lastSpecialIndex = i; + lastSpecial = ch; + newcount += 4; + } + continue; + } + + boolean special = (ch < 64 && (sepcialBits & (1L << ch)) != 0) || ch == '\\'; + if (special) { + specialCount++; + lastSpecialIndex = i; + lastSpecial = ch; + + if (ch == '(' + || ch == ')' + || ch == '<' + || ch == '>' + || (ch < IOUtils.specicalFlags_doubleQuotes.length // + && IOUtils.specicalFlags_doubleQuotes[ch] == 4) // + ) { + newcount += 4; + } + + if (firstSpecialIndex == -1) { + firstSpecialIndex = i; + } + } + } + + if (specialCount > 0) { + newcount += specialCount; + if (newcount > buf.length) { + expandCapacity(newcount); + } + count = newcount; + + if (specialCount == 1) { + if (lastSpecial == '\u2028') { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = valueEnd - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = 'u'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '0'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '8'; + } else if (lastSpecial == '\u2029') { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = valueEnd - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = 'u'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '0'; + buf[++lastSpecialIndex] = '2'; + buf[++lastSpecialIndex] = '9'; + } else if (lastSpecial == '(' || lastSpecial == ')' || lastSpecial == '<' || lastSpecial == '>') { + final char ch = lastSpecial; + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = valueEnd - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + + int bufIndex = lastSpecialIndex; + buf[bufIndex++] = '\\'; + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + } else { + final char ch = lastSpecial; + if (ch < IOUtils.specicalFlags_doubleQuotes.length // + && IOUtils.specicalFlags_doubleQuotes[ch] == 4) { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 6; + int LengthOfCopy = valueEnd - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + + int bufIndex = lastSpecialIndex; + buf[bufIndex++] = '\\'; + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + } else { + int srcPos = lastSpecialIndex + 1; + int destPos = lastSpecialIndex + 2; + int LengthOfCopy = valueEnd - lastSpecialIndex - 1; + System.arraycopy(buf, srcPos, buf, destPos, LengthOfCopy); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = replaceChars[(int) ch]; + } + } + } else if (specialCount > 1) { + int textIndex = firstSpecialIndex - valueStart; + int bufIndex = firstSpecialIndex; + for (int i = textIndex; i < value.length(); ++i) { + char ch = value.charAt(i); + + if (browserSecure && (ch == '(' + || ch == ')' + || ch == '<' + || ch == '>')) { + buf[bufIndex++] = '\\'; + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + valueEnd += 5; + } else if (ch < IOUtils.specicalFlags_doubleQuotes.length // + && IOUtils.specicalFlags_doubleQuotes[ch] != 0 // + || (ch == '/' && isEnabled(SerializerFeature.WriteSlashAsSpecial))) { + buf[bufIndex++] = '\\'; + if (IOUtils.specicalFlags_doubleQuotes[ch] == 4) { + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + valueEnd += 5; + } else { + buf[bufIndex++] = replaceChars[(int) ch]; + valueEnd++; + } + } else { + if (ch == '\u2028' || ch == '\u2029') { + buf[bufIndex++] = '\\'; + buf[bufIndex++] = 'u'; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 12) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 8) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[(ch >>> 4) & 15]; + buf[bufIndex++] = IOUtils.DIGITS[ch & 15]; + valueEnd += 5; + } else { + buf[bufIndex++] = ch; + } + } + } + } + } + + + buf[count - 1] = '\"'; + } + + public void writeFieldValueStringWithDoubleQuote(char seperator, String name, String value) { + int nameLen = name.length(); + int valueLen; + + int newcount = count; + + valueLen = value.length(); + newcount += nameLen + valueLen + 6; + + if (newcount > buf.length) { + if (writer != null) { + write(seperator); + writeStringWithDoubleQuote(name, ':'); + writeStringWithDoubleQuote(value, (char) 0); + return; + } + expandCapacity(newcount); + } + + buf[count] = seperator; + + int nameStart = count + 2; + int nameEnd = nameStart + nameLen; + + buf[count + 1] = '\"'; + name.getChars(0, nameLen, buf, nameStart); + + count = newcount; + + buf[nameEnd] = '\"'; + + int index = nameEnd + 1; + buf[index++] = ':'; + buf[index++] = '"'; + + int valueStart = index; + value.getChars(0, valueLen, buf, valueStart); + buf[count - 1] = '\"'; + } + + + + public void writeFieldValue(char seperator, String name, Enum value) { + if (value == null) { + write(seperator); + writeFieldName(name); + writeNull(); + return; + } + + if (writeEnumUsingName && !writeEnumUsingToString) { + writeEnumFieldValue(seperator, name, value.name()); + } else if (writeEnumUsingToString) { + writeEnumFieldValue(seperator, name, value.toString()); + } else { + writeFieldValue(seperator, name, value.ordinal()); + } + } + + private void writeEnumFieldValue(char seperator, String name, String value) { + if (useSingleQuotes) { + writeFieldValue(seperator, name, value); + } else { + writeFieldValueStringWithDoubleQuote(seperator, name, value); + } + } + + public void writeFieldValue(char seperator, String name, BigDecimal value) { + write(seperator); + writeFieldName(name); + if (value == null) { + writeNull(); + } else { + write(value.toString()); + } + } + + public void writeString(String text, char seperator) { + if (useSingleQuotes) { + writeStringWithSingleQuote(text); + write(seperator); + } else { + writeStringWithDoubleQuote(text, seperator); + } + } + + public void writeString(String text) { + if (useSingleQuotes) { + writeStringWithSingleQuote(text); + } else { + writeStringWithDoubleQuote(text, (char) 0); + } + } + + public void writeString(char[] chars) { + if (useSingleQuotes) { + writeStringWithSingleQuote(chars); + } else { + String text = new String(chars); + writeStringWithDoubleQuote(text, (char) 0); + } + } + + protected void writeStringWithSingleQuote(String text) { + if (text == null) { + int newcount = count + 4; + if (newcount > buf.length) { + expandCapacity(newcount); + } + "null".getChars(0, 4, buf, count); + count = newcount; + return; + } + + int len = text.length(); + int newcount = count + len + 2; + if (newcount > buf.length) { + if (writer != null) { + write('\''); + for (int i = 0; i < text.length(); ++i) { + char ch = text.charAt(i); + if (ch <= 13 || ch == '\\' || ch == '\'' // + || (ch == '/' && isEnabled(SerializerFeature.WriteSlashAsSpecial))) { + write('\\'); + write(replaceChars[(int) ch]); + } else { + write(ch); + } + } + write('\''); + return; + } + expandCapacity(newcount); + } + + int start = count + 1; + int end = start + len; + + buf[count] = '\''; + text.getChars(0, len, buf, start); + count = newcount; + + int specialCount = 0; + int lastSpecialIndex = -1; + char lastSpecial = '\0'; + for (int i = start; i < end; ++i) { + char ch = buf[i]; + if (ch <= 13 || ch == '\\' || ch == '\'' // + || (ch == '/' && isEnabled(SerializerFeature.WriteSlashAsSpecial))) { + specialCount++; + lastSpecialIndex = i; + lastSpecial = ch; + } + } + + newcount += specialCount; + if (newcount > buf.length) { + expandCapacity(newcount); + } + count = newcount; + + if (specialCount == 1) { + System.arraycopy(buf, lastSpecialIndex + 1, buf, lastSpecialIndex + 2, end - lastSpecialIndex - 1); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; + } else if (specialCount > 1) { + System.arraycopy(buf, lastSpecialIndex + 1, buf, lastSpecialIndex + 2, end - lastSpecialIndex - 1); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; + end++; + for (int i = lastSpecialIndex - 2; i >= start; --i) { + char ch = buf[i]; + + if (ch <= 13 || ch == '\\' || ch == '\'' // + || (ch == '/' && isEnabled(SerializerFeature.WriteSlashAsSpecial))) { + System.arraycopy(buf, i + 1, buf, i + 2, end - i - 1); + buf[i] = '\\'; + buf[i + 1] = replaceChars[(int) ch]; + end++; + } + } + } + + buf[count - 1] = '\''; + } + + protected void writeStringWithSingleQuote(char[] chars) { + if (chars == null) { + int newcount = count + 4; + if (newcount > buf.length) { + expandCapacity(newcount); + } + "null".getChars(0, 4, buf, count); + count = newcount; + return; + } + + int len = chars.length; + int newcount = count + len + 2; + if (newcount > buf.length) { + if (writer != null) { + write('\''); + for (int i = 0; i < chars.length; ++i) { + char ch = chars[i]; + if (ch <= 13 || ch == '\\' || ch == '\'' // + || (ch == '/' && isEnabled(SerializerFeature.WriteSlashAsSpecial))) { + write('\\'); + write(replaceChars[(int) ch]); + } else { + write(ch); + } + } + write('\''); + return; + } + expandCapacity(newcount); + } + + int start = count + 1; + int end = start + len; + + buf[count] = '\''; +// text.getChars(0, len, buf, start); + System.arraycopy(chars, 0, buf, start, chars.length); + count = newcount; + + int specialCount = 0; + int lastSpecialIndex = -1; + char lastSpecial = '\0'; + for (int i = start; i < end; ++i) { + char ch = buf[i]; + if (ch <= 13 || ch == '\\' || ch == '\'' // + || (ch == '/' && isEnabled(SerializerFeature.WriteSlashAsSpecial))) { + specialCount++; + lastSpecialIndex = i; + lastSpecial = ch; + } + } + + newcount += specialCount; + if (newcount > buf.length) { + expandCapacity(newcount); + } + count = newcount; + + if (specialCount == 1) { + System.arraycopy(buf, lastSpecialIndex + 1, buf, lastSpecialIndex + 2, end - lastSpecialIndex - 1); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; + } else if (specialCount > 1) { + System.arraycopy(buf, lastSpecialIndex + 1, buf, lastSpecialIndex + 2, end - lastSpecialIndex - 1); + buf[lastSpecialIndex] = '\\'; + buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; + end++; + for (int i = lastSpecialIndex - 2; i >= start; --i) { + char ch = buf[i]; + + if (ch <= 13 || ch == '\\' || ch == '\'' // + || (ch == '/' && isEnabled(SerializerFeature.WriteSlashAsSpecial))) { + System.arraycopy(buf, i + 1, buf, i + 2, end - i - 1); + buf[i] = '\\'; + buf[i + 1] = replaceChars[(int) ch]; + end++; + } + } + } + + buf[count - 1] = '\''; + } + + public void writeFieldName(String key) { + writeFieldName(key, false); + } + + public void writeFieldName(String key, boolean checkSpecial) { + if (key == null) { + write("null:"); + return; + } + + if (useSingleQuotes) { + if (quoteFieldNames) { + writeStringWithSingleQuote(key); + write(':'); + } else { + writeKeyWithSingleQuoteIfHasSpecial(key); + } + } else { + if (quoteFieldNames) { + writeStringWithDoubleQuote(key, ':'); + } else { + boolean hashSpecial = key.length() == 0; + for (int i = 0; i < key.length(); ++i) { + char ch = key.charAt(i); + boolean special = (ch < 64 && (sepcialBits & (1L << ch)) != 0) || ch == '\\'; + if (special) { + hashSpecial = true; + break; + } + } + if (hashSpecial) { + writeStringWithDoubleQuote(key, ':'); + } else { + write(key); + write(':'); + } + } + } + } + + private void writeKeyWithSingleQuoteIfHasSpecial(String text) { + final byte[] specicalFlags_singleQuotes = IOUtils.specicalFlags_singleQuotes; + + int len = text.length(); + int newcount = count + len + 1; + if (newcount > buf.length) { + if (writer != null) { + if (len == 0) { + write('\''); + write('\''); + write(':'); + return; + } + + boolean hasSpecial = false; + for (int i = 0; i < len; ++i) { + char ch = text.charAt(i); + if (ch < specicalFlags_singleQuotes.length && specicalFlags_singleQuotes[ch] != 0) { + hasSpecial = true; + break; + } + } + + if (hasSpecial) { + write('\''); + } + for (int i = 0; i < len; ++i) { + char ch = text.charAt(i); + if (ch < specicalFlags_singleQuotes.length && specicalFlags_singleQuotes[ch] != 0) { + write('\\'); + write(replaceChars[(int) ch]); + } else { + write(ch); + } + } + if (hasSpecial) { + write('\''); + } + write(':'); + return; + } + + expandCapacity(newcount); + } + + if (len == 0) { + int newCount = count + 3; + if (newCount > buf.length) { + expandCapacity(count + 3); + } + buf[count++] = '\''; + buf[count++] = '\''; + buf[count++] = ':'; + return; + } + + int start = count; + int end = start + len; + + text.getChars(0, len, buf, start); + count = newcount; + + boolean hasSpecial = false; + + for (int i = start; i < end; ++i) { + char ch = buf[i]; + if (ch < specicalFlags_singleQuotes.length && specicalFlags_singleQuotes[ch] != 0) { + if (!hasSpecial) { + newcount += 3; + if (newcount > buf.length) { + expandCapacity(newcount); + } + count = newcount; + + System.arraycopy(buf, i + 1, buf, i + 3, end - i - 1); + System.arraycopy(buf, 0, buf, 1, i); + buf[start] = '\''; + buf[++i] = '\\'; + buf[++i] = replaceChars[(int) ch]; + end += 2; + buf[count - 2] = '\''; + + hasSpecial = true; + } else { + newcount++; + if (newcount > buf.length) { + expandCapacity(newcount); + } + count = newcount; + + System.arraycopy(buf, i + 1, buf, i + 2, end - i); + buf[i] = '\\'; + buf[++i] = replaceChars[(int) ch]; + end++; + } + } + } + + buf[newcount - 1] = ':'; + } + + public void flush() { + if (writer == null) { + return; + } + + try { + writer.write(buf, 0, count); + writer.flush(); + } catch (IOException e) { + throw new JSONException(e.getMessage(), e); + } + count = 0; + } + - /** - * The buffer where data is stored. - */ - protected char buf[]; - - /** - * The number of chars in the buffer. - */ - protected int count; - - private final static ThreadLocal bufLocal = new ThreadLocal(); - - private int features; - - public SerializeWriter() { - this.features = JSON.DEFAULT_GENERATE_FEATURE; - - buf = bufLocal.get(); // new char[1024]; - if (buf == null) { - buf = new char[1024]; - } else { - bufLocal.set(null); - } - } - - /** - * Creates a new CharArrayWriter. - */ - public SerializeWriter(SerializerFeature... features) { - buf = bufLocal.get(); // new char[1024]; - if (buf == null) { - buf = new char[1024]; - } else { - bufLocal.set(null); - } - - int featuresValue = 0; - for (SerializerFeature feature : features) { - featuresValue |= feature.getMask(); - } - this.features = featuresValue; - } - - /** - * Creates a new CharArrayWriter with the specified initial size. - * - * @param initialSize - * an int specifying the initial buffer size. - * @exception IllegalArgumentException - * if initialSize is negative - */ - public SerializeWriter(int initialSize) { - if (initialSize <= 0) { - throw new IllegalArgumentException("Negative initial size: " - + initialSize); - } - buf = new char[initialSize]; - } - - public void config(SerializerFeature feature, boolean state) { - if (state) { - features |= feature.getMask(); - } else { - features &= ~feature.getMask(); - } - } - - public boolean isEnabled(SerializerFeature feature) { - return SerializerFeature.isEnabled(this.features, feature); - } - - /** - * Writes a character to the buffer. - */ - public void write(int c) { - int newcount = count + 1; - if (newcount > buf.length) { - expandCapacity(newcount); - } - buf[count] = (char) c; - count = newcount; - } - - public void write(char c) { - int newcount = count + 1; - if (newcount > buf.length) { - expandCapacity(newcount); - } - buf[count] = c; - count = newcount; - } - - /** - * Writes characters to the buffer. - * - * @param c - * the data to be written - * @param off - * the start offset in the data - * @param len - * the number of chars that are written - */ - public void write(char c[], int off, int len) { - if (off < 0 || off > c.length || len < 0 || off + len > c.length - || off + len < 0) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return; - } - - int newcount = count + len; - if (newcount > buf.length) { - expandCapacity(newcount); - } - System.arraycopy(c, off, buf, count, len); - count = newcount; - - } - - public void expandCapacity(int minimumCapacity) { - int newCapacity = (buf.length * 3) / 2 + 1; - - if (newCapacity < minimumCapacity) { - newCapacity = minimumCapacity; - } - char newValue[] = new char[newCapacity]; - System.arraycopy(buf, 0, newValue, 0, count); - buf = newValue; - } - - /** - * Write a portion of a string to the buffer. - * - * @param str - * String to be written from - * @param off - * Offset from which to start reading characters - * @param len - * Number of characters to be written - */ - public void write(String str, int off, int len) { - int newcount = count + len; - if (newcount > buf.length) { - expandCapacity(newcount); - } - str.getChars(off, off + len, buf, count); - count = newcount; - } - - /** - * Writes the contents of the buffer to another character stream. - * - * @param out - * the output stream to write to - * @throws IOException - * If an I/O error occurs. - */ - public void writeTo(Writer out) throws IOException { - out.write(buf, 0, count); - } - - public void writeTo(OutputStream out, String charset) throws IOException { - byte[] bytes = new String(buf, 0, count).getBytes(charset); - out.write(bytes); - } - - public SerializeWriter append(CharSequence csq) { - String s = (csq == null ? "null" : csq.toString()); - write(s, 0, s.length()); - return this; - } - - public SerializeWriter append(CharSequence csq, int start, int end) { - String s = (csq == null ? "null" : csq).subSequence(start, end) - .toString(); - write(s, 0, s.length()); - return this; - } - - /** - * Appends the specified character to this writer. - *

- * An invocation of this method of the form out.append(c) behaves - * in exactly the same way as the invocation - * - *

-	 * out.write(c)
-	 * 
- * - * @param c - * The 16-bit character to append - * @return This writer - * @since 1.5 - */ - public SerializeWriter append(char c) { - write(c); - return this; - } - - /** - * Resets the buffer so that you can use it again without throwing away the - * already allocated buffer. - */ - public void reset() { - count = 0; - } - - /** - * Returns a copy of the input data. - * - * @return an array of chars copied from the input data. - */ - public char[] toCharArray() { - char[] newValue = new char[count]; - System.arraycopy(buf, 0, newValue, 0, count); - return newValue; - } - - public byte[] toBytes(String charsetName) { - if (charsetName == null) { - charsetName = "UTF-8"; - } - - Charset cs = Charset.forName(charsetName); - SerialWriterStringEncoder encoder = new SerialWriterStringEncoder(cs); - - return encoder.encode(buf, 0, count); - } - - /** - * Returns the current size of the buffer. - * - * @return an int representing the current size of the buffer. - */ - public int size() { - return count; - } - - /** - * Converts input data to a string. - * - * @return the string. - */ - public String toString() { - return new String(buf, 0, count); - } - - /** - * Flush the stream. - */ - public void flush() { - } - - /** - * Close the stream. This method does not release the buffer, since its - * contents might still be required. Note: Invoking this method in this - * class will have no effect. - */ - public void close() { - bufLocal.set(buf); - } - - public void writeBooleanArray(boolean[] array) throws IOException { - int[] sizeArray = new int[array.length]; - int totalSize = 2; - for (int i = 0; i < array.length; ++i) { - if (i != 0) { - totalSize++; - } - boolean val = array[i]; - int size; - if (val) { - size = 4; // "true".length(); - } else { - size = 5; // "false".length(); - } - sizeArray[i] = size; - totalSize += size; - } - - int newcount = count + totalSize; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - buf[count] = '['; - - int currentSize = count + 1; - for (int i = 0; i < array.length; ++i) { - if (i != 0) { - buf[currentSize++] = ','; - } - - boolean val = array[i]; - if (val) { - // System.arraycopy("true".toCharArray(), 0, buf, currentSize, - // 4); - buf[currentSize++] = 't'; - buf[currentSize++] = 'r'; - buf[currentSize++] = 'u'; - buf[currentSize++] = 'e'; - } else { - buf[currentSize++] = 'f'; - buf[currentSize++] = 'a'; - buf[currentSize++] = 'l'; - buf[currentSize++] = 's'; - buf[currentSize++] = 'e'; - } - } - buf[currentSize] = ']'; - - count = newcount; - } - - public void write(String text) { - if (text == null) { - writeNull(); - return; - } - - int length = text.length(); - int newcount = count + length; - if (newcount > buf.length) { - expandCapacity(newcount); - } - text.getChars(0, length, buf, count); - count = newcount; - return; - - } - - public void writeInt(int i) { - if (i == Integer.MIN_VALUE) { - write("-2147483648"); - return; - } - - int size = (i < 0) ? IOUtils.stringSize(-i) + 1 : IOUtils.stringSize(i); - - int newcount = count + size; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - IOUtils.getChars(i, newcount, buf); - - count = newcount; - } - - public void writeShortArray(short[] array) throws IOException { - int[] sizeArray = new int[array.length]; - int totalSize = 2; - for (int i = 0; i < array.length; ++i) { - if (i != 0) { - totalSize++; - } - short val = array[i]; - int size = IOUtils.stringSize(val); - sizeArray[i] = size; - totalSize += size; - } - - int newcount = count + totalSize; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - buf[count] = '['; - - int currentSize = count + 1; - for (int i = 0; i < array.length; ++i) { - if (i != 0) { - buf[currentSize++] = ','; - } - - short val = array[i]; - currentSize += sizeArray[i]; - IOUtils.getChars(val, currentSize, buf); - } - buf[currentSize] = ']'; - - count = newcount; - } - - public void writeByteArray(byte[] array) { - int[] sizeArray = new int[array.length]; - int totalSize = 2; - for (int i = 0; i < array.length; ++i) { - if (i != 0) { - totalSize++; - } - byte val = array[i]; - int size = IOUtils.stringSize(val); - sizeArray[i] = size; - totalSize += size; - } - - int newcount = count + totalSize; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - buf[count] = '['; - - int currentSize = count + 1; - for (int i = 0; i < array.length; ++i) { - if (i != 0) { - buf[currentSize++] = ','; - } - - byte val = array[i]; - currentSize += sizeArray[i]; - IOUtils.getChars(val, currentSize, buf); - } - buf[currentSize] = ']'; - - count = newcount; - } - - public void writeIntArray(int[] array) { - int[] sizeArray = new int[array.length]; - int totalSize = 2; - for (int i = 0; i < array.length; ++i) { - if (i != 0) { - totalSize++; - } - int val = array[i]; - int size; - if (val == Integer.MIN_VALUE) { - size = "-2147483648".length(); - } else { - size = (val < 0) ? IOUtils.stringSize(-val) + 1 : IOUtils - .stringSize(val); - } - sizeArray[i] = size; - totalSize += size; - } - - int newcount = count + totalSize; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - buf[count] = '['; - - int currentSize = count + 1; - for (int i = 0; i < array.length; ++i) { - if (i != 0) { - buf[currentSize++] = ','; - } - - int val = array[i]; - if (val == Integer.MIN_VALUE) { - System.arraycopy("-2147483648".toCharArray(), 0, buf, - currentSize, sizeArray[i]); - currentSize += sizeArray[i]; - } else { - currentSize += sizeArray[i]; - IOUtils.getChars(val, currentSize, buf); - } - } - buf[currentSize] = ']'; - - count = newcount; - } - - public void writeIntAndChar(int i, char c) { - if (i == Integer.MIN_VALUE) { - write("-2147483648"); - write(c); - return; - } - - int size = (i < 0) ? IOUtils.stringSize(-i) + 1 : IOUtils.stringSize(i); - - int newcount0 = count + size; - int newcount1 = newcount0 + 1; - - if (newcount1 > buf.length) { - expandCapacity(newcount1); - } - - IOUtils.getChars(i, newcount0, buf); - buf[newcount0] = c; - - count = newcount1; - } - - public void writeLongAndChar(long i, char c) throws IOException { - if (i == Long.MIN_VALUE) { - write("-9223372036854775808"); - write(c); - return; - } - - int size = (i < 0) ? IOUtils.stringSize(-i) + 1 : IOUtils.stringSize(i); - - int newcount0 = count + size; - int newcount1 = newcount0 + 1; - - if (newcount1 > buf.length) { - expandCapacity(newcount1); - } - - IOUtils.getChars(i, newcount0, buf); - buf[newcount0] = c; - - count = newcount1; - } - - public void writeLong(long i) { - if (i == Long.MIN_VALUE) { - write("-9223372036854775808"); - return; - } - - int size = (i < 0) ? IOUtils.stringSize(-i) + 1 : IOUtils.stringSize(i); - - int newcount = count + size; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - IOUtils.getChars(i, newcount, buf); - - count = newcount; - } - - public void writeNull() { - int newcount = count + 4; - if (newcount > buf.length) { - expandCapacity(newcount); - } - buf[count] = 'n'; - buf[count + 1] = 'u'; - buf[count + 2] = 'l'; - buf[count + 3] = 'l'; - count = newcount; - } - - public void writeLongArray(long[] array) { - int[] sizeArray = new int[array.length]; - int totalSize = 2; - for (int i = 0; i < array.length; ++i) { - if (i != 0) { - totalSize++; - } - long val = array[i]; - int size; - if (val == Long.MIN_VALUE) { - size = "-9223372036854775808".length(); - } else { - size = (val < 0) ? IOUtils.stringSize(-val) + 1 : IOUtils - .stringSize(val); - } - sizeArray[i] = size; - totalSize += size; - } - - int newcount = count + totalSize; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - buf[count] = '['; - - int currentSize = count + 1; - for (int i = 0; i < array.length; ++i) { - if (i != 0) { - buf[currentSize++] = ','; - } - - long val = array[i]; - if (val == Long.MIN_VALUE) { - System.arraycopy("-9223372036854775808".toCharArray(), 0, buf, - currentSize, sizeArray[i]); - currentSize += sizeArray[i]; - } else { - currentSize += sizeArray[i]; - IOUtils.getChars(val, currentSize, buf); - } - } - buf[currentSize] = ']'; - - count = newcount; - } - - private void writeStringWithDoubleQuote(String text) { - // final boolean[] specicalFlags_doubleQuotes = - // CharTypes.specicalFlags_doubleQuotes; - // final int len_flags = specicalFlags_doubleQuotes.length; - - if (text == null) { - writeNull(); - return; - } - - int len = text.length(); - int newcount = count + len + 2; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - int start = count + 1; - int end = start + len; - - buf[count] = '\"'; - text.getChars(0, len, buf, start); - - count = newcount; - - int specialCount = 0; - int lastSpecialIndex = -1; - char lastSpecial = '\0'; - for (int i = start; i < end; ++i) { - char ch = buf[i]; - if (ch == '\b' || ch == '\n' - || ch == '\r' - || ch == '\f' - || ch == '\\' - || ch == '"' // - || (ch == '\t' && isEnabled(SerializerFeature.WriteTabAsSpecial))) { - specialCount++; - lastSpecialIndex = i; - lastSpecial = ch; - } - } - - newcount += specialCount; - if (newcount > buf.length) { - expandCapacity(newcount); - } - count = newcount; - - if (specialCount == 1) { - System.arraycopy(buf, lastSpecialIndex + 1, buf, - lastSpecialIndex + 2, end - lastSpecialIndex - 1); - buf[lastSpecialIndex] = '\\'; - buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; - } else if (specialCount > 1) { - System.arraycopy(buf, lastSpecialIndex + 1, buf, - lastSpecialIndex + 2, end - lastSpecialIndex - 1); - buf[lastSpecialIndex] = '\\'; - buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; - end++; - for (int i = lastSpecialIndex - 2; i >= start; --i) { - char ch = buf[i]; - - if (ch == '\b' || ch == '\n' - || ch == '\r' - || ch == '\f' - || ch == '\\' - || ch == '"' // - || (ch == '\t' && isEnabled(SerializerFeature.WriteTabAsSpecial))) { - System.arraycopy(buf, i + 1, buf, i + 2, end - i - 1); - buf[i] = '\\'; - buf[i + 1] = replaceChars[(int) ch]; - end++; - } - } - } - - buf[count - 1] = '\"'; - } - - public void writeKeyWithDoubleQuote(String text) { - final boolean[] specicalFlags_doubleQuotes = CharTypes.specicalFlags_doubleQuotes; - - int len = text.length(); - int newcount = count + len + 3; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - int start = count + 1; - int end = start + len; - - buf[count] = '\"'; - text.getChars(0, len, buf, start); - - count = newcount; - - for (int i = start; i < end; ++i) { - char ch = buf[i]; - if (ch < specicalFlags_doubleQuotes.length - && specicalFlags_doubleQuotes[ch] // - || (ch == '\t' && isEnabled(SerializerFeature.WriteTabAsSpecial))) { - newcount++; - if (newcount > buf.length) { - expandCapacity(newcount); - } - count = newcount; - - System.arraycopy(buf, i + 1, buf, i + 2, end - i - 1); - buf[i] = '\\'; - buf[++i] = replaceChars[(int) ch]; - end++; - } - } - - buf[count - 2] = '\"'; - buf[count - 1] = ':'; - } - - public void writeFieldNull(char seperator, String name) { - write(seperator); - writeFieldName(name); - writeNull(); - } - - public void writeFieldNullString(char seperator, String name) { - write(seperator); - writeFieldName(name); - if (isEnabled(SerializerFeature.WriteNullStringAsEmpty)) { - writeString(""); - } else { - writeNull(); - } - } - - public void writeFieldNullBoolean(char seperator, String name) { - write(seperator); - writeFieldName(name); - if (isEnabled(SerializerFeature.WriteNullBooleanAsFalse)) { - write("false"); - } else { - writeNull(); - } - } - - public void writeFieldNullList(char seperator, String name) { - write(seperator); - writeFieldName(name); - if (isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - write("[]"); - } else { - writeNull(); - } - } - - public void writeFieldNullNumber(char seperator, String name) { - write(seperator); - writeFieldName(name); - if (isEnabled(SerializerFeature.WriteNullNumberAsZero)) { - write('0'); - } else { - writeNull(); - } - } - - public void writeFieldValue(char seperator, String name, char value) { - write(seperator); - writeFieldName(name); - if (value == 0) { - writeString("\u0000"); - } else { - writeString(Character.toString(value)); - } - } - - public void writeFieldValue(char seperator, String name, boolean value) { - write(seperator); - writeFieldName(name); - if (value) { - write("true"); - } else { - write("false"); - } - } - - public void writeFieldValue(char seperator, String name, int value) { - write(seperator); - writeFieldName(name); - writeInt(value); - } - - public void writeFieldValue(char seperator, String name, long value) { - write(seperator); - writeFieldName(name); - writeLong(value); - } - - public void writeFieldValue(char seperator, String name, float value) { - write(seperator); - writeFieldName(name); - if (value == 0) { - write('0'); - } else if (Float.isNaN(value)) { - writeNull(); - } else if (Float.isInfinite(value)) { - writeNull(); - } else { - String text = Float.toString(value); - if (text.endsWith(".0")) { - text = text.substring(0, text.length() - 2); - } - write(text); - } - } - - public void writeFieldValue(char seperator, String name, double value) { - write(seperator); - writeFieldName(name); - if (value == 0) { - write('0'); - } else if (Double.isNaN(value)) { - writeNull(); - } else if (Double.isInfinite(value)) { - writeNull(); - } else { - String text = Double.toString(value); - if (text.endsWith(".0")) { - text = text.substring(0, text.length() - 2); - } - write(text); - } - } - - public void writeFieldValue(char seperator, String name, String value) { - if (isEnabled(SerializerFeature.QuoteFieldNames)) { - if (isEnabled(SerializerFeature.UseSingleQuotes)) { - write(seperator); - writeFieldName(name); - if (value == null) { - writeNull(); - } else { - writeString(value); - } - } else { - writeFieldValueStringWithDoubleQuote(seperator, name, value); - } - } else { - write(seperator); - writeFieldName(name); - if (value == null) { - writeNull(); - } else { - writeString(value); - } - } - } - - private void writeFieldValueStringWithDoubleQuote(char seperator, - String name, String value) { - int nameLen = name.length(); - int valueLen; - - int newcount = count; - - if (value == null) { - valueLen = 4; - newcount += nameLen + 8; - } else { - valueLen = value.length(); - newcount += nameLen + valueLen + 6; - } - - if (newcount > buf.length) { - expandCapacity(newcount); - } - - buf[count] = seperator; - - int nameStart = count + 2; - int nameEnd = nameStart + nameLen; - - buf[count + 1] = '\"'; - name.getChars(0, nameLen, buf, nameStart); - - count = newcount; - - int specialCount = 0; - int lastSpecialIndex = -1; - char lastSpecial = '\0'; - for (int i = nameStart; i < nameEnd; ++i) { - char ch = buf[i]; - if (ch == '\b' || ch == '\n' - || ch == '\r' - || ch == '\f' - || ch == '\\' - || ch == '"' // - || (ch == '\t' && isEnabled(SerializerFeature.WriteTabAsSpecial))) { - specialCount++; - lastSpecialIndex = i; - lastSpecial = ch; - } - } - - if (specialCount > 0) { - newcount += specialCount; - if (newcount > buf.length) { - expandCapacity(newcount); - } - count = newcount; - } - - if (specialCount == 1) { - System.arraycopy(buf, lastSpecialIndex + 1, buf, - lastSpecialIndex + 2, nameEnd - lastSpecialIndex - 1); - buf[lastSpecialIndex] = '\\'; - buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; - nameEnd++; - } else if (specialCount > 1) { - System.arraycopy(buf, lastSpecialIndex + 1, buf, - lastSpecialIndex + 2, nameEnd - lastSpecialIndex - 1); - buf[lastSpecialIndex] = '\\'; - buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; - nameEnd++; - for (int i = lastSpecialIndex - 2; i >= nameStart; --i) { - char ch = buf[i]; - - if (ch == '\b' || ch == '\n' - || ch == '\r' - || ch == '\f' - || ch == '\\' - || ch == '"' // - || (ch == '\t' && isEnabled(SerializerFeature.WriteTabAsSpecial))) { - System.arraycopy(buf, i + 1, buf, i + 2, nameEnd - i - 1); - buf[i] = '\\'; - buf[i + 1] = replaceChars[(int) ch]; - nameEnd++; - } - } - } - - buf[nameEnd] = '\"'; - - int index = nameEnd + 1; - buf[index++] = ':'; - - if (value == null) { - buf[index++] = 'n'; - buf[index++] = 'u'; - buf[index++] = 'l'; - buf[index++] = 'l'; - return; - } - - buf[index++] = '"'; - - int valueStart = index; - int valueEnd = valueStart + valueLen; - - value.getChars(0, valueLen, buf, valueStart); - - specialCount = 0; - lastSpecialIndex = -1; - lastSpecial = '\0'; - for (int i = valueStart; i < valueEnd; ++i) { - char ch = buf[i]; - if (ch == '\b' || ch == '\n' - || ch == '\r' - || ch == '\f' - || ch == '\\' - || ch == '"' // - || (ch == '\t' && isEnabled(SerializerFeature.WriteTabAsSpecial))) { - specialCount++; - lastSpecialIndex = i; - lastSpecial = ch; - } - } - - if (specialCount > 0) { - newcount += specialCount; - if (newcount > buf.length) { - expandCapacity(newcount); - } - count = newcount; - } - - if (specialCount == 1) { - System.arraycopy(buf, lastSpecialIndex + 1, buf, - lastSpecialIndex + 2, valueEnd - lastSpecialIndex - 1); - buf[lastSpecialIndex] = '\\'; - buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; - } else if (specialCount > 1) { - System.arraycopy(buf, lastSpecialIndex + 1, buf, - lastSpecialIndex + 2, valueEnd - lastSpecialIndex - 1); - buf[lastSpecialIndex] = '\\'; - buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; - valueEnd++; - for (int i = lastSpecialIndex - 2; i >= valueStart; --i) { - char ch = buf[i]; - - if (ch == '\b' || ch == '\n' - || ch == '\r' - || ch == '\f' - || ch == '\\' - || ch == '"' // - || (ch == '\t' && isEnabled(SerializerFeature.WriteTabAsSpecial))) { - System.arraycopy(buf, i + 1, buf, i + 2, valueEnd - i - 1); - buf[i] = '\\'; - buf[i + 1] = replaceChars[(int) ch]; - valueEnd++; - } - } - } - - buf[count - 1] = '\"'; - } - - // writeStringWithSingleQuote - - public void writeFieldValue(char seperator, String name, Enum value) { - write(seperator); - writeFieldName(name); - if (value == null) { - writeNull(); - } else { - if (isEnabled(SerializerFeature.WriteEnumUsingToString)) { - writeString(value.name()); - } else { - writeInt(value.ordinal()); - } - } - } - - public void writeFieldValue(char seperator, String name, BigDecimal value) { - write(seperator); - writeFieldName(name); - if (value == null) { - writeNull(); - } else { - write(value.toString()); - } - } - - public void writeString(String text, char seperator) { - writeString(text); - write(seperator); - } - - public void writeString(String text) { - if (isEnabled(SerializerFeature.UseSingleQuotes)) { - writeStringWithSingleQuote(text); - } else { - writeStringWithDoubleQuote(text); - } - } - - private void writeStringWithSingleQuote(String text) { - if (text == null) { - int newcount = count + 4; - if (newcount > buf.length) { - expandCapacity(newcount); - } - "null".getChars(0, 4, buf, count); - count = newcount; - return; - } - - int len = text.length(); - int newcount = count + len + 2; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - int start = count + 1; - int end = start + len; - - buf[count] = '\''; - text.getChars(0, len, buf, start); - count = newcount; - - int specialCount = 0; - int lastSpecialIndex = -1; - char lastSpecial = '\0'; - for (int i = start; i < end; ++i) { - char ch = buf[i]; - if (ch == '\b' || ch == '\n' - || ch == '\r' - || ch == '\f' - || ch == '\\' - || ch == '\'' // - || (ch == '\t' && isEnabled(SerializerFeature.WriteTabAsSpecial))) { - specialCount++; - lastSpecialIndex = i; - lastSpecial = ch; - } - } - - newcount += specialCount; - if (newcount > buf.length) { - expandCapacity(newcount); - } - count = newcount; - - if (specialCount == 1) { - System.arraycopy(buf, lastSpecialIndex + 1, buf, - lastSpecialIndex + 2, end - lastSpecialIndex - 1); - buf[lastSpecialIndex] = '\\'; - buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; - } else if (specialCount > 1) { - System.arraycopy(buf, lastSpecialIndex + 1, buf, - lastSpecialIndex + 2, end - lastSpecialIndex - 1); - buf[lastSpecialIndex] = '\\'; - buf[++lastSpecialIndex] = replaceChars[(int) lastSpecial]; - end++; - for (int i = lastSpecialIndex - 2; i >= start; --i) { - char ch = buf[i]; - - if (ch == '\b' || ch == '\n' - || ch == '\r' - || ch == '\f' - || ch == '\\' - || ch == '\'' // - || (ch == '\t' && isEnabled(SerializerFeature.WriteTabAsSpecial))) { - System.arraycopy(buf, i + 1, buf, i + 2, end - i - 1); - buf[i] = '\\'; - buf[i + 1] = replaceChars[(int) ch]; - end++; - } - } - } - - buf[count - 1] = '\''; - } - - public void writeFieldName(String key) { - if (isEnabled(SerializerFeature.UseSingleQuotes)) { - if (isEnabled(SerializerFeature.QuoteFieldNames)) { - writeKeyWithSingleQuote(key); - } else { - writeKeyWithSingleQuoteIfHasSpecial(key); - } - } else { - if (isEnabled(SerializerFeature.QuoteFieldNames)) { - writeKeyWithDoubleQuote(key); - } else { - writeKeyWithDoubleQuoteIfHasSpecial(key); - } - } - } - - private void writeKeyWithSingleQuote(String text) { - final boolean[] specicalFlags_singleQuotes = CharTypes.specicalFlags_singleQuotes; - - int len = text.length(); - int newcount = count + len + 3; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - int start = count + 1; - int end = start + len; - - buf[count] = '\''; - text.getChars(0, len, buf, start); - count = newcount; - - for (int i = start; i < end; ++i) { - char ch = buf[i]; - if (ch < specicalFlags_singleQuotes.length - && specicalFlags_singleQuotes[ch] // - || (ch == '\t' && isEnabled(SerializerFeature.WriteTabAsSpecial))) { - newcount++; - if (newcount > buf.length) { - expandCapacity(newcount); - } - count = newcount; - - System.arraycopy(buf, i + 1, buf, i + 2, end - i - 1); - buf[i] = '\\'; - buf[++i] = replaceChars[(int) ch]; - end++; - } - } - - buf[count - 2] = '\''; - buf[count - 1] = ':'; - } - - private void writeKeyWithDoubleQuoteIfHasSpecial(String text) { - final boolean[] specicalFlags_doubleQuotes = CharTypes.specicalFlags_doubleQuotes; - - int len = text.length(); - int newcount = count + len + 1; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - int start = count; - int end = start + len; - - text.getChars(0, len, buf, start); - count = newcount; - - boolean hasSpecial = false; - - for (int i = start; i < end; ++i) { - char ch = buf[i]; - if (ch < specicalFlags_doubleQuotes.length - && specicalFlags_doubleQuotes[ch]) { - if (!hasSpecial) { - newcount += 3; - if (newcount > buf.length) { - expandCapacity(newcount); - } - count = newcount; - - System.arraycopy(buf, i + 1, buf, i + 3, end - i - 1); - System.arraycopy(buf, 0, buf, 1, i); - buf[start] = '"'; - buf[++i] = '\\'; - buf[++i] = replaceChars[(int) ch]; - end += 2; - buf[count - 2] = '"'; - - hasSpecial = true; - } else { - newcount++; - if (newcount > buf.length) { - expandCapacity(newcount); - } - count = newcount; - - System.arraycopy(buf, i + 1, buf, i + 2, end - i); - buf[i] = '\\'; - buf[++i] = replaceChars[(int) ch]; - end++; - } - } - } - - buf[count - 1] = ':'; - } - - private void writeKeyWithSingleQuoteIfHasSpecial(String text) { - final boolean[] specicalFlags_singleQuotes = CharTypes.specicalFlags_singleQuotes; - - int len = text.length(); - int newcount = count + len + 1; - if (newcount > buf.length) { - expandCapacity(newcount); - } - - int start = count; - int end = start + len; - - text.getChars(0, len, buf, start); - count = newcount; - - boolean hasSpecial = false; - - for (int i = start; i < end; ++i) { - char ch = buf[i]; - if (ch < specicalFlags_singleQuotes.length - && specicalFlags_singleQuotes[ch]) { - if (!hasSpecial) { - newcount += 3; - if (newcount > buf.length) { - expandCapacity(newcount); - } - count = newcount; - - System.arraycopy(buf, i + 1, buf, i + 3, end - i - 1); - System.arraycopy(buf, 0, buf, 1, i); - buf[start] = '\''; - buf[++i] = '\\'; - buf[++i] = replaceChars[(int) ch]; - end += 2; - buf[count - 2] = '\''; - - hasSpecial = true; - } else { - newcount++; - if (newcount > buf.length) { - expandCapacity(newcount); - } - count = newcount; - - System.arraycopy(buf, i + 1, buf, i + 2, end - i); - buf[i] = '\\'; - buf[++i] = replaceChars[(int) ch]; - end++; - } - } - } - - buf[newcount - 1] = ':'; - } } diff --git a/src/main/java/com/alibaba/fastjson/serializer/SerializerFeature.java b/src/main/java/com/alibaba/fastjson/serializer/SerializerFeature.java old mode 100644 new mode 100755 index c657ddf3dc..0ef96489ba --- a/src/main/java/com/alibaba/fastjson/serializer/SerializerFeature.java +++ b/src/main/java/com/alibaba/fastjson/serializer/SerializerFeature.java @@ -1,89 +1,213 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -/** - * @author wenshao - */ -public enum SerializerFeature { - QuoteFieldNames, - /** - * - */ - UseSingleQuotes, - /** - * - */ - WriteMapNullValue, - /** - * - */ - WriteEnumUsingToString, - /** - * - */ - UseISO8601DateFormat, - /** - * @since 1.1 - */ - WriteNullListAsEmpty, - /** - * @since 1.1 - */ - WriteNullStringAsEmpty, - /** - * @since 1.1 - */ - WriteNullNumberAsZero, - /** - * @since 1.1 - */ - WriteNullBooleanAsFalse, - /** - * @since 1.1 - */ - SkipTransientField, - /** - * @since 1.1 - */ - SortField, - /** - * @since 1.1.1 - */ - WriteTabAsSpecial, - /** - * @since 1.1.2 - */ - PrettyFormat, - /** - * @since 1.1.2 - */ - WriteClassName; - - private SerializerFeature(){ - mask = (1 << ordinal()); - } - - private final int mask; - - public final int getMask() { - return mask; - } - - public static boolean isEnabled(int features, SerializerFeature feature) { - return (features & feature.getMask()) != 0; - } -} +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public enum SerializerFeature { + QuoteFieldNames, + /** + * + */ + UseSingleQuotes, + /** + * + */ + WriteMapNullValue, + /** + * 用枚举toString()值输出 + */ + WriteEnumUsingToString, + /** + * 用枚举name()输出 + */ + WriteEnumUsingName, + /** + * + */ + UseISO8601DateFormat, + /** + * @since 1.1 + */ + WriteNullListAsEmpty, + /** + * @since 1.1 + */ + WriteNullStringAsEmpty, + /** + * @since 1.1 + */ + WriteNullNumberAsZero, + /** + * @since 1.1 + */ + WriteNullBooleanAsFalse, + /** + * @since 1.1 + */ + SkipTransientField, + /** + * @since 1.1 + */ + SortField, + /** + * @since 1.1.1 + */ + @Deprecated + WriteTabAsSpecial, + /** + * @since 1.1.2 + */ + PrettyFormat, + /** + * @since 1.1.2 + */ + WriteClassName, + + /** + * @since 1.1.6 + */ + DisableCircularReferenceDetect, // 32768 + + /** + * @since 1.1.9 + */ + WriteSlashAsSpecial, + + /** + * @since 1.1.10 + */ + BrowserCompatible, + + /** + * @since 1.1.14 + */ + WriteDateUseDateFormat, + + /** + * @since 1.1.15 + */ + NotWriteRootClassName, + + /** + * @since 1.1.19 + * @deprecated + */ + DisableCheckSpecialChar, + + /** + * @since 1.1.35 + */ + BeanToArray, + + /** + * @since 1.1.37 + */ + WriteNonStringKeyAsString, + + /** + * @since 1.1.42 + */ + NotWriteDefaultValue, + + /** + * @since 1.2.6 + */ + BrowserSecure, + + /** + * @since 1.2.7 + */ + IgnoreNonFieldGetter, + + /** + * @since 1.2.9 + */ + WriteNonStringValueAsString, + + /** + * @since 1.2.11 + */ + IgnoreErrorGetter, + + /** + * @since 1.2.16 + */ + WriteBigDecimalAsPlain, + + /** + * @since 1.2.27 + */ + MapSortField; + + SerializerFeature(){ + mask = (1 << ordinal()); + } + + public final int mask; + + public final int getMask() { + return mask; + } + + public static boolean isEnabled(int features, SerializerFeature feature) { + return (features & feature.mask) != 0; + } + + public static boolean isEnabled(int features, int fieaturesB, SerializerFeature feature) { + int mask = feature.mask; + + return (features & mask) != 0 || (fieaturesB & mask) != 0; + } + + public static int config(int features, SerializerFeature feature, boolean state) { + if (state) { + features |= feature.mask; + } else { + features &= ~feature.mask; + } + + return features; + } + + public static int of(SerializerFeature[] features) { + if (features == null) { + return 0; + } + + int value = 0; + + for (SerializerFeature feature: features) { + value |= feature.mask; + } + + return value; + } + + public final static SerializerFeature[] EMPTY = new SerializerFeature[0]; + + /** + * whether should skip null fields in a bean object + */ + public static final int WRITE_BEAN_NULL_FEATURES + = WriteMapNullValue.getMask() + | WriteNullBooleanAsFalse.getMask() + | WriteNullListAsEmpty.getMask() + | WriteNullNumberAsZero.getMask() + | WriteNullStringAsEmpty.getMask() + ; +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ShortArraySerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ShortArraySerializer.java deleted file mode 100644 index 5218d9c4d9..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/ShortArraySerializer.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class ShortArraySerializer implements ObjectSerializer { - - public static ShortArraySerializer instance = new ShortArraySerializer(); - - public final void write(JSONSerializer serializer, Object object) throws IOException { - SerializeWriter out = serializer.getWriter(); - - if (object == null) { - if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) { - out.write("[]"); - } else { - out.writeNull(); - } - return; - } - - short[] array = (short[]) object; - out.writeShortArray(array); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/SimpleDateFormatSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/SimpleDateFormatSerializer.java old mode 100644 new mode 100755 index a6c84215ef..94cdd2bfd4 --- a/src/main/java/com/alibaba/fastjson/serializer/SimpleDateFormatSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/SimpleDateFormatSerializer.java @@ -1,6 +1,7 @@ package com.alibaba.fastjson.serializer; import java.io.IOException; +import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.Date; @@ -12,14 +13,15 @@ public SimpleDateFormatSerializer(String pattern){ this.pattern = pattern; } - public void write(JSONSerializer serializer, Object object) throws IOException { + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { if (object == null) { - serializer.getWriter().writeNull(); + serializer.out.writeNull(); return; } Date date = (Date) object; - SimpleDateFormat format = new SimpleDateFormat(pattern); + SimpleDateFormat format = new SimpleDateFormat(pattern, serializer.locale); + format.setTimeZone(serializer.timeZone); String text = format.format(date); serializer.write(text); diff --git a/src/main/java/com/alibaba/fastjson/serializer/SimplePropertyPreFilter.java b/src/main/java/com/alibaba/fastjson/serializer/SimplePropertyPreFilter.java new file mode 100755 index 0000000000..fc55e773a4 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/SimplePropertyPreFilter.java @@ -0,0 +1,100 @@ +package com.alibaba.fastjson.serializer; + +import java.util.HashSet; +import java.util.Set; + +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class SimplePropertyPreFilter implements PropertyPreFilter { + + private final Class clazz; + private final Set includes = new HashSet(); + private final Set excludes = new HashSet(); + private int maxLevel = 0; + + public SimplePropertyPreFilter(String... properties){ + this(null, properties); + } + + public SimplePropertyPreFilter(Class clazz, String... properties){ + super(); + this.clazz = clazz; + for (String item : properties) { + if (item != null) { + this.includes.add(item); + } + } + } + + /** + * @since 1.2.9 + */ + public int getMaxLevel() { + return maxLevel; + } + + /** + * @since 1.2.9 + */ + public void setMaxLevel(int maxLevel) { + this.maxLevel = maxLevel; + } + + public Class getClazz() { + return clazz; + } + + public Set getIncludes() { + return includes; + } + + public Set getExcludes() { + return excludes; + } + + public boolean apply(JSONSerializer serializer, Object source, String name) { + if (source == null) { + return true; + } + + if (clazz != null && !clazz.isInstance(source)) { + return true; + } + + if (this.excludes.contains(name)) { + return false; + } + + if (maxLevel > 0) { + int level = 0; + SerialContext context = serializer.context; + while (context != null) { + level++; + if (level > maxLevel) { + return false; + } + context = context.parent; + } + } + + if (includes.size() == 0 || includes.contains(name)) { + return true; + } + + return false; + } + +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/StringCodec.java b/src/main/java/com/alibaba/fastjson/serializer/StringCodec.java new file mode 100755 index 0000000000..693670f17a --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/StringCodec.java @@ -0,0 +1,117 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class StringCodec implements ObjectSerializer, ObjectDeserializer { + + public static StringCodec instance = new StringCodec(); + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) + throws IOException { + write(serializer, (String) object); + } + + public void write(JSONSerializer serializer, String value) { + SerializeWriter out = serializer.out; + + if (value == null) { + out.writeNull(SerializerFeature.WriteNullStringAsEmpty); + return; + } + + out.writeString(value); + } + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) { + if (clazz == StringBuffer.class) { + final JSONLexer lexer = parser.lexer; + if (lexer.token() == JSONToken.LITERAL_STRING) { + String val = lexer.stringVal(); + lexer.nextToken(JSONToken.COMMA); + + return (T) new StringBuffer(val); + } + + Object value = parser.parse(); + + if (value == null) { + return null; + } + + return (T) new StringBuffer(value.toString()); + } + + if (clazz == StringBuilder.class) { + final JSONLexer lexer = parser.lexer; + if (lexer.token() == JSONToken.LITERAL_STRING) { + String val = lexer.stringVal(); + lexer.nextToken(JSONToken.COMMA); + + return (T) new StringBuilder(val); + } + + Object value = parser.parse(); + + if (value == null) { + return null; + } + + return (T) new StringBuilder(value.toString()); + } + + return (T) deserialze(parser); + } + + @SuppressWarnings("unchecked") + public static T deserialze(DefaultJSONParser parser) { + final JSONLexer lexer = parser.getLexer(); + if (lexer.token() == JSONToken.LITERAL_STRING) { + String val = lexer.stringVal(); + lexer.nextToken(JSONToken.COMMA); + return (T) val; + } + + if (lexer.token() == JSONToken.LITERAL_INT) { + String val = lexer.numberString(); + lexer.nextToken(JSONToken.COMMA); + return (T) val; + } + + Object value = parser.parse(); + + if (value == null) { + return null; + } + + return (T) value.toString(); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_STRING; + } +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/StringSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/StringSerializer.java deleted file mode 100644 index 08cdcf5d8d..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/StringSerializer.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class StringSerializer implements ObjectSerializer { - - public static StringSerializer instance = new StringSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - write(serializer, (String) object); - } - - public void write(JSONSerializer serializer, String value) { - SerializeWriter out = serializer.getWriter(); - - if (value == null) { - if (out.isEnabled(SerializerFeature.WriteNullStringAsEmpty)) { - out.writeString(""); - } else { - out.writeNull(); - } - return; - } - - out.writeString(value); - } -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/TimeZoneSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/TimeZoneSerializer.java deleted file mode 100644 index 74de843747..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/TimeZoneSerializer.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.TimeZone; - -public class TimeZoneSerializer implements ObjectSerializer { - - public final static TimeZoneSerializer instance = new TimeZoneSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - if (object == null) { - serializer.writeNull(); - return; - } - - TimeZone timeZone = (TimeZone) object; - serializer.write(timeZone.getID()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ToStringSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/ToStringSerializer.java new file mode 100644 index 0000000000..c130b1a850 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/serializer/ToStringSerializer.java @@ -0,0 +1,24 @@ +package com.alibaba.fastjson.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; + +public class ToStringSerializer implements ObjectSerializer { + + public static final ToStringSerializer instance = new ToStringSerializer(); + + @Override + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, + int features) throws IOException { + SerializeWriter out = serializer.out; + + if (object == null) { + out.writeNull(); + return; + } + + String strVal = object.toString(); + out.writeString(strVal); + } + +} diff --git a/src/main/java/com/alibaba/fastjson/serializer/URISerializer.java b/src/main/java/com/alibaba/fastjson/serializer/URISerializer.java deleted file mode 100644 index 8dd391d07d..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/URISerializer.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.net.URI; - -/** - * @author wenshao - */ -public class URISerializer implements ObjectSerializer { - - public final static URISerializer instance = new URISerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - if (object == null) { - serializer.writeNull(); - return; - } - - URI uri = (URI) object; - serializer.write(uri.toString()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/URLSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/URLSerializer.java deleted file mode 100644 index 40df3bce93..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/URLSerializer.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; - -/** - * @author wenshao - */ -public class URLSerializer implements ObjectSerializer { - - public final static URLSerializer instance = new URLSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - if (object == null) { - serializer.writeNull(); - return; - } - - serializer.write(object.toString()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/UUIDSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/UUIDSerializer.java deleted file mode 100644 index 2621d87418..0000000000 --- a/src/main/java/com/alibaba/fastjson/serializer/UUIDSerializer.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.alibaba.fastjson.serializer; - -import java.io.IOException; -import java.util.UUID; - -public class UUIDSerializer implements ObjectSerializer { - - public final static UUIDSerializer instance = new UUIDSerializer(); - - public void write(JSONSerializer serializer, Object object) throws IOException { - if (object == null) { - serializer.writeNull(); - return; - } - - UUID uid = (UUID) object; - serializer.write(uid.toString()); - } - -} diff --git a/src/main/java/com/alibaba/fastjson/serializer/ValueFilter.java b/src/main/java/com/alibaba/fastjson/serializer/ValueFilter.java old mode 100644 new mode 100755 index 5ca67a6c11..b63206b55b --- a/src/main/java/com/alibaba/fastjson/serializer/ValueFilter.java +++ b/src/main/java/com/alibaba/fastjson/serializer/ValueFilter.java @@ -1,6 +1,21 @@ +/* + * Copyright 1999-2018 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.fastjson.serializer; -public interface ValueFilter { +public interface ValueFilter extends SerializeFilter { - Object process(Object source, String name, Object value); + Object process(Object object, String name, Object value); } diff --git a/src/main/java/com/alibaba/fastjson/support/config/FastJsonConfig.java b/src/main/java/com/alibaba/fastjson/support/config/FastJsonConfig.java new file mode 100644 index 0000000000..c3666f757c --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/config/FastJsonConfig.java @@ -0,0 +1,217 @@ + +package com.alibaba.fastjson.support.config; + +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.util.IOUtils; + +import java.nio.charset.Charset; +import java.util.Map; +import java.util.Map.Entry; + +/** + * Config for FastJson. + * + * @author VictorZeng + * @see SerializeConfig + * @see ParserConfig + * @see SerializerFeature + * @see SerializeFilter + * @see Feature + * @since 1.2.11 + */ + +public class FastJsonConfig { + + /** + * default charset + */ + private Charset charset; + + /** + * serializeConfig + */ + private SerializeConfig serializeConfig; + + /** + * parserConfig + */ + private ParserConfig parserConfig; + + /** + * serializerFeatures + */ + private SerializerFeature[] serializerFeatures; + + /** + * serializeFilters + */ + private SerializeFilter[] serializeFilters; + + /** + * features + */ + private Feature[] features; + + /** + * class level serializeFilter + */ + private Map, SerializeFilter> classSerializeFilters; + + /** + * format date type + */ + private String dateFormat; + + protected boolean writeContentLength = true; + + /** + * init param. + */ + public FastJsonConfig() { + + this.charset = Charset.forName("UTF-8"); + + this.serializeConfig = SerializeConfig.getGlobalInstance(); + this.parserConfig = new ParserConfig(); + + this.serializerFeatures = new SerializerFeature[] { + SerializerFeature.BrowserSecure + }; + + this.serializeFilters = new SerializeFilter[0]; + this.features = new Feature[0]; + } + + /** + * @return the serializeConfig + */ + public SerializeConfig getSerializeConfig() { + return serializeConfig; + } + + /** + * @param serializeConfig the serializeConfig to set + */ + public void setSerializeConfig(SerializeConfig serializeConfig) { + this.serializeConfig = serializeConfig; + } + + /** + * @return the parserConfig + */ + public ParserConfig getParserConfig() { + return parserConfig; + } + + /** + * @param parserConfig the parserConfig to set + */ + public void setParserConfig(ParserConfig parserConfig) { + this.parserConfig = parserConfig; + } + + /** + * @return the serializerFeatures + */ + public SerializerFeature[] getSerializerFeatures() { + return serializerFeatures; + } + + /** + * @param serializerFeatures the serializerFeatures to set + */ + public void setSerializerFeatures(SerializerFeature... serializerFeatures) { + this.serializerFeatures = serializerFeatures; + } + + /** + * @return the serializeFilters + */ + public SerializeFilter[] getSerializeFilters() { + return serializeFilters; + } + + /** + * @param serializeFilters the serializeFilters to set + */ + public void setSerializeFilters(SerializeFilter... serializeFilters) { + this.serializeFilters = serializeFilters; + } + + /** + * @return the features + */ + public Feature[] getFeatures() { + return features; + } + + /** + * @param features the features to set + */ + public void setFeatures(Feature... features) { + this.features = features; + } + + /** + * @return the classSerializeFilters + */ + public Map, SerializeFilter> getClassSerializeFilters() { + return classSerializeFilters; + } + + /** + * @param classSerializeFilters the classSerializeFilters to set + */ + public void setClassSerializeFilters( + Map, SerializeFilter> classSerializeFilters) { + + if (classSerializeFilters == null) + return; + + for (Entry, SerializeFilter> entry : classSerializeFilters.entrySet()) + + this.serializeConfig.addFilter(entry.getKey(), entry.getValue()); + + this.classSerializeFilters = classSerializeFilters; + } + + /** + * @return the dateFormat + */ + public String getDateFormat() { + return dateFormat; + } + + /** + * @param dateFormat the dateFormat to set + */ + public void setDateFormat(String dateFormat) { + this.dateFormat = dateFormat; + } + + /** + * @return the charset + */ + public Charset getCharset() { + return charset; + } + + /** + * @param charset the charset to set + */ + public void setCharset(Charset charset) { + this.charset = charset; + } + + public boolean isWriteContentLength() { + return writeContentLength; + } + + public void setWriteContentLength(boolean writeContentLength) { + this.writeContentLength = writeContentLength; + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/hsf/HSFJSONUtils.java b/src/main/java/com/alibaba/fastjson/support/hsf/HSFJSONUtils.java new file mode 100644 index 0000000000..5c63ca5ad2 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/hsf/HSFJSONUtils.java @@ -0,0 +1,120 @@ +package com.alibaba.fastjson.support.hsf; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.*; +import com.alibaba.fastjson.util.TypeUtils; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; + +import static com.alibaba.fastjson.parser.JSONLexer.NOT_MATCH_NAME; + +public class HSFJSONUtils { + final static SymbolTable typeSymbolTable = new SymbolTable(1024); + final static char[] fieldName_argsTypes = "\"argsTypes\"".toCharArray(); + final static char[] fieldName_argsObjs = "\"argsObjs\"".toCharArray(); + + final static char[] fieldName_type = "\"@type\":".toCharArray(); + + public static Object[] parseInvocationArguments(String json, MethodLocator methodLocator) { + DefaultJSONParser parser = new DefaultJSONParser(json); + + JSONLexerBase lexer = (JSONLexerBase) parser.getLexer(); + + ParseContext rootContext = parser.setContext(null, null); + + Object[] values; + int token = lexer.token(); + if (token == JSONToken.LBRACE) { + String[] typeNames = lexer.scanFieldStringArray(fieldName_argsTypes, -1, typeSymbolTable); + if (typeNames == null && lexer.matchStat == NOT_MATCH_NAME) { + String type = lexer.scanFieldString(fieldName_type); + if ("com.alibaba.fastjson.JSONObject".equals(type)) { + typeNames = lexer.scanFieldStringArray(fieldName_argsTypes, -1, typeSymbolTable); + } + } + Method method = methodLocator.findMethod(typeNames); + + if (method == null) { + lexer.close(); + + JSONObject jsonObject = JSON.parseObject(json); + typeNames = jsonObject.getObject("argsTypes", String[].class); + method = methodLocator.findMethod(typeNames); + + JSONArray argsObjs = jsonObject.getJSONArray("argsObjs"); + if (argsObjs == null) { + values = null; + } else { + Type[] argTypes = method.getGenericParameterTypes(); + values = new Object[argTypes.length]; + for (int i = 0; i < argTypes.length; i++) { + Type type = argTypes[i]; + values[i] = argsObjs.getObject(i, type); + } + } + } else { + Type[] argTypes = method.getGenericParameterTypes(); + + lexer.skipWhitespace(); + if (lexer.getCurrent() == ',') { + lexer.next(); + } + + if (lexer.matchField2(fieldName_argsObjs)) { + lexer.nextToken(); + + ParseContext context = parser.setContext(rootContext, null, "argsObjs"); + values = parser.parseArray(argTypes); + context.object = values; + + parser.accept(JSONToken.RBRACE); + + parser.handleResovleTask(null); + } else { + values = null; + } + + parser.close(); + } + } else if (token == JSONToken.LBRACKET) { + String[] typeNames = lexer.scanFieldStringArray(null, -1, typeSymbolTable); + + lexer.skipWhitespace(); + + char ch = lexer.getCurrent(); + + if (ch == ']') { + Method method = methodLocator.findMethod(null); + Type[] argTypes = method.getGenericParameterTypes(); + values = new Object[typeNames.length]; + for (int i = 0; i < typeNames.length; ++i) { + Type argType = argTypes[i]; + String typeName = typeNames[i]; + if (argType != String.class) { + values[i] = TypeUtils.cast(typeName, argType, parser.getConfig()); + } else { + values[i] = typeName; + } + } + return values; + } + if (ch == ',') { + lexer.next(); + lexer.skipWhitespace(); + } + lexer.nextToken(JSONToken.LBRACKET); + + Method method = methodLocator.findMethod(typeNames); + Type[] argTypes = method.getGenericParameterTypes(); + values = parser.parseArray(argTypes); + lexer.close(); + } else { + values = null; + } + + return values; + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/hsf/MethodLocator.java b/src/main/java/com/alibaba/fastjson/support/hsf/MethodLocator.java new file mode 100644 index 0000000000..dd90341026 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/hsf/MethodLocator.java @@ -0,0 +1,7 @@ +package com.alibaba.fastjson.support.hsf; + +import java.lang.reflect.Method; + +public interface MethodLocator { + Method findMethod(String[] types); +} diff --git a/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonAutoDiscoverable.java b/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonAutoDiscoverable.java new file mode 100644 index 0000000000..308483b254 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonAutoDiscoverable.java @@ -0,0 +1,33 @@ +package com.alibaba.fastjson.support.jaxrs; + +import org.glassfish.jersey.internal.spi.AutoDiscoverable; + +import javax.annotation.Priority; +import javax.ws.rs.core.Configuration; +import javax.ws.rs.core.FeatureContext; + +/** + *

Title: FastJsonAutoDiscoverable

+ *

Description: FastJsonAutoDiscoverable

+ * + * @author Victor.Zxy + * @see AutoDiscoverable + * @since 1.2.37 + */ +@Priority(AutoDiscoverable.DEFAULT_PRIORITY - 1) +public class FastJsonAutoDiscoverable implements AutoDiscoverable { + + public volatile static boolean autoDiscover = true; + + @Override + public void configure(final FeatureContext context) { + + final Configuration config = context.getConfiguration(); + + // Register FastJson. + if (!config.isRegistered(FastJsonFeature.class) && autoDiscover) { + + context.register(FastJsonFeature.class); + } + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonFeature.java b/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonFeature.java new file mode 100644 index 0000000000..1712c7fef9 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonFeature.java @@ -0,0 +1,48 @@ +package com.alibaba.fastjson.support.jaxrs; + +import org.glassfish.jersey.CommonProperties; +import org.glassfish.jersey.internal.InternalProperties; +import org.glassfish.jersey.internal.util.PropertiesHelper; + +import javax.ws.rs.core.Configuration; +import javax.ws.rs.core.Feature; +import javax.ws.rs.core.FeatureContext; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.MessageBodyWriter; + +/** + *

Title: FastJsonFeature

+ *

Description: FastJsonFeature

+ * + * @author Victor.Zxy + * @see Feature + * @since 1.2.37 + */ +public class FastJsonFeature implements Feature { + + private final static String JSON_FEATURE = FastJsonFeature.class.getSimpleName(); + + @Override + public boolean configure(final FeatureContext context) { + + final Configuration config = context.getConfiguration(); + + final String jsonFeature = CommonProperties.getValue(config.getProperties(), config.getRuntimeType(), InternalProperties.JSON_FEATURE, JSON_FEATURE, + String.class); + + // Other JSON providers registered. + if (!JSON_FEATURE.equalsIgnoreCase(jsonFeature)) + + return false; + + // Disable other JSON providers. + context.property(PropertiesHelper.getPropertyNameForRuntime(InternalProperties.JSON_FEATURE, config.getRuntimeType()), JSON_FEATURE); + + // Register FastJson. + if (!config.isRegistered(FastJsonProvider.class)) + + context.register(FastJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class); + + return true; + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonProvider.java b/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonProvider.java new file mode 100644 index 0000000000..3d7a3a4ce6 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonProvider.java @@ -0,0 +1,400 @@ +package com.alibaba.fastjson.support.jaxrs; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.support.config.FastJsonConfig; + +import javax.ws.rs.Consumes; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.*; +import javax.ws.rs.ext.*; +import java.io.*; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Fastjson for JAX-RS Provider. + * + * @author smallnest + * @author VictorZeng + * @see MessageBodyReader + * @see MessageBodyWriter + * @since 1.2.9 + */ + +@Provider +@Consumes({MediaType.WILDCARD}) +@Produces({MediaType.WILDCARD}) +public class FastJsonProvider // + implements MessageBodyReader, MessageBodyWriter { + + /** + * These are classes that we never use for reading + * (never try to deserialize instances of these types). + */ + public final static Class[] DEFAULT_UNREADABLES = new Class[]{ + InputStream.class, Reader.class + }; + + /** + * These are classes that we never use for writing + * (never try to serialize instances of these types). + */ + public final static Class[] DEFAULT_UNWRITABLES = new Class[]{ + InputStream.class, + OutputStream.class, Writer.class, + StreamingOutput.class, Response.class + }; + + @Deprecated + protected Charset charset = Charset.forName("UTF-8"); + + @Deprecated + protected SerializerFeature[] features = new SerializerFeature[0]; + + @Deprecated + protected SerializeFilter[] filters = new SerializeFilter[0]; + + @Deprecated + protected String dateFormat; + + /** + * Injectable context object used to locate configured + * instance of {@link FastJsonConfig} to use for actual + * serialization. + */ + @Context + protected Providers providers; + + /** + * with fastJson config + */ + private FastJsonConfig fastJsonConfig = new FastJsonConfig(); + + /** + * allow serialize/deserialize types in clazzes + */ + private Class[] clazzes = null; + + /** + * whether set PrettyFormat while exec WriteTo() + */ + private boolean pretty; + + + /** + * @return the fastJsonConfig. + * @since 1.2.11 + */ + public FastJsonConfig getFastJsonConfig() { + return fastJsonConfig; + } + + /** + * @param fastJsonConfig the fastJsonConfig to set. + * @since 1.2.11 + */ + public void setFastJsonConfig(FastJsonConfig fastJsonConfig) { + this.fastJsonConfig = fastJsonConfig; + } + + /** + * Can serialize/deserialize all types. + */ + public FastJsonProvider() { + + } + + /** + * Only serialize/deserialize all types in clazzes. + */ + public FastJsonProvider(Class[] clazzes) { + this.clazzes = clazzes; + } + + /** + * Set pretty format + */ + public FastJsonProvider setPretty(boolean p) { + this.pretty = p; + return this; + } + + /** + * Set charset. the default charset is UTF-8 + */ + @Deprecated + public FastJsonProvider(String charset) { + this.fastJsonConfig.setCharset(Charset.forName(charset)); + } + + @Deprecated + public Charset getCharset() { + return this.fastJsonConfig.getCharset(); + } + + @Deprecated + public void setCharset(Charset charset) { + this.fastJsonConfig.setCharset(charset); + } + + @Deprecated + public String getDateFormat() { + return this.fastJsonConfig.getDateFormat(); + } + + @Deprecated + public void setDateFormat(String dateFormat) { + this.fastJsonConfig.setDateFormat(dateFormat); + } + + @Deprecated + public SerializerFeature[] getFeatures() { + return this.fastJsonConfig.getSerializerFeatures(); + } + + @Deprecated + public void setFeatures(SerializerFeature... features) { + this.fastJsonConfig.setSerializerFeatures(features); + } + + @Deprecated + public SerializeFilter[] getFilters() { + return this.fastJsonConfig.getSerializeFilters(); + } + + @Deprecated + public void setFilters(SerializeFilter... filters) { + this.fastJsonConfig.setSerializeFilters(filters); + } + + /** + * Check some are interface/abstract classes to exclude. + * + * @param type the type + * @param classes the classes + * @return the boolean + */ + protected boolean isAssignableFrom(Class type, Class[] classes) { + + if (type == null) + return false; + + // there are some other abstract/interface types to exclude too: + for (Class cls : classes) { + if (cls.isAssignableFrom(type)) { + return false; + } + } + + return true; + } + + /** + * Check whether a class can be serialized or deserialized. It can check + * based on packages, annotations on entities or explicit classes. + * + * @param type class need to check + * @return true if valid + */ + protected boolean isValidType(Class type, Annotation[] classAnnotations) { + if (type == null) + return false; + + if (clazzes != null) { + for (Class cls : clazzes) { // must strictly equal. Don't check + // inheritance + if (cls == type) + return true; + } + + return false; + } + + return true; + } + + /** + * Check media type like "application/json". + * + * @param mediaType media type + * @return true if the media type is valid + */ + protected boolean hasMatchingMediaType(MediaType mediaType) { + if (mediaType != null) { + String subtype = mediaType.getSubtype(); + + return (("json".equalsIgnoreCase(subtype)) // + || (subtype.endsWith("+json")) // + || ("javascript".equals(subtype)) // + || ("x-javascript".equals(subtype)) // + || ("x-json".equals(subtype)) // + || ("x-www-form-urlencoded".equalsIgnoreCase(subtype)) // + || (subtype.endsWith("x-www-form-urlencoded"))); + } + return true; + } + + /* + * /********************************************************** /* Partial + * MessageBodyWriter impl + * /********************************************************** + */ + + /** + * Method that JAX-RS container calls to try to check whether given value + * (of specified type) can be serialized by this provider. + */ + public boolean isWriteable(Class type, // + Type genericType, // + Annotation[] annotations, // + MediaType mediaType) { + if (!hasMatchingMediaType(mediaType)) { + return false; + } + + if (!isAssignableFrom(type, DEFAULT_UNWRITABLES)) + return false; + + return isValidType(type, annotations); + } + + /** + * Method that JAX-RS container calls to try to figure out serialized length + * of given value. always return -1 to denote "not known". + */ + public long getSize(Object t, // + Class type, // + Type genericType, // + Annotation[] annotations, // + MediaType mediaType) { + return -1; + } + + /** + * Method that JAX-RS container calls to serialize given value. + */ + public void writeTo(Object obj, // + Class type, // + Type genericType, // + Annotation[] annotations, // + MediaType mediaType, // + MultivaluedMap httpHeaders, // + OutputStream entityStream // + ) throws IOException, WebApplicationException { + + FastJsonConfig fastJsonConfig = locateConfigProvider(type, mediaType); + + SerializerFeature[] serializerFeatures = fastJsonConfig.getSerializerFeatures(); + if (pretty) { + if (serializerFeatures == null) + serializerFeatures = new SerializerFeature[]{SerializerFeature.PrettyFormat}; + else { + List featureList = new ArrayList(Arrays + .asList(serializerFeatures)); + featureList.add(SerializerFeature.PrettyFormat); + serializerFeatures = featureList.toArray(serializerFeatures); + } + fastJsonConfig.setSerializerFeatures(serializerFeatures); + } + + try { + int len = JSON.writeJSONString(entityStream, // + fastJsonConfig.getCharset(), // + obj, // + fastJsonConfig.getSerializeConfig(), // + fastJsonConfig.getSerializeFilters(), // + fastJsonConfig.getDateFormat(), // + JSON.DEFAULT_GENERATE_FEATURE, // + fastJsonConfig.getSerializerFeatures()); + +// // add Content-Length +// if (fastJsonConfig.isWriteContentLength()) { +// httpHeaders.add("Content-Length", String.valueOf(len)); +// } + + entityStream.flush(); + + } catch (JSONException ex) { + + throw new WebApplicationException("Could not write JSON: " + ex.getMessage(), ex); + } + } + + /* + * /********************************************************** /* + * MessageBodyReader impl + * /********************************************************** + */ + + /** + * Method that JAX-RS container calls to try to check whether values of + * given type (and media type) can be deserialized by this provider. + */ + public boolean isReadable(Class type, // + Type genericType, // + Annotation[] annotations, // + MediaType mediaType) { + + if (!hasMatchingMediaType(mediaType)) { + return false; + } + + if (!isAssignableFrom(type, DEFAULT_UNREADABLES)) + return false; + + return isValidType(type, annotations); + } + + /** + * Method that JAX-RS container calls to deserialize given value. + */ + public Object readFrom(Class type, // + Type genericType, // + Annotation[] annotations, // + MediaType mediaType, // + MultivaluedMap httpHeaders, // + InputStream entityStream) throws IOException, WebApplicationException { + + try { + FastJsonConfig fastJsonConfig = locateConfigProvider(type, mediaType); + + return JSON.parseObject(entityStream, fastJsonConfig.getCharset(), genericType, fastJsonConfig.getFeatures()); + + } catch (JSONException ex) { + + throw new WebApplicationException("JSON parse error: " + ex.getMessage(), ex); + } + } + + /** + * Helper method that is called if no config has been explicitly configured. + */ + protected FastJsonConfig locateConfigProvider(Class type, MediaType mediaType) { + + if (providers != null) { + + ContextResolver resolver = providers.getContextResolver(FastJsonConfig.class, mediaType); + + if (resolver == null) { + + resolver = providers.getContextResolver(FastJsonConfig.class, null); + } + + if (resolver != null) { + + return resolver.getContext(type); + } + } + + return fastJsonConfig; + } + +} diff --git a/src/main/java/com/alibaba/fastjson/support/retrofit/Retrofit2ConverterFactory.java b/src/main/java/com/alibaba/fastjson/support/retrofit/Retrofit2ConverterFactory.java new file mode 100644 index 0000000000..1774f29a49 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/retrofit/Retrofit2ConverterFactory.java @@ -0,0 +1,135 @@ +package com.alibaba.fastjson.support.retrofit; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import okhttp3.MediaType; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Converter; +import retrofit2.Retrofit; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +/** + * @author ligboy, wenshao + */ +public class Retrofit2ConverterFactory extends Converter.Factory { + private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8"); + private static final Feature[] EMPTY_SERIALIZER_FEATURES = new Feature[0]; + + private ParserConfig parserConfig = ParserConfig.getGlobalInstance(); + private int featureValues = JSON.DEFAULT_PARSER_FEATURE; + private Feature[] features; + + private SerializeConfig serializeConfig; + private SerializerFeature[] serializerFeatures; + + public Retrofit2ConverterFactory() { + } + + @Override + public Converter responseBodyConverter(Type type, // + Annotation[] annotations, // + Retrofit retrofit) { + return new ResponseBodyConverter(type); + } + + @Override + public Converter requestBodyConverter(Type type, // + Annotation[] parameterAnnotations, // + Annotation[] methodAnnotations, // + Retrofit retrofit) { + return new RequestBodyConverter(); + } + + public ParserConfig getParserConfig() { + return parserConfig; + } + + public Retrofit2ConverterFactory setParserConfig(ParserConfig config) { + this.parserConfig = config; + return this; + } + + public int getParserFeatureValues() { + return featureValues; + } + + public Retrofit2ConverterFactory setParserFeatureValues(int featureValues) { + this.featureValues = featureValues; + return this; + } + + public Feature[] getParserFeatures() { + return features; + } + + public Retrofit2ConverterFactory setParserFeatures(Feature[] features) { + this.features = features; + return this; + } + + public SerializeConfig getSerializeConfig() { + return serializeConfig; + } + + public Retrofit2ConverterFactory setSerializeConfig(SerializeConfig serializeConfig) { + this.serializeConfig = serializeConfig; + return this; + } + + public SerializerFeature[] getSerializerFeatures() { + return serializerFeatures; + } + + public Retrofit2ConverterFactory setSerializerFeatures(SerializerFeature[] features) { + this.serializerFeatures = features; + return this; + } + + final class ResponseBodyConverter implements Converter { + private Type type; + + ResponseBodyConverter(Type type) { + this.type = type; + } + + public T convert(ResponseBody value) throws IOException { + try { + return JSON.parseObject(value.string() + , type + , parserConfig + , featureValues + , features != null + ? features + : EMPTY_SERIALIZER_FEATURES + ); + } finally { + value.close(); + } + } + } + + final class RequestBodyConverter implements Converter { + RequestBodyConverter() { + } + + public RequestBody convert(T value) throws IOException { + byte[] content = JSON.toJSONBytes(value + , serializeConfig == null + ? SerializeConfig.globalInstance + : serializeConfig + , serializerFeatures == null + ? SerializerFeature.EMPTY + : serializerFeatures + ); + + return RequestBody.create(MEDIA_TYPE, content); + } + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/FastJsonContainer.java b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonContainer.java new file mode 100755 index 0000000000..3accf3431d --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonContainer.java @@ -0,0 +1,31 @@ +package com.alibaba.fastjson.support.spring; + +/** + * 一个简单的PO对象,包含原始输出对象和对应的过滤条件{@link PropertyPreFilters} + * @author yanquanyu + * @author liuming + */ +public class FastJsonContainer { + private Object value; + private PropertyPreFilters filters; + + FastJsonContainer(Object body){ + this.value = body; + } + + public Object getValue() { + return this.value; + } + + public void setValue(Object value) { + this.value = value; + } + + public PropertyPreFilters getFilters() { + return this.filters; + } + + public void setFilters(PropertyPreFilters filters) { + this.filters = filters; + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/FastJsonHttpMessageConverter.java b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonHttpMessageConverter.java new file mode 100644 index 0000000000..dd327f0bb7 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonHttpMessageConverter.java @@ -0,0 +1,370 @@ +package com.alibaba.fastjson.support.spring; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONPObject; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.support.config.FastJsonConfig; +import com.alibaba.fastjson.util.IOUtils; +import org.springframework.core.ResolvableType; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.MediaType; +import org.springframework.http.converter.AbstractHttpMessageConverter; +import org.springframework.http.converter.GenericHttpMessageConverter; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.http.converter.HttpMessageNotWritableException; +import org.springframework.util.StringUtils; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Fastjson for Spring MVC Converter. + *

+ * Compatible Spring MVC version 3.2+ + * + * @author VictorZeng + * @see AbstractHttpMessageConverter + * @see GenericHttpMessageConverter + * @since 1.2.10 + *

+ *

+ *

+ * Supported return type: + *

+ * Simple object: Object + *

+ *

+ * With property filter :FastJsonContainer[Object] + *

+ *

+ * Jsonp :MappingFastJsonValue[Object] + *

+ * Jsonp with property filter: MappingFastJsonValue[FastJsonContainer[Object]] + */ + +public class FastJsonHttpMessageConverter extends AbstractHttpMessageConverter// + implements GenericHttpMessageConverter { + + public static final MediaType APPLICATION_JAVASCRIPT = new MediaType("application", "javascript"); + + private Charset charset = Charset.forName("UTF-8"); + + @Deprecated + protected SerializerFeature[] features = new SerializerFeature[0]; + + @Deprecated + protected SerializeFilter[] filters = new SerializeFilter[0]; + + @Deprecated + protected String dateFormat; + + /** + * with fastJson config + */ + private FastJsonConfig fastJsonConfig = new FastJsonConfig(); + + /** + * @return the fastJsonConfig. + * @since 1.2.11 + */ + public FastJsonConfig getFastJsonConfig() { + return fastJsonConfig; + } + + /** + * @param fastJsonConfig the fastJsonConfig to set. + * @since 1.2.11 + */ + public void setFastJsonConfig(FastJsonConfig fastJsonConfig) { + this.fastJsonConfig = fastJsonConfig; + } + + /** + * Can serialize/deserialize all types. + */ + public FastJsonHttpMessageConverter() { + + super(MediaType.ALL); + } + + @Deprecated + public Charset getCharset() { + return this.fastJsonConfig.getCharset(); + } + + @Deprecated + public void setCharset(Charset charset) { + this.fastJsonConfig.setCharset(charset); + } + + @Deprecated + public String getDateFormat() { + return this.fastJsonConfig.getDateFormat(); + } + + @Deprecated + public void setDateFormat(String dateFormat) { + this.fastJsonConfig.setDateFormat(dateFormat); + } + + @Deprecated + public SerializerFeature[] getFeatures() { + return this.fastJsonConfig.getSerializerFeatures(); + } + + @Deprecated + public void setFeatures(SerializerFeature... features) { + this.fastJsonConfig.setSerializerFeatures(features); + } + + @Deprecated + public SerializeFilter[] getFilters() { + return this.fastJsonConfig.getSerializeFilters(); + } + + @Deprecated + public void setFilters(SerializeFilter... filters) { + this.fastJsonConfig.setSerializeFilters(filters); + } + + @Deprecated + public void addSerializeFilter(SerializeFilter filter) { + if (filter == null) { + return; + } + + int length = this.fastJsonConfig.getSerializeFilters().length; + SerializeFilter[] filters = new SerializeFilter[length + 1]; + System.arraycopy(this.fastJsonConfig.getSerializeFilters(), 0, filters, 0, length); + filters[filters.length - 1] = filter; + this.fastJsonConfig.setSerializeFilters(filters); + } + + @Override + protected boolean supports(Class clazz) { + return true; + } + + + public boolean canRead(Type type, Class contextClass, MediaType mediaType) { + return super.canRead(contextClass, mediaType); + } + + + public boolean canWrite(Type type, Class clazz, MediaType mediaType) { + return super.canWrite(clazz, mediaType); + } + + /* + * @see org.springframework.http.converter.GenericHttpMessageConverter#read(java.lang.reflect.Type, java.lang.Class, org.springframework.http.HttpInputMessage) + */ + public Object read(Type type, // + Class contextClass, // + HttpInputMessage inputMessage // + ) throws IOException, HttpMessageNotReadableException { + return readType(getType(type, contextClass), inputMessage); + } + + /* + * @see org.springframework.http.converter.GenericHttpMessageConverter.write + */ + public void write(Object o, Type type, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { + super.write(o, contentType, outputMessage);// support StreamingHttpOutputMessage in spring4.0+ + //writeInternal(o, outputMessage); + } + + + /* + * @see org.springframework.http.converter.AbstractHttpMessageConverter#readInternal(java.lang.Class, org.springframework.http.HttpInputMessage) + */ + @Override + protected Object readInternal(Class clazz, // + HttpInputMessage inputMessage // + ) throws IOException, HttpMessageNotReadableException { + return readType(getType(clazz, null), inputMessage); + } + + private Object readType(Type type, HttpInputMessage inputMessage) throws IOException { + + try { + InputStream in = inputMessage.getBody(); + return JSON.parseObject(in, fastJsonConfig.getCharset(), type, fastJsonConfig.getFeatures()); + } catch (JSONException ex) { + throw new HttpMessageNotReadableException("JSON parse error: " + ex.getMessage(), ex); + } catch (IOException ex) { + throw new HttpMessageNotReadableException("I/O error while reading input message", ex); + } + } + + @Override + protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { + + ByteArrayOutputStream outnew = new ByteArrayOutputStream(); + try { + HttpHeaders headers = outputMessage.getHeaders(); + + //获取全局配置的filter + SerializeFilter[] globalFilters = fastJsonConfig.getSerializeFilters(); + List allFilters = new ArrayList(Arrays.asList(globalFilters)); + + boolean isJsonp = false; + + //不知道为什么会有这行代码, 但是为了保持和原来的行为一致,还是保留下来 + Object value = strangeCodeForJackson(object); + + if (value instanceof FastJsonContainer) { + FastJsonContainer fastJsonContainer = (FastJsonContainer) value; + PropertyPreFilters filters = fastJsonContainer.getFilters(); + allFilters.addAll(filters.getFilters()); + value = fastJsonContainer.getValue(); + } + + //revise 2017-10-23 , + // 保持原有的MappingFastJsonValue对象的contentType不做修改 保持旧版兼容。 + // 但是新的JSONPObject将返回标准的contentType:application/javascript ,不对是否有function进行判断 + if (value instanceof MappingFastJsonValue) { + if(!StringUtils.isEmpty(((MappingFastJsonValue) value).getJsonpFunction())){ + isJsonp = true; + } + } else if (value instanceof JSONPObject) { + isJsonp = true; + } + + + int len = JSON.writeJSONString(outnew, // + fastJsonConfig.getCharset(), // + value, // + fastJsonConfig.getSerializeConfig(), // + //fastJsonConfig.getSerializeFilters(), // + allFilters.toArray(new SerializeFilter[allFilters.size()]), + fastJsonConfig.getDateFormat(), // + JSON.DEFAULT_GENERATE_FEATURE, // + fastJsonConfig.getSerializerFeatures()); + + if (isJsonp) { + headers.setContentType(APPLICATION_JAVASCRIPT); + } + + if (fastJsonConfig.isWriteContentLength()) { + headers.setContentLength(len); + } + + outnew.writeTo(outputMessage.getBody()); + + } catch (JSONException ex) { + throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); + } finally { + outnew.close(); + } + } + + private Object strangeCodeForJackson(Object obj) { + if (obj != null) { + String className = obj.getClass().getName(); + if ("com.fasterxml.jackson.databind.node.ObjectNode".equals(className)) { + return obj.toString(); + } + } + return obj; + } + + protected Type getType(Type type, Class contextClass) { + if (Spring4TypeResolvableHelper.isSupport()) { + return Spring4TypeResolvableHelper.getType(type, contextClass); + } + + return type; + } + + + private static class Spring4TypeResolvableHelper { + private static boolean hasClazzResolvableType; + + static { + try { + Class.forName("org.springframework.core.ResolvableType"); + hasClazzResolvableType = true; + } catch (ClassNotFoundException e) { + hasClazzResolvableType = false; + } + } + + private static boolean isSupport() { + return hasClazzResolvableType; + } + + + private static Type getType(Type type, Class contextClass) { + if (contextClass != null) { + ResolvableType resolvedType = ResolvableType.forType(type); + if (type instanceof TypeVariable) { + ResolvableType resolvedTypeVariable = resolveVariable((TypeVariable) type, ResolvableType.forClass(contextClass)); + if (resolvedTypeVariable != ResolvableType.NONE) { + return resolvedTypeVariable.resolve(); + } + } else if (type instanceof ParameterizedType && resolvedType.hasUnresolvableGenerics()) { + ParameterizedType parameterizedType = (ParameterizedType) type; + Class[] generics = new Class[parameterizedType.getActualTypeArguments().length]; + Type[] typeArguments = parameterizedType.getActualTypeArguments(); + + for (int i = 0; i < typeArguments.length; ++i) { + Type typeArgument = typeArguments[i]; + if (typeArgument instanceof TypeVariable) { + ResolvableType resolvedTypeArgument = resolveVariable((TypeVariable) typeArgument, ResolvableType.forClass(contextClass)); + if (resolvedTypeArgument != ResolvableType.NONE) { + generics[i] = resolvedTypeArgument.resolve(); + } else { + generics[i] = ResolvableType.forType(typeArgument).resolve(); + } + } else { + generics[i] = ResolvableType.forType(typeArgument).resolve(); + } + } + + return ResolvableType.forClassWithGenerics(resolvedType.getRawClass(), generics).getType(); + } + } + + return type; + } + + private static ResolvableType resolveVariable(TypeVariable typeVariable, ResolvableType contextType) { + ResolvableType resolvedType; + if (contextType.hasGenerics()) { + resolvedType = ResolvableType.forType(typeVariable, contextType); + if (resolvedType.resolve() != null) { + return resolvedType; + } + } + + ResolvableType superType = contextType.getSuperType(); + if (superType != ResolvableType.NONE) { + resolvedType = resolveVariable(typeVariable, superType); + if (resolvedType.resolve() != null) { + return resolvedType; + } + } + for (ResolvableType ifc : contextType.getInterfaces()) { + resolvedType = resolveVariable(typeVariable, ifc); + if (resolvedType.resolve() != null) { + return resolvedType; + } + } + return ResolvableType.NONE; + } + } + + +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/FastJsonHttpMessageConverter4.java b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonHttpMessageConverter4.java new file mode 100644 index 0000000000..b0d778d3e2 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonHttpMessageConverter4.java @@ -0,0 +1,53 @@ +package com.alibaba.fastjson.support.spring; + +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.http.converter.HttpMessageNotWritableException; + +import java.io.IOException; +import java.lang.reflect.Type; + + +/** + * keep the class for compatibility + * @see FastJsonHttpMessageConverter + */ +@Deprecated +public class FastJsonHttpMessageConverter4 extends FastJsonHttpMessageConverter { + @Override + protected boolean supports(Class clazz) { + return super.supports(clazz); + } + + @Override + public boolean canRead(Type type, Class contextClass, MediaType mediaType) { + return super.canRead(type, contextClass, mediaType); + } + + @Override + public boolean canWrite(Type type, Class clazz, MediaType mediaType) { + return super.canWrite(type, clazz, mediaType); + } + + @Override + public Object read(Type type, Class contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { + return super.read(type, contextClass, inputMessage); + } + + @Override + public void write(Object o, Type type, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { + super.write(o, type, contentType, outputMessage); + } + + @Override + protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { + return super.readInternal(clazz, inputMessage); + } + + @Override + protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { + super.writeInternal(object, outputMessage); + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/FastJsonJsonView.java b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonJsonView.java new file mode 100755 index 0000000000..ce0fab3726 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonJsonView.java @@ -0,0 +1,336 @@ +package com.alibaba.fastjson.support.spring; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPObject; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.support.config.FastJsonConfig; +import com.alibaba.fastjson.util.IOUtils; +import org.springframework.util.Assert; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; +import org.springframework.validation.BindingResult; +import org.springframework.web.servlet.view.AbstractView; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.ByteArrayOutputStream; +import java.nio.charset.Charset; +import java.util.*; +import java.util.regex.Pattern; + +/** + * Fastjson for Spring MVC View. + * + * @author libinsong1204@gmail.com + * @author VictorZeng + * @see AbstractView + * @since 1.2.9 + */ + +public class FastJsonJsonView extends AbstractView { + + + /** + * default content type + */ + public static final String DEFAULT_CONTENT_TYPE = "application/json;charset=UTF-8"; + + /** + * Default content type for JSONP: "application/javascript". + */ + public static final String DEFAULT_JSONP_CONTENT_TYPE = "application/javascript"; + + /** + * Pattern for validating jsonp callback parameter values. + */ + private static final Pattern CALLBACK_PARAM_PATTERN = Pattern.compile("[0-9A-Za-z_\\.]*"); + + @Deprecated + protected Charset charset = Charset.forName("UTF-8"); + + @Deprecated + protected SerializerFeature[] features = new SerializerFeature[0]; + + @Deprecated + protected SerializeFilter[] filters = new SerializeFilter[0]; + + @Deprecated + protected String dateFormat; + + /** + * renderedAttributes + */ + private Set renderedAttributes; + + /** + * disableCaching + */ + private boolean disableCaching = true; + + /** + * updateContentLength + */ + private boolean updateContentLength = true; + + /** + * extractValueFromSingleKeyModel + */ + private boolean extractValueFromSingleKeyModel = false; + + /** + * with fastJson config + */ + private FastJsonConfig fastJsonConfig = new FastJsonConfig(); + + /** + * jsonp parameter name + */ + private String[] jsonpParameterNames = {"jsonp", "callback"}; + + /** + * Set default param. + */ + public FastJsonJsonView() { + + setContentType(DEFAULT_CONTENT_TYPE); + setExposePathVariables(false); + } + + /** + * @return the fastJsonConfig. + * @since 1.2.11 + */ + public FastJsonConfig getFastJsonConfig() { + return fastJsonConfig; + } + + /** + * @param fastJsonConfig the fastJsonConfig to set. + * @since 1.2.11 + */ + public void setFastJsonConfig(FastJsonConfig fastJsonConfig) { + this.fastJsonConfig = fastJsonConfig; + } + + @Deprecated + public void setSerializerFeature(SerializerFeature... features) { + this.fastJsonConfig.setSerializerFeatures(features); + } + + @Deprecated + public Charset getCharset() { + return this.fastJsonConfig.getCharset(); + } + + @Deprecated + public void setCharset(Charset charset) { + this.fastJsonConfig.setCharset(charset); + } + + @Deprecated + public String getDateFormat() { + return this.fastJsonConfig.getDateFormat(); + } + + @Deprecated + public void setDateFormat(String dateFormat) { + this.fastJsonConfig.setDateFormat(dateFormat); + } + + @Deprecated + public SerializerFeature[] getFeatures() { + return this.fastJsonConfig.getSerializerFeatures(); + } + + @Deprecated + public void setFeatures(SerializerFeature... features) { + this.fastJsonConfig.setSerializerFeatures(features); + } + + @Deprecated + public SerializeFilter[] getFilters() { + return this.fastJsonConfig.getSerializeFilters(); + } + + @Deprecated + public void setFilters(SerializeFilter... filters) { + this.fastJsonConfig.setSerializeFilters(filters); + } + + /** + * Set renderedAttributes. + * + * @param renderedAttributes renderedAttributes + */ + public void setRenderedAttributes(Set renderedAttributes) { + this.renderedAttributes = renderedAttributes; + } + + /** + * Check extractValueFromSingleKeyModel. + * + * @return extractValueFromSingleKeyModel + */ + public boolean isExtractValueFromSingleKeyModel() { + return extractValueFromSingleKeyModel; + } + + /** + * Set extractValueFromSingleKeyModel. + * + * @param extractValueFromSingleKeyModel + */ + public void setExtractValueFromSingleKeyModel( + boolean extractValueFromSingleKeyModel) { + this.extractValueFromSingleKeyModel = extractValueFromSingleKeyModel; + } + + /** + * Set JSONP request parameter names. Each time a request has one of those + * parameters, the resulting JSON will be wrapped into a function named as + * specified by the JSONP request parameter value. + *

The parameter names configured by default are "jsonp" and "callback". + * @since 4.1 + * @see JSONP Wikipedia article + */ + public void setJsonpParameterNames(Set jsonpParameterNames) { + Assert.notEmpty(jsonpParameterNames, "jsonpParameterName cannot be empty"); + this.jsonpParameterNames = jsonpParameterNames.toArray(new String[jsonpParameterNames.size()]); + } + + + private String getJsonpParameterValue(HttpServletRequest request) { + if (this.jsonpParameterNames != null) { + for (String name : this.jsonpParameterNames) { + String value = request.getParameter(name); + + if (IOUtils.isValidJsonpQueryParam(value)) { + return value; + } + + if (logger.isDebugEnabled()) { + logger.debug("Ignoring invalid jsonp parameter value: " + value); + } + } + } + return null; + } + + + + @Override + protected void renderMergedOutputModel(Map model, // + HttpServletRequest request, // + HttpServletResponse response) throws Exception { + Object value = filterModel(model); + String jsonpParameterValue = getJsonpParameterValue(request); + if(jsonpParameterValue != null) { + JSONPObject jsonpObject = new JSONPObject(jsonpParameterValue); + jsonpObject.addParameter(value); + value = jsonpObject; + } + + ByteArrayOutputStream outnew = new ByteArrayOutputStream(); + + int len = JSON.writeJSONString(outnew, // + fastJsonConfig.getCharset(), // + value, // + fastJsonConfig.getSerializeConfig(), // + fastJsonConfig.getSerializeFilters(), // + fastJsonConfig.getDateFormat(), // + JSON.DEFAULT_GENERATE_FEATURE, // + fastJsonConfig.getSerializerFeatures()); + + if (this.updateContentLength) { + // Write content length (determined via byte array). + response.setContentLength(len); + } + + // Flush byte array to servlet output stream. + ServletOutputStream out = response.getOutputStream(); + outnew.writeTo(out); + outnew.close(); + out.flush(); + } + + @Override + protected void prepareResponse(HttpServletRequest request, // + HttpServletResponse response) { + + setResponseContentType(request, response); + response.setCharacterEncoding(fastJsonConfig.getCharset().name()); + if (this.disableCaching) { + response.addHeader("Pragma", "no-cache"); + response.addHeader("Cache-Control", "no-cache, no-store, max-age=0"); + response.addDateHeader("Expires", 1L); + } + } + + /** + * Disables caching of the generated JSON. + *

+ * Default is {@code true}, which will prevent the client from caching the + * generated JSON. + */ + public void setDisableCaching(boolean disableCaching) { + this.disableCaching = disableCaching; + } + + /** + * Whether to update the 'Content-Length' header of the response. When set + * to {@code true}, the response is buffered in order to determine the + * content length and set the 'Content-Length' header of the response. + *

+ * The default setting is {@code false}. + */ + public void setUpdateContentLength(boolean updateContentLength) { + this.updateContentLength = updateContentLength; + } + + /** + * Filters out undesired attributes from the given model. The return value + * can be either another {@link Map}, or a single value object. + *

+ * Default implementation removes {@link BindingResult} instances and + * entries not included in the {@link #setRenderedAttributes(Set) + * renderedAttributes} property. + * + * @param model the model, as passed on to {@link #renderMergedOutputModel} + * @return the object to be rendered + */ + protected Object filterModel(Map model) { + Map result = new HashMap(model.size()); + Set renderedAttributes = !CollectionUtils.isEmpty(this.renderedAttributes) ? // + this.renderedAttributes // + : model.keySet(); + + for (Map.Entry entry : model.entrySet()) { + if (!(entry.getValue() instanceof BindingResult) + && renderedAttributes.contains(entry.getKey())) { + result.put(entry.getKey(), entry.getValue()); + } + } + if (extractValueFromSingleKeyModel) { + if (result.size() == 1) { + for (Map.Entry entry : result.entrySet()) { + return entry.getValue(); + } + } + } + return result; + } + + @Override + protected void setResponseContentType(HttpServletRequest request, HttpServletResponse response) { + if (getJsonpParameterValue(request) != null) { + response.setContentType(DEFAULT_JSONP_CONTENT_TYPE); + } + else { + super.setResponseContentType(request, response); + } + } + + +} \ No newline at end of file diff --git a/src/main/java/com/alibaba/fastjson/support/spring/FastJsonRedisSerializer.java b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonRedisSerializer.java new file mode 100644 index 0000000000..ce2cb843e9 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonRedisSerializer.java @@ -0,0 +1,52 @@ +package com.alibaba.fastjson.support.spring; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.support.config.FastJsonConfig; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.SerializationException; + +/** + * {@link RedisSerializer} FastJson Impl + * @author lihengming + * @since 1.2.36 + */ +public class FastJsonRedisSerializer implements RedisSerializer { + private FastJsonConfig fastJsonConfig = new FastJsonConfig(); + private Class type; + + public FastJsonRedisSerializer(Class type) { + this.type = type; + } + + public FastJsonConfig getFastJsonConfig() { + return fastJsonConfig; + } + + public void setFastJsonConfig(FastJsonConfig fastJsonConfig) { + this.fastJsonConfig = fastJsonConfig; + } + + @Override + public byte[] serialize(T t) throws SerializationException { + if (t == null) { + return new byte[0]; + } + try { + return JSON.toJSONBytes(t, fastJsonConfig.getSerializeConfig(), fastJsonConfig.getSerializerFeatures()); + } catch (Exception ex) { + throw new SerializationException("Could not serialize: " + ex.getMessage(), ex); + } + } + + @Override + public T deserialize(byte[] bytes) throws SerializationException { + if (bytes == null || bytes.length == 0) { + return null; + } + try { + return (T) JSON.parseObject(bytes, type, fastJsonConfig.getFeatures()); + } catch (Exception ex) { + throw new SerializationException("Could not deserialize: " + ex.getMessage(), ex); + } + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/FastJsonViewResponseBodyAdvice.java b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonViewResponseBodyAdvice.java new file mode 100644 index 0000000000..8c91e267c0 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonViewResponseBodyAdvice.java @@ -0,0 +1,57 @@ +package com.alibaba.fastjson.support.spring; + +import com.alibaba.fastjson.support.spring.annotation.FastJsonFilter; +import com.alibaba.fastjson.support.spring.annotation.FastJsonView; +import org.springframework.core.MethodParameter; +import org.springframework.core.annotation.Order; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServerHttpResponse; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; + +/** + * A convenient base class for {@code ResponseBodyAdvice} implementations + * that customize the response before JSON serialization with {@link FastJsonHttpMessageConverter4}'s concrete + * subclasses. + *

+ * + * @author yanquanyu + * @author liuming + */ +@Order +@ControllerAdvice +public class FastJsonViewResponseBodyAdvice implements ResponseBodyAdvice { + + public boolean supports(MethodParameter returnType, Class> converterType) { + return FastJsonHttpMessageConverter.class.isAssignableFrom(converterType) && returnType.hasMethodAnnotation(FastJsonView.class); + } + + public FastJsonContainer beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { + FastJsonContainer container = getOrCreateContainer(body); + beforeBodyWriteInternal(container, selectedContentType, returnType, request, response); + return container; + } + + private FastJsonContainer getOrCreateContainer(Object body) { + return (body instanceof FastJsonContainer ? (FastJsonContainer) body : new FastJsonContainer(body)); + + } + + protected void beforeBodyWriteInternal(FastJsonContainer container, MediaType contentType, + MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) { + FastJsonView annotation = returnType.getMethodAnnotation(FastJsonView.class); + + FastJsonFilter[] include = annotation.include(); + FastJsonFilter[] exclude = annotation.exclude(); + PropertyPreFilters filters = new PropertyPreFilters(); + for (FastJsonFilter item : include) { + filters.addFilter(item.clazz(),item.props()); + } + for (FastJsonFilter item : exclude) { + filters.addFilter(item.clazz()).addExcludes(item.props()); + } + container.setFilters(filters); + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/FastJsonpHttpMessageConverter4.java b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonpHttpMessageConverter4.java new file mode 100644 index 0000000000..2766bcf9c1 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonpHttpMessageConverter4.java @@ -0,0 +1,52 @@ +package com.alibaba.fastjson.support.spring; + +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.http.converter.HttpMessageNotWritableException; + +import java.io.IOException; +import java.lang.reflect.Type; + +/** + * keep the class for compatibility + * @see FastJsonHttpMessageConverter + */ +@Deprecated +public class FastJsonpHttpMessageConverter4 extends FastJsonHttpMessageConverter { + @Override + protected boolean supports(Class clazz) { + return super.supports(clazz); + } + + @Override + public boolean canRead(Type type, Class contextClass, MediaType mediaType) { + return super.canRead(type, contextClass, mediaType); + } + + @Override + public boolean canWrite(Type type, Class clazz, MediaType mediaType) { + return super.canWrite(type, clazz, mediaType); + } + + @Override + public Object read(Type type, Class contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { + return super.read(type, contextClass, inputMessage); + } + + @Override + public void write(Object o, Type type, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { + super.write(o, type, contentType, outputMessage); + } + + @Override + protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { + return super.readInternal(clazz, inputMessage); + } + + @Override + protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { + super.writeInternal(object, outputMessage); + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/FastJsonpResponseBodyAdvice.java b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonpResponseBodyAdvice.java new file mode 100644 index 0000000000..bd362664cd --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/FastJsonpResponseBodyAdvice.java @@ -0,0 +1,115 @@ +package com.alibaba.fastjson.support.spring; + +import org.springframework.core.MethodParameter; +import org.springframework.core.annotation.Order; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServerHttpResponse; +import org.springframework.http.server.ServletServerHttpRequest; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; + +import javax.servlet.http.HttpServletRequest; +import java.util.regex.Pattern; + +/** + * A convenient base class for {@code ResponseBodyAdvice} implementations + * that customize the response before JSON serialization with {@link FastJsonpHttpMessageConverter4}'s concrete + * subclasses. + *

+ * Compatible Spring MVC version 4.2+ + * + * @author Jerry.Chen + * @see JSONPResponseBodyAdvice + * @since 1.2.20 + */ +@Deprecated +@Order(Integer.MIN_VALUE) //before FastJsonViewResponseBodyAdvice +@ControllerAdvice +public class FastJsonpResponseBodyAdvice implements ResponseBodyAdvice { + /** + * Pattern for validating jsonp callback parameter values. + */ + private static final Pattern CALLBACK_PARAM_PATTERN = Pattern.compile("[0-9A-Za-z_\\.]*"); + private final String[] jsonpQueryParamNames; + /** + * Default JSONP query param names: callback/jsonp + */ + public static final String[] DEFAULT_JSONP_QUERY_PARAM_NAMES = {"callback", "jsonp"}; + + public FastJsonpResponseBodyAdvice() { + this.jsonpQueryParamNames = DEFAULT_JSONP_QUERY_PARAM_NAMES; + } + + public FastJsonpResponseBodyAdvice(String... queryParamNames) { + Assert.isTrue(!ObjectUtils.isEmpty(queryParamNames), "At least one query param name is required"); + this.jsonpQueryParamNames = queryParamNames; + } + + public boolean supports(MethodParameter returnType, Class> converterType) { + return FastJsonHttpMessageConverter.class.isAssignableFrom(converterType); + } + + public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, + Class> selectedConverterType, ServerHttpRequest request, + ServerHttpResponse response) { + MappingFastJsonValue container = getOrCreateContainer(body); + beforeBodyWriteInternal(container, selectedContentType, returnType, request, response); + return container; + } + + /** + * Wrap the body in a {@link MappingFastJsonValue} value container (for providing + * additional serialization instructions) or simply cast it if already wrapped. + */ + protected MappingFastJsonValue getOrCreateContainer(Object body) { + return (body instanceof MappingFastJsonValue ? (MappingFastJsonValue) body : new MappingFastJsonValue(body)); + } + + /** + * Invoked only if the converter type is {@code FastJsonpHttpMessageConverter4}. + */ + public void beforeBodyWriteInternal(MappingFastJsonValue bodyContainer, MediaType contentType, + MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) { + HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); + for (String name : this.jsonpQueryParamNames) { + String value = servletRequest.getParameter(name); + if (value != null) { + if (!isValidJsonpQueryParam(value)) { + continue; + } + // MediaType contentTypeToUse = getContentType(contentType, request, response); + // response.getHeaders().setContentType(contentTypeToUse); + bodyContainer.setJsonpFunction(value); + break; + } + } + } + + /** + * Validate the jsonp query parameter value. The default implementation + * returns true if it consists of digits, letters, or "_" and ".". + * Invalid parameter values are ignored. + * + * @param value the query param value, never {@code null} + */ + protected boolean isValidJsonpQueryParam(String value) { + return CALLBACK_PARAM_PATTERN.matcher(value).matches(); + } + + /** + * Return the content type to set the response to. + * This implementation always returns "application/javascript". + * + * @param contentType the content type selected through content negotiation + * @param request the current request + * @param response the current response + * @return the content type to set the response to + */ + protected MediaType getContentType(MediaType contentType, ServerHttpRequest request, ServerHttpResponse response) { + return new MediaType("application", "javascript"); + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/FastjsonSockJsMessageCodec.java b/src/main/java/com/alibaba/fastjson/support/spring/FastjsonSockJsMessageCodec.java new file mode 100644 index 0000000000..8768033401 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/FastjsonSockJsMessageCodec.java @@ -0,0 +1,34 @@ +package com.alibaba.fastjson.support.spring; + +import java.io.IOException; +import java.io.InputStream; + +import org.springframework.web.socket.sockjs.frame.AbstractSockJsMessageCodec; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; + +public class FastjsonSockJsMessageCodec extends AbstractSockJsMessageCodec { + + public String[] decode(String content) throws IOException { + return JSON.parseObject(content, String[].class); + } + + public String[] decodeInputStream(InputStream content) throws IOException { + return JSON.parseObject(content, String[].class); + } + + @Override + protected char[] applyJsonQuoting(String content) { + SerializeWriter out = new SerializeWriter(); + try { + JSONSerializer serializer = new JSONSerializer(out); + serializer.write(content); + return out.toCharArrayForSpringWebSocket(); + } finally { + out.close(); + } + } + +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/GenericFastJsonRedisSerializer.java b/src/main/java/com/alibaba/fastjson/support/spring/GenericFastJsonRedisSerializer.java new file mode 100644 index 0000000000..6d764ae67e --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/GenericFastJsonRedisSerializer.java @@ -0,0 +1,40 @@ +package com.alibaba.fastjson.support.spring; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.util.IOUtils; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.SerializationException; + +/** + * {@link RedisSerializer} FastJson Generic Impl + * @author lihengming + * @since 1.2.36 + */ +public class GenericFastJsonRedisSerializer implements RedisSerializer { + private final static ParserConfig defaultRedisConfig = new ParserConfig(); + static { defaultRedisConfig.setAutoTypeSupport(true);} + + public byte[] serialize(Object object) throws SerializationException { + if (object == null) { + return new byte[0]; + } + try { + return JSON.toJSONBytes(object, SerializerFeature.WriteClassName); + } catch (Exception ex) { + throw new SerializationException("Could not serialize: " + ex.getMessage(), ex); + } + } + + public Object deserialize(byte[] bytes) throws SerializationException { + if (bytes == null || bytes.length == 0) { + return null; + } + try { + return JSON.parseObject(new String(bytes, IOUtils.UTF8), Object.class, defaultRedisConfig); + } catch (Exception ex) { + throw new SerializationException("Could not deserialize: " + ex.getMessage(), ex); + } + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/JSONPResponseBodyAdvice.java b/src/main/java/com/alibaba/fastjson/support/spring/JSONPResponseBodyAdvice.java new file mode 100644 index 0000000000..d34b96de47 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/JSONPResponseBodyAdvice.java @@ -0,0 +1,100 @@ +package com.alibaba.fastjson.support.spring; + +import com.alibaba.fastjson.JSONPObject; +import com.alibaba.fastjson.support.spring.annotation.ResponseJSONP; +import com.alibaba.fastjson.util.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.core.MethodParameter; +import org.springframework.core.annotation.Order; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServerHttpResponse; +import org.springframework.http.server.ServletServerHttpRequest; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; + +import javax.servlet.http.HttpServletRequest; + +/** + * Created by SongLing.Dong on 7/22/2017. + *

+ * Wrap with the return object from method annotated by @ResponseJSONP + * in order to be serialized into jsonp format. + *

+ *

+ *

+ * url: /path/to/your/api?callback=functionName + *

+ * + * @see JSONPObject + * @see ResponseJSONP + * @since Spring 4.2 when ResponseBodyAdvice is supported. + *

+ * In Spring 3.x, use method directly return a JSONPObject instead. + *

+ */ +@Order(Integer.MIN_VALUE)//before FastJsonViewResponseBodyAdvice +@ControllerAdvice +public class JSONPResponseBodyAdvice implements ResponseBodyAdvice { + + public final Log logger = LogFactory.getLog(this.getClass()); + + public JSONPResponseBodyAdvice() { + } + + + public boolean supports(MethodParameter returnType, Class> converterType) { + + + return FastJsonHttpMessageConverter.class.isAssignableFrom(converterType) + && + (returnType.getContainingClass().isAnnotationPresent(ResponseJSONP.class) || returnType.hasMethodAnnotation(ResponseJSONP.class)); + } + + public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, + Class> selectedConverterType, ServerHttpRequest request, + ServerHttpResponse response) { + + ResponseJSONP responseJsonp = returnType.getMethodAnnotation(ResponseJSONP.class); + if(responseJsonp == null){ + responseJsonp = returnType.getContainingClass().getAnnotation(ResponseJSONP.class); + } + + HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); + String callbackMethodName = servletRequest.getParameter(responseJsonp.callback()); + + if (!IOUtils.isValidJsonpQueryParam(callbackMethodName)) { + if (logger.isDebugEnabled()) { + logger.debug("Invalid jsonp parameter value:" + callbackMethodName); + } + callbackMethodName = null; + } + + JSONPObject jsonpObject = new JSONPObject(callbackMethodName); + jsonpObject.addParameter(body); + beforeBodyWriteInternal(jsonpObject, selectedContentType, returnType, request, response); + return jsonpObject; + } + + + public void beforeBodyWriteInternal(JSONPObject jsonpObject, MediaType contentType, + MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) { + //MediaType contentTypeToUse = getContentType(contentType, request, response); + //response.getHeaders().setContentType(contentTypeToUse); + } + + /** + * Return the content type to set the response to. + * This implementation always returns "application/javascript". + * + * @param contentType the content type selected through content negotiation + * @param request the current request + * @param response the current response + * @return the content type to set the response to + */ + protected MediaType getContentType(MediaType contentType, ServerHttpRequest request, ServerHttpResponse response) { + return FastJsonHttpMessageConverter.APPLICATION_JAVASCRIPT; + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/MappingFastJsonValue.java b/src/main/java/com/alibaba/fastjson/support/spring/MappingFastJsonValue.java new file mode 100644 index 0000000000..0f58354a8b --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/MappingFastJsonValue.java @@ -0,0 +1,91 @@ +package com.alibaba.fastjson.support.spring; + +import com.alibaba.fastjson.JSONPObject; +import com.alibaba.fastjson.serializer.JSONSerializable; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import java.io.IOException; +import java.lang.reflect.Type; + +/** + * A simple holder for the POJO to serialize via {@link FastJsonHttpMessageConverter} along with further + * serialization instructions to be passed in to the converter. + * + *

+ * On the server side this wrapper is added with a {@code ResponseBodyInterceptor} after content negotiation selects the + * converter to use but before the write. + * + *

+ * On the client side, simply wrap the POJO and pass it in to the {@code RestTemplate}. + * + * @author Jerry.Chen + * @since 1.2.20 + * + * @see JSONPObject + */ +@Deprecated +public class MappingFastJsonValue implements JSONSerializable { + private static final String SECURITY_PREFIX = "/**/"; + private static final int BrowserSecureMask = SerializerFeature.BrowserSecure.mask; + + private Object value; + private String jsonpFunction; + + /** + * Create a new instance wrapping the given POJO to be serialized. + * + * @param value the Object to be serialized + */ + public MappingFastJsonValue(Object value) { + this.value = value; + } + + /** + * Modify the POJO to serialize. + */ + public void setValue(Object value) { + this.value = value; + } + + /** + * Return the POJO that needs to be serialized. + */ + public Object getValue() { + return this.value; + } + + /** + * Set the name of the JSONP function name. + */ + public void setJsonpFunction(String functionName) { + this.jsonpFunction = functionName; + } + + /** + * Return the configured JSONP function name. + */ + public String getJsonpFunction() { + return this.jsonpFunction; + } + + public void write(JSONSerializer serializer, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter writer = serializer.out; + + if(jsonpFunction == null){ + serializer.write(value); + return; + } + + + if ((features & BrowserSecureMask) != 0 || (writer.isEnabled(BrowserSecureMask))) { + writer.write(SECURITY_PREFIX); + } + + writer.write(jsonpFunction); + writer.write('('); + serializer.write(value); + writer.write(')'); + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/PropertyPreFilters.java b/src/main/java/com/alibaba/fastjson/support/spring/PropertyPreFilters.java new file mode 100755 index 0000000000..252e76bb77 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/PropertyPreFilters.java @@ -0,0 +1,73 @@ +package com.alibaba.fastjson.support.spring; + +import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; + +import java.util.ArrayList; +import java.util.List; + +/** + * {@link SimplePropertyPreFilter}的一个简单封装 + * @author yanquanyu + * @author liuming + */ +public class PropertyPreFilters { + private List filters = new ArrayList(); + + + public MySimplePropertyPreFilter addFilter(){ + MySimplePropertyPreFilter filter = new MySimplePropertyPreFilter(); + filters.add(filter); + return filter; + } + + public MySimplePropertyPreFilter addFilter(String... properties){ + MySimplePropertyPreFilter filter = new MySimplePropertyPreFilter(properties); + filters.add(filter); + return filter; + } + + public MySimplePropertyPreFilter addFilter(Class clazz, String... properties){ + MySimplePropertyPreFilter filter = new MySimplePropertyPreFilter(clazz,properties); + filters.add(filter); + return filter; + } + + public List getFilters() { + return filters; + } + + public void setFilters(List filters) { + this.filters = filters; + } + + public MySimplePropertyPreFilter[] toFilters(){ + return filters.toArray(new MySimplePropertyPreFilter[]{}); + } + + public class MySimplePropertyPreFilter extends SimplePropertyPreFilter { + + public MySimplePropertyPreFilter(){} + + public MySimplePropertyPreFilter(String... properties){ + super(properties); + } + + public MySimplePropertyPreFilter(Class clazz, String... properties){ + super(clazz,properties); + } + + public MySimplePropertyPreFilter addExcludes(String... filters){ + for (int i = 0; i < filters.length; i++) { + this.getExcludes().add(filters[i]); + } + return this; + } + + public MySimplePropertyPreFilter addIncludes(String... filters){ + for (int i = 0; i < filters.length; i++) { + this.getIncludes().add(filters[i]); + } + return this; + } + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonFilter.java b/src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonFilter.java new file mode 100644 index 0000000000..689f7ba1d8 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonFilter.java @@ -0,0 +1,18 @@ +package com.alibaba.fastjson.support.spring.annotation; + +import java.lang.annotation.*; + +/** + *

+ * 设置过滤对象对应的class和对应的属性
+ * 
+ * @author yanquanyu + * @author liuming + */ +@Target(ElementType.ANNOTATION_TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface FastJsonFilter { + Class clazz(); + String[] props(); +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonView.java b/src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonView.java new file mode 100644 index 0000000000..99be4733ff --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonView.java @@ -0,0 +1,22 @@ +package com.alibaba.fastjson.support.spring.annotation; + +import java.lang.annotation.*; + +/** + *
+ * 一个放置到 {@link org.springframework.stereotype.Controller Controller}方法上的注解.
+ * 设置返回对象针对某个类需要排除或者包括的字段
+ * 例如:
+ * @FastJsonView(exclude = {@FastJsonFilter(clazz = JSON.class,props = {"data"})})
+ *
+ * 
+ * @author yanquanyu + * @author liuming + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface FastJsonView { + FastJsonFilter[] include() default {}; + FastJsonFilter[] exclude() default {}; +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/annotation/ResponseJSONP.java b/src/main/java/com/alibaba/fastjson/support/spring/annotation/ResponseJSONP.java new file mode 100644 index 0000000000..dd9ead8ff5 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/annotation/ResponseJSONP.java @@ -0,0 +1,20 @@ +package com.alibaba.fastjson.support.spring.annotation; + +import org.springframework.web.bind.annotation.ResponseBody; + +import java.lang.annotation.*; + +/** + * Created by SongLing.Dong on 7/22/2017. + * @see com.alibaba.fastjson.support.spring.JSONPResponseBodyAdvice + */ +@Documented +@Target({ElementType.TYPE,ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@ResponseBody +public @interface ResponseJSONP { + /** + * The parameter's name of the callback method. + */ + String callback() default "callback"; +} diff --git a/src/main/java/com/alibaba/fastjson/support/spring/messaging/MappingFastJsonMessageConverter.java b/src/main/java/com/alibaba/fastjson/support/spring/messaging/MappingFastJsonMessageConverter.java new file mode 100644 index 0000000000..8e969c46cd --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/spring/messaging/MappingFastJsonMessageConverter.java @@ -0,0 +1,84 @@ +package com.alibaba.fastjson.support.spring.messaging; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.support.config.FastJsonConfig; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageHeaders; +import org.springframework.messaging.converter.AbstractMessageConverter; +import org.springframework.util.MimeType; + +import java.nio.charset.Charset; + +/** + * Fastjson for Spring Messaging Json Converter. + *

+ * Compatible Spring Messaging version 4+ + * + * @author KimmKing + * @see AbstractMessageConverter + * @since 1.2.47 + */ +public class MappingFastJsonMessageConverter extends AbstractMessageConverter { + + /** + * with fastJson config + */ + private FastJsonConfig fastJsonConfig = new FastJsonConfig(); + + /** + * @return the fastJsonConfig. + * @since 1.2.47 + */ + public FastJsonConfig getFastJsonConfig() { + return fastJsonConfig; + } + + /** + * @param fastJsonConfig the fastJsonConfig to set. + * @since 1.2.47 + */ + public void setFastJsonConfig(FastJsonConfig fastJsonConfig) { + this.fastJsonConfig = fastJsonConfig; + } + + public MappingFastJsonMessageConverter() { + super(new MimeType("application", "json", Charset.forName("UTF-8"))); + } + + protected boolean supports(Class clazz) { + return true; + } + + @Override + protected boolean canConvertFrom(Message message, Class targetClass) { + return supports(targetClass); + } + + @Override + protected boolean canConvertTo(Object payload, MessageHeaders headers) { + return supports(payload.getClass()); + } + + @Override + protected Object convertFromInternal(Message message, Class targetClass, Object conversionHint) { + // parse byte[] or String payload to Java Object + Object payload = message.getPayload(); + Object obj = null; + if (payload instanceof byte[]) { + obj = JSON.parseObject((byte[]) payload, 0, ((byte[]) payload).length, + fastJsonConfig.getCharset(), targetClass, fastJsonConfig.getFeatures()); + }else if(payload instanceof String) { + obj = JSON.parseObject((String) payload,targetClass,fastJsonConfig.getFeatures()); + } + + return obj; + } + + @Override + protected Object convertToInternal(Object payload, MessageHeaders headers, Object conversionHint) { + // encode payload to json string + return JSON.toJSONString(payload,fastJsonConfig.getSerializeConfig(), + fastJsonConfig.getSerializeFilters(),fastJsonConfig.getSerializerFeatures()); + + } +} diff --git a/src/main/java/com/alibaba/fastjson/support/springfox/SwaggerJsonSerializer.java b/src/main/java/com/alibaba/fastjson/support/springfox/SwaggerJsonSerializer.java new file mode 100644 index 0000000000..a8352411b0 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/support/springfox/SwaggerJsonSerializer.java @@ -0,0 +1,30 @@ +package com.alibaba.fastjson.support.springfox; + +import java.io.IOException; +import java.lang.reflect.Type; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; + +import springfox.documentation.spring.web.json.Json; + +/** + * Swagger的Json处理,解决/v2/api-docs获取不到内容导致获取不到API页面内容的问题 + * + * @author zhaiyongchao [http://blog.didispace.com] + * @since 1.2.15 + */ +public class SwaggerJsonSerializer implements ObjectSerializer { + + public final static SwaggerJsonSerializer instance = new SwaggerJsonSerializer(); + + public void write(JSONSerializer serializer, // + Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.getWriter(); + Json json = (Json) object; + String value = json.value(); + out.write(value); + } + +} diff --git a/src/main/java/com/alibaba/fastjson/util/ASMClassLoader.java b/src/main/java/com/alibaba/fastjson/util/ASMClassLoader.java old mode 100644 new mode 100755 index e6b2015f63..290338842e --- a/src/main/java/com/alibaba/fastjson/util/ASMClassLoader.java +++ b/src/main/java/com/alibaba/fastjson/util/ASMClassLoader.java @@ -1,25 +1,198 @@ package com.alibaba.fastjson.util; +import java.security.PrivilegedAction; +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONAware; import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import com.alibaba.fastjson.JSONPathException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.JSONStreamAware; +import com.alibaba.fastjson.JSONWriter; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.JSONLexer; +import com.alibaba.fastjson.parser.JSONLexerBase; +import com.alibaba.fastjson.parser.JSONReaderScanner; +import com.alibaba.fastjson.parser.JSONScanner; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParseContext; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.SymbolTable; +import com.alibaba.fastjson.parser.deserializer.AutowiredObjectDeserializer; +import com.alibaba.fastjson.parser.deserializer.DefaultFieldDeserializer; +import com.alibaba.fastjson.parser.deserializer.ExtraProcessable; +import com.alibaba.fastjson.parser.deserializer.ExtraProcessor; +import com.alibaba.fastjson.parser.deserializer.ExtraTypeProvider; +import com.alibaba.fastjson.parser.deserializer.FieldDeserializer; +import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.serializer.AfterFilter; +import com.alibaba.fastjson.serializer.BeanContext; +import com.alibaba.fastjson.serializer.BeforeFilter; +import com.alibaba.fastjson.serializer.ContextObjectSerializer; +import com.alibaba.fastjson.serializer.ContextValueFilter; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.JavaBeanSerializer; +import com.alibaba.fastjson.serializer.LabelFilter; +import com.alibaba.fastjson.serializer.Labels; +import com.alibaba.fastjson.serializer.NameFilter; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import com.alibaba.fastjson.serializer.PropertyFilter; +import com.alibaba.fastjson.serializer.PropertyPreFilter; +import com.alibaba.fastjson.serializer.SerialContext; +import com.alibaba.fastjson.serializer.SerializeBeanInfo; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.SerializeFilterable; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.serializer.ValueFilter; public class ASMClassLoader extends ClassLoader { + private static java.security.ProtectionDomain DOMAIN; + + private static Map> classMapping = new HashMap>(); + + static { + DOMAIN = (java.security.ProtectionDomain) java.security.AccessController.doPrivileged(new PrivilegedAction() { + + public Object run() { + return ASMClassLoader.class.getProtectionDomain(); + } + }); + + Class[] jsonClasses = new Class[] {JSON.class, + JSONObject.class, + JSONArray.class, + JSONPath.class, + JSONAware.class, + JSONException.class, + JSONPathException.class, + JSONReader.class, + JSONStreamAware.class, + JSONWriter.class, + TypeReference.class, + + FieldInfo.class, + TypeUtils.class, + IOUtils.class, + IdentityHashMap.class, + ParameterizedTypeImpl.class, + JavaBeanInfo.class, + + ObjectSerializer.class, + JavaBeanSerializer.class, + SerializeFilterable.class, + SerializeBeanInfo.class, + JSONSerializer.class, + SerializeWriter.class, + SerializeFilter.class, + Labels.class, + LabelFilter.class, + ContextValueFilter.class, + AfterFilter.class, + BeforeFilter.class, + NameFilter.class, + PropertyFilter.class, + PropertyPreFilter.class, + ValueFilter.class, + SerializerFeature.class, + ContextObjectSerializer.class, + SerialContext.class, + SerializeConfig.class, + + JavaBeanDeserializer.class, + ParserConfig.class, + DefaultJSONParser.class, + JSONLexer.class, + JSONLexerBase.class, + ParseContext.class, + JSONToken.class, + SymbolTable.class, + Feature.class, + JSONScanner.class, + JSONReaderScanner.class, + + AutowiredObjectDeserializer.class, + ObjectDeserializer.class, + ExtraProcessor.class, + ExtraProcessable.class, + ExtraTypeProvider.class, + BeanContext.class, + FieldDeserializer.class, + DefaultFieldDeserializer.class, + }; + + for (Class clazz : jsonClasses) { + classMapping.put(clazz.getName(), clazz); + } + } + public ASMClassLoader(){ - super(ASMClassLoader.class.getClassLoader()); + super(getParentClassLoader()); } - public Class defineClassPublic(String name, byte[] b, int off, int len) throws ClassFormatError { - Class clazz = defineClass(name, b, off, len, null); + public ASMClassLoader(ClassLoader parent){ + super (parent); + } - return clazz; + static ClassLoader getParentClassLoader() { + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + if (contextClassLoader != null) { + try { + contextClassLoader.loadClass(JSON.class.getName()); + return contextClassLoader; + } catch (ClassNotFoundException e) { + // skip + } + } + return JSON.class.getClassLoader(); } - public static Class forName(String className) { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + Class mappingClass = classMapping.get(name); + if (mappingClass != null) { + return mappingClass; + } + try { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - return classLoader.loadClass(className); + return super.loadClass(name, resolve); } catch (ClassNotFoundException e) { - throw new JSONException("class nout found : " + className); + throw e; + } + } + + public Class defineClassPublic(String name, byte[] b, int off, int len) throws ClassFormatError { + Class clazz = defineClass(name, b, off, len, DOMAIN); + + return clazz; + } + + public boolean isExternalClass(Class clazz) { + ClassLoader classLoader = clazz.getClassLoader(); + + if (classLoader == null) { + return false; + } + + ClassLoader current = this; + while (current != null) { + if (current == classLoader) { + return false; + } + + current = current.getParent(); } + + return true; } + } diff --git a/src/main/java/com/alibaba/fastjson/util/ASMUtils.java b/src/main/java/com/alibaba/fastjson/util/ASMUtils.java old mode 100644 new mode 100755 index f2bc22d289..570dd05960 --- a/src/main/java/com/alibaba/fastjson/util/ASMUtils.java +++ b/src/main/java/com/alibaba/fastjson/util/ASMUtils.java @@ -1,71 +1,184 @@ package com.alibaba.fastjson.util; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.asm.ClassReader; +import com.alibaba.fastjson.asm.TypeCollector; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Constructor; import java.lang.reflect.Method; +import java.lang.reflect.Type; public class ASMUtils { - public static String getDesc(Method method) { - StringBuffer buf = new StringBuffer(); - buf.append("("); - java.lang.Class[] types = method.getParameterTypes(); + public static final String JAVA_VM_NAME = System.getProperty("java.vm.name"); + + public static final boolean IS_ANDROID = isAndroid(JAVA_VM_NAME); + + public static boolean isAndroid(String vmName) { + if (vmName == null) { // default is false + return false; + } + + String lowerVMName = vmName.toLowerCase(); + + return lowerVMName.contains("dalvik") // + || lowerVMName.contains("lemur") // aliyun-vm name + ; + } + + public static String desc(Method method) { + Class[] types = method.getParameterTypes(); + StringBuilder buf = new StringBuilder((types.length + 1) << 4); + buf.append('('); for (int i = 0; i < types.length; ++i) { - buf.append(getDesc(types[i])); + buf.append(desc(types[i])); } - buf.append(")"); - buf.append(getDesc(method.getReturnType())); + buf.append(')'); + buf.append(desc(method.getReturnType())); return buf.toString(); } - public static String getDesc(Class returnType) { + public static String desc(Class returnType) { if (returnType.isPrimitive()) { return getPrimitiveLetter(returnType); } else if (returnType.isArray()) { - return "[" + getDesc(returnType.getComponentType()); + return "[" + desc(returnType.getComponentType()); } else { - return "L" + getType(returnType) + ";"; + return "L" + type(returnType) + ";"; } } - public static String getType(Class parameterType) { + public static String type(Class parameterType) { if (parameterType.isArray()) { - return "[" + getDesc(parameterType.getComponentType()); + return "[" + desc(parameterType.getComponentType()); } else { if (!parameterType.isPrimitive()) { - String clsName = parameterType.getCanonicalName(); - - if (parameterType.isMemberClass()) { - int lastDot = clsName.lastIndexOf("."); - clsName = clsName.substring(0, lastDot) + "$" + clsName.substring(lastDot + 1); - } - return clsName.replaceAll("\\.", "/"); + String clsName = parameterType.getName(); + return clsName.replace('.', '/'); // 直接基于字符串替换,不使用正则替换 } else { return getPrimitiveLetter(parameterType); } } } + public static String getPrimitiveLetter(Class type) { - if (Integer.TYPE.equals(type)) { + if (Integer.TYPE == type) { return "I"; - } else if (Void.TYPE.equals(type)) { + } else if (Void.TYPE == type) { return "V"; - } else if (Boolean.TYPE.equals(type)) { + } else if (Boolean.TYPE == type) { return "Z"; - } else if (Character.TYPE.equals(type)) { + } else if (Character.TYPE == type) { return "C"; - } else if (Byte.TYPE.equals(type)) { + } else if (Byte.TYPE == type) { return "B"; - } else if (Short.TYPE.equals(type)) { + } else if (Short.TYPE == type) { return "S"; - } else if (Float.TYPE.equals(type)) { + } else if (Float.TYPE == type) { return "F"; - } else if (Long.TYPE.equals(type)) { + } else if (Long.TYPE == type) { return "J"; - } else if (Double.TYPE.equals(type)) { + } else if (Double.TYPE == type) { return "D"; } throw new IllegalStateException("Type: " + type.getCanonicalName() + " is not a primitive type"); } + public static Type getMethodType(Class clazz, String methodName) { + try { + Method method = clazz.getMethod(methodName); + + return method.getGenericReturnType(); + } catch (Exception ex) { + return null; + } + } + + public static boolean checkName(String name) { + for (int i = 0; i < name.length(); ++i) { + char c = name.charAt(i); + if (c < '\001' || c > '\177' || c == '.') { + return false; + } + } + + return true; + } + + + public static String[] lookupParameterNames(AccessibleObject methodOrCtor) { + if (IS_ANDROID) { + return new String[0]; + } + + final Class[] types; + final Class declaringClass; + final String name; + + Annotation[][] parameterAnnotations; + if (methodOrCtor instanceof Method) { + Method method = (Method) methodOrCtor; + types = method.getParameterTypes(); + name = method.getName(); + declaringClass = method.getDeclaringClass(); + parameterAnnotations = method.getParameterAnnotations(); + } else { + Constructor constructor = (Constructor) methodOrCtor; + types = constructor.getParameterTypes(); + declaringClass = constructor.getDeclaringClass(); + name = ""; + parameterAnnotations = constructor.getParameterAnnotations(); + } + + if (types.length == 0) { + return new String[0]; + } + + ClassLoader classLoader = declaringClass.getClassLoader(); + if (classLoader == null) { + classLoader = ClassLoader.getSystemClassLoader(); + } + + String className = declaringClass.getName(); + String resourceName = className.replace('.', '/') + ".class"; + InputStream is = classLoader.getResourceAsStream(resourceName); + + if (is == null) { + return new String[0]; + } + + try { + ClassReader reader = new ClassReader(is); + TypeCollector visitor = new TypeCollector(name, types); + reader.accept(visitor); + String[] parameterNames = visitor.getParameterNamesForMethod(); + + for (int i = 0; i < parameterNames.length; i++) { + Annotation[] annotations = parameterAnnotations[i]; + if (annotations != null) { + for (int j = 0; j < annotations.length; j++) { + if (annotations[j] instanceof JSONField) { + JSONField jsonField = (JSONField) annotations[j]; + String fieldName = jsonField.name(); + if (fieldName != null && fieldName.length() > 0) { + parameterNames[i] = fieldName; + } + } + } + } + } + + return parameterNames; + } catch (IOException e) { + return new String[0]; + } finally { + IOUtils.close(is); + } + } } diff --git a/src/main/java/com/alibaba/fastjson/util/AntiCollisionHashMap.java b/src/main/java/com/alibaba/fastjson/util/AntiCollisionHashMap.java new file mode 100644 index 0000000000..a97ea0093e --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/util/AntiCollisionHashMap.java @@ -0,0 +1,992 @@ +package com.alibaba.fastjson.util; + +import java.io.IOException; +import java.io.Serializable; +import java.util.*; + +/** + * @deprecated + */ +public class AntiCollisionHashMap extends AbstractMap implements + Map, Cloneable, Serializable { + + transient volatile Set keySet = null; + transient volatile Collection values = null; + + /** + * The default initial capacity - MUST be a power of two. + */ + static final int DEFAULT_INITIAL_CAPACITY = 16; + + /** + * The maximum capacity, used if a higher value is implicitly specified by + * either of the constructors with arguments. MUST be a power of two <= + * 1<<30. + */ + static final int MAXIMUM_CAPACITY = 1 << 30; + + /** + * The load factor used when none specified in constructor. + */ + static final float DEFAULT_LOAD_FACTOR = 0.75f; + + /** + * The table, resized as necessary. Length MUST Always be a power of two. + */ + transient Entry[] table; + + /** + * The number of key-value mappings contained in this map. + */ + transient int size; + + /** + * The next size value at which to resize (capacity * load factor). + * + * @serial + */ + int threshold; + + /** + * The load factor for the hash table. + * + * @serial + */ + final float loadFactor; + + /** + * The number of times this SafelyHashMap has been structurally modified + * Structural modifications are those that change the number of mappings in + * the SafelyHashMap or otherwise modify its internal structure (e.g., + * rehash). This field is used to make iterators on Collection-views of the + * SafelyHashMap fail-fast. (See ConcurrentModificationException). + */ + transient volatile int modCount; + + /** + * Constructs an empty SafelyHashMap with the specified initial + * capacity and load factor. + * + * @param initialCapacity + * the initial capacity + * @param loadFactor + * the load factor + * @throws IllegalArgumentException + * if the initial capacity is negative or the load factor is + * nonpositive + */ + + final static int M_MASK = 0x8765fed3; + final static int SEED = -2128831035; + final static int KEY = 16777619; + + final int random = new Random().nextInt(99999); // a fixed value in an instance + private int hashString(String key) { + + int hash = SEED * random; + for (int i = 0; i < key.length(); i++) + hash = (hash * KEY) ^ key.charAt(i); + return (hash ^ (hash >> 1)) & M_MASK; + } + + public AntiCollisionHashMap(int initialCapacity, float loadFactor) { + if (initialCapacity < 0) + throw new IllegalArgumentException("Illegal initial capacity: " + + initialCapacity); + if (initialCapacity > MAXIMUM_CAPACITY) + initialCapacity = MAXIMUM_CAPACITY; + if (loadFactor <= 0 || Float.isNaN(loadFactor)) + throw new IllegalArgumentException("Illegal load factor: " + + loadFactor); + + // Find a power of 2 >= initialCapacity + int capacity = 1; + while (capacity < initialCapacity) + capacity <<= 1; + + this.loadFactor = loadFactor; + threshold = (int) (capacity * loadFactor); + table = new Entry[capacity]; + init(); + } + + /** + * Constructs an empty SafelyHashMap with the specified initial + * capacity and the default load factor (0.75). + * + * @param initialCapacity + * the initial capacity. + * @throws IllegalArgumentException + * if the initial capacity is negative. + */ + public AntiCollisionHashMap(int initialCapacity) { + this(initialCapacity, DEFAULT_LOAD_FACTOR); + } + + /** + * Constructs an empty SafelyHashMap with the default initial + * capacity (16) and the default load factor (0.75). + */ + public AntiCollisionHashMap() { + this.loadFactor = DEFAULT_LOAD_FACTOR; + threshold = (int) (DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); + table = new Entry[DEFAULT_INITIAL_CAPACITY]; + init(); + } + + /** + * Constructs a new SafelyHashMap with the same mappings as the + * specified Map. The SafelyHashMap is created with + * default load factor (0.75) and an initial capacity sufficient to hold the + * mappings in the specified Map. + * + * @param m + * the map whose mappings are to be placed in this map + * @throws NullPointerException + * if the specified map is null + */ + public AntiCollisionHashMap(Map m) { + this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, + DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR); + putAllForCreate(m); + } + + // internal utilities + + /** + * Initialization hook for subclasses. This method is called in all + * constructors and pseudo-constructors (clone, readObject) after + * SafelyHashMap has been initialized but before any entries have been + * inserted. (In the absence of this method, readObject would require + * explicit knowledge of subclasses.) + */ + void init() { + } + + /** + * Applies a supplemental hash function to a given hashCode, which defends + * against poor quality hash functions. This is critical because + * SafelyHashMap uses power-of-two length hash tables, that otherwise + * encounter collisions for hashCodes that do not differ in lower bits. + * Note: Null keys always map to hash 0, thus index 0. + */ + static int hash(int h) { + // This function ensures that hashCodes that differ only by + // constant multiples at each bit position have a bounded + // number of collisions (approximately 8 at default load factor). + h = h * h; + h ^= (h >>> 20) ^ (h >>> 12); + return h ^ (h >>> 7) ^ (h >>> 4); + } + + /** + * Returns index for hash code h. + */ + static int indexFor(int h, int length) { + return h & (length - 1); + } + + /** + * Returns the number of key-value mappings in this map. + * + * @return the number of key-value mappings in this map + */ + public int size() { + return size; + } + + /** + * Returns true if this map contains no key-value mappings. + * + * @return true if this map contains no key-value mappings + */ + public boolean isEmpty() { + return size == 0; + } + + /** + * Returns the value to which the specified key is mapped, or {@code null} + * if this map contains no mapping for the key. + * + *

+ * More formally, if this map contains a mapping from a key {@code k} to a + * value {@code v} such that {@code (key==null ? k==null : + * key.equals(k))}, then this method returns {@code v}; otherwise it returns + * {@code null}. (There can be at most one such mapping.) + * + *

+ * A return value of {@code null} does not necessarily indicate that + * the map contains no mapping for the key; it's also possible that the map + * explicitly maps the key to {@code null}. The {@link #containsKey + * containsKey} operation may be used to distinguish these two cases. + * + * @see #put(Object, Object) + */ + public V get(Object key) { + if (key == null) + return getForNullKey(); + int hash = 0; + if (key instanceof String) + hash = hash(hashString((String) key)); + else + hash = hash(key.hashCode()); + for (Entry e = table[indexFor(hash, table.length)]; e != null; e = e.next) { + Object k; + if (e.hash == hash && ((k = e.key) == key || key.equals(k))) + return e.value; + } + return null; + } + + /** + * Offloaded version of get() to look up null keys. Null keys map to index + * 0. This null case is split out into separate methods for the sake of + * performance in the two most commonly used operations (get and put), but + * incorporated with conditionals in others. + */ + private V getForNullKey() { + for (Entry e = table[0]; e != null; e = e.next) { + if (e.key == null) + return e.value; + } + return null; + } + + /** + * Returns true if this map contains a mapping for the specified + * key. + * + * @param key + * The key whose presence in this map is to be tested + * @return true if this map contains a mapping for the specified + * key. + */ + public boolean containsKey(Object key) { + return getEntry(key) != null; + } + + /** + * Returns the entry associated with the specified key in the SafelyHashMap. + * Returns null if the SafelyHashMap contains no mapping for the key. + */ + final Entry getEntry(Object key) { + int hash = (key == null) ? 0 + : (key instanceof String) ? hash(hashString((String) key)) + : hash(key.hashCode()); + for (Entry e = table[indexFor(hash, table.length)]; e != null; e = e.next) { + Object k; + if (e.hash == hash + && ((k = e.key) == key || (key != null && key.equals(k)))) + return e; + } + return null; + } + + /** + * Associates the specified value with the specified key in this map. If the + * map previously contained a mapping for the key, the old value is + * replaced. + * + * @param key + * key with which the specified value is to be associated + * @param value + * value to be associated with the specified key + * @return the previous value associated with key, or null + * if there was no mapping for key. (A null return + * can also indicate that the map previously associated + * null with key.) + */ + public V put(K key, V value) { + if (key == null) + return putForNullKey(value); + int hash = 0; + if (key instanceof String) + hash = hash(hashString((String) key)); + else + hash = hash(key.hashCode()); + int i = indexFor(hash, table.length); + for (Entry e = table[i]; e != null; e = e.next) { + Object k; + if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { + V oldValue = e.value; + e.value = value; + e.recordAccess(this); + return oldValue; + } + } + + modCount++; + addEntry(hash, key, value, i); + return null; + } + + /** + * Offloaded version of put for null keys + */ + private V putForNullKey(V value) { + for (Entry e = table[0]; e != null; e = e.next) { + if (e.key == null) { + V oldValue = e.value; + e.value = value; + e.recordAccess(this); + return oldValue; + } + } + modCount++; + addEntry(0, null, value, 0); + return null; + } + + /** + * This method is used instead of put by constructors and pseudoconstructors + * (clone, readObject). It does not resize the table, check for + * comodification, etc. It calls createEntry rather than addEntry. + */ + private void putForCreate(K key, V value) { + int hash = (key == null) ? 0 + : (key instanceof String) ? hash(hashString((String) key)) + : hash(key.hashCode()); + int i = indexFor(hash, table.length); + + /** + * Look for preexisting entry for key. This will never happen for clone + * or deserialize. It will only happen for construction if the input Map + * is a sorted map whose ordering is inconsistent w/ equals. + */ + for (Entry e = table[i]; e != null; e = e.next) { + Object k; + if (e.hash == hash + && ((k = e.key) == key || (key != null && key.equals(k)))) { + e.value = value; + return; + } + } + + createEntry(hash, key, value, i); + } + + private void putAllForCreate(Map m) { + for (Iterator> i = m + .entrySet().iterator(); i.hasNext();) { + Map.Entry e = i.next(); + putForCreate(e.getKey(), e.getValue()); + } + } + + /** + * Rehashes the contents of this map into a new array with a larger + * capacity. This method is called automatically when the number of keys in + * this map reaches its threshold. + * + * If current capacity is MAXIMUM_CAPACITY, this method does not resize the + * map, but sets threshold to Integer.MAX_VALUE. This has the effect of + * preventing future calls. + * + * @param newCapacity + * the new capacity, MUST be a power of two; must be greater than + * current capacity unless current capacity is MAXIMUM_CAPACITY + * (in which case value is irrelevant). + */ + void resize(int newCapacity) { + Entry[] oldTable = table; + int oldCapacity = oldTable.length; + if (oldCapacity == MAXIMUM_CAPACITY) { + threshold = Integer.MAX_VALUE; + return; + } + + Entry[] newTable = new Entry[newCapacity]; + transfer(newTable); + table = newTable; + threshold = (int) (newCapacity * loadFactor); + } + + /** + * Transfers all entries from current table to newTable. + */ + void transfer(Entry[] newTable) { + Entry[] src = table; + int newCapacity = newTable.length; + for (int j = 0; j < src.length; j++) { + Entry e = src[j]; + if (e != null) { + src[j] = null; + do { + Entry next = e.next; + int i = indexFor(e.hash, newCapacity); + e.next = newTable[i]; + newTable[i] = e; + e = next; + } while (e != null); + } + } + } + + /** + * Copies all of the mappings from the specified map to this map. These + * mappings will replace any mappings that this map had for any of the keys + * currently in the specified map. + * + * @param m + * mappings to be stored in this map + * @throws NullPointerException + * if the specified map is null + */ + public void putAll(Map m) { + int numKeysToBeAdded = m.size(); + if (numKeysToBeAdded == 0) + return; + + /* + * Expand the map if the map if the number of mappings to be added is + * greater than or equal to threshold. This is conservative; the obvious + * condition is (m.size() + size) >= threshold, but this condition could + * result in a map with twice the appropriate capacity, if the keys to + * be added overlap with the keys already in this map. By using the + * conservative calculation, we subject ourself to at most one extra + * resize. + */ + if (numKeysToBeAdded > threshold) { + int targetCapacity = (int) (numKeysToBeAdded / loadFactor + 1); + if (targetCapacity > MAXIMUM_CAPACITY) + targetCapacity = MAXIMUM_CAPACITY; + int newCapacity = table.length; + while (newCapacity < targetCapacity) + newCapacity <<= 1; + if (newCapacity > table.length) + resize(newCapacity); + } + + for (Iterator> i = m + .entrySet().iterator(); i.hasNext();) { + Map.Entry e = i.next(); + put(e.getKey(), e.getValue()); + } + } + + /** + * Removes the mapping for the specified key from this map if present. + * + * @param key + * key whose mapping is to be removed from the map + * @return the previous value associated with key, or null + * if there was no mapping for key. (A null return + * can also indicate that the map previously associated + * null with key.) + */ + public V remove(Object key) { + Entry e = removeEntryForKey(key); + return (e == null ? null : e.value); + } + + /** + * Removes and returns the entry associated with the specified key in the + * SafelyHashMap. Returns null if the SafelyHashMap contains no mapping for + * this key. + */ + final Entry removeEntryForKey(Object key) { + int hash = (key == null) ? 0 + : (key instanceof String) ? hash(hashString((String) key)) + : hash(key.hashCode()); + int i = indexFor(hash, table.length); + Entry prev = table[i]; + Entry e = prev; + + while (e != null) { + Entry next = e.next; + Object k; + if (e.hash == hash + && ((k = e.key) == key || (key != null && key.equals(k)))) { + modCount++; + size--; + if (prev == e) + table[i] = next; + else + prev.next = next; + e.recordRemoval(this); + return e; + } + prev = e; + e = next; + } + + return e; + } + + /** + * Special version of remove for EntrySet. + */ + final Entry removeMapping(Object o) { + if (!(o instanceof Map.Entry)) + return null; + + Map.Entry entry = (Map.Entry) o; + Object key = entry.getKey(); + int hash = (key == null) ? 0 + : (key instanceof String) ? hash(hashString((String) key)) + : hash(key.hashCode()); + int i = indexFor(hash, table.length); + Entry prev = table[i]; + Entry e = prev; + + while (e != null) { + Entry next = e.next; + if (e.hash == hash && e.equals(entry)) { + modCount++; + size--; + if (prev == e) + table[i] = next; + else + prev.next = next; + e.recordRemoval(this); + return e; + } + prev = e; + e = next; + } + + return e; + } + + /** + * Removes all of the mappings from this map. The map will be empty after + * this call returns. + */ + public void clear() { + modCount++; + Entry[] tab = table; + for (int i = 0; i < tab.length; i++) + tab[i] = null; + size = 0; + } + + /** + * Returns true if this map maps one or more keys to the specified + * value. + * + * @param value + * value whose presence in this map is to be tested + * @return true if this map maps one or more keys to the specified + * value + */ + public boolean containsValue(Object value) { + if (value == null) + return containsNullValue(); + + Entry[] tab = table; + for (int i = 0; i < tab.length; i++) + for (Entry e = tab[i]; e != null; e = e.next) + if (value.equals(e.value)) + return true; + return false; + } + + /** + * Special-case code for containsValue with null argument + */ + private boolean containsNullValue() { + Entry[] tab = table; + for (int i = 0; i < tab.length; i++) + for (Entry e = tab[i]; e != null; e = e.next) + if (e.value == null) + return true; + return false; + } + + /** + * Returns a shallow copy of this SafelyHashMap instance: the keys + * and values themselves are not cloned. + * + * @return a shallow copy of this map + */ + public Object clone() { + AntiCollisionHashMap result = null; + try { + result = (AntiCollisionHashMap) super.clone(); + } catch (CloneNotSupportedException e) { + // assert false; + } + result.table = new Entry[table.length]; + result.entrySet = null; + result.modCount = 0; + result.size = 0; + result.init(); + result.putAllForCreate(this); + + return result; + } + + static class Entry implements Map.Entry { + final K key; + V value; + Entry next; + final int hash; + + /** + * Creates new entry. + */ + Entry(int h, K k, V v, Entry n) { + value = v; + next = n; + key = k; + hash = h; + } + + public final K getKey() { + return key; + } + + public final V getValue() { + return value; + } + + public final V setValue(V newValue) { + V oldValue = value; + value = newValue; + return oldValue; + } + + public final boolean equals(Object o) { + if (!(o instanceof Map.Entry)) + return false; + Map.Entry e = (Map.Entry) o; + Object k1 = getKey(); + Object k2 = e.getKey(); + if (k1 == k2 || (k1 != null && k1.equals(k2))) { + Object v1 = getValue(); + Object v2 = e.getValue(); + if (v1 == v2 || (v1 != null && v1.equals(v2))) + return true; + } + return false; + } + + public final int hashCode() { + return (key == null ? 0 : key.hashCode()) + ^ (value == null ? 0 : value.hashCode()); + } + + public final String toString() { + return getKey() + "=" + getValue(); + } + + /** + * This method is invoked whenever the value in an entry is overwritten + * by an invocation of put(k,v) for a key k that's already in the + * SafelyHashMap. + */ + void recordAccess(AntiCollisionHashMap m) { + } + + /** + * This method is invoked whenever the entry is removed from the table. + */ + void recordRemoval(AntiCollisionHashMap m) { + } + } + + /** + * Adds a new entry with the specified key, value and hash code to the + * specified bucket. It is the responsibility of this method to resize the + * table if appropriate. + * + * Subclass overrides this to alter the behavior of put method. + */ + void addEntry(int hash, K key, V value, int bucketIndex) { + Entry e = table[bucketIndex]; + table[bucketIndex] = new Entry(hash, key, value, e); + if (size++ >= threshold) + resize(2 * table.length); + } + + /** + * Like addEntry except that this version is used when creating entries as + * part of Map construction or "pseudo-construction" (cloning, + * deserialization). This version needn't worry about resizing the table. + * + * Subclass overrides this to alter the behavior of SafelyHashMap(Map), + * clone, and readObject. + */ + void createEntry(int hash, K key, V value, int bucketIndex) { + Entry e = table[bucketIndex]; + table[bucketIndex] = new Entry(hash, key, value, e); + size++; + } + + private abstract class HashIterator implements Iterator { + Entry next; // next entry to return + int expectedModCount; // For fast-fail + int index; // current slot + Entry current; // current entry + + HashIterator() { + expectedModCount = modCount; + if (size > 0) { // advance to first entry + Entry[] t = table; + while (index < t.length && (next = t[index++]) == null) + ; + } + } + + public final boolean hasNext() { + return next != null; + } + + final Entry nextEntry() { + if (modCount != expectedModCount) + throw new ConcurrentModificationException(); + Entry e = next; + if (e == null) + throw new NoSuchElementException(); + + if ((next = e.next) == null) { + Entry[] t = table; + while (index < t.length && (next = t[index++]) == null) + ; + } + current = e; + return e; + } + + public void remove() { + if (current == null) + throw new IllegalStateException(); + if (modCount != expectedModCount) + throw new ConcurrentModificationException(); + Object k = current.key; + current = null; + AntiCollisionHashMap.this.removeEntryForKey(k); + expectedModCount = modCount; + } + + } + + private final class ValueIterator extends HashIterator { + public V next() { + return nextEntry().value; + } + } + + private final class KeyIterator extends HashIterator { + public K next() { + return nextEntry().getKey(); + } + } + + private final class EntryIterator extends HashIterator> { + public Map.Entry next() { + return nextEntry(); + } + } + + // Subclass overrides these to alter behavior of views' iterator() method + Iterator newKeyIterator() { + return new KeyIterator(); + } + + Iterator newValueIterator() { + return new ValueIterator(); + } + + Iterator> newEntryIterator() { + return new EntryIterator(); + } + + // Views + + private transient Set> entrySet = null; + + /** + * Returns a {@link Set} view of the keys contained in this map. The set is + * backed by the map, so changes to the map are reflected in the set, and + * vice-versa. If the map is modified while an iteration over the set is in + * progress (except through the iterator's own remove operation), + * the results of the iteration are undefined. The set supports element + * removal, which removes the corresponding mapping from the map, via the + * Iterator.remove, Set.remove, removeAll, + * retainAll, and clear operations. It does not support + * the add or addAll operations. + */ + public Set keySet() { + + Set ks = keySet; + return (ks != null ? ks : (keySet = new KeySet())); + } + + private final class KeySet extends AbstractSet { + public Iterator iterator() { + return newKeyIterator(); + } + + public int size() { + return size; + } + + public boolean contains(Object o) { + return containsKey(o); + } + + public boolean remove(Object o) { + return AntiCollisionHashMap.this.removeEntryForKey(o) != null; + } + + public void clear() { + AntiCollisionHashMap.this.clear(); + } + } + + /** + * Returns a {@link Collection} view of the values contained in this map. + * The collection is backed by the map, so changes to the map are reflected + * in the collection, and vice-versa. If the map is modified while an + * iteration over the collection is in progress (except through the + * iterator's own remove operation), the results of the iteration + * are undefined. The collection supports element removal, which removes the + * corresponding mapping from the map, via the Iterator.remove, + * Collection.remove, removeAll, retainAll and + * clear operations. It does not support the add or + * addAll operations. + */ + public Collection values() { + Collection vs = values; + return (vs != null ? vs : (values = new Values())); + } + + private final class Values extends AbstractCollection { + public Iterator iterator() { + return newValueIterator(); + } + + public int size() { + return size; + } + + public boolean contains(Object o) { + return containsValue(o); + } + + public void clear() { + AntiCollisionHashMap.this.clear(); + } + } + + /** + * Returns a {@link Set} view of the mappings contained in this map. The set + * is backed by the map, so changes to the map are reflected in the set, and + * vice-versa. If the map is modified while an iteration over the set is in + * progress (except through the iterator's own remove operation, or + * through the setValue operation on a map entry returned by the + * iterator) the results of the iteration are undefined. The set supports + * element removal, which removes the corresponding mapping from the map, + * via the Iterator.remove, Set.remove, removeAll + * , retainAll and clear operations. It does not support + * the add or addAll operations. + * + * @return a set view of the mappings contained in this map + */ + public Set> entrySet() { + return entrySet0(); + } + + private Set> entrySet0() { + Set> es = entrySet; + return es != null ? es : (entrySet = new EntrySet()); + } + + private final class EntrySet extends AbstractSet> { + public Iterator> iterator() { + return newEntryIterator(); + } + + public boolean contains(Object o) { + if (!(o instanceof Map.Entry)) + return false; + Map.Entry e = (Map.Entry) o; + Entry candidate = getEntry(e.getKey()); + return candidate != null && candidate.equals(e); + } + + public boolean remove(Object o) { + return removeMapping(o) != null; + } + + public int size() { + return size; + } + + public void clear() { + AntiCollisionHashMap.this.clear(); + } + } + + /** + * Save the state of the SafelyHashMap instance to a stream (i.e., + * serialize it). + * + * @serialData The capacity of the SafelyHashMap (the length of the + * bucket array) is emitted (int), followed by the size + * (an int, the number of key-value mappings), followed by the + * key (Object) and value (Object) for each key-value mapping. + * The key-value mappings are emitted in no particular order. + */ + private void writeObject(java.io.ObjectOutputStream s) throws IOException { + Iterator> i = (size > 0) ? entrySet0().iterator() + : null; + + // Write out the threshold, loadfactor, and any hidden stuff + s.defaultWriteObject(); + + // Write out number of buckets + s.writeInt(table.length); + + // Write out size (number of Mappings) + s.writeInt(size); + + // Write out keys and values (alternating) + if (i != null) { + while (i.hasNext()) { + Map.Entry e = i.next(); + s.writeObject(e.getKey()); + s.writeObject(e.getValue()); + } + } + } + + private static final long serialVersionUID = 362498820763181265L; + + /** + * Reconstitute the SafelyHashMap instance from a stream (i.e., + * deserialize it). + */ + private void readObject(java.io.ObjectInputStream s) throws IOException, + ClassNotFoundException { + // Read in the threshold, loadfactor, and any hidden stuff + s.defaultReadObject(); + + // Read in number of buckets and allocate the bucket array; + int numBuckets = s.readInt(); + table = new Entry[numBuckets]; + + init(); // Give subclass a chance to do its thing. + + // Read in size (number of Mappings) + int size = s.readInt(); + + // Read the keys and values, and put the mappings in the SafelyHashMap + for (int i = 0; i < size; i++) { + K key = (K) s.readObject(); + V value = (V) s.readObject(); + putForCreate(key, value); + } + } + + // These methods are used when serializing HashSets + int capacity() { + return table.length; + } + + float loadFactor() { + return loadFactor; + } + +} \ No newline at end of file diff --git a/src/main/java/com/alibaba/fastjson/util/Base64.java b/src/main/java/com/alibaba/fastjson/util/Base64.java new file mode 100644 index 0000000000..08216a38b2 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/util/Base64.java @@ -0,0 +1,210 @@ +package com.alibaba.fastjson.util; + +import java.util.Arrays; + +/** + * + * @version 2.2 + * @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11 + * @deprecated internal api, don't use. + */ +public class Base64 { + + public static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); + public static final int[] IA = new int[256]; + static { + Arrays.fill(IA, -1); + for (int i = 0, iS = CA.length; i < iS; i++) + IA[CA[i]] = i; + IA['='] = 0; + } + + /** + * Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as + * fast as #decode(char[]). The preconditions are:
+ * + The array must have a line length of 76 chars OR no line separators at all (one line).
+ * + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within + * the encoded string
+ * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.
+ * + * @param chars The source array. Length 0 will return an empty array. null will throw an exception. + * @return The decoded array of bytes. May be of length 0. + */ + public static byte[] decodeFast(char[] chars, int offset, int charsLen) { + // Check special case + if (charsLen == 0) { + return new byte[0]; + } + + int sIx = offset, eIx = offset + charsLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while (sIx < eIx && IA[chars[sIx]] < 0) + sIx++; + + // Trim illegal chars from end + while (eIx > 0 && IA[chars[eIx]] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = chars[eIx] == '=' ? (chars[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = charsLen > 76 ? (chars[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes + byte[] bytes = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[chars[sIx++]] << 18 | IA[chars[sIx++]] << 12 | IA[chars[sIx++]] << 6 | IA[chars[sIx++]]; + + // Add the bytes + bytes[d++] = (byte) (i >> 16); + bytes[d++] = (byte) (i >> 8); + bytes[d++] = (byte) i; + + // If line separator, jump over it. + if (sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if (d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for (int j = 0; sIx <= eIx - pad; j++) + i |= IA[chars[sIx++]] << (18 - j * 6); + + for (int r = 16; d < len; r -= 8) + bytes[d++] = (byte) (i >> r); + } + + return bytes; + } + + public static byte[] decodeFast(String chars, int offset, int charsLen) { + // Check special case + if (charsLen == 0) { + return new byte[0]; + } + + int sIx = offset, eIx = offset + charsLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while (sIx < eIx && IA[chars.charAt(sIx)] < 0) + sIx++; + + // Trim illegal chars from end + while (eIx > 0 && IA[chars.charAt(eIx)] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = chars.charAt(eIx) == '=' ? (chars.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = charsLen > 76 ? (chars.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes + byte[] bytes = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[chars.charAt(sIx++)] << 18 | IA[chars.charAt(sIx++)] << 12 | IA[chars.charAt(sIx++)] << 6 | IA[chars.charAt(sIx++)]; + + // Add the bytes + bytes[d++] = (byte) (i >> 16); + bytes[d++] = (byte) (i >> 8); + bytes[d++] = (byte) i; + + // If line separator, jump over it. + if (sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if (d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for (int j = 0; sIx <= eIx - pad; j++) + i |= IA[chars.charAt(sIx++)] << (18 - j * 6); + + for (int r = 16; d < len; r -= 8) + bytes[d++] = (byte) (i >> r); + } + + return bytes; + } + + /** + * Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as fast + * as decode(String). The preconditions are:
+ * + The array must have a line length of 76 chars OR no line separators at all (one line).
+ * + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within + * the encoded string
+ * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.
+ * + * @param s The source string. Length 0 will return an empty array. null will throw an exception. + * @return The decoded array of bytes. May be of length 0. + */ + public static byte[] decodeFast(String s) { + // Check special case + int sLen = s.length(); + if (sLen == 0) { + return new byte[0]; + } + + int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0) + sIx++; + + // Trim illegal chars from end + while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 + | IA[s.charAt(sIx++)]; + + // Add the bytes + dArr[d++] = (byte) (i >> 16); + dArr[d++] = (byte) (i >> 8); + dArr[d++] = (byte) i; + + // If line separator, jump over it. + if (sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if (d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for (int j = 0; sIx <= eIx - pad; j++) + i |= IA[s.charAt(sIx++)] << (18 - j * 6); + + for (int r = 16; d < len; r -= 8) + dArr[d++] = (byte) (i >> r); + } + + return dArr; + } +} \ No newline at end of file diff --git a/src/main/java/com/alibaba/fastjson/util/FieldInfo.java b/src/main/java/com/alibaba/fastjson/util/FieldInfo.java old mode 100644 new mode 100755 index d318f49304..66ee78bfe9 --- a/src/main/java/com/alibaba/fastjson/util/FieldInfo.java +++ b/src/main/java/com/alibaba/fastjson/util/FieldInfo.java @@ -1,67 +1,505 @@ package com.alibaba.fastjson.util; import java.lang.annotation.Annotation; +import java.lang.reflect.Array; import java.lang.reflect.Field; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.GenericDeclaration; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Member; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.util.Arrays; + +import com.alibaba.fastjson.annotation.JSONField; public class FieldInfo implements Comparable { - private final String name; - private final Method method; - private final Field field; + public final String name; + public final Method method; + public final Field field; + + private int ordinal = 0; + public final Class fieldClass; + public final Type fieldType; + public final Class declaringClass; + public final boolean getOnly; + public final int serialzeFeatures; + public final int parserFeatures; + public final String label; + + private final JSONField fieldAnnotation; + private final JSONField methodAnnotation; + + public final boolean fieldAccess; + public final boolean fieldTransient; + + public final char[] name_chars; + + public final boolean isEnum; + public final boolean jsonDirect; + public final boolean unwrapped; + + public final String format; + + public final String[] alternateNames; + + public FieldInfo(String name, // + Class declaringClass, // + Class fieldClass, // + Type fieldType, // + Field field, // + int ordinal, // + int serialzeFeatures, // + int parserFeatures){ + this.name = name; + this.declaringClass = declaringClass; + this.fieldClass = fieldClass; + this.fieldType = fieldType; + this.method = null; + this.field = field; + this.ordinal = ordinal; + this.serialzeFeatures = serialzeFeatures; + this.parserFeatures = parserFeatures; + + isEnum = fieldClass.isEnum(); + + if (field != null) { + int modifiers = field.getModifiers(); + fieldAccess = (modifiers & Modifier.PUBLIC) != 0 || method == null; + fieldTransient = Modifier.isTransient(modifiers); + } else { + fieldTransient = false; + fieldAccess = false; + } + + name_chars = genFieldNameChars(); - private final Class fieldClass; - private final Type fieldType; + if (field != null) { + TypeUtils.setAccessible(field); + } + + this.label = ""; + fieldAnnotation = null; + methodAnnotation = null; + this.getOnly = false; + this.jsonDirect = false; + this.unwrapped = false; + this.format = null; + this.alternateNames = new String[0]; + } - public FieldInfo(String name, Method method, Field field){ + public FieldInfo(String name, // + Method method, // + Field field, // + Class clazz, // + Type type, // + int ordinal, // + int serialzeFeatures, // + int parserFeatures, // + JSONField fieldAnnotation, // + JSONField methodAnnotation, // + String label){ + if (field != null) { + String fieldName = field.getName(); + if (fieldName.equals(name)) { + name = fieldName; + } + } + this.name = name; this.method = method; this.field = field; + this.ordinal = ordinal; + this.serialzeFeatures = serialzeFeatures; + this.parserFeatures = parserFeatures; + this.fieldAnnotation = fieldAnnotation; + this.methodAnnotation = methodAnnotation; + + if (field != null) { + int modifiers = field.getModifiers(); + fieldAccess = ((modifiers & Modifier.PUBLIC) != 0 || method == null); + fieldTransient = Modifier.isTransient(modifiers) + || TypeUtils.isTransient(method); + } else { + fieldAccess = false; + fieldTransient = false; + } + + if (label != null && label.length() > 0) { + this.label = label; + } else { + this.label = ""; + } + + String format = null; + JSONField annotation = getAnnotation(); - if (method.getParameterTypes().length == 1) { - this.fieldClass = method.getParameterTypes()[0]; - this.fieldType = method.getGenericParameterTypes()[0]; + boolean jsonDirect = false; + if (annotation != null) { + format = annotation.format(); + + if (format.trim().length() == 0) { + format = null; + } + jsonDirect = annotation.jsonDirect(); + unwrapped = annotation.unwrapped(); + alternateNames = annotation.alternateNames(); } else { - this.fieldClass = method.getReturnType(); - this.fieldType = method.getGenericReturnType(); + jsonDirect = false; + unwrapped = false; + alternateNames = new String[0]; + } + this.format = format; + + name_chars = genFieldNameChars(); + + if (method != null) { + TypeUtils.setAccessible(method); + } + + if (field != null) { + TypeUtils.setAccessible(field); + } + + boolean getOnly = false; + Type fieldType; + Class fieldClass; + if (method != null) { + Class[] types; + if ((types = method.getParameterTypes()).length == 1) { + fieldClass = types[0]; + fieldType = method.getGenericParameterTypes()[0]; + } else if (types.length == 2 && types[0] == String.class && types[1] == Object.class) { + fieldType = fieldClass = types[0]; + } else { + fieldClass = method.getReturnType(); + fieldType = method.getGenericReturnType(); + getOnly = true; + } + this.declaringClass = method.getDeclaringClass(); + } else { + fieldClass = field.getType(); + fieldType = field.getGenericType(); + this.declaringClass = field.getDeclaringClass(); + getOnly = Modifier.isFinal(field.getModifiers()); + } + this.getOnly = getOnly; + this.jsonDirect = jsonDirect && fieldClass == String.class; + + if (clazz != null && fieldClass == Object.class && fieldType instanceof TypeVariable) { + TypeVariable tv = (TypeVariable) fieldType; + Type genericFieldType = getInheritGenericType(clazz, type, tv); + if (genericFieldType != null) { + this.fieldClass = TypeUtils.getClass(genericFieldType); + this.fieldType = genericFieldType; + + isEnum = fieldClass.isEnum(); + return; + } + } + + Type genericFieldType = fieldType; + + if (!(fieldType instanceof Class)) { + genericFieldType = getFieldType(clazz, type != null ? type : clazz, fieldType); + + if (genericFieldType != fieldType) { + if (genericFieldType instanceof ParameterizedType) { + fieldClass = TypeUtils.getClass(genericFieldType); + } else if (genericFieldType instanceof Class) { + fieldClass = TypeUtils.getClass(genericFieldType); + } + } } - } - public Class getFieldClass() { - return fieldClass; + this.fieldType = genericFieldType; + this.fieldClass = fieldClass; + + isEnum = fieldClass.isEnum(); + } + + protected char[] genFieldNameChars() { + int nameLen = this.name.length(); + char[] name_chars = new char[nameLen + 3]; + this.name.getChars(0, this.name.length(), name_chars, 1); + name_chars[0] = '"'; + name_chars[nameLen + 1] = '"'; + name_chars[nameLen + 2] = ':'; + return name_chars; } + + @SuppressWarnings("unchecked") + public T getAnnation(Class annotationClass) { + if (annotationClass == JSONField.class) { + return (T) getAnnotation(); + } + + T annotatition = null; + if (method != null) { + annotatition = method.getAnnotation(annotationClass); + } + + if (annotatition == null && field != null) { + annotatition = field.getAnnotation(annotationClass); + } + + return annotatition; + } + + public static Type getFieldType(final Class clazz, final Type type, Type fieldType) { + if (clazz == null || type == null) { + return fieldType; + } + + if (fieldType instanceof GenericArrayType) { + GenericArrayType genericArrayType = (GenericArrayType) fieldType; + Type componentType = genericArrayType.getGenericComponentType(); + Type componentTypeX = getFieldType(clazz, type, componentType); + if (componentType != componentTypeX) { + Type fieldTypeX = Array.newInstance(TypeUtils.getClass(componentTypeX), 0).getClass(); + return fieldTypeX; + } + + return fieldType; + } + + if (!TypeUtils.isGenericParamType(type)) { + return fieldType; + } + + if (fieldType instanceof TypeVariable) { + ParameterizedType paramType = (ParameterizedType) TypeUtils.getGenericParamType(type); + Class parameterizedClass = TypeUtils.getClass(paramType); + final TypeVariable typeVar = (TypeVariable) fieldType; + + TypeVariable[] typeVariables = parameterizedClass.getTypeParameters(); + for (int i = 0; i < typeVariables.length; ++i) { + if (typeVariables[i].getName().equals(typeVar.getName())) { + fieldType = paramType.getActualTypeArguments()[i]; + return fieldType; + } + } + } + + if (fieldType instanceof ParameterizedType) { + ParameterizedType parameterizedFieldType = (ParameterizedType) fieldType; + + Type[] arguments = parameterizedFieldType.getActualTypeArguments(); + TypeVariable[] typeVariables; + ParameterizedType paramType; + if (type instanceof ParameterizedType) { + paramType = (ParameterizedType) type; + typeVariables = clazz.getTypeParameters(); + } else if(clazz.getGenericSuperclass() instanceof ParameterizedType) { + paramType = (ParameterizedType) clazz.getGenericSuperclass(); + typeVariables = clazz.getSuperclass().getTypeParameters(); + } else { + paramType = parameterizedFieldType; + typeVariables = type.getClass().getTypeParameters(); + } + + boolean changed = getArgument(arguments, typeVariables, paramType.getActualTypeArguments()); + if (changed) { + fieldType = new ParameterizedTypeImpl(arguments, parameterizedFieldType.getOwnerType(), + parameterizedFieldType.getRawType()); + return fieldType; + } + } - public Type getFieldType() { return fieldType; } - public String getName() { - return name; + private static boolean getArgument(Type[] typeArgs, TypeVariable[] typeVariables, Type[] arguments) { + if (arguments == null || typeVariables.length == 0) { + return false; + } + + boolean changed = false; + for (int i = 0; i < typeArgs.length; ++i) { + Type typeArg = typeArgs[i]; + if (typeArg instanceof ParameterizedType) { + ParameterizedType p_typeArg = (ParameterizedType) typeArg; + Type[] p_typeArg_args = p_typeArg.getActualTypeArguments(); + boolean p_changed = getArgument(p_typeArg_args, typeVariables, arguments); + if (p_changed) { + typeArgs[i] = new ParameterizedTypeImpl(p_typeArg_args, p_typeArg.getOwnerType(), p_typeArg.getRawType()); + changed = true; + } + } else if (typeArg instanceof TypeVariable) { + for (int j = 0; j < typeVariables.length; ++j) { + if (typeArg.equals(typeVariables[j])) { + typeArgs[i] = arguments[j]; + changed = true; + } + } + } + } + + return changed; } - public Method getMethod() { - return method; + private static Type getInheritGenericType(Class clazz, Type type, TypeVariable tv) { + GenericDeclaration gd = tv.getGenericDeclaration(); + + Class class_gd = null; + if (gd instanceof Class) { + class_gd = (Class) tv.getGenericDeclaration(); + } + + Type[] arguments = null; + if (class_gd == clazz) { + if (type instanceof ParameterizedType) { + ParameterizedType ptype = (ParameterizedType) type; + arguments = ptype.getActualTypeArguments(); + } + } else { + for (Class c = clazz; c != null && c != Object.class && c != class_gd; c = c.getSuperclass()) { + Type superType = c.getGenericSuperclass(); + + if (superType instanceof ParameterizedType) { + ParameterizedType p_superType = (ParameterizedType) superType; + Type[] p_superType_args = p_superType.getActualTypeArguments(); + getArgument(p_superType_args, c.getTypeParameters(), arguments); + arguments = p_superType_args; + } + } + } + + if (arguments == null || class_gd == null) { + return null; + } + + Type actualType = null; + TypeVariable[] typeVariables = class_gd.getTypeParameters(); + for (int j = 0; j < typeVariables.length; ++j) { + if (tv.equals(typeVariables[j])) { + actualType = arguments[j]; + break; + } + } + + return actualType; } - public Field getField() { - return field; + public String toString() { + return this.name; } - public int compareTo(FieldInfo o) { - return this.name.compareTo(o.name); + public Member getMember() { + if (method != null) { + return method; + } else { + return field; + } + } + + protected Class getDeclaredClass() { + if (this.method != null) { + return this.method.getDeclaringClass(); + } + + if (this.field != null) { + return this.field.getDeclaringClass(); + } + + return null; } - public T getAnnotation(Class annotationClass) { - T annotation = null; - annotation = method.getAnnotation(annotationClass); + public int compareTo(FieldInfo o) { + if (this.ordinal < o.ordinal) { + return -1; + } - if (annotation == null) { - if (field != null) { - annotation = field.getAnnotation(annotationClass); + if (this.ordinal > o.ordinal) { + return 1; + } + + int result = this.name.compareTo(o.name); + + if (result != 0) { + return result; + } + + Class thisDeclaringClass = this.getDeclaredClass(); + Class otherDeclaringClass = o.getDeclaredClass(); + + if (thisDeclaringClass != null && otherDeclaringClass != null && thisDeclaringClass != otherDeclaringClass) { + if (thisDeclaringClass.isAssignableFrom(otherDeclaringClass)) { + return -1; } + + if (otherDeclaringClass.isAssignableFrom(thisDeclaringClass)) { + return 1; + } + } + + boolean isSampeType = this.field != null && this.field.getType() == this.fieldClass; + boolean oSameType = o.field != null && o.field.getType() == o.fieldClass; + + if (isSampeType && !oSameType) { + return 1; + } + + if (oSameType && !isSampeType) { + return -1; + } + + if (o.fieldClass.isPrimitive() && !this.fieldClass.isPrimitive()) { + return 1; + } + + if (this.fieldClass.isPrimitive() && !o.fieldClass.isPrimitive()) { + return -1; + } + + if (o.fieldClass.getName().startsWith("java.") && !this.fieldClass.getName().startsWith("java.")) { + return 1; + } + + if (this.fieldClass.getName().startsWith("java.") && !o.fieldClass.getName().startsWith("java.")) { + return -1; + } + + return this.fieldClass.getName().compareTo(o.fieldClass.getName()); + } + + public JSONField getAnnotation() { + if (this.fieldAnnotation != null) { + return this.fieldAnnotation; + } + + return this.methodAnnotation; + } + + public String getFormat() { + return format; + } + + public Object get(Object javaObject) throws IllegalAccessException, InvocationTargetException { + return method != null + ? method.invoke(javaObject) + : field.get(javaObject); + } + + public void set(Object javaObject, Object value) throws IllegalAccessException, InvocationTargetException { + if (method != null) { + method.invoke(javaObject, new Object[] { value }); + return; + } + + field.set(javaObject, value); + } + + public void setAccessible() throws SecurityException { + if (method != null) { + TypeUtils.setAccessible(method); + return; } - return annotation; + TypeUtils.setAccessible(field); } } diff --git a/src/main/java/com/alibaba/fastjson/util/IOUtils.java b/src/main/java/com/alibaba/fastjson/util/IOUtils.java old mode 100644 new mode 100755 index 3299c817f1..76df6cfda6 --- a/src/main/java/com/alibaba/fastjson/util/IOUtils.java +++ b/src/main/java/com/alibaba/fastjson/util/IOUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,18 +15,202 @@ */ package com.alibaba.fastjson.util; +import java.io.Closeable; +import java.io.InputStream; +import java.io.Reader; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; +import java.nio.charset.MalformedInputException; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Arrays; +import java.util.Properties; import com.alibaba.fastjson.JSONException; /** - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public class IOUtils { + + public final static String FASTJSON_PROPERTIES ="fastjson.properties"; + + public final static String FASTJSON_COMPATIBLEWITHJAVABEAN="fastjson.compatibleWithJavaBean"; + + public final static String FASTJSON_COMPATIBLEWITHFIELDNAME="fastjson.compatibleWithFieldName"; + + public final static Properties DEFAULT_PROPERTIES =new Properties(); + + public final static Charset UTF8 = Charset.forName("UTF-8"); + + public final static char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', + 'B', 'C', 'D', 'E', 'F' }; + + public final static boolean[] firstIdentifierFlags = new boolean[256]; + static { + for (char c = 0; c < firstIdentifierFlags.length; ++c) { + if (c >= 'A' && c <= 'Z') { + firstIdentifierFlags[c] = true; + } else if (c >= 'a' && c <= 'z') { + firstIdentifierFlags[c] = true; + } else if (c == '_' || c == '$') { + firstIdentifierFlags[c] = true; + } + } + } + + public final static boolean[] identifierFlags = new boolean[256]; + + static { + for (char c = 0; c < identifierFlags.length; ++c) { + if (c >= 'A' && c <= 'Z') { + identifierFlags[c] = true; + } else if (c >= 'a' && c <= 'z') { + identifierFlags[c] = true; + } else if (c == '_') { + identifierFlags[c] = true; + } else if (c >= '0' && c <= '9') { + identifierFlags[c] = true; + } + } + } + + static { + try { + loadPropertiesFromFile(); + } catch (Throwable e) { + //skip + } + } + + public static String getStringProperty(String name) { + String prop = null; + try { + prop = System.getProperty(name); + } catch (SecurityException e) { + //skip + } + return (prop == null) ? DEFAULT_PROPERTIES.getProperty(name) : prop; + } + + public static void loadPropertiesFromFile(){ + InputStream imputStream = AccessController.doPrivileged(new PrivilegedAction() { + public InputStream run() { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + if (cl != null) { + return cl.getResourceAsStream(FASTJSON_PROPERTIES); + } else { + return ClassLoader.getSystemResourceAsStream(FASTJSON_PROPERTIES); + } + } + }); + + if (null != imputStream) { + try { + DEFAULT_PROPERTIES.load(imputStream); + imputStream.close(); + } catch (java.io.IOException e) { + // skip + } + } + } + + public final static byte[] specicalFlags_doubleQuotes = new byte[161]; + public final static byte[] specicalFlags_singleQuotes = new byte[161]; + public final static boolean[] specicalFlags_doubleQuotesFlags = new boolean[161]; + public final static boolean[] specicalFlags_singleQuotesFlags = new boolean[161]; + + public final static char[] replaceChars = new char[93]; + static { + specicalFlags_doubleQuotes['\0'] = 4; + specicalFlags_doubleQuotes['\1'] = 4; + specicalFlags_doubleQuotes['\2'] = 4; + specicalFlags_doubleQuotes['\3'] = 4; + specicalFlags_doubleQuotes['\4'] = 4; + specicalFlags_doubleQuotes['\5'] = 4; + specicalFlags_doubleQuotes['\6'] = 4; + specicalFlags_doubleQuotes['\7'] = 4; + specicalFlags_doubleQuotes['\b'] = 1; // 8 + specicalFlags_doubleQuotes['\t'] = 1; // 9 + specicalFlags_doubleQuotes['\n'] = 1; // 10 + specicalFlags_doubleQuotes['\u000B'] = 4; // 11 + specicalFlags_doubleQuotes['\f'] = 1; // 12 + specicalFlags_doubleQuotes['\r'] = 1; // 13 + specicalFlags_doubleQuotes['\"'] = 1; // 34 + specicalFlags_doubleQuotes['\\'] = 1; // 92 + + specicalFlags_singleQuotes['\0'] = 4; + specicalFlags_singleQuotes['\1'] = 4; + specicalFlags_singleQuotes['\2'] = 4; + specicalFlags_singleQuotes['\3'] = 4; + specicalFlags_singleQuotes['\4'] = 4; + specicalFlags_singleQuotes['\5'] = 4; + specicalFlags_singleQuotes['\6'] = 4; + specicalFlags_singleQuotes['\7'] = 4; + specicalFlags_singleQuotes['\b'] = 1; // 8 + specicalFlags_singleQuotes['\t'] = 1; // 9 + specicalFlags_singleQuotes['\n'] = 1; // 10 + specicalFlags_singleQuotes['\u000B'] = 4; // 11 + specicalFlags_singleQuotes['\f'] = 1; // 12 + specicalFlags_singleQuotes['\r'] = 1; // 13 + specicalFlags_singleQuotes['\\'] = 1; // 92 + specicalFlags_singleQuotes['\''] = 1; // 39 + + for (int i = 14; i <= 31; ++i) { + specicalFlags_doubleQuotes[i] = 4; + specicalFlags_singleQuotes[i] = 4; + } + + for (int i = 127; i < 160; ++i) { + specicalFlags_doubleQuotes[i] = 4; + specicalFlags_singleQuotes[i] = 4; + } + + for (int i = 0; i < 161; ++i) { + specicalFlags_doubleQuotesFlags[i] = specicalFlags_doubleQuotes[i] != 0; + specicalFlags_singleQuotesFlags[i] = specicalFlags_singleQuotes[i] != 0; + } + + replaceChars['\0'] = '0'; + replaceChars['\1'] = '1'; + replaceChars['\2'] = '2'; + replaceChars['\3'] = '3'; + replaceChars['\4'] = '4'; + replaceChars['\5'] = '5'; + replaceChars['\6'] = '6'; + replaceChars['\7'] = '7'; + replaceChars['\b'] = 'b'; // 8 + replaceChars['\t'] = 't'; // 9 + replaceChars['\n'] = 'n'; // 10 + replaceChars['\u000B'] = 'v'; // 11 + replaceChars['\f'] = 'f'; // 12 + replaceChars['\r'] = 'r'; // 13 + replaceChars['\"'] = '"'; // 34 + replaceChars['\''] = '\''; // 39 + replaceChars['/'] = '/'; // 47 + replaceChars['\\'] = '\\'; // 92 + } + + public final static char[] ASCII_CHARS = { '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', + '5', '0', '6', '0', '7', '0', '8', '0', '9', '0', 'A', '0', 'B', '0', 'C', '0', 'D', '0', 'E', '0', 'F', + '1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '1', + 'A', '1', 'B', '1', 'C', '1', 'D', '1', 'E', '1', 'F', '2', '0', '2', '1', '2', '2', '2', '3', '2', '4', + '2', '5', '2', '6', '2', '7', '2', '8', '2', '9', '2', 'A', '2', 'B', '2', 'C', '2', 'D', '2', 'E', '2', + 'F', }; + + public static void close(Closeable x) { + if (x != null) { + try { + x.close(); + } catch (Exception e) { + // skip + } + } + } // Requires positive x public static int stringSize(long x) { @@ -91,8 +275,7 @@ public static void getChars(long i, int index, char[] buf) { * backwards from there. Will fail if i == Integer.MIN_VALUE */ public static void getChars(int i, int index, char[] buf) { - int q, r; - int charPos = index; + int q, r, p = index; char sign = 0; if (i < 0) { @@ -100,14 +283,13 @@ public static void getChars(int i, int index, char[] buf) { i = -i; } - // Generate two digits per iteration while (i >= 65536) { q = i / 100; // really: r = i - (q * 100); r = i - ((q << 6) + (q << 5) + (q << 2)); i = q; - buf[--charPos] = DigitOnes[r]; - buf[--charPos] = DigitTens[r]; + buf[--p] = DigitOnes[r]; + buf[--p] = DigitTens[r]; } // Fall thru to fast mode for smaller numbers @@ -115,12 +297,12 @@ public static void getChars(int i, int index, char[] buf) { for (;;) { q = (i * 52429) >>> (16 + 3); r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... - buf[--charPos] = digits[r]; + buf[--p] = digits[r]; i = q; if (i == 0) break; } if (sign != 0) { - buf[--charPos] = sign; + buf[--p] = sign; } } @@ -152,34 +334,32 @@ public static void getChars(byte b, int index, char[] buf) { /** * All possible chars for representing a number as a String */ - final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; + final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; - final static char[] DigitTens = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6', '6', '6', '6', - '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', }; + final static char[] DigitTens = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', + '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3', '3', + '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', + '5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', + '7', '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', }; - final static char[] DigitOnes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', }; + final static char[] DigitOnes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', + '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', + '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', }; final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE }; // Requires positive x - static int stringSize(int x) { - for (int i = 0;; i++) - if (x <= sizeTable[i]) return i + 1; - } - - final static int[] byte_len_array = new int[256]; - static { - for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; ++i) { - int size = (i < 0) ? IOUtils.stringSize(-i) + 1 : IOUtils.stringSize(i); - byte_len_array[i & 0xFF] = size; + public static int stringSize(int x) { + for (int i = 0;; i++) { + if (x <= sizeTable[i]) { + return i + 1; + } } } - public static int stringSize(byte i) { - return byte_len_array[i & 0xFF]; - } - public static void decode(CharsetDecoder charsetDecoder, ByteBuffer byteBuf, CharBuffer charByte) { try { CoderResult cr = charsetDecoder.decode(byteBuf, charByte, true); @@ -196,7 +376,401 @@ public static void decode(CharsetDecoder charsetDecoder, ByteBuffer byteBuf, Cha } catch (CharacterCodingException x) { // Substitution is always enabled, // so this shouldn't happen - throw new JSONException(x.getMessage(), x); + throw new JSONException("utf8 decode error, " + x.getMessage(), x); } } + + public static boolean firstIdentifier(char ch) { + return ch < IOUtils.firstIdentifierFlags.length && IOUtils.firstIdentifierFlags[ch]; + } + + public static boolean isIdent(char ch) { + return ch < identifierFlags.length && identifierFlags[ch]; + } + + public static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); + public static final int[] IA = new int[256]; + static { + Arrays.fill(IA, -1); + for (int i = 0, iS = CA.length; i < iS; i++) + IA[CA[i]] = i; + IA['='] = 0; + } + + /** + * Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as + * fast as #decode(char[]). The preconditions are:
+ * + The array must have a line length of 76 chars OR no line separators at all (one line).
+ * + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within + * the encoded string
+ * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.
+ * + * @param chars The source array. Length 0 will return an empty array. null will throw an exception. + * @return The decoded array of bytes. May be of length 0. + */ + public static byte[] decodeBase64(char[] chars, int offset, int charsLen) { + // Check special case + if (charsLen == 0) { + return new byte[0]; + } + + int sIx = offset, eIx = offset + charsLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while (sIx < eIx && IA[chars[sIx]] < 0) + sIx++; + + // Trim illegal chars from end + while (eIx > 0 && IA[chars[eIx]] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = chars[eIx] == '=' ? (chars[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = charsLen > 76 ? (chars[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes + byte[] bytes = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[chars[sIx++]] << 18 | IA[chars[sIx++]] << 12 | IA[chars[sIx++]] << 6 | IA[chars[sIx++]]; + + // Add the bytes + bytes[d++] = (byte) (i >> 16); + bytes[d++] = (byte) (i >> 8); + bytes[d++] = (byte) i; + + // If line separator, jump over it. + if (sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if (d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for (int j = 0; sIx <= eIx - pad; j++) + i |= IA[chars[sIx++]] << (18 - j * 6); + + for (int r = 16; d < len; r -= 8) + bytes[d++] = (byte) (i >> r); + } + + return bytes; + } + + public static byte[] decodeBase64(String chars, int offset, int charsLen) { + // Check special case + if (charsLen == 0) { + return new byte[0]; + } + + int sIx = offset, eIx = offset + charsLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while (sIx < eIx && IA[chars.charAt(sIx)] < 0) + sIx++; + + // Trim illegal chars from end + while (eIx > 0 && IA[chars.charAt(eIx)] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = chars.charAt(eIx) == '=' ? (chars.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = charsLen > 76 ? (chars.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes + byte[] bytes = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[chars.charAt(sIx++)] << 18 | IA[chars.charAt(sIx++)] << 12 | IA[chars.charAt(sIx++)] << 6 | IA[chars.charAt(sIx++)]; + + // Add the bytes + bytes[d++] = (byte) (i >> 16); + bytes[d++] = (byte) (i >> 8); + bytes[d++] = (byte) i; + + // If line separator, jump over it. + if (sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if (d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for (int j = 0; sIx <= eIx - pad; j++) + i |= IA[chars.charAt(sIx++)] << (18 - j * 6); + + for (int r = 16; d < len; r -= 8) + bytes[d++] = (byte) (i >> r); + } + + return bytes; + } + + /** + * Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as fast + * as decode(String). The preconditions are:
+ * + The array must have a line length of 76 chars OR no line separators at all (one line).
+ * + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within + * the encoded string
+ * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.
+ * + * @param s The source string. Length 0 will return an empty array. null will throw an exception. + * @return The decoded array of bytes. May be of length 0. + */ + public static byte[] decodeBase64(String s) { + // Check special case + int sLen = s.length(); + if (sLen == 0) { + return new byte[0]; + } + + int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0) + sIx++; + + // Trim illegal chars from end + while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 + | IA[s.charAt(sIx++)]; + + // Add the bytes + dArr[d++] = (byte) (i >> 16); + dArr[d++] = (byte) (i >> 8); + dArr[d++] = (byte) i; + + // If line separator, jump over it. + if (sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if (d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for (int j = 0; sIx <= eIx - pad; j++) + i |= IA[s.charAt(sIx++)] << (18 - j * 6); + + for (int r = 16; d < len; r -= 8) + dArr[d++] = (byte) (i >> r); + } + + return dArr; + } + + public static int encodeUTF8(char[] chars, int offset, int len, byte[] bytes) { + int sl = offset + len; + int dp = 0; + int dlASCII = dp + Math.min(len, bytes.length); + + // ASCII only optimized loop + while (dp < dlASCII && chars[offset] < '\u0080') { + bytes[dp++] = (byte) chars[offset++]; + } + + while (offset < sl) { + char c = chars[offset++]; + if (c < 0x80) { + // Have at most seven bits + bytes[dp++] = (byte) c; + } else if (c < 0x800) { + // 2 bytes, 11 bits + bytes[dp++] = (byte) (0xc0 | (c >> 6)); + bytes[dp++] = (byte) (0x80 | (c & 0x3f)); + } else if (c >= '\uD800' && c < ('\uDFFF' + 1)) { //Character.isSurrogate(c) but 1.7 + final int uc; + int ip = offset - 1; + if (Character.isHighSurrogate(c)) { + if (sl - ip < 2) { + uc = -1; + } else { + char d = chars[ip + 1]; + if (Character.isLowSurrogate(d)) { + uc = Character.toCodePoint(c, d); + } else { + throw new JSONException("encodeUTF8 error", new MalformedInputException(1)); + } + } + } else { + if (Character.isLowSurrogate(c)) { + throw new JSONException("encodeUTF8 error", new MalformedInputException(1)); + } else { + uc = c; + } + } + + if (uc < 0) { + bytes[dp++] = (byte) '?'; + } else { + bytes[dp++] = (byte) (0xf0 | ((uc >> 18))); + bytes[dp++] = (byte) (0x80 | ((uc >> 12) & 0x3f)); + bytes[dp++] = (byte) (0x80 | ((uc >> 6) & 0x3f)); + bytes[dp++] = (byte) (0x80 | (uc & 0x3f)); + offset++; // 2 chars + } + } else { + // 3 bytes, 16 bits + bytes[dp++] = (byte) (0xe0 | ((c >> 12))); + bytes[dp++] = (byte) (0x80 | ((c >> 6) & 0x3f)); + bytes[dp++] = (byte) (0x80 | (c & 0x3f)); + } + } + return dp; + } + + /** + * @deprecated + */ + public static int decodeUTF8(byte[] sa, int sp, int len, char[] da) { + final int sl = sp + len; + int dp = 0; + int dlASCII = Math.min(len, da.length); + + // ASCII only optimized loop + while (dp < dlASCII && sa[sp] >= 0) + da[dp++] = (char) sa[sp++]; + + while (sp < sl) { + int b1 = sa[sp++]; + if (b1 >= 0) { + // 1 byte, 7 bits: 0xxxxxxx + da[dp++] = (char) b1; + } else if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) { + // 2 bytes, 11 bits: 110xxxxx 10xxxxxx + if (sp < sl) { + int b2 = sa[sp++]; + if ((b2 & 0xc0) != 0x80) { // isNotContinuation(b2) + return -1; + } else { + da[dp++] = (char) (((b1 << 6) ^ b2)^ + (((byte) 0xC0 << 6) ^ + ((byte) 0x80 << 0))); + } + continue; + } + return -1; + } else if ((b1 >> 4) == -2) { + // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx + if (sp + 1 < sl) { + int b2 = sa[sp++]; + int b3 = sa[sp++]; + if ((b1 == (byte) 0xe0 && (b2 & 0xe0) == 0x80) // + || (b2 & 0xc0) != 0x80 // + || (b3 & 0xc0) != 0x80) { // isMalformed3(b1, b2, b3) + return -1; + } else { + char c = (char)((b1 << 12) ^ + (b2 << 6) ^ + (b3 ^ + (((byte) 0xE0 << 12) ^ + ((byte) 0x80 << 6) ^ + ((byte) 0x80 << 0)))); + boolean isSurrogate = c >= Character.MIN_SURROGATE && c < (Character.MAX_SURROGATE + 1); + if (isSurrogate) { + return -1; + } else { + da[dp++] = c; + } + } + continue; + } + return -1; + } else if ((b1 >> 3) == -2) { + // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if (sp + 2 < sl) { + int b2 = sa[sp++]; + int b3 = sa[sp++]; + int b4 = sa[sp++]; + int uc = ((b1 << 18) ^ + (b2 << 12) ^ + (b3 << 6) ^ + (b4 ^ + (((byte) 0xF0 << 18) ^ + ((byte) 0x80 << 12) ^ + ((byte) 0x80 << 6) ^ + ((byte) 0x80 << 0)))); + if (((b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 || (b4 & 0xc0) != 0x80) // isMalformed4 + || + // shortest form check + !Character.isSupplementaryCodePoint(uc)) { + return -1; + } else { + da[dp++] = (char) ((uc >>> 10) + (Character.MIN_HIGH_SURROGATE - (Character.MIN_SUPPLEMENTARY_CODE_POINT >>> 10))); // Character.highSurrogate(uc); + da[dp++] = (char) ((uc & 0x3ff) + Character.MIN_LOW_SURROGATE); // Character.lowSurrogate(uc); + } + continue; + } + return -1; + } else { + return -1; + } + } + return dp; + } + + /** + * @deprecated + */ + public static String readAll(Reader reader) { + StringBuilder buf = new StringBuilder(); + + try { + char[] chars = new char[2048]; + for (;;) { + int len = reader.read(chars, 0, chars.length); + if (len < 0) { + break; + } + buf.append(chars, 0, len); + } + } catch(Exception ex) { + throw new JSONException("read string from reader error", ex); + } + + return buf.toString(); + } + + public static boolean isValidJsonpQueryParam(String value){ + if (value == null || value.length() == 0) { + return false; + } + + for (int i = 0, len = value.length(); i < len; ++i) { + char ch = value.charAt(i); + if(ch != '.' && !IOUtils.isIdent(ch)){ + return false; + } + } + + return true; + } + } diff --git a/src/main/java/com/alibaba/fastjson/util/IdentityHashMap.java b/src/main/java/com/alibaba/fastjson/util/IdentityHashMap.java old mode 100644 new mode 100755 index b41dfb3e17..36d2f7cb11 --- a/src/main/java/com/alibaba/fastjson/util/IdentityHashMap.java +++ b/src/main/java/com/alibaba/fastjson/util/IdentityHashMap.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,21 +15,22 @@ */ package com.alibaba.fastjson.util; +import java.util.Arrays; +import java.util.Collections; + /** * for concurrent IdentityHashMap * - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ @SuppressWarnings("unchecked") public class IdentityHashMap { - - public static final int DEFAULT_TABLE_SIZE = 1024; - private final Entry[] buckets; private final int indexMask; + public final static int DEFAULT_SIZE = 8192; public IdentityHashMap(){ - this(DEFAULT_TABLE_SIZE); + this(DEFAULT_SIZE); } public IdentityHashMap(int tableSize){ @@ -50,12 +51,36 @@ public final V get(K key) { return null; } - public final boolean put(K key, V value) { + public Class findClass(String keyString) { + for (int i = 0; i < buckets.length; i++) { + Entry bucket = buckets[i]; + + if (bucket == null) { + continue; + } + + for (Entry entry = bucket; entry != null; entry = entry.next) { + Object key = bucket.key; + if (key instanceof Class) { + Class clazz = ((Class) key); + String className = clazz.getName(); + if (className.equals(keyString)) { + return clazz; + } + } + } + } + + return null; + } + + public boolean put(K key, V value) { final int hash = System.identityHashCode(key); final int bucket = hash & indexMask; for (Entry entry = buckets[bucket]; entry != null; entry = entry.next) { if (key == entry.key) { + entry.value = value; return true; } } @@ -66,21 +91,11 @@ public final boolean put(K key, V value) { return false; } - public int size() { - int size = 0; - for (int i = 0; i < buckets.length; ++i) { - for (Entry entry = buckets[i]; entry != null; entry = entry.next) { - size++; - } - } - return size; - } - protected static final class Entry { public final int hashCode; public final K key; - public final V value; + public V value; public final Entry next; @@ -92,4 +107,7 @@ public Entry(K key, V value, int hash, Entry next){ } } + public void clear() { + Arrays.fill(this.buckets, null); + } } diff --git a/src/main/java/com/alibaba/fastjson/util/JavaBeanInfo.java b/src/main/java/com/alibaba/fastjson/util/JavaBeanInfo.java new file mode 100644 index 0000000000..584d1b7eff --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/util/JavaBeanInfo.java @@ -0,0 +1,965 @@ +package com.alibaba.fastjson.util; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Type; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.PropertyNamingStrategy; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONPOJOBuilder; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class JavaBeanInfo { + + public final Class clazz; + public final Class builderClass; + public final Constructor defaultConstructor; + public final Constructor creatorConstructor; + public final Method factoryMethod; + public final Method buildMethod; + + public final int defaultConstructorParameterSize; + + public final FieldInfo[] fields; + public final FieldInfo[] sortedFields; + + public final int parserFeatures; + + public final JSONType jsonType; + + public final String typeName; + public final String typeKey; + + public String[] orders; + + public Type[] creatorConstructorParameterTypes; + public String[] creatorConstructorParameters; + + public JavaBeanInfo(Class clazz, // + Class builderClass, // + Constructor defaultConstructor, // + Constructor creatorConstructor, // + Method factoryMethod, // + Method buildMethod, // + JSONType jsonType, // + List fieldList) { + this.clazz = clazz; + this.builderClass = builderClass; + this.defaultConstructor = defaultConstructor; + this.creatorConstructor = creatorConstructor; + this.factoryMethod = factoryMethod; + this.parserFeatures = TypeUtils.getParserFeatures(clazz); + this.buildMethod = buildMethod; + + this.jsonType = jsonType; + if (jsonType != null) { + String typeName = jsonType.typeName(); + String typeKey = jsonType.typeKey(); + this.typeKey = typeKey.length() > 0 ? typeKey : null; + + if (typeName.length() != 0) { + this.typeName = typeName; + } else { + this.typeName = clazz.getName(); + } + String[] orders = jsonType.orders(); + this.orders = orders.length == 0 ? null : orders; + } else { + this.typeName = clazz.getName(); + this.typeKey = null; + this.orders = null; + } + + fields = new FieldInfo[fieldList.size()]; + fieldList.toArray(fields); + + FieldInfo[] sortedFields = new FieldInfo[fields.length]; + if (orders != null) { + LinkedHashMap map = new LinkedHashMap(fieldList.size()); + for (FieldInfo field : fields) { + map.put(field.name, field); + } + int i = 0; + for (String item : orders) { + FieldInfo field = map.get(item); + if (field != null) { + sortedFields[i++] = field; + map.remove(item); + } + } + for (FieldInfo field : map.values()) { + sortedFields[i++] = field; + } + } else { + System.arraycopy(fields, 0, sortedFields, 0, fields.length); + Arrays.sort(sortedFields); + } + + if (Arrays.equals(fields, sortedFields)) { + sortedFields = fields; + } + this.sortedFields = sortedFields; + + if (defaultConstructor != null) { + defaultConstructorParameterSize = defaultConstructor.getParameterTypes().length; + } else if (factoryMethod != null) { + defaultConstructorParameterSize = factoryMethod.getParameterTypes().length; + } else { + defaultConstructorParameterSize = 0; + } + + if (creatorConstructor != null) { + this.creatorConstructorParameterTypes = creatorConstructor.getParameterTypes(); + + + boolean kotlin = TypeUtils.isKotlin(clazz); + if (kotlin) { + this.creatorConstructorParameters = TypeUtils.getKoltinConstructorParameters(clazz); + + Annotation[][] paramAnnotationArrays = creatorConstructor.getParameterAnnotations(); + for (int i = 0; i < creatorConstructorParameters.length && i < paramAnnotationArrays.length; ++i) { + Annotation[] paramAnnotations = paramAnnotationArrays[i]; + JSONField fieldAnnotation = null; + for (Annotation paramAnnotation : paramAnnotations) { + if (paramAnnotation instanceof JSONField) { + fieldAnnotation = (JSONField) paramAnnotation; + break; + } + } + if (fieldAnnotation != null) { + String fieldAnnotationName = fieldAnnotation.name(); + if (fieldAnnotationName.length() > 0) { + creatorConstructorParameters[i] = fieldAnnotationName; + } + } + } + } else { + boolean match; + if (creatorConstructorParameterTypes.length != fields.length) { + match = false; + } else { + match = true; + for (int i = 0; i < creatorConstructorParameterTypes.length; i++) { + if (creatorConstructorParameterTypes[i] != fields[i].fieldClass) { + match = false; + break; + } + } + } + + if (!match) { + this.creatorConstructorParameters = ASMUtils.lookupParameterNames(creatorConstructor); + } + } + } + } + + private static FieldInfo getField(List fieldList, String propertyName) { + for (FieldInfo item : fieldList) { + if (item.name.equals(propertyName)) { + return item; + } + + Field field = item.field; + if (field != null && item.getAnnotation() != null && field.getName().equals(propertyName)) { + return item; + } + } + return null; + } + + + static boolean add(List fieldList, FieldInfo field) { + for (int i = fieldList.size() - 1; i >= 0; --i) { + FieldInfo item = fieldList.get(i); + + if (item.name.equals(field.name)) { + if (item.getOnly && !field.getOnly) { + continue; + } + + if (item.fieldClass.isAssignableFrom(field.fieldClass)) { + fieldList.remove(i); + break; + } + + int result = item.compareTo(field); + + if (result < 0) { + fieldList.remove(i); + break; + } else { + return false; + } + } + } + fieldList.add(field); + + return true; + } + + public static JavaBeanInfo build(Class clazz, Type type, PropertyNamingStrategy propertyNamingStrategy) { + return build(clazz, type, propertyNamingStrategy, false, TypeUtils.compatibleWithJavaBean); + } + + public static JavaBeanInfo build(Class clazz // + , Type type // + , PropertyNamingStrategy propertyNamingStrategy // + , boolean fieldBased // + , boolean compatibleWithJavaBean + ) { + JSONType jsonType = TypeUtils.getAnnotation(clazz,JSONType.class); + if (jsonType != null) { + PropertyNamingStrategy jsonTypeNaming = jsonType.naming(); + if (jsonTypeNaming != null && jsonTypeNaming != PropertyNamingStrategy.CamelCase) { + propertyNamingStrategy = jsonTypeNaming; + } + } + + Class builderClass = getBuilderClass(clazz, jsonType); + + Field[] declaredFields = clazz.getDeclaredFields(); + Method[] methods = clazz.getMethods(); + + boolean kotlin = TypeUtils.isKotlin(clazz); + Constructor[] constructors = clazz.getDeclaredConstructors(); + + Constructor defaultConstructor = null; + if ((!kotlin) || constructors.length == 1) { + if (builderClass == null) { + defaultConstructor = getDefaultConstructor(clazz, constructors); + } else { + defaultConstructor = getDefaultConstructor(builderClass, builderClass.getDeclaredConstructors()); + } + } + + Constructor creatorConstructor = null; + Method buildMethod = null; + Method factoryMethod = null; + + List fieldList = new ArrayList(); + + if (fieldBased) { + for (Class currentClass = clazz; currentClass != null; currentClass = currentClass.getSuperclass()) { + Field[] fields = currentClass.getDeclaredFields(); + + computeFields(clazz, type, propertyNamingStrategy, fieldList, fields); + } + return new JavaBeanInfo(clazz, builderClass, defaultConstructor, null, factoryMethod, buildMethod, jsonType, fieldList); + } + + boolean isInterfaceOrAbstract = clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()); + if ((defaultConstructor == null && builderClass == null) || isInterfaceOrAbstract) { + creatorConstructor = getCreatorConstructor(constructors); + + if (creatorConstructor != null && !isInterfaceOrAbstract) { // 基于标记 JSONCreator 注解的构造方法 + TypeUtils.setAccessible(creatorConstructor); + + Class[] types = creatorConstructor.getParameterTypes(); + + String[] lookupParameterNames = null; + if (types.length > 0) { + Annotation[][] paramAnnotationArrays = creatorConstructor.getParameterAnnotations(); + for (int i = 0; i < types.length; ++i) { + Annotation[] paramAnnotations = paramAnnotationArrays[i]; + JSONField fieldAnnotation = null; + for (Annotation paramAnnotation : paramAnnotations) { + if (paramAnnotation instanceof JSONField) { + fieldAnnotation = (JSONField) paramAnnotation; + break; + } + } + + Class fieldClass = types[i]; + Type fieldType = creatorConstructor.getGenericParameterTypes()[i]; + + String fieldName = null; + Field field = null; + int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; + if (fieldAnnotation != null) { + field = TypeUtils.getField(clazz, fieldAnnotation.name(), declaredFields); + ordinal = fieldAnnotation.ordinal(); + serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); + parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); + fieldName = fieldAnnotation.name(); + } + + if (fieldName == null || fieldName.length() == 0) { + if (lookupParameterNames == null) { + lookupParameterNames = ASMUtils.lookupParameterNames(creatorConstructor); + } + fieldName = lookupParameterNames[i]; + } + + FieldInfo fieldInfo = new FieldInfo(fieldName, clazz, fieldClass, fieldType, field, + ordinal, serialzeFeatures, parserFeatures); + add(fieldList, fieldInfo); + } + } + + //return new JavaBeanInfo(clazz, builderClass, null, creatorConstructor, null, null, jsonType, fieldList); + } else if ((factoryMethod = getFactoryMethod(clazz, methods)) != null) { + TypeUtils.setAccessible(factoryMethod); + + Class[] types = factoryMethod.getParameterTypes(); + if (types.length > 0) { + Annotation[][] paramAnnotationArrays = factoryMethod.getParameterAnnotations(); + for (int i = 0; i < types.length; ++i) { + Annotation[] paramAnnotations = paramAnnotationArrays[i]; + JSONField fieldAnnotation = null; + for (Annotation paramAnnotation : paramAnnotations) { + if (paramAnnotation instanceof JSONField) { + fieldAnnotation = (JSONField) paramAnnotation; + break; + } + } + if (fieldAnnotation == null) { + throw new JSONException("illegal json creator"); + } + + Class fieldClass = types[i]; + Type fieldType = factoryMethod.getGenericParameterTypes()[i]; + Field field = TypeUtils.getField(clazz, fieldAnnotation.name(), declaredFields); + final int ordinal = fieldAnnotation.ordinal(); + final int serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); + final int parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); + FieldInfo fieldInfo = new FieldInfo(fieldAnnotation.name(), clazz, fieldClass, fieldType, field, + ordinal, serialzeFeatures, parserFeatures); + add(fieldList, fieldInfo); + } + + return new JavaBeanInfo(clazz, builderClass, null, null, factoryMethod, null, jsonType, fieldList); + } + } else if (!isInterfaceOrAbstract) { + String className = clazz.getName(); + + String[] paramNames = null; + if (kotlin && constructors.length > 0) { + paramNames = TypeUtils.getKoltinConstructorParameters(clazz); + creatorConstructor = TypeUtils.getKoltinConstructor(constructors); + TypeUtils.setAccessible(creatorConstructor); + } else { + + for (Constructor constructor : constructors) { + Class[] parameterTypes = constructor.getParameterTypes(); + + if (className.equals("org.springframework.security.web.authentication.WebAuthenticationDetails")) { + if (parameterTypes.length == 2 && parameterTypes[0] == String.class && parameterTypes[1] == String.class) { + creatorConstructor = constructor; + creatorConstructor.setAccessible(true); + paramNames = ASMUtils.lookupParameterNames(constructor); + break; + } + } + + if (className.equals("org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken")) { + if (parameterTypes.length == 3 + && parameterTypes[0] == Object.class + && parameterTypes[1] == Object.class + && parameterTypes[2] == Collection.class) { + creatorConstructor = constructor; + creatorConstructor.setAccessible(true); + paramNames = new String[] {"principal", "credentials", "authorities"}; + break; + } + } + + if (className.equals("org.springframework.security.core.authority.SimpleGrantedAuthority")) { + if (parameterTypes.length == 1 + && parameterTypes[0] == String.class) { + creatorConstructor = constructor; + paramNames = new String[] {"authority"}; + break; + } + } + + // + + + boolean is_public = (constructor.getModifiers() & Modifier.PUBLIC) != 0; + if (!is_public) { + continue; + } + String[] lookupParameterNames = ASMUtils.lookupParameterNames(constructor); + if (lookupParameterNames == null || lookupParameterNames.length == 0) { + continue; + } + + if (creatorConstructor != null + && paramNames != null && lookupParameterNames.length <= paramNames.length) { + continue; + } + + paramNames = lookupParameterNames; + creatorConstructor = constructor; + } + } + + Class[] types = null; + if (paramNames != null) { + types = creatorConstructor.getParameterTypes(); + } + + if (paramNames != null + && types.length == paramNames.length) { + Annotation[][] paramAnnotationArrays = creatorConstructor.getParameterAnnotations(); + for (int i = 0; i < types.length; ++i) { + Annotation[] paramAnnotations = paramAnnotationArrays[i]; + String paramName = paramNames[i]; + + JSONField fieldAnnotation = null; + for (Annotation paramAnnotation : paramAnnotations) { + if (paramAnnotation instanceof JSONField) { + fieldAnnotation = (JSONField) paramAnnotation; + break; + } + } + + Class fieldClass = types[i]; + Type fieldType = creatorConstructor.getGenericParameterTypes()[i]; + Field field = TypeUtils.getField(clazz, paramName, declaredFields); + if (field != null) { + if (fieldAnnotation == null) { + fieldAnnotation = field.getAnnotation(JSONField.class); + } + } + final int ordinal, serialzeFeatures, parserFeatures; + if (fieldAnnotation == null) { + ordinal = 0; + serialzeFeatures = 0; + + if ("org.springframework.security.core.userdetails.User".equals(className) + && "password".equals(paramName)) { + parserFeatures = Feature.InitStringFieldAsEmpty.mask; + } else { + parserFeatures = 0; + } + } else { + String nameAnnotated = fieldAnnotation.name(); + if (nameAnnotated.length() != 0) { + paramName = nameAnnotated; + } + ordinal = fieldAnnotation.ordinal(); + serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); + parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); + } + FieldInfo fieldInfo = new FieldInfo(paramName, clazz, fieldClass, fieldType, field, + ordinal, serialzeFeatures, parserFeatures); + add(fieldList, fieldInfo); + } + + if ((!kotlin) + && !clazz.getName().equals("javax.servlet.http.Cookie")) { + return new JavaBeanInfo(clazz, builderClass, null, creatorConstructor, null, null, jsonType, fieldList); + } + } else { + throw new JSONException("default constructor not found. " + clazz); + } + } + } + + if (defaultConstructor != null) { + TypeUtils.setAccessible(defaultConstructor); + } + + if (builderClass != null) { + String withPrefix = null; + + JSONPOJOBuilder builderAnno = builderClass.getAnnotation(JSONPOJOBuilder.class); + if (builderAnno != null) { + withPrefix = builderAnno.withPrefix(); + } + + if (withPrefix == null || withPrefix.length() == 0) { + withPrefix = "with"; + } + + for (Method method : builderClass.getMethods()) { + if (Modifier.isStatic(method.getModifiers())) { + continue; + } + + if (!(method.getReturnType().equals(builderClass))) { + continue; + } + + int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; + + JSONField annotation = method.getAnnotation(JSONField.class); + + if (annotation == null) { + annotation = TypeUtils.getSuperMethodAnnotation(clazz, method); + } + + if (annotation != null) { + if (!annotation.deserialize()) { + continue; + } + + ordinal = annotation.ordinal(); + serialzeFeatures = SerializerFeature.of(annotation.serialzeFeatures()); + parserFeatures = Feature.of(annotation.parseFeatures()); + + if (annotation.name().length() != 0) { + String propertyName = annotation.name(); + add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures, parserFeatures, + annotation, null, null)); + continue; + } + } + + String methodName = method.getName(); + StringBuilder properNameBuilder; + if (methodName.startsWith("set") && methodName.length() > 3) { + properNameBuilder = new StringBuilder(methodName.substring(3)); + } else { + if (!methodName.startsWith(withPrefix)) { + continue; + } + + if (methodName.length() <= withPrefix.length()) { + continue; + } + + properNameBuilder = new StringBuilder(methodName.substring(withPrefix.length())); + } + + char c0 = properNameBuilder.charAt(0); + if (!Character.isUpperCase(c0)) { + continue; + } + + properNameBuilder.setCharAt(0, Character.toLowerCase(c0)); + + String propertyName = properNameBuilder.toString(); + + add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures, parserFeatures, + annotation, null, null)); + } + + if (builderClass != null) { + JSONPOJOBuilder builderAnnotation = builderClass.getAnnotation(JSONPOJOBuilder.class); + + String buildMethodName = null; + if (builderAnnotation != null) { + buildMethodName = builderAnnotation.buildMethod(); + } + + if (buildMethodName == null || buildMethodName.length() == 0) { + buildMethodName = "build"; + } + + try { + buildMethod = builderClass.getMethod(buildMethodName); + } catch (NoSuchMethodException e) { + // skip + } catch (SecurityException e) { + // skip + } + + if (buildMethod == null) { + try { + buildMethod = builderClass.getMethod("create"); + } catch (NoSuchMethodException e) { + // skip + } catch (SecurityException e) { + // skip + } + } + + if (buildMethod == null) { + throw new JSONException("buildMethod not found."); + } + + TypeUtils.setAccessible(buildMethod); + } + } + + for (Method method : methods) { // + int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; + String methodName = method.getName(); + + if (Modifier.isStatic(method.getModifiers())) { + continue; + } + + // support builder set + Class returnType = method.getReturnType(); + if (!(returnType.equals(Void.TYPE) || returnType.equals(method.getDeclaringClass()))) { + continue; + } + + if (method.getDeclaringClass() == Object.class) { + continue; + } + + Class[] types = method.getParameterTypes(); + + if (types.length == 0 || types.length > 2) { + continue; + } + + JSONField annotation = method.getAnnotation(JSONField.class); + if (annotation != null + && types.length == 2 + && types[0] == String.class + && types[1] == Object.class) { + add(fieldList, new FieldInfo("", method, null, clazz, type, ordinal, + serialzeFeatures, parserFeatures, annotation, null, null)); + continue; + } + + if (types.length != 1) { + continue; + } + + if (annotation == null) { + annotation = TypeUtils.getSuperMethodAnnotation(clazz, method); + } + + if (annotation == null && methodName.length() < 4) { + continue; + } + + if (annotation != null) { + if (!annotation.deserialize()) { + continue; + } + + ordinal = annotation.ordinal(); + serialzeFeatures = SerializerFeature.of(annotation.serialzeFeatures()); + parserFeatures = Feature.of(annotation.parseFeatures()); + + if (annotation.name().length() != 0) { + String propertyName = annotation.name(); + add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures, parserFeatures, + annotation, null, null)); + continue; + } + } + + if (annotation == null && !methodName.startsWith("set")) { // TODO "set"的判断放在 JSONField 注解后面,意思是允许非 setter 方法标记 JSONField 注解? + continue; + } + + char c3 = methodName.charAt(3); + + String propertyName; + if (Character.isUpperCase(c3) // + || c3 > 512 // for unicode method name + ) { + if (TypeUtils.compatibleWithJavaBean) { + propertyName = TypeUtils.decapitalize(methodName.substring(3)); + } else { + propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); + } + } else if (c3 == '_') { + propertyName = methodName.substring(4); + } else if (c3 == 'f') { + propertyName = methodName.substring(3); + } else if (methodName.length() >= 5 && Character.isUpperCase(methodName.charAt(4))) { + propertyName = TypeUtils.decapitalize(methodName.substring(3)); + } else { + continue; + } + + Field field = TypeUtils.getField(clazz, propertyName, declaredFields); + if (field == null && types[0] == boolean.class) { + String isFieldName = "is" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); + field = TypeUtils.getField(clazz, isFieldName, declaredFields); + } + + JSONField fieldAnnotation = null; + if (field != null) { + fieldAnnotation = field.getAnnotation(JSONField.class); + + if (fieldAnnotation != null) { + if (!fieldAnnotation.deserialize()) { + continue; + } + + ordinal = fieldAnnotation.ordinal(); + serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); + parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); + + if (fieldAnnotation.name().length() != 0) { + propertyName = fieldAnnotation.name(); + add(fieldList, new FieldInfo(propertyName, method, field, clazz, type, ordinal, + serialzeFeatures, parserFeatures, annotation, fieldAnnotation, null)); + continue; + } + } + + } + + if (propertyNamingStrategy != null) { + propertyName = propertyNamingStrategy.translate(propertyName); + } + + add(fieldList, new FieldInfo(propertyName, method, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, + annotation, fieldAnnotation, null)); + } + + Field[] fields = clazz.getFields(); + computeFields(clazz, type, propertyNamingStrategy, fieldList, fields); + + for (Method method : clazz.getMethods()) { // getter methods + String methodName = method.getName(); + if (methodName.length() < 4) { + continue; + } + + if (Modifier.isStatic(method.getModifiers())) { + continue; + } + + if (builderClass == null && methodName.startsWith("get") && Character.isUpperCase(methodName.charAt(3))) { + if (method.getParameterTypes().length != 0) { + continue; + } + + if (Collection.class.isAssignableFrom(method.getReturnType()) // + || Map.class.isAssignableFrom(method.getReturnType()) // + || AtomicBoolean.class == method.getReturnType() // + || AtomicInteger.class == method.getReturnType() // + || AtomicLong.class == method.getReturnType() // + ) { + String propertyName; + + JSONField annotation = method.getAnnotation(JSONField.class); + if (annotation != null && annotation.deserialize()) { + continue; + } + + if (annotation != null && annotation.name().length() > 0) { + propertyName = annotation.name(); + } else { + propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); + + Field field = TypeUtils.getField(clazz, propertyName, declaredFields); + if (field != null) { + JSONField fieldAnnotation = field.getAnnotation(JSONField.class); + if (fieldAnnotation != null && !fieldAnnotation.deserialize()) { + continue; + } + } + } + + if (propertyNamingStrategy != null) { + propertyName = propertyNamingStrategy.translate(propertyName); + } + + FieldInfo fieldInfo = getField(fieldList, propertyName); + if (fieldInfo != null) { + continue; + } + + add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, 0, 0, 0, annotation, null, null)); + } + } + } + + return new JavaBeanInfo(clazz, builderClass, defaultConstructor, creatorConstructor, factoryMethod, buildMethod, jsonType, fieldList); + } + + private static void computeFields(Class clazz, Type type, PropertyNamingStrategy propertyNamingStrategy, List fieldList, Field[] fields) { + for (Field field : fields) { // public static fields + int modifiers = field.getModifiers(); + if ((modifiers & Modifier.STATIC) != 0) { + continue; + } + + if ((modifiers & Modifier.FINAL) != 0) { + Class fieldType = field.getType(); + boolean supportReadOnly = Map.class.isAssignableFrom(fieldType) + || Collection.class.isAssignableFrom(fieldType) + || AtomicLong.class.equals(fieldType) // + || AtomicInteger.class.equals(fieldType) // + || AtomicBoolean.class.equals(fieldType); + if (!supportReadOnly) { + continue; + } + } + + boolean contains = false; + for (FieldInfo item : fieldList) { + if (item.name.equals(field.getName())) { + contains = true; + break; // 已经是 contains = true,无需继续遍历 + } + } + + if (contains) { + continue; + } + + int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; + String propertyName = field.getName(); + + JSONField fieldAnnotation = field.getAnnotation(JSONField.class); + + if (fieldAnnotation != null) { + if (!fieldAnnotation.deserialize()) { + continue; + } + + ordinal = fieldAnnotation.ordinal(); + serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); + parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); + + if (fieldAnnotation.name().length() != 0) { + propertyName = fieldAnnotation.name(); + } + } + + if (propertyNamingStrategy != null) { + propertyName = propertyNamingStrategy.translate(propertyName); + } + + add(fieldList, new FieldInfo(propertyName, null, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, null, + fieldAnnotation, null)); + } + } + + static Constructor getDefaultConstructor(Class clazz, final Constructor[] constructors) { + if (Modifier.isAbstract(clazz.getModifiers())) { + return null; + } + + Constructor defaultConstructor = null; + + for (Constructor constructor : constructors) { + if (constructor.getParameterTypes().length == 0) { + defaultConstructor = constructor; + break; + } + } + + if (defaultConstructor == null) { + if (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) { + Class[] types; + for (Constructor constructor : constructors) { + if ((types = constructor.getParameterTypes()).length == 1 + && types[0].equals(clazz.getDeclaringClass())) { + defaultConstructor = constructor; + break; + } + } + } + } + + return defaultConstructor; + } + + public static Constructor getCreatorConstructor(Constructor[] constructors) { + Constructor creatorConstructor = null; + + for (Constructor constructor : constructors) { + JSONCreator annotation = constructor.getAnnotation(JSONCreator.class); + if (annotation != null) { + if (creatorConstructor != null) { + throw new JSONException("multi-JSONCreator"); + } + + creatorConstructor = constructor; + // 不应该break,否则多个构造方法上存在 JSONCreator 注解时,并不会触发上述异常抛出 + } + } + if (creatorConstructor != null) { + return creatorConstructor; + } + + for (Constructor constructor : constructors) { + Annotation[][] paramAnnotationArrays = constructor.getParameterAnnotations(); + if (paramAnnotationArrays.length == 0) { + continue; + } + boolean match = true; + for (Annotation[] paramAnnotationArray : paramAnnotationArrays) { + boolean paramMatch = false; + for (Annotation paramAnnotation : paramAnnotationArray) { + if (paramAnnotation instanceof JSONField) { + paramMatch = true; + break; + } + } + if (!paramMatch) { + match = false; + break; + } + } + + if (match) { + if (creatorConstructor != null) { + throw new JSONException("multi-JSONCreator"); + } + + creatorConstructor = constructor; + } + } + + if (creatorConstructor != null) { + return creatorConstructor; + } + + return creatorConstructor; + } + + private static Method getFactoryMethod(Class clazz, Method[] methods) { + Method factoryMethod = null; + + for (Method method : methods) { + if (!Modifier.isStatic(method.getModifiers())) { + continue; + } + + if (!clazz.isAssignableFrom(method.getReturnType())) { + continue; + } + + JSONCreator annotation = method.getAnnotation(JSONCreator.class); + if (annotation != null) { + if (factoryMethod != null) { + throw new JSONException("multi-JSONCreator"); + } + + factoryMethod = method; + // 不应该break,否则多个静态工厂方法上存在 JSONCreator 注解时,并不会触发上述异常抛出 + } + } + return factoryMethod; + } + + public static Class getBuilderClass(JSONType type) { + return getBuilderClass(null, type); + } + + public static Class getBuilderClass(Class clazz, JSONType type) { + if (clazz != null && clazz.getName().equals("org.springframework.security.web.savedrequest.DefaultSavedRequest")) { + return TypeUtils.loadClass("org.springframework.security.web.savedrequest.DefaultSavedRequest$Builder"); + } + + if (type == null) { + return null; + } + + Class builderClass = type.builder(); + + if (builderClass == Void.class) { + return null; + } + + return builderClass; + } +} diff --git a/src/main/java/com/alibaba/fastjson/util/ParameterizedTypeImpl.java b/src/main/java/com/alibaba/fastjson/util/ParameterizedTypeImpl.java new file mode 100755 index 0000000000..8b15e7be56 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/util/ParameterizedTypeImpl.java @@ -0,0 +1,53 @@ +package com.alibaba.fastjson.util; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Arrays; + +public class ParameterizedTypeImpl implements ParameterizedType { + + private final Type[] actualTypeArguments; + private final Type ownerType; + private final Type rawType; + + public ParameterizedTypeImpl(Type[] actualTypeArguments, Type ownerType, Type rawType){ + this.actualTypeArguments = actualTypeArguments; + this.ownerType = ownerType; + this.rawType = rawType; + } + + public Type[] getActualTypeArguments() { + return actualTypeArguments; + } + + public Type getOwnerType() { + return ownerType; + } + + public Type getRawType() { + return rawType; + } + + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + ParameterizedTypeImpl that = (ParameterizedTypeImpl) o; + + // Probably incorrect - comparing Object[] arrays with Arrays.equals + if (!Arrays.equals(actualTypeArguments, that.actualTypeArguments)) return false; + if (ownerType != null ? !ownerType.equals(that.ownerType) : that.ownerType != null) return false; + return rawType != null ? rawType.equals(that.rawType) : that.rawType == null; + + } + + @Override + public int hashCode() { + int result = actualTypeArguments != null ? Arrays.hashCode(actualTypeArguments) : 0; + result = 31 * result + (ownerType != null ? ownerType.hashCode() : 0); + result = 31 * result + (rawType != null ? rawType.hashCode() : 0); + return result; + } +} diff --git a/src/main/java/com/alibaba/fastjson/util/ServiceLoader.java b/src/main/java/com/alibaba/fastjson/util/ServiceLoader.java old mode 100644 new mode 100755 index ea50146e6e..b5b77d5b9e --- a/src/main/java/com/alibaba/fastjson/util/ServiceLoader.java +++ b/src/main/java/com/alibaba/fastjson/util/ServiceLoader.java @@ -1,21 +1,27 @@ package com.alibaba.fastjson.util; import java.io.BufferedReader; -import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; +import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; public class ServiceLoader { - private static final String PREFIX = "META-INF/services/"; + private static final String PREFIX = "META-INF/services/"; + + private static final Set loadedUrls = new HashSet(); @SuppressWarnings("unchecked") public static Set load(Class clazz, ClassLoader classLoader) { + if (classLoader == null) { + return Collections.emptySet(); + } + Set services = new HashSet(); String className = clazz.getName(); @@ -27,7 +33,11 @@ public static Set load(Class clazz, ClassLoader classLoader) { Enumeration urls = classLoader.getResources(path); while (urls.hasMoreElements()) { URL url = urls.nextElement(); + if (loadedUrls.contains(url.toString())) { + continue; + } load(url, serviceNames); + loadedUrls.add(url.toString()); } } catch (IOException ex) { // skip @@ -66,17 +76,11 @@ public static void load(URL url, Set set) throws IOException { if (line.length() == 0) { continue; } + set.add(line); } } finally { - close(reader); - close(is); + IOUtils.close(reader); + IOUtils.close(is); } } - - public static void close(Closeable x) throws IOException { - if (x != null) { - x.close(); - } - } - } diff --git a/src/main/java/com/alibaba/fastjson/util/ThreadLocalCache.java b/src/main/java/com/alibaba/fastjson/util/ThreadLocalCache.java index 32491bef48..f04fb723c2 100644 --- a/src/main/java/com/alibaba/fastjson/util/ThreadLocalCache.java +++ b/src/main/java/com/alibaba/fastjson/util/ThreadLocalCache.java @@ -1,22 +1,45 @@ package com.alibaba.fastjson.util; +import java.lang.ref.SoftReference; +import java.nio.charset.CharsetDecoder; + +/** + * @deprecated + */ public class ThreadLocalCache { - public final static int CHARS_CACH_INIT_SIZE = 1024; // 1k; - public final static int CHARS_CACH_MAX_SIZE = 1024 * 128; // 1k; - private final static ThreadLocal charsBufLocal = new ThreadLocal(); + public final static int CHARS_CACH_INIT_SIZE = 1024; // 1k, 2^10; + public final static int CHARS_CACH_INIT_SIZE_EXP = 10; + public final static int CHARS_CACH_MAX_SIZE = 1024 * 128; // 128k, 2^17; + public final static int CHARS_CACH_MAX_SIZE_EXP = 17; + private final static ThreadLocal> charsBufLocal = new ThreadLocal>(); + + private final static ThreadLocal decoderLocal = new ThreadLocal(); + + public static CharsetDecoder getUTF8Decoder() { + CharsetDecoder decoder = decoderLocal.get(); + if (decoder == null) { + decoder = new UTF8Decoder(); + decoderLocal.set(decoder); + } + return decoder; + } public static void clearChars() { charsBufLocal.set(null); } public static char[] getChars(int length) { - char[] chars = charsBufLocal.get(); + SoftReference ref = charsBufLocal.get(); - if (chars == null) { - chars = allocate(length); + if (ref == null) { + return allocate(length); + } + + char[] chars = ref.get(); - return chars; + if (chars == null) { + return allocate(length); } if (chars.length < length) { @@ -27,50 +50,51 @@ public static char[] getChars(int length) { } private static char[] allocate(int length) { - int allocateLength = getAllocateLength(CHARS_CACH_INIT_SIZE, CHARS_CACH_MAX_SIZE, length); - - if (allocateLength <= CHARS_CACH_MAX_SIZE) { - char[] chars = new char[allocateLength]; - charsBufLocal.set(chars); - return chars; + if(length> CHARS_CACH_MAX_SIZE) { + return new char[length]; } - return new char[length]; + int allocateLength = getAllocateLengthExp(CHARS_CACH_INIT_SIZE_EXP, CHARS_CACH_MAX_SIZE_EXP, length); + char[] chars = new char[allocateLength]; + charsBufLocal.set(new SoftReference(chars)); + return chars; } - private static int getAllocateLength(int init, int max, int length) { - int value = init; - for (;;) { - if (value >= length) { - return value; - } - - value *= 2; - - if (value > max) { - break; - } + private static int getAllocateLengthExp(int minExp, int maxExp, int length) { + assert (1<= length; +// int max = 1 << maxExp; +// if(length>= max) { +// return length; +// } + int part = length >>> minExp; + if(part <= 0) { + return 1<< minExp; } - - return length; + return 1 << 32 - Integer.numberOfLeadingZeros(length-1); } // ///////// - public final static int BYTES_CACH_INIT_SIZE = 1024; // 1k; - public final static int BYTeS_CACH_MAX_SIZE = 1024 * 128; // 1k; - private final static ThreadLocal bytesBufLocal = new ThreadLocal(); + public final static int BYTES_CACH_INIT_SIZE = 1024; // 1k, 2^10; + public final static int BYTES_CACH_INIT_SIZE_EXP = 10; + public final static int BYTES_CACH_MAX_SIZE = 1024 * 128; // 128k, 2^17; + public final static int BYTES_CACH_MAX_SIZE_EXP = 17; + private final static ThreadLocal> bytesBufLocal = new ThreadLocal>(); public static void clearBytes() { bytesBufLocal.set(null); } public static byte[] getBytes(int length) { - byte[] bytes = bytesBufLocal.get(); + SoftReference ref = bytesBufLocal.get(); - if (bytes == null) { - bytes = allocateBytes(length); + if (ref == null) { + return allocateBytes(length); + } + + byte[] bytes = ref.get(); - return bytes; + if (bytes == null) { + return allocateBytes(length); } if (bytes.length < length) { @@ -81,15 +105,14 @@ public static byte[] getBytes(int length) { } private static byte[] allocateBytes(int length) { - int allocateLength = getAllocateLength(CHARS_CACH_INIT_SIZE, CHARS_CACH_MAX_SIZE, length); - - if (allocateLength <= CHARS_CACH_MAX_SIZE) { - byte[] chars = new byte[allocateLength]; - bytesBufLocal.set(chars); - return chars; + if(length > BYTES_CACH_MAX_SIZE) { + return new byte[length]; } - return new byte[length]; + int allocateLength = getAllocateLengthExp(BYTES_CACH_INIT_SIZE_EXP, BYTES_CACH_MAX_SIZE_EXP, length); + byte[] chars = new byte[allocateLength]; + bytesBufLocal.set(new SoftReference(chars)); + return chars; } -} +} \ No newline at end of file diff --git a/src/main/java/com/alibaba/fastjson/util/TypeUtils.java b/src/main/java/com/alibaba/fastjson/util/TypeUtils.java old mode 100644 new mode 100755 index e6a4f897a3..4851fcbd8e --- a/src/main/java/com/alibaba/fastjson/util/TypeUtils.java +++ b/src/main/java/com/alibaba/fastjson/util/TypeUtils.java @@ -1,654 +1,2356 @@ -/* - * Copyright 1999-2101 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.fastjson.util; - -import java.lang.reflect.Array; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.ParserConfig; -import com.alibaba.fastjson.parser.deserializer.FieldDeserializer; - -/** - * @author wenshao - */ -public class TypeUtils { - - public static final String castToString(Object value) { - if (value == null) { - return null; - } - - return value.toString(); - } - - public static final Byte castToByte(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Number) { - return ((Number) value).byteValue(); - } - - if (value instanceof String) { - String strVal = (String) value; - if (strVal.length() == 0) { - return null; - } - return Byte.parseByte(strVal); - } - - throw new JSONException("can not cast to byte, value : " + value); - } - - public static final Character castToChar(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Character) { - return (Character) value; - } - - if (value instanceof String) { - String strVal = (String) value; - - if (strVal.length() == 0) { - return null; - } - - if (strVal.length() != 1) { - throw new JSONException("can not cast to byte, value : " + value); - } - - return strVal.charAt(0); - } - - throw new JSONException("can not cast to byte, value : " + value); - } - - public static final Short castToShort(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Number) { - return ((Number) value).shortValue(); - } - - if (value instanceof String) { - String strVal = (String) value; - if (strVal.length() == 0) { - return null; - } - return Short.parseShort(strVal); - } - - throw new JSONException("can not cast to short, value : " + value); - } - - public static final BigDecimal castToBigDecimal(Object value) { - if (value == null) { - return null; - } - - if (value instanceof BigDecimal) { - return (BigDecimal) value; - } - - if (value instanceof BigInteger) { - return new BigDecimal((BigInteger) value); - } - - String strVal = value.toString(); - if (strVal.length() == 0) { - return null; - } - - return new BigDecimal(strVal); - } - - public static final BigInteger castToBigInteger(Object value) { - if (value == null) { - return null; - } - - if (value instanceof BigInteger) { - return (BigInteger) value; - } - - String strVal = value.toString(); - if (strVal.length() == 0) { - return null; - } - - return new BigInteger(strVal); - } - - public static final Float castToFloat(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Number) { - return ((Number) value).floatValue(); - } - - if (value instanceof String) { - String strVal = value.toString(); - if (strVal.length() == 0) { - return null; - } - - return Float.parseFloat(strVal); - } - - throw new JSONException("can not cast to float, value : " + value); - } - - public static final Double castToDouble(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Number) { - return ((Number) value).doubleValue(); - } - - if (value instanceof String) { - String strVal = value.toString(); - if (strVal.length() == 0) { - return null; - } - return Double.parseDouble(strVal); - } - - throw new JSONException("can not cast to double, value : " + value); - } - - public static final Date castToDate(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Calendar) { - return ((Calendar) value).getTime(); - } - - if (value instanceof Date) { - return (Date) value; - } - - long longValue = 0; - - if (value instanceof Number) { - longValue = ((Number) value).longValue(); - } - - if (value instanceof String) { - String strVal = (String) value; - if (strVal.length() == 0) { - return null; - } - - longValue = Long.parseLong(strVal); - } - - if (longValue <= 0) { - throw new JSONException("can not cast to Date, value : " + value); - } - - return new Date(longValue); - } - - public static final java.sql.Date castToSqlDate(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Calendar) { - return new java.sql.Date(((Calendar) value).getTimeInMillis()); - } - - if (value instanceof java.sql.Date) { - return (java.sql.Date) value; - } - - if (value instanceof java.util.Date) { - return new java.sql.Date(((java.util.Date) value).getTime()); - } - - long longValue = 0; - - if (value instanceof Number) { - longValue = ((Number) value).longValue(); - } - - if (value instanceof String) { - String strVal = (String) value; - if (strVal.length() == 0) { - return null; - } - - longValue = Long.parseLong(strVal); - } - - if (longValue <= 0) { - throw new JSONException("can not cast to Date, value : " + value); - } - - return new java.sql.Date(longValue); - } - - public static final java.sql.Timestamp castToTimestamp(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Calendar) { - return new java.sql.Timestamp(((Calendar) value).getTimeInMillis()); - } - - if (value instanceof java.sql.Timestamp) { - return (java.sql.Timestamp) value; - } - - if (value instanceof java.util.Date) { - return new java.sql.Timestamp(((java.util.Date) value).getTime()); - } - - long longValue = 0; - - if (value instanceof Number) { - longValue = ((Number) value).longValue(); - } - - if (value instanceof String) { - String strVal = (String) value; - if (strVal.length() == 0) { - return null; - } - - longValue = Long.parseLong(strVal); - } - - if (longValue <= 0) { - throw new JSONException("can not cast to Date, value : " + value); - } - - return new java.sql.Timestamp(longValue); - } - - public static final Long castToLong(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Number) { - return ((Number) value).longValue(); - } - - if (value instanceof String) { - String strVal = (String) value; - if (strVal.length() == 0) { - return null; - } - - return Long.parseLong(strVal); - } - - throw new JSONException("can not cast to long, value : " + value); - } - - public static final Integer castToInt(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Integer) { - return (Integer) value; - } - - if (value instanceof Number) { - return ((Number) value).intValue(); - } - - if (value instanceof String) { - String strVal = (String) value; - if (strVal.length() == 0) { - return null; - } - - return Integer.parseInt(strVal); - } - - throw new JSONException("can not cast to int, value : " + value); - } - - public static final Boolean castToBoolean(Object value) { - if (value == null) { - return null; - } - - if (value instanceof Boolean) { - return (Boolean) value; - } - - if (value instanceof Number) { - return ((Number) value).intValue() == 1; - } - - if (value instanceof String) { - String str = (String) value; - if (str.length() == 0) { - return null; - } - - if ("true".equals(str)) { - return Boolean.TRUE; - } - if ("false".equals(str)) { - return Boolean.FALSE; - } - - if ("1".equals(str)) { - return Boolean.TRUE; - } - } - - throw new JSONException("can not cast to int, value : " + value); - } - - public static final T castToJavaBean(Object obj, Class clazz) { - return cast(obj, clazz, ParserConfig.getGlobalInstance()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static final T cast(Object obj, Class clazz, ParserConfig mapping) { - if (obj == null) { - return null; - } - - if (clazz == obj.getClass()) { - return (T) obj; - } - - if (obj instanceof Map) { - if (clazz == Map.class) { - return (T) obj; - } - - return castToJavaBean((Map) obj, clazz, mapping); - } - - if (clazz.isArray()) { - if (obj instanceof Collection) { - - Collection collection = (Collection) obj; - int index = 0; - Object array = Array.newInstance(clazz.getComponentType(), collection.size()); - for (Object item : collection) { - Object value = cast(item, clazz.getComponentType(), mapping); - Array.set(array, index, value); - index++; - } - - return (T) array; - } - } - - if (clazz.isAssignableFrom(obj.getClass())) { - return (T) obj; - } - - if (clazz == boolean.class || clazz == Boolean.class) { - return (T) castToBoolean(obj); - } - - if (clazz == byte.class || clazz == Byte.class) { - return (T) castToByte(obj); - } - - // if (clazz == char.class || clazz == Character.class) { - // return (T) castToCharacter(obj); - // } - - if (clazz == short.class || clazz == Short.class) { - return (T) castToShort(obj); - } - - if (clazz == int.class || clazz == Integer.class) { - return (T) castToInt(obj); - } - - if (clazz == long.class || clazz == Long.class) { - return (T) castToLong(obj); - } - - if (clazz == float.class || clazz == Float.class) { - return (T) castToFloat(obj); - } - - if (clazz == double.class || clazz == Double.class) { - return (T) castToDouble(obj); - } - - if (clazz == String.class) { - return (T) castToString(obj); - } - - if (clazz == BigDecimal.class) { - return (T) castToBigDecimal(obj); - } - - if (clazz == BigInteger.class) { - return (T) castToBigInteger(obj); - } - - if (clazz == Date.class) { - return (T) castToDate(obj); - } - - if (clazz == java.sql.Date.class) { - return (T) castToSqlDate(obj); - } - - if (clazz == java.sql.Timestamp.class) { - return (T) castToTimestamp(obj); - } - - if (clazz.isEnum()) { - return (T) castToEnum(obj, clazz, mapping); - } - - if (obj instanceof String) { - String strVal = (String) obj; - if (strVal.length() == 0) { - return null; - } - } - - throw new JSONException("can not cast to : " + clazz.getName()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static final T castToEnum(Object obj, Class clazz, ParserConfig mapping) { - try { - if (obj instanceof String) { - String name = (String) obj; - if (name.length() == 0) { - return null; - } - - return (T) Enum.valueOf((Class) clazz, name); - } - - if (obj instanceof Number) { - int ordinal = ((Number) obj).intValue(); - - Method method = clazz.getMethod("values"); - Object[] values = (Object[]) method.invoke(null); - for (Object value : values) { - Enum e = (Enum) value; - if (e.ordinal() == ordinal) { - return (T) e; - } - } - } - } catch (Exception ex) { - throw new JSONException("can not cast to : " + clazz.getName(), ex); - } - - throw new JSONException("can not cast to : " + clazz.getName()); - } - - @SuppressWarnings("unchecked") - public static final T cast(Object obj, Type type, ParserConfig mapping) { - if (obj == null) { - return null; - } - - if (type instanceof Class) { - return (T) cast(obj, (Class) type, mapping); - } - - if (type instanceof ParameterizedType) { - return (T) cast(obj, (ParameterizedType) type, mapping); - } - - if (obj instanceof String) { - String strVal = (String) obj; - if (strVal.length() == 0) { - return null; - } - } - - throw new JSONException("can not cast to : " + type); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static final T cast(Object obj, ParameterizedType type, ParserConfig mapping) { - Type rawTye = type.getRawType(); - - if (rawTye == List.class || rawTye == ArrayList.class) { - Type itemType = type.getActualTypeArguments()[0]; - - if (obj instanceof Iterable) { - List list = new ArrayList(); - - for (Iterator it = ((Iterable) obj).iterator(); it.hasNext();) { - Object item = it.next(); - list.add(cast(item, itemType, mapping)); - } - - return (T) list; - } - } - - if (rawTye == Map.class || rawTye == HashMap.class) { - Type keyType = type.getActualTypeArguments()[0]; - Type valueType = type.getActualTypeArguments()[1]; - - if (obj instanceof Map) { - Map map = new HashMap(); - - for (Map.Entry entry : ((Map) obj).entrySet()) { - Object key = cast(entry.getKey(), keyType, mapping); - Object value = cast(entry.getValue(), valueType, mapping); - - map.put(key, value); - } - - return (T) map; - } - } - - if (obj instanceof String) { - String strVal = (String) obj; - if (strVal.length() == 0) { - return null; - } - } - - throw new JSONException("can not cast to : " + type); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static final T castToJavaBean(Map map, Class clazz, ParserConfig mapping) { - try { - if (clazz == StackTraceElement.class) { - String declaringClass = (String) map.get("className"); - String methodName = (String) map.get("methodName"); - String fileName = (String) map.get("fileName"); - int lineNumber; - { - Number value = (Number) map.get("lineNumber"); - if (value == null) { - lineNumber = 0; - } else { - lineNumber = value.intValue(); - } - } - - return (T) new StackTraceElement(declaringClass, methodName, fileName, lineNumber); - } - - { - Object iClassObject = map.get("class"); - if (iClassObject instanceof String) { - String className = (String) iClassObject; - - try { - Class iClass = Thread.currentThread().getContextClassLoader().loadClass(className); - clazz = iClass; - } catch (Throwable e) { - // skip - } - } - } - - Map setters = mapping.getFieldDeserializers(clazz); - - T object = clazz.newInstance(); - - for (Map.Entry entry : setters.entrySet()) { - String key = entry.getKey(); - Method method = entry.getValue().getMethod(); - - Object value = map.get(key); - value = cast(value, method.getGenericParameterTypes()[0], mapping); - method.invoke(object, new Object[] { value }); - } - - return object; - } catch (Exception e) { - throw new JSONException(e.getMessage(), e); - } - } -} +/* + * Copyright 1999-2017 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.fastjson.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.PropertyNamingStrategy; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.JSONScanner; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.EnumDeserializer; +import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.serializer.CalendarCodec; +import com.alibaba.fastjson.serializer.SerializeBeanInfo; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import java.lang.annotation.Annotation; +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Array; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Proxy; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.security.AccessControlException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.AbstractCollection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * @author wenshao[szujobs@hotmail.com] + */ +public class TypeUtils{ + + public static boolean compatibleWithJavaBean = false; + /** 根据field name的大小写输出输入数据 */ + public static boolean compatibleWithFieldName = false; + private static boolean setAccessibleEnable = true; + private static boolean oracleTimestampMethodInited = false; + private static Method oracleTimestampMethod; + private static boolean oracleDateMethodInited = false; + private static Method oracleDateMethod; + private static boolean optionalClassInited = false; + private static Class optionalClass; + private static boolean transientClassInited = false; + private static Class transientClass; + + private static Class class_OneToMany = null; + private static boolean class_OneToMany_error = false; + private static Class class_ManyToMany = null; + private static boolean class_ManyToMany_error = false; + + private static Method method_HibernateIsInitialized = null; + private static boolean method_HibernateIsInitialized_error = false; + private static volatile Class kotlin_metadata; + private static volatile boolean kotlin_metadata_error; + private static volatile boolean kotlin_class_klass_error; + private static volatile Constructor kotlin_kclass_constructor; + private static volatile Method kotlin_kclass_getConstructors; + private static volatile Method kotlin_kfunction_getParameters; + private static volatile Method kotlin_kparameter_getName; + private static volatile boolean kotlin_error; + private static volatile Map kotlinIgnores; + private static volatile boolean kotlinIgnores_error; + private static ConcurrentMap> mappings = new ConcurrentHashMap>(16, 0.75f, 1); + private static Class pathClass; + private static boolean pathClass_error = false; + + static{ + try{ + TypeUtils.compatibleWithJavaBean = "true".equals(IOUtils.getStringProperty(IOUtils.FASTJSON_COMPATIBLEWITHJAVABEAN)); + TypeUtils.compatibleWithFieldName = "true".equals(IOUtils.getStringProperty(IOUtils.FASTJSON_COMPATIBLEWITHFIELDNAME)); + } catch(Throwable e){ + // skip + } + } + + static{ + addBaseClassMappings(); + } + + public static String castToString(Object value){ + if(value == null){ + return null; + } + return value.toString(); + } + + public static Byte castToByte(Object value){ + if(value == null){ + return null; + } + if(value instanceof Number){ + return ((Number) value).byteValue(); + } + if(value instanceof String){ + String strVal = (String) value; + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + return Byte.parseByte(strVal); + } + throw new JSONException("can not cast to byte, value : " + value); + } + + public static Character castToChar(Object value){ + if(value == null){ + return null; + } + if(value instanceof Character){ + return (Character) value; + } + if(value instanceof String){ + String strVal = (String) value; + if(strVal.length() == 0){ + return null; + } + if(strVal.length() != 1){ + throw new JSONException("can not cast to char, value : " + value); + } + return strVal.charAt(0); + } + throw new JSONException("can not cast to char, value : " + value); + } + + public static Short castToShort(Object value){ + if(value == null){ + return null; + } + if(value instanceof Number){ + return ((Number) value).shortValue(); + } + if(value instanceof String){ + String strVal = (String) value; + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + return Short.parseShort(strVal); + } + throw new JSONException("can not cast to short, value : " + value); + } + + public static BigDecimal castToBigDecimal(Object value){ + if(value == null){ + return null; + } + if(value instanceof BigDecimal){ + return (BigDecimal) value; + } + if(value instanceof BigInteger){ + return new BigDecimal((BigInteger) value); + } + String strVal = value.toString(); + if(strVal.length() == 0){ + return null; + } + if(value instanceof Map && ((Map) value).size() == 0){ + return null; + } + return new BigDecimal(strVal); + } + + public static BigInteger castToBigInteger(Object value){ + if(value == null){ + return null; + } + if(value instanceof BigInteger){ + return (BigInteger) value; + } + if(value instanceof Float || value instanceof Double){ + return BigInteger.valueOf(((Number) value).longValue()); + } + String strVal = value.toString(); + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + return new BigInteger(strVal); + } + + public static Float castToFloat(Object value){ + if(value == null){ + return null; + } + if(value instanceof Number){ + return ((Number) value).floatValue(); + } + if(value instanceof String){ + String strVal = value.toString(); + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + if(strVal.indexOf(',') != 0){ + strVal = strVal.replaceAll(",", ""); + } + return Float.parseFloat(strVal); + } + throw new JSONException("can not cast to float, value : " + value); + } + + public static Double castToDouble(Object value){ + if(value == null){ + return null; + } + if(value instanceof Number){ + return ((Number) value).doubleValue(); + } + if(value instanceof String){ + String strVal = value.toString(); + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + if(strVal.indexOf(',') != 0){ + strVal = strVal.replaceAll(",", ""); + } + return Double.parseDouble(strVal); + } + throw new JSONException("can not cast to double, value : " + value); + } + + public static Date castToDate(Object value){ + return castToDate(value, null); + } + + public static Date castToDate(Object value, String format){ + if(value == null){ + return null; + } + if(value instanceof Date){ // 使用频率最高的,应优先处理 + return (Date) value; + } + if(value instanceof Calendar){ + return ((Calendar) value).getTime(); + } + long longValue = -1; + if(value instanceof Number){ + longValue = ((Number) value).longValue(); + return new Date(longValue); + } + if(value instanceof String){ + String strVal = (String) value; + JSONScanner dateLexer = new JSONScanner(strVal); + try{ + if(dateLexer.scanISO8601DateIfMatch(false)){ + Calendar calendar = dateLexer.getCalendar(); + return calendar.getTime(); + } + } finally{ + dateLexer.close(); + } + if(strVal.startsWith("/Date(") && strVal.endsWith(")/")){ + strVal = strVal.substring(6, strVal.length() - 2); + } + if(strVal.indexOf('-') != -1){ + if (format == null) { + if (strVal.length() == JSON.DEFFAULT_DATE_FORMAT.length() + || (strVal.length() == 22 && JSON.DEFFAULT_DATE_FORMAT.equals("yyyyMMddHHmmssSSSZ"))) { + format = JSON.DEFFAULT_DATE_FORMAT; + } else if (strVal.length() == 10) { + format = "yyyy-MM-dd"; + } else if (strVal.length() == "yyyy-MM-dd HH:mm:ss".length()) { + format = "yyyy-MM-dd HH:mm:ss"; + } else if (strVal.length() == 29 + && strVal.charAt(26) == ':' + && strVal.charAt(28) == '0') { + format = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } else { + format = "yyyy-MM-dd HH:mm:ss.SSS"; + } + } + + SimpleDateFormat dateFormat = new SimpleDateFormat(format, JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + try{ + return dateFormat.parse(strVal); + } catch(ParseException e){ + throw new JSONException("can not cast to Date, value : " + strVal); + } + } + if(strVal.length() == 0){ + return null; + } + longValue = Long.parseLong(strVal); + } + if(longValue < 0){ + Class clazz = value.getClass(); + if("oracle.sql.TIMESTAMP".equals(clazz.getName())){ + if(oracleTimestampMethod == null && !oracleTimestampMethodInited){ + try{ + oracleTimestampMethod = clazz.getMethod("toJdbc"); + } catch(NoSuchMethodException e){ + // skip + } finally{ + oracleTimestampMethodInited = true; + } + } + Object result; + try{ + result = oracleTimestampMethod.invoke(value); + } catch(Exception e){ + throw new JSONException("can not cast oracle.sql.TIMESTAMP to Date", e); + } + return (Date) result; + } + if("oracle.sql.DATE".equals(clazz.getName())){ + if(oracleDateMethod == null && !oracleDateMethodInited){ + try{ + oracleDateMethod = clazz.getMethod("toJdbc"); + } catch(NoSuchMethodException e){ + // skip + } finally{ + oracleDateMethodInited = true; + } + } + Object result; + try{ + result = oracleDateMethod.invoke(value); + } catch(Exception e){ + throw new JSONException("can not cast oracle.sql.DATE to Date", e); + } + return (Date) result; + } + throw new JSONException("can not cast to Date, value : " + value); + } + return new Date(longValue); + } + + public static java.sql.Date castToSqlDate(Object value){ + if(value == null){ + return null; + } + if(value instanceof java.sql.Date){ + return (java.sql.Date) value; + } + if(value instanceof java.util.Date){ + return new java.sql.Date(((java.util.Date) value).getTime()); + } + if(value instanceof Calendar){ + return new java.sql.Date(((Calendar) value).getTimeInMillis()); + } + long longValue = 0; + if(value instanceof Number){ + longValue = ((Number) value).longValue(); + } + if(value instanceof String){ + String strVal = (String) value; + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + if(isNumber(strVal)){ + longValue = Long.parseLong(strVal); + } else{ + JSONScanner scanner = new JSONScanner(strVal); + if(scanner.scanISO8601DateIfMatch(false)){ + longValue = scanner.getCalendar().getTime().getTime(); + } else{ + throw new JSONException("can not cast to Timestamp, value : " + strVal); + } + } + } + if(longValue <= 0){ + throw new JSONException("can not cast to Date, value : " + value); // TODO 忽略 1970-01-01 之前的时间处理? + } + return new java.sql.Date(longValue); + } + + public static java.sql.Time castToSqlTime(Object value){ + if(value == null){ + return null; + } + if(value instanceof java.sql.Time){ + return (java.sql.Time) value; + } + if(value instanceof java.util.Date){ + return new java.sql.Time(((java.util.Date) value).getTime()); + } + if(value instanceof Calendar){ + return new java.sql.Time(((Calendar) value).getTimeInMillis()); + } + long longValue = 0; + if(value instanceof Number){ + longValue = ((Number) value).longValue(); + } + if(value instanceof String){ + String strVal = (String) value; + if(strVal.length() == 0 // + || "null".equalsIgnoreCase(strVal)){ + return null; + } + if(isNumber(strVal)){ + longValue = Long.parseLong(strVal); + } else{ + JSONScanner scanner = new JSONScanner(strVal); + if(scanner.scanISO8601DateIfMatch(false)){ + longValue = scanner.getCalendar().getTime().getTime(); + } else{ + throw new JSONException("can not cast to Timestamp, value : " + strVal); + } + } + } + if(longValue <= 0){ + throw new JSONException("can not cast to Date, value : " + value); // TODO 忽略 1970-01-01 之前的时间处理? + } + return new java.sql.Time(longValue); + } + + public static java.sql.Timestamp castToTimestamp(Object value){ + if(value == null){ + return null; + } + if(value instanceof Calendar){ + return new java.sql.Timestamp(((Calendar) value).getTimeInMillis()); + } + if(value instanceof java.sql.Timestamp){ + return (java.sql.Timestamp) value; + } + if(value instanceof java.util.Date){ + return new java.sql.Timestamp(((java.util.Date) value).getTime()); + } + long longValue = 0; + if(value instanceof Number){ + longValue = ((Number) value).longValue(); + } + if(value instanceof String){ + String strVal = (String) value; + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + if(strVal.endsWith(".000000000")){ + strVal = strVal.substring(0, strVal.length() - 10); + } else if(strVal.endsWith(".000000")){ + strVal = strVal.substring(0, strVal.length() - 7); + } + if(isNumber(strVal)){ + longValue = Long.parseLong(strVal); + } else{ + JSONScanner scanner = new JSONScanner(strVal); + if(scanner.scanISO8601DateIfMatch(false)){ + longValue = scanner.getCalendar().getTime().getTime(); + } else{ + throw new JSONException("can not cast to Timestamp, value : " + strVal); + } + } + } + if(longValue <= 0){ + throw new JSONException("can not cast to Timestamp, value : " + value); + } + return new java.sql.Timestamp(longValue); + } + + public static boolean isNumber(String str){ + for(int i = 0; i < str.length(); ++i){ + char ch = str.charAt(i); + if(ch == '+' || ch == '-'){ + if(i != 0){ + return false; + } + } else if(ch < '0' || ch > '9'){ + return false; + } + } + return true; + } + + public static Long castToLong(Object value){ + if(value == null){ + return null; + } + if(value instanceof Number){ + return ((Number) value).longValue(); + } + if(value instanceof String){ + String strVal = (String) value; + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + if(strVal.indexOf(',') != 0){ + strVal = strVal.replaceAll(",", ""); + } + try{ + return Long.parseLong(strVal); + } catch(NumberFormatException ex){ + // + } + JSONScanner dateParser = new JSONScanner(strVal); + Calendar calendar = null; + if(dateParser.scanISO8601DateIfMatch(false)){ + calendar = dateParser.getCalendar(); + } + dateParser.close(); + if(calendar != null){ + return calendar.getTimeInMillis(); + } + } + if(value instanceof Map){ + Map map = (Map) value; + if(map.size() == 2 + && map.containsKey("andIncrement") + && map.containsKey("andDecrement")){ + Iterator iter = map.values().iterator(); + iter.next(); + Object value2 = iter.next(); + return castToLong(value2); + } + } + throw new JSONException("can not cast to long, value : " + value); + } + + public static Integer castToInt(Object value){ + if(value == null){ + return null; + } + if(value instanceof Integer){ + return (Integer) value; + } + if(value instanceof Number){ + return ((Number) value).intValue(); + } + if(value instanceof String){ + String strVal = (String) value; + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + if(strVal.indexOf(',') != 0){ + strVal = strVal.replaceAll(",", ""); + } + return Integer.parseInt(strVal); + } + if(value instanceof Boolean){ + return ((Boolean) value).booleanValue() ? 1 : 0; + } + if(value instanceof Map){ + Map map = (Map) value; + if(map.size() == 2 + && map.containsKey("andIncrement") + && map.containsKey("andDecrement")){ + Iterator iter = map.values().iterator(); + iter.next(); + Object value2 = iter.next(); + return castToInt(value2); + } + } + throw new JSONException("can not cast to int, value : " + value); + } + + public static byte[] castToBytes(Object value){ + if(value instanceof byte[]){ + return (byte[]) value; + } + if(value instanceof String){ + return IOUtils.decodeBase64((String) value); + } + throw new JSONException("can not cast to int, value : " + value); + } + + public static Boolean castToBoolean(Object value){ + if(value == null){ + return null; + } + if(value instanceof Boolean){ + return (Boolean) value; + } + if(value instanceof Number){ + return ((Number) value).intValue() == 1; + } + if(value instanceof String){ + String strVal = (String) value; + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + if("true".equalsIgnoreCase(strVal) // + || "1".equals(strVal)){ + return Boolean.TRUE; + } + if("false".equalsIgnoreCase(strVal) // + || "0".equals(strVal)){ + return Boolean.FALSE; + } + if("Y".equalsIgnoreCase(strVal) // + || "T".equals(strVal)){ + return Boolean.TRUE; + } + if("F".equalsIgnoreCase(strVal) // + || "N".equals(strVal)){ + return Boolean.FALSE; + } + } + throw new JSONException("can not cast to boolean, value : " + value); + } + + public static T castToJavaBean(Object obj, Class clazz){ + return cast(obj, clazz, ParserConfig.getGlobalInstance()); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static T cast(Object obj, Class clazz, ParserConfig config){ + if(obj == null){ + if(clazz == int.class){ + return (T) Integer.valueOf(0); + } else if(clazz == long.class){ + return (T) Long.valueOf(0); + } else if(clazz == short.class){ + return (T) Short.valueOf((short) 0); + } else if(clazz == byte.class){ + return (T) Byte.valueOf((byte) 0); + } else if(clazz == float.class){ + return (T) Float.valueOf(0); + } else if(clazz == double.class){ + return (T) Double.valueOf(0); + } else if(clazz == boolean.class){ + return (T) Boolean.FALSE; + } + return null; + } + if(clazz == null){ + throw new IllegalArgumentException("clazz is null"); + } + if(clazz == obj.getClass()){ + return (T) obj; + } + if(obj instanceof Map){ + if(clazz == Map.class){ + return (T) obj; + } + Map map = (Map) obj; + if(clazz == Object.class && !map.containsKey(JSON.DEFAULT_TYPE_KEY)){ + return (T) obj; + } + return castToJavaBean((Map) obj, clazz, config); + } + if(clazz.isArray()){ + if(obj instanceof Collection){ + Collection collection = (Collection) obj; + int index = 0; + Object array = Array.newInstance(clazz.getComponentType(), collection.size()); + for(Object item : collection){ + Object value = cast(item, clazz.getComponentType(), config); + Array.set(array, index, value); + index++; + } + return (T) array; + } + if(clazz == byte[].class){ + return (T) castToBytes(obj); + } + } + if(clazz.isAssignableFrom(obj.getClass())){ + return (T) obj; + } + if(clazz == boolean.class || clazz == Boolean.class){ + return (T) castToBoolean(obj); + } + if(clazz == byte.class || clazz == Byte.class){ + return (T) castToByte(obj); + } + if(clazz == char.class || clazz == Character.class){ + return (T) castToChar(obj); + } + if(clazz == short.class || clazz == Short.class){ + return (T) castToShort(obj); + } + if(clazz == int.class || clazz == Integer.class){ + return (T) castToInt(obj); + } + if(clazz == long.class || clazz == Long.class){ + return (T) castToLong(obj); + } + if(clazz == float.class || clazz == Float.class){ + return (T) castToFloat(obj); + } + if(clazz == double.class || clazz == Double.class){ + return (T) castToDouble(obj); + } + if(clazz == String.class){ + return (T) castToString(obj); + } + if(clazz == BigDecimal.class){ + return (T) castToBigDecimal(obj); + } + if(clazz == BigInteger.class){ + return (T) castToBigInteger(obj); + } + if(clazz == Date.class){ + return (T) castToDate(obj); + } + if(clazz == java.sql.Date.class){ + return (T) castToSqlDate(obj); + } + if(clazz == java.sql.Time.class){ + return (T) castToSqlTime(obj); + } + if(clazz == java.sql.Timestamp.class){ + return (T) castToTimestamp(obj); + } + if(clazz.isEnum()){ + return (T) castToEnum(obj, clazz, config); + } + if(Calendar.class.isAssignableFrom(clazz)){ + Date date = castToDate(obj); + Calendar calendar; + if(clazz == Calendar.class){ + calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + } else{ + try{ + calendar = (Calendar) clazz.newInstance(); + } catch(Exception e){ + throw new JSONException("can not cast to : " + clazz.getName(), e); + } + } + calendar.setTime(date); + return (T) calendar; + } + + String className = clazz.getName(); + if(className.equals("javax.xml.datatype.XMLGregorianCalendar")){ + Date date = castToDate(obj); + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(date); + return (T) CalendarCodec.instance.createXMLGregorianCalendar(calendar); + } + + if(obj instanceof String){ + String strVal = (String) obj; + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + if(clazz == java.util.Currency.class){ + return (T) java.util.Currency.getInstance(strVal); + } + if(clazz == java.util.Locale.class){ + return (T) toLocale(strVal); + } + + if (className.startsWith("java.time.")) { + String json = JSON.toJSONString(strVal); + return JSON.parseObject(json, clazz); + } + } + throw new JSONException("can not cast to : " + clazz.getName()); + } + + public static Locale toLocale(String strVal){ + String[] items = strVal.split("_"); + if(items.length == 1){ + return new Locale(items[0]); + } + if(items.length == 2){ + return new Locale(items[0], items[1]); + } + return new Locale(items[0], items[1], items[2]); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static T castToEnum(Object obj, Class clazz, ParserConfig mapping){ + try{ + if(obj instanceof String){ + String name = (String) obj; + if(name.length() == 0){ + return null; + } + + if (mapping == null) { + mapping = ParserConfig.getGlobalInstance(); + } + + ObjectDeserializer derializer = mapping.getDeserializer(clazz); + if (derializer instanceof EnumDeserializer) { + EnumDeserializer enumDeserializer = (EnumDeserializer) derializer; + return (T) enumDeserializer.getEnumByHashCode(TypeUtils.fnv1a_64(name)); + } + + return (T) Enum.valueOf((Class) clazz, name); + } + if(obj instanceof Number){ + int ordinal = ((Number) obj).intValue(); + Object[] values = clazz.getEnumConstants(); + if(ordinal < values.length){ + return (T) values[ordinal]; + } + } + } catch(Exception ex){ + throw new JSONException("can not cast to : " + clazz.getName(), ex); + } + throw new JSONException("can not cast to : " + clazz.getName()); + } + + @SuppressWarnings("unchecked") + public static T cast(Object obj, Type type, ParserConfig mapping){ + if(obj == null){ + return null; + } + if(type instanceof Class){ + return (T) cast(obj, (Class) type, mapping); + } + if(type instanceof ParameterizedType){ + return (T) cast(obj, (ParameterizedType) type, mapping); + } + if(obj instanceof String){ + String strVal = (String) obj; + if(strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)){ + return null; + } + } + if(type instanceof TypeVariable){ + return (T) obj; + } + throw new JSONException("can not cast to : " + type); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static T cast(Object obj, ParameterizedType type, ParserConfig mapping){ + Type rawTye = type.getRawType(); + if(rawTye == Set.class || rawTye == HashSet.class // + || rawTye == TreeSet.class // + || rawTye == Collection.class // + || rawTye == List.class // + || rawTye == ArrayList.class){ + Type itemType = type.getActualTypeArguments()[0]; + if(obj instanceof Iterable){ + Collection collection; + if(rawTye == Set.class || rawTye == HashSet.class){ + collection = new HashSet(); + } else if(rawTye == TreeSet.class){ + collection = new TreeSet(); + } else{ + collection = new ArrayList(); + } + for(Iterator it = ((Iterable) obj).iterator(); it.hasNext(); ){ + Object item = it.next(); + collection.add(cast(item, itemType, mapping)); + } + return (T) collection; + } + } + if(rawTye == Map.class || rawTye == HashMap.class){ + Type keyType = type.getActualTypeArguments()[0]; + Type valueType = type.getActualTypeArguments()[1]; + if(obj instanceof Map){ + Map map = new HashMap(); + for(Map.Entry entry : ((Map) obj).entrySet()){ + Object key = cast(entry.getKey(), keyType, mapping); + Object value = cast(entry.getValue(), valueType, mapping); + map.put(key, value); + } + return (T) map; + } + } + if(obj instanceof String){ + String strVal = (String) obj; + if(strVal.length() == 0){ + return null; + } + } + if(type.getActualTypeArguments().length == 1){ + Type argType = type.getActualTypeArguments()[0]; + if(argType instanceof WildcardType){ + return (T) cast(obj, rawTye, mapping); + } + } + + if (rawTye == Map.Entry.class && obj instanceof Map && ((Map) obj).size() == 1) { + Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next(); + return (T) entry; + } + + if (rawTye instanceof Class) { + if (mapping == null) { + mapping = ParserConfig.global; + } + ObjectDeserializer deserializer = mapping.getDeserializer(rawTye); + if (deserializer != null) { + String str = JSON.toJSONString(obj); + DefaultJSONParser parser = new DefaultJSONParser(str, mapping); + return (T) deserializer.deserialze(parser, type, null); + } + } + + throw new JSONException("can not cast to : " + type); + } + + @SuppressWarnings({"unchecked"}) + public static T castToJavaBean(Map map, Class clazz, ParserConfig config){ + try{ + if(clazz == StackTraceElement.class){ + String declaringClass = (String) map.get("className"); + String methodName = (String) map.get("methodName"); + String fileName = (String) map.get("fileName"); + int lineNumber; + { + Number value = (Number) map.get("lineNumber"); + if(value == null){ + lineNumber = 0; + } else{ + lineNumber = value.intValue(); + } + } + return (T) new StackTraceElement(declaringClass, methodName, fileName, lineNumber); + } + + { + Object iClassObject = map.get(JSON.DEFAULT_TYPE_KEY); + if(iClassObject instanceof String){ + String className = (String) iClassObject; + Class loadClazz; + if(config == null){ + config = ParserConfig.global; + } + loadClazz = config.checkAutoType(className, null); + if(loadClazz == null){ + throw new ClassNotFoundException(className + " not found"); + } + if(!loadClazz.equals(clazz)){ + return (T) castToJavaBean(map, loadClazz, config); + } + } + } + + if(clazz.isInterface()){ + JSONObject object; + if(map instanceof JSONObject){ + object = (JSONObject) map; + } else{ + object = new JSONObject(map); + } + if(config == null){ + config = ParserConfig.getGlobalInstance(); + } + ObjectDeserializer deserializer = config.getDeserializers().get(clazz); + if(deserializer != null){ + String json = JSON.toJSONString(object); + return (T) JSON.parseObject(json, clazz); + } + return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), + new Class[]{clazz}, object); + } + + if(clazz == Locale.class){ + Object arg0 = map.get("language"); + Object arg1 = map.get("country"); + if(arg0 instanceof String){ + String language = (String) arg0; + if(arg1 instanceof String){ + String country = (String) arg1; + return (T) new Locale(language, country); + } else if(arg1 == null){ + return (T) new Locale(language); + } + } + } + + if (clazz == String.class && map instanceof JSONObject) { + return (T) map.toString(); + } + + if (clazz == LinkedHashMap.class && map instanceof JSONObject) { + JSONObject jsonObject = (JSONObject) map; + Map innerMap = jsonObject.getInnerMap(); + if (innerMap instanceof LinkedHashMap) { + return (T) innerMap; + } else { + LinkedHashMap linkedHashMap = new LinkedHashMap(); + linkedHashMap.putAll(innerMap); + } + } + + if (config == null) { + config = ParserConfig.getGlobalInstance(); + } + + JavaBeanDeserializer javaBeanDeser = null; + ObjectDeserializer deserizer = config.getDeserializer(clazz); + if (deserizer instanceof JavaBeanDeserializer) { + javaBeanDeser = (JavaBeanDeserializer) deserizer; + } + + if(javaBeanDeser == null){ + throw new JSONException("can not get javaBeanDeserializer. " + clazz.getName()); + } + return (T) javaBeanDeser.createInstance(map, config); + } catch(Exception e){ + throw new JSONException(e.getMessage(), e); + } + } + + private static void addBaseClassMappings(){ + mappings.put("byte", byte.class); + mappings.put("short", short.class); + mappings.put("int", int.class); + mappings.put("long", long.class); + mappings.put("float", float.class); + mappings.put("double", double.class); + mappings.put("boolean", boolean.class); + mappings.put("char", char.class); + mappings.put("[byte", byte[].class); + mappings.put("[short", short[].class); + mappings.put("[int", int[].class); + mappings.put("[long", long[].class); + mappings.put("[float", float[].class); + mappings.put("[double", double[].class); + mappings.put("[boolean", boolean[].class); + mappings.put("[char", char[].class); + mappings.put("[B", byte[].class); + mappings.put("[S", short[].class); + mappings.put("[I", int[].class); + mappings.put("[J", long[].class); + mappings.put("[F", float[].class); + mappings.put("[D", double[].class); + mappings.put("[C", char[].class); + mappings.put("[Z", boolean[].class); + Class[] classes = new Class[]{ + Object.class, + java.lang.Cloneable.class, + loadClass("java.lang.AutoCloseable"), + java.lang.Exception.class, + java.lang.RuntimeException.class, + java.lang.IllegalAccessError.class, + java.lang.IllegalAccessException.class, + java.lang.IllegalArgumentException.class, + java.lang.IllegalMonitorStateException.class, + java.lang.IllegalStateException.class, + java.lang.IllegalThreadStateException.class, + java.lang.IndexOutOfBoundsException.class, + java.lang.InstantiationError.class, + java.lang.InstantiationException.class, + java.lang.InternalError.class, + java.lang.InterruptedException.class, + java.lang.LinkageError.class, + java.lang.NegativeArraySizeException.class, + java.lang.NoClassDefFoundError.class, + java.lang.NoSuchFieldError.class, + java.lang.NoSuchFieldException.class, + java.lang.NoSuchMethodError.class, + java.lang.NoSuchMethodException.class, + java.lang.NullPointerException.class, + java.lang.NumberFormatException.class, + java.lang.OutOfMemoryError.class, + java.lang.SecurityException.class, + java.lang.StackOverflowError.class, + java.lang.StringIndexOutOfBoundsException.class, + java.lang.TypeNotPresentException.class, + java.lang.VerifyError.class, + java.lang.StackTraceElement.class, + java.util.HashMap.class, + java.util.Hashtable.class, + java.util.TreeMap.class, + java.util.IdentityHashMap.class, + java.util.WeakHashMap.class, + java.util.LinkedHashMap.class, + java.util.HashSet.class, + java.util.LinkedHashSet.class, + java.util.TreeSet.class, + java.util.concurrent.TimeUnit.class, + java.util.concurrent.ConcurrentHashMap.class, + loadClass("java.util.concurrent.ConcurrentSkipListMap"), + loadClass("java.util.concurrent.ConcurrentSkipListSet"), + java.util.concurrent.atomic.AtomicInteger.class, + java.util.concurrent.atomic.AtomicLong.class, + java.util.Collections.EMPTY_MAP.getClass(), + java.util.BitSet.class, + java.util.Calendar.class, + java.util.Date.class, + java.util.Locale.class, + java.util.UUID.class, + java.sql.Time.class, + java.sql.Date.class, + java.sql.Timestamp.class, + java.text.SimpleDateFormat.class, + com.alibaba.fastjson.JSONObject.class, + }; + for(Class clazz : classes){ + if(clazz == null){ + continue; + } + mappings.put(clazz.getName(), clazz); + } + String[] awt = new String[]{ + "java.awt.Rectangle", + "java.awt.Point", + "java.awt.Font", + "java.awt.Color"}; + for(String className : awt){ + Class clazz = loadClass(className); + if(clazz == null){ + break; + } + mappings.put(clazz.getName(), clazz); + } + String[] spring = new String[]{ + "org.springframework.util.LinkedMultiValueMap", + "org.springframework.util.LinkedCaseInsensitiveMap", + "org.springframework.remoting.support.RemoteInvocation", + "org.springframework.remoting.support.RemoteInvocationResult", + "org.springframework.security.web.savedrequest.DefaultSavedRequest", + "org.springframework.security.web.savedrequest.SavedCookie", + "org.springframework.security.web.csrf.DefaultCsrfToken", + "org.springframework.security.web.authentication.WebAuthenticationDetails", + "org.springframework.security.core.context.SecurityContextImpl", + "org.springframework.security.authentication.UsernamePasswordAuthenticationToken", + "org.springframework.security.core.authority.SimpleGrantedAuthority", + "org.springframework.security.core.userdetails.User" + }; + for(String className : spring){ + Class clazz = loadClass(className); + if(clazz == null){ + break; + } + mappings.put(clazz.getName(), clazz); + } + } + + public static void clearClassMapping(){ + mappings.clear(); + addBaseClassMappings(); + } + + public static Class loadClass(String className){ + return loadClass(className, null); + } + + public static boolean isPath(Class clazz){ + if(pathClass == null && !pathClass_error){ + try{ + pathClass = Class.forName("java.nio.file.Path"); + } catch(Throwable ex){ + pathClass_error = true; + } + } + if(pathClass != null){ + return pathClass.isAssignableFrom(clazz); + } + return false; + } + + public static Class getClassFromMapping(String className){ + return mappings.get(className); + } + + public static Class loadClass(String className, ClassLoader classLoader) { + return loadClass(className, classLoader, true); + } + + public static Class loadClass(String className, ClassLoader classLoader, boolean cache) { + if(className == null || className.length() == 0){ + return null; + } + Class clazz = mappings.get(className); + if(clazz != null){ + return clazz; + } + if(className.charAt(0) == '['){ + Class componentType = loadClass(className.substring(1), classLoader); + return Array.newInstance(componentType, 0).getClass(); + } + if(className.startsWith("L") && className.endsWith(";")){ + String newClassName = className.substring(1, className.length() - 1); + return loadClass(newClassName, classLoader); + } + try{ + if(classLoader != null){ + clazz = classLoader.loadClass(className); + if (cache) { + mappings.put(className, clazz); + } + return clazz; + } + } catch(Throwable e){ + e.printStackTrace(); + // skip + } + try{ + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + if(contextClassLoader != null && contextClassLoader != classLoader){ + clazz = contextClassLoader.loadClass(className); + if (cache) { + mappings.put(className, clazz); + } + return clazz; + } + } catch(Throwable e){ + // skip + } + try{ + clazz = Class.forName(className); + mappings.put(className, clazz); + return clazz; + } catch(Throwable e){ + // skip + } + return clazz; + } + + public static SerializeBeanInfo buildBeanInfo(Class beanType // + , Map aliasMap // + , PropertyNamingStrategy propertyNamingStrategy){ + return buildBeanInfo(beanType, aliasMap, propertyNamingStrategy, false); + } + + public static SerializeBeanInfo buildBeanInfo(Class beanType // + , Map aliasMap // + , PropertyNamingStrategy propertyNamingStrategy // + , boolean fieldBased // + ){ + JSONType jsonType = TypeUtils.getAnnotation(beanType,JSONType.class); + String[] orders = null; + final int features; + String typeName = null, typeKey = null; + if(jsonType != null){ + orders = jsonType.orders(); + + typeName = jsonType.typeName(); + if(typeName.length() == 0){ + typeName = null; + } + + PropertyNamingStrategy jsonTypeNaming = jsonType.naming(); + if (jsonTypeNaming != PropertyNamingStrategy.CamelCase) { + propertyNamingStrategy = jsonTypeNaming; + } + + features = SerializerFeature.of(jsonType.serialzeFeatures()); + for(Class supperClass = beanType.getSuperclass() + ; supperClass != null && supperClass != Object.class + ; supperClass = supperClass.getSuperclass()){ + JSONType superJsonType = TypeUtils.getAnnotation(supperClass,JSONType.class); + if(superJsonType == null){ + break; + } + typeKey = superJsonType.typeKey(); + if(typeKey.length() != 0){ + break; + } + } + + for(Class interfaceClass : beanType.getInterfaces()){ + JSONType superJsonType = TypeUtils.getAnnotation(interfaceClass,JSONType.class); + if(superJsonType != null){ + typeKey = superJsonType.typeKey(); + if(typeKey.length() != 0){ + break; + } + } + } + + if(typeKey != null && typeKey.length() == 0){ + typeKey = null; + } + } else{ + features = 0; + } + // fieldName,field ,先生成fieldName的快照,减少之后的findField的轮询 + Map fieldCacheMap = new HashMap(); + ParserConfig.parserAllFieldToCache(beanType, fieldCacheMap); + List fieldInfoList = fieldBased + ? computeGettersWithFieldBase(beanType, aliasMap, false, propertyNamingStrategy) // + : computeGetters(beanType, jsonType, aliasMap, fieldCacheMap, false, propertyNamingStrategy); + FieldInfo[] fields = new FieldInfo[fieldInfoList.size()]; + fieldInfoList.toArray(fields); + FieldInfo[] sortedFields; + List sortedFieldList; + if(orders != null && orders.length != 0){ + sortedFieldList = fieldBased + ? computeGettersWithFieldBase(beanType, aliasMap, true, propertyNamingStrategy) // + : computeGetters(beanType, jsonType, aliasMap, fieldCacheMap, true, propertyNamingStrategy); + } else{ + sortedFieldList = new ArrayList(fieldInfoList); + Collections.sort(sortedFieldList); + } + sortedFields = new FieldInfo[sortedFieldList.size()]; + sortedFieldList.toArray(sortedFields); + if(Arrays.equals(sortedFields, fields)){ + sortedFields = fields; + } + return new SerializeBeanInfo(beanType, jsonType, typeName, typeKey, features, fields, sortedFields); + } + + public static List computeGettersWithFieldBase( + Class clazz, // + Map aliasMap, // + boolean sorted, // + PropertyNamingStrategy propertyNamingStrategy){ + Map fieldInfoMap = new LinkedHashMap(); + for(Class currentClass = clazz; currentClass != null; currentClass = currentClass.getSuperclass()){ + Field[] fields = currentClass.getDeclaredFields(); + computeFields(currentClass, aliasMap, propertyNamingStrategy, fieldInfoMap, fields); + } + return getFieldInfos(clazz, sorted, fieldInfoMap); + } + + public static List computeGetters(Class clazz, Map aliasMap){ + return computeGetters(clazz, aliasMap, true); + } + + public static List computeGetters(Class clazz, Map aliasMap, boolean sorted){ + JSONType jsonType = TypeUtils.getAnnotation(clazz,JSONType.class); + Map fieldCacheMap = new HashMap(); + ParserConfig.parserAllFieldToCache(clazz, fieldCacheMap); + return computeGetters(clazz, jsonType, aliasMap, fieldCacheMap, sorted, PropertyNamingStrategy.CamelCase); + } + + public static List computeGetters(Class clazz, // + JSONType jsonType, // + Map aliasMap, // + Map fieldCacheMap, // + boolean sorted, // + PropertyNamingStrategy propertyNamingStrategy // + ){ + Map fieldInfoMap = new LinkedHashMap(); + boolean kotlin = TypeUtils.isKotlin(clazz); + // for kotlin + Constructor[] constructors = null; + Annotation[][] paramAnnotationArrays = null; + String[] paramNames = null; + short[] paramNameMapping = null; + Method[] methods = clazz.getMethods(); + for(Method method : methods){ + String methodName = method.getName(); + int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; + String label = null; + if(Modifier.isStatic(method.getModifiers())){ + continue; + } + if(method.getReturnType().equals(Void.TYPE)){ + continue; + } + if(method.getParameterTypes().length != 0){ + continue; + } + if(method.getReturnType() == ClassLoader.class){ + continue; + } + + if(methodName.equals("getMetaClass") + && method.getReturnType().getName().equals("groovy.lang.MetaClass")){ + continue; + } + if(methodName.equals("getSuppressed") + && method.getDeclaringClass() == Throwable.class){ + continue; + } + + if(kotlin && isKotlinIgnore(clazz, methodName)){ + continue; + } + /** + * 如果在属性或者方法上存在JSONField注解,并且定制了name属性,不以类上的propertyNamingStrategy设置为准,以此字段的JSONField的name定制为准。 + */ + Boolean fieldAnnotationAndNameExists = false; + JSONField annotation = method.getAnnotation(JSONField.class); + if(annotation == null){ + annotation = getSuperMethodAnnotation(clazz, method); + } + if(annotation == null && kotlin){ + if(constructors == null){ + constructors = clazz.getDeclaredConstructors(); + Constructor creatorConstructor = TypeUtils.getKoltinConstructor(constructors); + if(creatorConstructor != null){ + paramAnnotationArrays = creatorConstructor.getParameterAnnotations(); + paramNames = TypeUtils.getKoltinConstructorParameters(clazz); + if(paramNames != null){ + String[] paramNames_sorted = new String[paramNames.length]; + System.arraycopy(paramNames, 0, paramNames_sorted, 0, paramNames.length); + + Arrays.sort(paramNames_sorted); + paramNameMapping = new short[paramNames.length]; + for(short p = 0; p < paramNames.length; p++){ + int index = Arrays.binarySearch(paramNames_sorted, paramNames[p]); + paramNameMapping[index] = p; + } + paramNames = paramNames_sorted; + } + } + } + if(paramNames != null && paramNameMapping != null && methodName.startsWith("get")){ + String propertyName = decapitalize(methodName.substring(3)); + int p = Arrays.binarySearch(paramNames, propertyName); + if (p < 0) { + for (int i = 0; i < paramNames.length; i++) { + if (propertyName.equalsIgnoreCase(paramNames[i])) { + p = i; + break; + } + } + } + if(p >= 0){ + short index = paramNameMapping[p]; + Annotation[] paramAnnotations = paramAnnotationArrays[index]; + if(paramAnnotations != null){ + for(Annotation paramAnnotation : paramAnnotations){ + if(paramAnnotation instanceof JSONField){ + annotation = (JSONField) paramAnnotation; + break; + } + } + } + if(annotation == null){ + Field field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); + if(field != null){ + annotation = field.getAnnotation(JSONField.class); + } + } + } + } + } + if(annotation != null){ + if(!annotation.serialize()){ + continue; + } + ordinal = annotation.ordinal(); + serialzeFeatures = SerializerFeature.of(annotation.serialzeFeatures()); + parserFeatures = Feature.of(annotation.parseFeatures()); + if(annotation.name().length() != 0){ + String propertyName = annotation.name(); + if(aliasMap != null){ + propertyName = aliasMap.get(propertyName); + if(propertyName == null){ + continue; + } + } + FieldInfo fieldInfo = new FieldInfo(propertyName, method, null, clazz, null, ordinal, + serialzeFeatures, parserFeatures, annotation, null, label); + fieldInfoMap.put(propertyName, fieldInfo); + continue; + } + if(annotation.label().length() != 0){ + label = annotation.label(); + } + } + if(methodName.startsWith("get")){ + if(methodName.length() < 4){ + continue; + } + if(methodName.equals("getClass")){ + continue; + } + if(methodName.equals("getDeclaringClass") && clazz.isEnum()){ + continue; + } + char c3 = methodName.charAt(3); + String propertyName; + if(Character.isUpperCase(c3) // + || c3 > 512 // for unicode method name + ){ + if(compatibleWithJavaBean){ + propertyName = decapitalize(methodName.substring(3)); + } else{ + propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); + } + propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 3); + } else if(c3 == '_'){ + propertyName = methodName.substring(4); + } else if(c3 == 'f'){ + propertyName = methodName.substring(3); + } else if(methodName.length() >= 5 && Character.isUpperCase(methodName.charAt(4))){ + propertyName = decapitalize(methodName.substring(3)); + } else{ + continue; + } + boolean ignore = isJSONTypeIgnore(clazz, propertyName); + if(ignore){ + continue; + } + //假如bean的field很多的情况一下,轮询时将大大降低效率 + Field field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); + if(field == null && propertyName.length() > 1){ + char ch = propertyName.charAt(1); + if(ch >= 'A' && ch <= 'Z'){ + String javaBeanCompatiblePropertyName = decapitalize(methodName.substring(3)); + field = ParserConfig.getFieldFromCache(javaBeanCompatiblePropertyName, fieldCacheMap); + } + } + JSONField fieldAnnotation = null; + if(field != null){ + fieldAnnotation = field.getAnnotation(JSONField.class); + if(fieldAnnotation != null){ + if(!fieldAnnotation.serialize()){ + continue; + } + ordinal = fieldAnnotation.ordinal(); + serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); + parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); + if(fieldAnnotation.name().length() != 0){ + fieldAnnotationAndNameExists = true; + propertyName = fieldAnnotation.name(); + if(aliasMap != null){ + propertyName = aliasMap.get(propertyName); + if(propertyName == null){ + continue; + } + } + } + if(fieldAnnotation.label().length() != 0){ + label = fieldAnnotation.label(); + } + } + } + if(aliasMap != null){ + propertyName = aliasMap.get(propertyName); + if(propertyName == null){ + continue; + } + } + if(propertyNamingStrategy != null && !fieldAnnotationAndNameExists){ + propertyName = propertyNamingStrategy.translate(propertyName); + } + FieldInfo fieldInfo = new FieldInfo(propertyName, method, field, clazz, null, ordinal, serialzeFeatures, parserFeatures, + annotation, fieldAnnotation, label); + fieldInfoMap.put(propertyName, fieldInfo); + } + if(methodName.startsWith("is")){ + if(methodName.length() < 3){ + continue; + } + if(method.getReturnType() != Boolean.TYPE + && method.getReturnType() != Boolean.class){ + continue; + } + char c2 = methodName.charAt(2); + String propertyName; + if(Character.isUpperCase(c2)){ + if(compatibleWithJavaBean){ + propertyName = decapitalize(methodName.substring(2)); + } else{ + propertyName = Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3); + } + propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 2); + } else if(c2 == '_'){ + propertyName = methodName.substring(3); + } else if(c2 == 'f'){ + propertyName = methodName.substring(2); + } else{ + continue; + } + boolean ignore = isJSONTypeIgnore(clazz, propertyName); + if(ignore){ + continue; + } + Field field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); + if(field == null){ + field = ParserConfig.getFieldFromCache(methodName, fieldCacheMap); + } + JSONField fieldAnnotation = null; + if(field != null){ + fieldAnnotation = field.getAnnotation(JSONField.class); + if(fieldAnnotation != null){ + if(!fieldAnnotation.serialize()){ + continue; + } + ordinal = fieldAnnotation.ordinal(); + serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); + parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); + if(fieldAnnotation.name().length() != 0){ + propertyName = fieldAnnotation.name(); + if(aliasMap != null){ + propertyName = aliasMap.get(propertyName); + if(propertyName == null){ + continue; + } + } + } + if(fieldAnnotation.label().length() != 0){ + label = fieldAnnotation.label(); + } + } + } + if(aliasMap != null){ + propertyName = aliasMap.get(propertyName); + if(propertyName == null){ + continue; + } + } + if(propertyNamingStrategy != null){ + propertyName = propertyNamingStrategy.translate(propertyName); + } + //优先选择get + if(fieldInfoMap.containsKey(propertyName)){ + continue; + } + FieldInfo fieldInfo = new FieldInfo(propertyName, method, field, clazz, null, ordinal, serialzeFeatures, parserFeatures, + annotation, fieldAnnotation, label); + fieldInfoMap.put(propertyName, fieldInfo); + } + } + Field[] fields = clazz.getFields(); + computeFields(clazz, aliasMap, propertyNamingStrategy, fieldInfoMap, fields); + return getFieldInfos(clazz, sorted, fieldInfoMap); + } + + private static List getFieldInfos(Class clazz, boolean sorted, Map fieldInfoMap){ + List fieldInfoList = new ArrayList(); + String[] orders = null; + JSONType annotation = TypeUtils.getAnnotation(clazz,JSONType.class); + if(annotation != null){ + orders = annotation.orders(); + } + if(orders != null && orders.length > 0){ + LinkedHashMap map = new LinkedHashMap(fieldInfoList.size()); + for(FieldInfo field : fieldInfoMap.values()){ + map.put(field.name, field); + } + int i = 0; + for(String item : orders){ + FieldInfo field = map.get(item); + if(field != null){ + fieldInfoList.add(field); + map.remove(item); + } + } + for(FieldInfo field : map.values()){ + fieldInfoList.add(field); + } + } else{ + for(FieldInfo fieldInfo : fieldInfoMap.values()){ + fieldInfoList.add(fieldInfo); + } + if(sorted){ + Collections.sort(fieldInfoList); + } + } + return fieldInfoList; + } + + private static void computeFields( + Class clazz, // + Map aliasMap, // + PropertyNamingStrategy propertyNamingStrategy, // + Map fieldInfoMap, // + Field[] fields){ + for(Field field : fields){ + if(Modifier.isStatic(field.getModifiers())){ + continue; + } + JSONField fieldAnnotation = field.getAnnotation(JSONField.class); + int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; + String propertyName = field.getName(); + String label = null; + if(fieldAnnotation != null){ + if(!fieldAnnotation.serialize()){ + continue; + } + ordinal = fieldAnnotation.ordinal(); + serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); + parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); + if(fieldAnnotation.name().length() != 0){ + propertyName = fieldAnnotation.name(); + } + if(fieldAnnotation.label().length() != 0){ + label = fieldAnnotation.label(); + } + } + if(aliasMap != null){ + propertyName = aliasMap.get(propertyName); + if(propertyName == null){ + continue; + } + } + if(propertyNamingStrategy != null){ + propertyName = propertyNamingStrategy.translate(propertyName); + } + if(!fieldInfoMap.containsKey(propertyName)){ + FieldInfo fieldInfo = new FieldInfo(propertyName, null, field, clazz, null, ordinal, serialzeFeatures, parserFeatures, + null, fieldAnnotation, label); + fieldInfoMap.put(propertyName, fieldInfo); + } + } + } + + private static String getPropertyNameByCompatibleFieldName(Map fieldCacheMap, String methodName, + String propertyName, int fromIdx){ + if(compatibleWithFieldName){ + if(!fieldCacheMap.containsKey(propertyName)){ + String tempPropertyName = methodName.substring(fromIdx); + return fieldCacheMap.containsKey(tempPropertyName) ? tempPropertyName : propertyName; + } + } + return propertyName; + } + + public static JSONField getSuperMethodAnnotation(final Class clazz, final Method method){ + Class[] interfaces = clazz.getInterfaces(); + if(interfaces.length > 0){ + Class[] types = method.getParameterTypes(); + for(Class interfaceClass : interfaces){ + for(Method interfaceMethod : interfaceClass.getMethods()){ + Class[] interfaceTypes = interfaceMethod.getParameterTypes(); + if(interfaceTypes.length != types.length){ + continue; + } + if(!interfaceMethod.getName().equals(method.getName())){ + continue; + } + boolean match = true; + for(int i = 0; i < types.length; ++i){ + if(!interfaceTypes[i].equals(types[i])){ + match = false; + break; + } + } + if(!match){ + continue; + } + JSONField annotation = interfaceMethod.getAnnotation(JSONField.class); + if(annotation != null){ + return annotation; + } + } + } + } + Class superClass = clazz.getSuperclass(); + if(superClass == null){ + return null; + } + if(Modifier.isAbstract(superClass.getModifiers())){ + Class[] types = method.getParameterTypes(); + for(Method interfaceMethod : superClass.getMethods()){ + Class[] interfaceTypes = interfaceMethod.getParameterTypes(); + if(interfaceTypes.length != types.length){ + continue; + } + if(!interfaceMethod.getName().equals(method.getName())){ + continue; + } + boolean match = true; + for(int i = 0; i < types.length; ++i){ + if(!interfaceTypes[i].equals(types[i])){ + match = false; + break; + } + } + if(!match){ + continue; + } + JSONField annotation = interfaceMethod.getAnnotation(JSONField.class); + if(annotation != null){ + return annotation; + } + } + } + return null; + } + + private static boolean isJSONTypeIgnore(Class clazz, String propertyName){ + JSONType jsonType = TypeUtils.getAnnotation(clazz,JSONType.class); + if(jsonType != null){ + // 1、新增 includes 支持,如果 JSONType 同时设置了includes 和 ignores 属性,则以includes为准。 + // 2、个人认为对于大小写敏感的Java和JS而言,使用 equals() 比 equalsIgnoreCase() 更好,改动的唯一风险就是向后兼容性的问题 + // 不过,相信开发者应该都是严格按照大小写敏感的方式进行属性设置的 + String[] fields = jsonType.includes(); + if(fields.length > 0){ + for(int i = 0; i < fields.length; i++){ + if(propertyName.equals(fields[i])){ + return false; + } + } + return true; + } else{ + fields = jsonType.ignores(); + for(int i = 0; i < fields.length; i++){ + if(propertyName.equals(fields[i])){ + return true; + } + } + } + } + if(clazz.getSuperclass() != Object.class && clazz.getSuperclass() != null){ + if(isJSONTypeIgnore(clazz.getSuperclass(), propertyName)){ + return true; + } + } + return false; + } + + public static boolean isGenericParamType(Type type){ + if(type instanceof ParameterizedType){ + return true; + } + if(type instanceof Class) { + Type superType = ((Class) type).getGenericSuperclass(); + return superType != Object.class && isGenericParamType(superType); + } + return false; + } + + public static Type getGenericParamType(Type type){ + if(type instanceof ParameterizedType){ + return type; + } + if(type instanceof Class){ + return getGenericParamType(((Class) type).getGenericSuperclass()); + } + return type; + } + + public static Type unwrapOptional(Type type){ + if(!optionalClassInited){ + try{ + optionalClass = Class.forName("java.util.Optional"); + } catch(Exception e){ + // skip + } finally{ + optionalClassInited = true; + } + } + if(type instanceof ParameterizedType){ + ParameterizedType parameterizedType = (ParameterizedType) type; + if(parameterizedType.getRawType() == optionalClass){ + return parameterizedType.getActualTypeArguments()[0]; + } + } + return type; + } + + public static Class getClass(Type type){ + if(type.getClass() == Class.class){ + return (Class) type; + } + + if(type instanceof ParameterizedType){ + return getClass(((ParameterizedType) type).getRawType()); + } + + if(type instanceof TypeVariable){ + Type boundType = ((TypeVariable) type).getBounds()[0]; + return (Class) boundType; + } + + if(type instanceof WildcardType){ + Type[] upperBounds = ((WildcardType) type).getUpperBounds(); + if (upperBounds.length == 1) { + return getClass(upperBounds[0]); + } + } + + return Object.class; + } + + public static Field getField(Class clazz, String fieldName, Field[] declaredFields){ + for(Field field : declaredFields){ + String itemName = field.getName(); + if(fieldName.equals(itemName)){ + return field; + } + + char c0, c1; + if (fieldName.length() > 2 + && (c0 = fieldName.charAt(0)) >= 'a' && c0 <= 'z' + && (c1 = fieldName.charAt(1)) >= 'A' && c1 <= 'Z' + && fieldName.equalsIgnoreCase(itemName)) { + return field; + } + } + Class superClass = clazz.getSuperclass(); + if(superClass != null && superClass != Object.class){ + return getField(superClass, fieldName, superClass.getDeclaredFields()); + } + return null; + } + + public static int getSerializeFeatures(Class clazz){ + JSONType annotation = TypeUtils.getAnnotation(clazz,JSONType.class); + if(annotation == null){ + return 0; + } + return SerializerFeature.of(annotation.serialzeFeatures()); + } + + public static int getParserFeatures(Class clazz){ + JSONType annotation = TypeUtils.getAnnotation(clazz,JSONType.class); + if(annotation == null){ + return 0; + } + return Feature.of(annotation.parseFeatures()); + } + + public static String decapitalize(String name){ + if(name == null || name.length() == 0){ + return name; + } + if(name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isUpperCase(name.charAt(0))){ + return name; + } + char chars[] = name.toCharArray(); + chars[0] = Character.toLowerCase(chars[0]); + return new String(chars); + } + + static void setAccessible(AccessibleObject obj){ + if(!setAccessibleEnable){ + return; + } + if(obj.isAccessible()){ + return; + } + try{ + obj.setAccessible(true); + } catch(AccessControlException error){ + setAccessibleEnable = false; + } + } + + public static Type getCollectionItemType(Type fieldType){ + Type itemType = null; + Class clazz; + if(fieldType instanceof ParameterizedType){ + Type actualTypeArgument = ((ParameterizedType) fieldType).getActualTypeArguments()[0]; + if(actualTypeArgument instanceof WildcardType){ + WildcardType wildcardType = (WildcardType) actualTypeArgument; + Type[] upperBounds = wildcardType.getUpperBounds(); + if(upperBounds.length == 1){ + actualTypeArgument = upperBounds[0]; + } + } + itemType = actualTypeArgument; + } else if(fieldType instanceof Class // + && !(clazz = (Class) fieldType).getName().startsWith("java.")){ + Type superClass = clazz.getGenericSuperclass(); + itemType = TypeUtils.getCollectionItemType(superClass); + } + if(itemType == null){ + itemType = Object.class; + } + return itemType; + } + + public static Class getCollectionItemClass(Type fieldType){ + if(fieldType instanceof ParameterizedType){ + Class itemClass; + Type actualTypeArgument = ((ParameterizedType) fieldType).getActualTypeArguments()[0]; + if(actualTypeArgument instanceof WildcardType){ + WildcardType wildcardType = (WildcardType) actualTypeArgument; + Type[] upperBounds = wildcardType.getUpperBounds(); + if(upperBounds.length == 1){ + actualTypeArgument = upperBounds[0]; + } + } + if(actualTypeArgument instanceof Class){ + itemClass = (Class) actualTypeArgument; + if(!Modifier.isPublic(itemClass.getModifiers())){ + throw new JSONException("can not create ASMParser"); + } + } else{ + throw new JSONException("can not create ASMParser"); + } + return itemClass; + } + return Object.class; + } + + public static Type checkPrimitiveArray(GenericArrayType genericArrayType) { + Type clz = genericArrayType; + Type genericComponentType = genericArrayType.getGenericComponentType(); + + String prefix = "["; + while (genericComponentType instanceof GenericArrayType) { + genericComponentType = ((GenericArrayType) genericComponentType) + .getGenericComponentType(); + prefix += prefix; + } + + if (genericComponentType instanceof Class) { + Class ck = (Class) genericComponentType; + if (ck.isPrimitive()) { + try { + if (ck == boolean.class) { + clz = Class.forName(prefix + "Z"); + } else if (ck == char.class) { + clz = Class.forName(prefix + "C"); + } else if (ck == byte.class) { + clz = Class.forName(prefix + "B"); + } else if (ck == short.class) { + clz = Class.forName(prefix + "S"); + } else if (ck == int.class) { + clz = Class.forName(prefix + "I"); + } else if (ck == long.class) { + clz = Class.forName(prefix + "J"); + } else if (ck == float.class) { + clz = Class.forName(prefix + "F"); + } else if (ck == double.class) { + clz = Class.forName(prefix + "D"); + } + } catch (ClassNotFoundException e) { + } + } + } + + return clz; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static Collection createCollection(Type type) { + Class rawClass = getRawClass(type); + Collection list; + if(rawClass == AbstractCollection.class // + || rawClass == Collection.class){ + list = new ArrayList(); + } else if(rawClass.isAssignableFrom(HashSet.class)){ + list = new HashSet(); + } else if(rawClass.isAssignableFrom(LinkedHashSet.class)){ + list = new LinkedHashSet(); + } else if(rawClass.isAssignableFrom(TreeSet.class)){ + list = new TreeSet(); + } else if(rawClass.isAssignableFrom(ArrayList.class)){ + list = new ArrayList(); + } else if(rawClass.isAssignableFrom(EnumSet.class)){ + Type itemType; + if(type instanceof ParameterizedType){ + itemType = ((ParameterizedType) type).getActualTypeArguments()[0]; + } else{ + itemType = Object.class; + } + list = EnumSet.noneOf((Class) itemType); + } else{ + try{ + list = (Collection) rawClass.newInstance(); + } catch(Exception e){ + throw new JSONException("create instance error, class " + rawClass.getName()); + } + } + return list; + } + + public static Class getRawClass(Type type){ + if(type instanceof Class){ + return (Class) type; + } else if(type instanceof ParameterizedType){ + return getRawClass(((ParameterizedType) type).getRawType()); + } else{ + throw new JSONException("TODO"); + } + } + + public static boolean isProxy(Class clazz){ + for(Class item : clazz.getInterfaces()){ + String interfaceName = item.getName(); + if(interfaceName.equals("net.sf.cglib.proxy.Factory") // + || interfaceName.equals("org.springframework.cglib.proxy.Factory")){ + return true; + } + if(interfaceName.equals("javassist.util.proxy.ProxyObject") // + || interfaceName.equals("org.apache.ibatis.javassist.util.proxy.ProxyObject") + ){ + return true; + } + } + return false; + } + + public static boolean isTransient(Method method){ + if(method == null){ + return false; + } + if(!transientClassInited){ + try{ + transientClass = (Class) Class.forName("java.beans.Transient"); + } catch(Exception e){ + // skip + } finally{ + transientClassInited = true; + } + } + if(transientClass != null){ + Annotation annotation = method.getAnnotation(transientClass); + return annotation != null; + } + return false; + } + + public static boolean isAnnotationPresentOneToMany(Method method) { + if (method == null) { + return false; + } + + if (class_OneToMany == null && !class_OneToMany_error) { + try { + class_OneToMany = (Class) Class.forName("javax.persistence.OneToMany"); + } catch (Throwable e) { + // skip + class_OneToMany_error = true; + } + } + return class_OneToMany != null && method.isAnnotationPresent(class_OneToMany); + + } + + public static boolean isAnnotationPresentManyToMany(Method method) { + if (method == null) { + return false; + } + + if (class_ManyToMany == null && !class_ManyToMany_error) { + try { + class_ManyToMany = (Class) Class.forName("javax.persistence.ManyToMany"); + } catch (Throwable e) { + // skip + class_ManyToMany_error = true; + } + } + return class_ManyToMany != null && (method.isAnnotationPresent(class_OneToMany) || method.isAnnotationPresent(class_ManyToMany)); + + } + + public static boolean isHibernateInitialized(Object object){ + if(object == null){ + return false; + } + if(method_HibernateIsInitialized == null && !method_HibernateIsInitialized_error){ + try{ + Class class_Hibernate = Class.forName("org.hibernate.Hibernate"); + method_HibernateIsInitialized = class_Hibernate.getMethod("isInitialized", Object.class); + } catch(Throwable e){ + // skip + method_HibernateIsInitialized_error = true; + } + } + if(method_HibernateIsInitialized != null){ + try{ + Boolean initialized = (Boolean) method_HibernateIsInitialized.invoke(null, object); + return initialized.booleanValue(); + } catch(Throwable e){ + // skip + } + } + return true; + } + + public static long fnv1a_64_lower(String key){ + long hashCode = 0xcbf29ce484222325L; + for(int i = 0; i < key.length(); ++i){ + char ch = key.charAt(i); + if(ch == '_' || ch == '-'){ + continue; + } + if(ch >= 'A' && ch <= 'Z'){ + ch = (char) (ch + 32); + } + hashCode ^= ch; + hashCode *= 0x100000001b3L; + } + return hashCode; + } + + public static long fnv1a_64(String key){ + long hashCode = 0xcbf29ce484222325L; + for(int i = 0; i < key.length(); ++i){ + char ch = key.charAt(i); + hashCode ^= ch; + hashCode *= 0x100000001b3L; + } + return hashCode; + } + + public static boolean isKotlin(Class clazz) { + if (kotlin_metadata == null && !kotlin_metadata_error) { + try { + kotlin_metadata = Class.forName("kotlin.Metadata"); + } catch (Throwable e) { + kotlin_metadata_error = true; + } + } + return kotlin_metadata != null && clazz.isAnnotationPresent(kotlin_metadata); + } + + public static Constructor getKoltinConstructor(Constructor[] constructors){ + Constructor creatorConstructor = null; + for(Constructor constructor : constructors){ + Class[] parameterTypes = constructor.getParameterTypes(); + if(parameterTypes.length > 0 && parameterTypes[parameterTypes.length - 1].getName().equals("kotlin.jvm.internal.DefaultConstructorMarker")){ + continue; + } + if(creatorConstructor != null && creatorConstructor.getParameterTypes().length >= parameterTypes.length){ + continue; + } + creatorConstructor = constructor; + } + return creatorConstructor; + } + + public static String[] getKoltinConstructorParameters(Class clazz){ + if(kotlin_kclass_constructor == null && !kotlin_class_klass_error){ + try{ + Class class_kotlin_kclass = Class.forName("kotlin.reflect.jvm.internal.KClassImpl"); + kotlin_kclass_constructor = class_kotlin_kclass.getConstructor(Class.class); + } catch(Throwable e){ + kotlin_class_klass_error = true; + } + } + if (kotlin_kclass_constructor == null){ + return null; + } + + if (kotlin_kclass_getConstructors == null && !kotlin_class_klass_error) { + try{ + Class class_kotlin_kclass = Class.forName("kotlin.reflect.jvm.internal.KClassImpl"); + kotlin_kclass_getConstructors = class_kotlin_kclass.getMethod("getConstructors"); + } catch(Throwable e){ + kotlin_class_klass_error = true; + } + } + + if (kotlin_kfunction_getParameters == null && !kotlin_class_klass_error) { + try{ + Class class_kotlin_kfunction = Class.forName("kotlin.reflect.KFunction"); + kotlin_kfunction_getParameters = class_kotlin_kfunction.getMethod("getParameters"); + } catch(Throwable e){ + kotlin_class_klass_error = true; + } + } + + if (kotlin_kparameter_getName == null && !kotlin_class_klass_error) { + try{ + Class class_kotlinn_kparameter = Class.forName("kotlin.reflect.KParameter"); + kotlin_kparameter_getName = class_kotlinn_kparameter.getMethod("getName"); + } catch(Throwable e){ + kotlin_class_klass_error = true; + } + } + + if (kotlin_error){ + return null; + } + + try{ + Object constructor = null; + Object kclassImpl = kotlin_kclass_constructor.newInstance(clazz); + Iterable it = (Iterable) kotlin_kclass_getConstructors.invoke(kclassImpl); + for(Iterator iterator = it.iterator(); iterator.hasNext(); iterator.hasNext()){ + Object item = iterator.next(); + List parameters = (List) kotlin_kfunction_getParameters.invoke(item); + if (constructor != null && parameters.size() == 0) { + continue; + } + constructor = item; + } + List parameters = (List) kotlin_kfunction_getParameters.invoke(constructor); + String[] names = new String[parameters.size()]; + for(int i = 0; i < parameters.size(); i++){ + Object param = parameters.get(i); + names[i] = (String) kotlin_kparameter_getName.invoke(param); + } + return names; + } catch(Throwable e){ + e.printStackTrace(); + kotlin_error = true; + } + return null; + } + + private static boolean isKotlinIgnore(Class clazz, String methodName) { + if (kotlinIgnores == null && !kotlinIgnores_error) { + try { + Map map = new HashMap(); + Class charRangeClass = Class.forName("kotlin.ranges.CharRange"); + map.put(charRangeClass, new String[]{"getEndInclusive", "isEmpty"}); + Class intRangeClass = Class.forName("kotlin.ranges.IntRange"); + map.put(intRangeClass, new String[]{"getEndInclusive", "isEmpty"}); + Class longRangeClass = Class.forName("kotlin.ranges.LongRange"); + map.put(longRangeClass, new String[]{"getEndInclusive", "isEmpty"}); + Class floatRangeClass = Class.forName("kotlin.ranges.ClosedFloatRange"); + map.put(floatRangeClass, new String[]{"getEndInclusive", "isEmpty"}); + Class doubleRangeClass = Class.forName("kotlin.ranges.ClosedDoubleRange"); + map.put(doubleRangeClass, new String[]{"getEndInclusive", "isEmpty"}); + kotlinIgnores = map; + } catch (Throwable error) { + kotlinIgnores_error = true; + } + } + if (kotlinIgnores == null) { + return false; + } + String[] ignores = kotlinIgnores.get(clazz); + return ignores != null && Arrays.binarySearch(ignores, methodName) >= 0; + } + + public static A getAnnotation(Class clazz, Class annotationClass){ + A a = clazz.getAnnotation(annotationClass); + if (a != null){ + return a; + } + + if(clazz.getAnnotations().length > 0){ + for(Annotation annotation : clazz.getAnnotations()){ + a = annotation.annotationType().getAnnotation(annotationClass); + if(a != null){ + return a; + } + } + } + return null; + } +} diff --git a/src/main/java/com/alibaba/fastjson/util/UTF8Decoder.java b/src/main/java/com/alibaba/fastjson/util/UTF8Decoder.java index 040c4fd6e1..27d5b232c9 100644 --- a/src/main/java/com/alibaba/fastjson/util/UTF8Decoder.java +++ b/src/main/java/com/alibaba/fastjson/util/UTF8Decoder.java @@ -27,6 +27,9 @@ * */ +/** + * @deprecated + */ public class UTF8Decoder extends CharsetDecoder { private final static Charset charset = Charset.forName("UTF-8"); @@ -40,7 +43,7 @@ private static boolean isNotContinuation(int b) { } // [C2..DF] [80..BF] - private static final boolean isMalformed2(int b1, int b2) { + private static boolean isMalformed2(int b1, int b2) { return (b1 & 0x1e) == 0x0 || (b2 & 0xc0) != 0x80; } @@ -55,7 +58,7 @@ private static boolean isMalformed3(int b1, int b2, int b3) { // [F4] [80..8F] [80..BF] [80..BF] // only check 80-be range here, the [0xf0,0x80...] and [0xf4,0x90-...] // will be checked by Surrogate.neededFor(uc) - private static final boolean isMalformed4(int b2, int b3, int b4) { + private static boolean isMalformed4(int b2, int b3, int b4) { return (b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 || (b4 & 0xc0) != 0x80; } @@ -186,11 +189,11 @@ protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) { return decodeArrayLoop(src, dst); } - static final void updatePositions(Buffer src, int sp, Buffer dst, int dp) { + static void updatePositions(Buffer src, int sp, Buffer dst, int dp) { // src.position(sp - src.arrayOffset()); // dst.position(dp - dst.arrayOffset()); - src.position(sp); - dst.position(dp); + src.position(sp); + dst.position(dp); } private static class Surrogate { diff --git a/src/main/resources/META-INF/LICENSE.txt b/src/main/resources/META-INF/LICENSE.txt old mode 100644 new mode 100755 diff --git a/src/main/resources/META-INF/NOTICE.txt b/src/main/resources/META-INF/NOTICE.txt old mode 100644 new mode 100755 index dbfb8b7c45..9fdd955d99 --- a/src/main/resources/META-INF/NOTICE.txt +++ b/src/main/resources/META-INF/NOTICE.txt @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/resources/META-INF/services/com.alibaba.fastjson.serializer.AutowiredObjectDeserializer b/src/main/resources/META-INF/services/com.alibaba.fastjson.serializer.AutowiredObjectDeserializer deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/src/main/resources/META-INF/services/javax.ws.rs.ext.MessageBodyReader b/src/main/resources/META-INF/services/javax.ws.rs.ext.MessageBodyReader new file mode 100644 index 0000000000..7dd33df04d --- /dev/null +++ b/src/main/resources/META-INF/services/javax.ws.rs.ext.MessageBodyReader @@ -0,0 +1 @@ +com.alibaba.fastjson.support.jaxrs.FastJsonProvider \ No newline at end of file diff --git a/src/main/resources/META-INF/services/javax.ws.rs.ext.MessageBodyWriter b/src/main/resources/META-INF/services/javax.ws.rs.ext.MessageBodyWriter new file mode 100644 index 0000000000..7dd33df04d --- /dev/null +++ b/src/main/resources/META-INF/services/javax.ws.rs.ext.MessageBodyWriter @@ -0,0 +1 @@ +com.alibaba.fastjson.support.jaxrs.FastJsonProvider \ No newline at end of file diff --git a/src/main/resources/META-INF/services/javax.ws.rs.ext.Providers b/src/main/resources/META-INF/services/javax.ws.rs.ext.Providers new file mode 100644 index 0000000000..7dd33df04d --- /dev/null +++ b/src/main/resources/META-INF/services/javax.ws.rs.ext.Providers @@ -0,0 +1 @@ +com.alibaba.fastjson.support.jaxrs.FastJsonProvider \ No newline at end of file diff --git a/src/main/resources/META-INF/services/org.glassfish.jersey.internal.spi.AutoDiscoverable b/src/main/resources/META-INF/services/org.glassfish.jersey.internal.spi.AutoDiscoverable new file mode 100644 index 0000000000..e5cd8cdd30 --- /dev/null +++ b/src/main/resources/META-INF/services/org.glassfish.jersey.internal.spi.AutoDiscoverable @@ -0,0 +1 @@ +com.alibaba.fastjson.support.jaxrs.FastJsonAutoDiscoverable \ No newline at end of file diff --git a/src/test/java/cn/com/tx/domain/notifyDetail/NotifyDetail.java b/src/test/java/cn/com/tx/domain/notifyDetail/NotifyDetail.java new file mode 100755 index 0000000000..7ce5e5cd6c --- /dev/null +++ b/src/test/java/cn/com/tx/domain/notifyDetail/NotifyDetail.java @@ -0,0 +1,127 @@ +package cn.com.tx.domain.notifyDetail; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +public class NotifyDetail implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 8760630447394929224L; + + private int detailId; + + private int hotId; + + private int templateId; + + private int srcId; + + private int destId; + + private boolean display; + + private Date foundTime; + + private List args = new ArrayList(); + + + public int getDetailId() { + return detailId; + } + + public void setDetailId(int detailId) { + this.detailId = detailId; + } + + public int getHotId() { + return hotId; + } + + public void setHotId(int hotId) { + this.hotId = hotId; + } + + public int getTemplateId() { + return templateId; + } + + public List getArgs() { + return args; + } + + public void setArgs(List args) { + this.args = args; + } + + public void setTemplateId(int templateId) { + this.templateId = templateId; + } + + public int getSrcId() { + return srcId; + } + + public void setSrcId(int srcId) { + this.srcId = srcId; + } + + public int getDestId() { + return destId; + } + + public void setDestId(int destId) { + this.destId = destId; + } + + public boolean isDisplay() { + return display; + } + + public void setDisplay(boolean display) { + this.display = display; + } + + public Date getFoundTime() { + return foundTime; + } + + public void setFoundTime(Date foundTime) { + this.foundTime = foundTime; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + int hasCode = 0; + if (this.detailId != 0) { + hasCode += this.detailId; + } + return hasCode; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof NotifyDetail)) { + return false; + } + return this.hashCode() == obj.hashCode(); + } + + +} diff --git a/src/test/java/cn/com/tx/domain/pagination/Pagination.java b/src/test/java/cn/com/tx/domain/pagination/Pagination.java new file mode 100755 index 0000000000..af4e10e4de --- /dev/null +++ b/src/test/java/cn/com/tx/domain/pagination/Pagination.java @@ -0,0 +1,195 @@ +package cn.com.tx.domain.pagination; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class Pagination implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 5038839734218582220L; + + private int totalResult = 0; + + private int totalPage = 1; + + private int pageIndex = 1; + + private int maxLength = 5; + + private int fromIndex = 0; + + private int toIndex = 0; + + private List list = new ArrayList(); + + public Pagination(){ + + } + + + + public void setTotalResult(int totalResult) { + this.totalResult = totalResult; + } + + + + public void setTotalPage(int totalPage) { + this.totalPage = totalPage; + } + + + + public void setPageIndex(int pageIndex) { + this.pageIndex = pageIndex; + } + + + + public void setMaxLength(int maxLength) { + this.maxLength = maxLength; + } + + + + public void setFromIndex(int fromIndex) { + this.fromIndex = fromIndex; + } + + + + public void setToIndex(int toIndex) { + this.toIndex = toIndex; + } + + + + public int getFromIndex() { + return this.fromIndex; + } + + public int getToIndex() { + return this.toIndex; + } + + public int getNextPage() { + if (this.pageIndex < this.totalPage) { + return this.pageIndex + 1; + } else { + return this.pageIndex; + } + } + + public int getPrevPage() { + if (this.pageIndex > 1) { + return this.pageIndex - 1; + } + return this.pageIndex; + } + + /** + * @return the currentPage + */ + public int getPageIndex() { + return pageIndex; + } + + /** + * @return the list + */ + public List getList() { + if (list == null) { + return new ArrayList(); + } + return new ArrayList(list); + } + + /** + * @return the totalPage + */ + public int getTotalPage() { + return totalPage; + } + + /** + * @return the totalRecord + */ + public int getTotalResult() { + return totalResult; + } + + public int getMaxLength() { + return maxLength; + } + + /** + * + * @param totalResult + * @param pageIndex + * @param maxLength + */ + public Pagination(int totalResult, int pageIndex, int maxLength) { + if (maxLength > 0) { + this.maxLength = maxLength; + } + if (totalResult > 0) { + this.totalResult = totalResult; + } + if (pageIndex > 0) { + this.pageIndex = pageIndex; + } + this.totalPage = this.totalResult / this.maxLength; + if (this.totalResult % this.maxLength != 0) { + this.totalPage = this.totalPage + 1; + } + if (this.totalPage == 0) { + this.totalPage = 1; + } + if (this.pageIndex > this.totalPage) { + this.pageIndex = this.totalPage; + } + if (this.pageIndex <= 0) { + this.pageIndex = 1; + } + this.fromIndex = (this.pageIndex - 1) * maxLength; + this.toIndex = this.fromIndex + maxLength; + if (this.toIndex < 0) { + this.toIndex = fromIndex; + } + if (this.toIndex > this.totalResult) { + this.toIndex = this.totalResult; + } + + } + + /** + * @param datas + * the datas to set + */ + public void setList(List list) { + this.list = list; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("Pagination:\r\n"); + sb.append("\tpageIndex\t" + this.pageIndex + "\r\n"); + sb.append("\ttotalPage\t" + this.totalPage + "\r\n"); + sb.append("\tmaxLength\t" + this.maxLength + "\r\n"); + sb.append("\ttotalResult\t" + this.totalResult + "\r\n"); + for (T t : list) { + sb.append(t + "\r\n"); + } + return sb.toString(); + } + +} diff --git a/src/test/java/com/alibaba/china/bolt/biz/daili/merchants/vo/MerchantsVO.java b/src/test/java/com/alibaba/china/bolt/biz/daili/merchants/vo/MerchantsVO.java new file mode 100644 index 0000000000..3aea728f6b --- /dev/null +++ b/src/test/java/com/alibaba/china/bolt/biz/daili/merchants/vo/MerchantsVO.java @@ -0,0 +1,537 @@ +package com.alibaba.china.bolt.biz.daili.merchants.vo; + +import java.io.Serializable; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.apache.commons.lang.builder.ToStringBuilder; + +import com.alibaba.fastjson.JSON; + + +/** + * 商家基本信息 + * @author hongwei.quhw + * + */ +public class MerchantsVO implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + + /** -----------------实体商家信息----------**/ + //店铺类型code + private String type; + //店铺类型name + private String typename; + //招商区域code + private String[] region; + //招商区域name + private String[] regionname; + //最小面积 + private Integer minarea = -1; + //最大面积 + private Integer maxarea; + //启动资金 + private Long initialcapital; + //加盟保证金 + private Long cashdeposit; + /** -----------------网络商家信息----------**/ + //招商渠道搜索索引名 + private String[] shoptype; + //招商渠道搜索名称 + private String[] shoptypename; + //主营类目 + private String[] categoryids; + //主营类目名称 + private String[] categoryidsname; + + /** -----------------商家共有信息----------**/ + //MemberId + private String memberid; + //商家类型 + private int merchantstype; + //是否已删除 + private boolean isdelete; + //招商截止日期 + private Date expirationdate; + //旺旺 + private String wangwang; + //联系电话 + private String tel; + //是否品牌 + private boolean hasbrand; + //(30天)加盟人数 + private int joincount; + //公司旺铺地址 + private String winportdomain; + /** ----------------下面是品牌库信息---------------- **/ + //logo/商标 图片URL + private String brandlogourl; + //品牌名称 + private String brandname; + //创立时间 + private Date brandfoundtime; + //详情 + private String brandintroduction; + //证书 图片URL + private String brandcertificateurl; + + /** ----------------下面是公司库信息---------------- **/ + //公司名 + private String companyname; + //成立年份 + private String companyestablishedyear; + //注册资本 + private Double companyregcapital; + //注册地 + private String companyfoundedplace; + //简介 + private String companyintroduction; + + /** ----------------下面是DW交易信息---------------- **/ + //最近30天代理商支付订单金额(单位为分) + private Double payordamt30; + //最近30天代理商支付订单数 + private long payordcnt30; + //最近30天支付订单代理商买家数 + private long payordbuyercnt30; + //最近90天旺铺回头率 + private Double returnordrate90; + //截至当日成功申请代理商人数 + private int membercnttd; + //主营一级类目ID(主营top1、top2、top3一级类目以char(6)拼装成一串,需要解析出top1一级类目即可)example:"7" + private String stdcategoryid1; + //主营二级类目ID(主营top1、top2、top3二级类目以char(6)拼装成一串,需要解析出top1二级类目即可)example:"7" + private String stdcategoryid2; + //主营一级类目ID名称 example:"服装" + private String stdcategoryname1; + //主营二级类目ID名称 example:"男装" + private String stdcategoryname2; + + /** ----------------下面是offer信息---------------- **/ + //offer缩略图url地址 + private String[] summimageurilist; + //offer链接url地址 + private String[] detailurl; + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getTypename() { + return typename; + } + + public void setTypename(String typename) { + this.typename = typename; + } + + public String[] getRegion() { + return region; + } + + public void setRegionArray(String[] region) { + this.region = region; + } + + public String[] getRegionname() { + return regionname; + } + + public void setRegionnameArray(String[] regionname) { + this.regionname = regionname; + } + + public Integer getMinarea() { + return minarea; + } + + public void setMinarea(Integer minarea) { + if (null == minarea) { + minarea = -1; //opensearch 搜索空问题 ,设置默认值 + } + this.minarea = minarea; + } + + public Integer getMaxarea() { + return maxarea; + } + + public void setMaxarea(Integer maxarea) { + this.maxarea = maxarea; + } + + public Long getInitialcapital() { + return initialcapital; + } + + public void setInitialcapital(Long initialcapital) { + this.initialcapital = initialcapital; + } + + public Long getCashdeposit() { + return cashdeposit; + } + + public void setCashdeposit(Long cashdeposit) { + this.cashdeposit = cashdeposit; + } + + public String[] getShoptype() { + return shoptype; + } + + public void setShoptypeArray(String[] shoptype) { + this.shoptype = shoptype; + } + + public String[] getShoptypename() { + return shoptypename; + } + + public void setShoptypenameArray(String[] shoptypename) { + this.shoptypename = shoptypename; + } + + public String[] getCategoryids() { + return categoryids; + } + + public void setCategoryidsArray(String[] categoryids) { + this.categoryids = categoryids; + } + + public String[] getCategoryidsname() { + return categoryidsname; + } + + public void setCategoryidsnameArray(String[] categoryidsname) { + this.categoryidsname = categoryidsname; + } + + public String getMemberid() { + return memberid; + } + + public void setMemberid(String memberid) { + this.memberid = memberid; + } + + public int getMerchantstype() { + return merchantstype; + } + + public void setMerchantstype(int merchantstype) { + this.merchantstype = merchantstype; + } + + public boolean isIsdelete() { + return isdelete; + } + + public void setIsdelete(boolean isdelete) { + this.isdelete = isdelete; + } + + public Date getExpirationdate() { + return expirationdate; + } + + public void setExpirationdate(Date expirationdate) { + this.expirationdate = expirationdate; + } + + public String getWangwang() { + return wangwang; + } + + public void setWangwang(String wangwang) { + this.wangwang = wangwang; + } + + public String getTel() { + return tel; + } + + public void setTel(String tel) { + this.tel = tel; + } + + public boolean isHasbrand() { + return hasbrand; + } + + public void setHasbrand(boolean hasbrand) { + this.hasbrand = hasbrand; + } + + public int getJoincount() { + return joincount; + } + + public void setJoincount(int joincount) { + this.joincount = joincount; + } + + public String getWinportdomain() { + return winportdomain; + } + + public void setWinportdomain(String winportdomain) { + this.winportdomain = winportdomain; + } + + public String getBrandlogourl() { + return brandlogourl; + } + + public void setBrandlogourl(String brandlogourl) { + this.brandlogourl = brandlogourl; + } + + public String getBrandname() { + return brandname; + } + + public void setBrandname(String brandname) { + this.brandname = brandname; + } + + public Date getBrandfoundtime() { + return brandfoundtime; + } + + public void setBrandfoundtime(Date brandfoundtime) { + this.brandfoundtime = brandfoundtime; + } + + public String getBrandintroduction() { + return brandintroduction; + } + + public void setBrandintroduction(String brandintroduction) { + this.brandintroduction = brandintroduction; + } + + public String getBrandcertificateurl() { + return brandcertificateurl; + } + + public void setBrandcertificateurl(String brandcertificateurl) { + this.brandcertificateurl = brandcertificateurl; + } + + public String getCompanyname() { + return companyname; + } + + public void setCompanyname(String companyname) { + this.companyname = companyname; + } + + public String getCompanyestablishedyear() { + return companyestablishedyear; + } + + public void setCompanyestablishedyear(String companyestablishedyear) { + this.companyestablishedyear = companyestablishedyear; + } + + public Double getCompanyregcapital() { + return companyregcapital; + } + + public void setCompanyregcapital(Double companyregcapital) { + this.companyregcapital = companyregcapital; + } + + public String getCompanyfoundedplace() { + return companyfoundedplace; + } + + public void setCompanyfoundedplace(String companyfoundedplace) { + this.companyfoundedplace = companyfoundedplace; + } + + public String getCompanyintroduction() { + return companyintroduction; + } + + public void setCompanyintroduction(String companyintroduction) { + this.companyintroduction = companyintroduction; + } + + public String[] getSummimageurilist() { + return summimageurilist; + } + + public void setSummimageurilistArray(String[] summimageuriList) { + this.summimageurilist = summimageuriList; + } + + public String[] getDetailurl() { + return detailurl; + } + + public void setDetailurlArray(String[] detailurl) { + this.detailurl = detailurl; + } + + public String getExpirationdateForString(){ + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + return dateFormat.format(this.expirationdate); + } + + /** + * 为opensearch特供 + * @param region + */ + public void setRegion(String region) { + this.region = region== null ?new String[0]:region.split("\\t"); + } + + public void setRegionname(String regionname) { + this.regionname = regionname== null ?new String[0]:regionname.split("\\t");; + } + + public void setShoptype(String shoptype) { + this.shoptype = shoptype== null ?new String[0]:shoptype.split("\\t");; + } + + public void setShoptypename(String shoptypename) { + this.shoptypename = shoptypename== null ?new String[0]:shoptypename.split("\\t");; + } + + public void setCategoryids(String categoryids) { + this.categoryids = categoryids== null ?new String[0]:categoryids.split("\\t");; + } + + public void setCategoryidsname(String categoryidsname) { + this.categoryidsname = categoryidsname== null ?new String[0]:categoryidsname.split("\\t");; + } + + public void setSummimageurilist(String summimageuriList) { + this.summimageurilist = summimageuriList== null ?new String[0]:summimageuriList.split("\\t");; + } + + public void setDetailurl(String detailurl) { + this.detailurl = detailurl== null ?new String[0]:detailurl.split("\\t");; + } + + /** + * @return the payordamt30 + */ + public Double getPayordamt30() { + return payordamt30; + } + + /** + * @param payordamt30 the payordamt30 to set + */ + public void setPayordamt30(Double payordamt30) { + this.payordamt30 = payordamt30; + } + + /** + * @return the payordcnt30 + */ + public long getPayordcnt30() { + return payordcnt30; + } + + /** + * @param payordcnt30 the payordcnt30 to set + */ + public void setPayordcnt30(long payordcnt30) { + this.payordcnt30 = payordcnt30; + } + + /** + * @return the payordbuyercnt30 + */ + public long getPayordbuyercnt30() { + return payordbuyercnt30; + } + + /** + * @param payordbuyercnt30 the payordbuyercnt30 to set + */ + public void setPayordbuyercnt30(long payordbuyercnt30) { + this.payordbuyercnt30 = payordbuyercnt30; + } + + /** + * @return the returnordrate90 + */ + public Double getReturnordrate90() { + return returnordrate90; + } + + /** + * @param returnordrate90 the returnordrate90 to set + */ + public void setReturnordrate90(Double returnordrate90) { + this.returnordrate90 = returnordrate90; + } + + /** + * @return the membercnttd + */ + public int getMembercnttd() { + return membercnttd; + } + + /** + * @param membercnttd the membercnttd to set + */ + public void setMembercnttd(int membercnttd) { + this.membercnttd = membercnttd; + } + + public String getStdcategoryid1() { + return stdcategoryid1; + } + + public void setStdcategoryid1(String stdcategoryid1) { + this.stdcategoryid1 = stdcategoryid1; + } + + public String getStdcategoryid2() { + return stdcategoryid2; + } + + public void setStdcategoryid2(String stdcategoryid2) { + this.stdcategoryid2 = stdcategoryid2; + } + + public String getStdcategoryname1() { + return stdcategoryname1; + } + + public void setStdcategoryname1(String stdcategoryname1) { + this.stdcategoryname1 = stdcategoryname1; + } + + public String getStdcategoryname2() { + return stdcategoryname2; + } + + public void setStdcategoryname2(String stdcategoryname2) { + this.stdcategoryname2 = stdcategoryname2; + } + + + +} \ No newline at end of file diff --git a/src/test/java/com/alibaba/fastjson/codegen/ClassGen.java b/src/test/java/com/alibaba/fastjson/codegen/ClassGen.java new file mode 100644 index 0000000000..20baebf86c --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/codegen/ClassGen.java @@ -0,0 +1,105 @@ +package com.alibaba.fastjson.codegen; + +import java.io.IOException; +import java.lang.reflect.Type; + +public abstract class ClassGen { + + protected Class clazz; + protected Type type; + protected Appendable out; + + private String indent = "\t"; + private int indentCount = 0; + + public ClassGen(Class clazz, Appendable out){ + this(clazz, null, out); + } + + public ClassGen(Class clazz, Type type, Appendable out){ + this.clazz = clazz; + this.type = type; + this.out = out; + } + + public abstract void gen() throws IOException; + + protected void println() throws IOException { + out.append("\n"); + printIndent(); + } + + protected void println(String text) throws IOException { + out.append(text); + out.append("\n"); + printIndent(); + } + + protected void print(String text) throws IOException { + out.append(text); + } + + protected void printPackage() throws IOException { + print("package "); + print(clazz.getPackage().getName()); + println(";"); + } + + protected void beginClass(String className) throws IOException { + print("public class "); + print(className); + print(" implements ObjectDeserializer {"); + incrementIndent(); + println(); + } + + protected void endClass() throws IOException { + decrementIndent(); + println(); + print("}"); + println(); + } + + protected void genField(String name, Class feildClass) throws IOException { + if (feildClass == char[].class) { + print("char[]"); + } + + print(" "); + print(name); + println(";"); + } + + protected void beginInit(String className) throws IOException { + print("public "); + print(className); + println(" () {"); + incrementIndent(); + } + + protected void endInit() throws IOException { + decrementIndent(); + print("}"); + println(); + } + + public void decrementIndent() { + this.indentCount -= 1; + } + + public void incrementIndent() { + this.indentCount += 1; + } + + public void printIndent() throws IOException { + for (int i = 0; i < this.indentCount; ++i) { + print(this.indent); + } + } + + protected void printClassName(Class clazz) throws IOException { + String name = clazz.getName(); + name = name.replace('$', '.'); + print(name); + } +} diff --git a/src/test/java/com/alibaba/fastjson/codegen/DeserializerGen.java b/src/test/java/com/alibaba/fastjson/codegen/DeserializerGen.java new file mode 100644 index 0000000000..6bc971daa6 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/codegen/DeserializerGen.java @@ -0,0 +1,648 @@ +package com.alibaba.fastjson.codegen; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.TreeSet; + +import com.alibaba.fastjson.util.JavaBeanInfo; +import com.alibaba.fastjson.util.FieldInfo; +import com.alibaba.fastjson.util.TypeUtils; + +public class DeserializerGen extends ClassGen { + + private JavaBeanInfo beanInfo; + private String genClassName; + + public DeserializerGen(Class clazz, Appendable out){ + super(clazz, out); + } + + @Override + public void gen() throws IOException { + beanInfo = JavaBeanInfo.build(clazz, type, null); + genClassName = clazz.getSimpleName() + "GenDecoder"; + + print("package "); + print(clazz.getPackage().getName()); + println(";"); + println(); + + println("import java.lang.reflect.Type;"); + println(); + + println("import com.alibaba.fastjson.parser.DefaultJSONParser;"); + println("import com.alibaba.fastjson.parser.DefaultJSONParser.ResolveTask;"); + println("import com.alibaba.fastjson.parser.ParserConfig;"); + println("import com.alibaba.fastjson.parser.Feature;"); + println("import com.alibaba.fastjson.parser.JSONLexerBase;"); + println("import com.alibaba.fastjson.parser.JSONToken;"); + println("import com.alibaba.fastjson.parser.ParseContext;"); + println("import com.alibaba.fastjson.parser.deserializer.ASMJavaBeanDeserializer;"); + println("import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;"); + println(); + + print("public class "); + print(genClassName); + print(" extends ASMJavaBeanDeserializer implements ObjectDeserializer {"); + incrementIndent(); + println(); + + genConstructor(); + + genCreateInstance(); + + genDeserialze(); + + endClass(); + } + + protected void genCreateInstance() throws IOException { + println(); + print("public Object createInstance(DefaultJSONParser parser, Type type) {"); + incrementIndent(); + println(); + + print("return new "); + print(clazz.getSimpleName()); + print("();"); + println(); + + decrementIndent(); + println(); + print("}"); + } + + protected void genDeserialze() throws IOException { + if (beanInfo.fields.length == 0) { + return; + } + + for (FieldInfo fieldInfo : beanInfo.fields) { + Class fieldClass = fieldInfo.fieldClass; + Type fieldType = fieldInfo.fieldType; + + if (fieldClass == char.class) { + return; + } + + if (Collection.class.isAssignableFrom(fieldClass)) { + if (fieldType instanceof ParameterizedType) { + Type itemType = ((ParameterizedType) fieldType).getActualTypeArguments()[0]; + if (itemType instanceof Class) { + continue; + } else { + return; + } + } else { + return; + } + } + } + + FieldInfo[] fieldList = beanInfo.sortedFields; + + println(); + print("public Object deserialze(DefaultJSONParser parser, Type type, Object fieldName) {"); + incrementIndent(); + println(); + + println("JSONLexerBase lexer = (JSONLexerBase) parser.getLexer();"); + println(); + + println("if (!lexer.isEnabled(Feature.SortFeidFastMatch)) {"); + println("\treturn super.deserialze(parser, type, fieldName);"); + println("}"); + + println(); + + println("if (isSupportArrayToBean(lexer)) {"); + println("\t// deserialzeArrayMapping"); + println("}"); + + println(); + println("if (lexer.scanType(\"Department\") == JSONLexerBase.NOT_MATCH) {"); + println("\treturn super.deserialze(parser, type, fieldName);"); + println("}"); + + println(); + + println("ParseContext mark_context = parser.getContext();"); + println("int matchedCount = 0;"); + + print(clazz.getSimpleName()); + print(" instance = "); + Constructor defaultConstructor = beanInfo.defaultConstructor; + if (Modifier.isPublic(defaultConstructor.getModifiers())) { + print("new "); + print(clazz.getSimpleName()); + println("();"); + } else { + print("("); + print(clazz.getSimpleName()); + print(") createInstance(parser);"); + } + + println(); + + println("ParseContext context = parser.getContext();"); + println("ParseContext childContext = parser.setContext(context, instance, fieldName);"); + + println(); + + println("if (lexer.matchStat == JSONLexerBase.END) {"); + println("\treturn instance;"); + println("}"); + + println(); + + println("int matchStat = 0;"); + + int fieldListSize = fieldList.length; + for (int i = 0; i < fieldListSize; i += 32) { + print("int _asm_flag_"); + print(Integer.toString(i / 32)); + println(" = 0;"); + } + + for (int i = 0; i < fieldListSize; ++i) { + FieldInfo fieldInfo = fieldList[i]; + Class fieldClass = fieldInfo.fieldClass; + + if (fieldClass == boolean.class) { + print("boolean "); + printFieldVarName(fieldInfo); + println(" = false;"); + } else if (fieldClass == byte.class // + || fieldClass == short.class // + || fieldClass == int.class // + || fieldClass == long.class // + || fieldClass == float.class // + || fieldClass == double.class // + ) { + print(fieldClass.getSimpleName()); + print(" "); + printFieldVarName(fieldInfo); + println(" = 0;"); + } else { + if (fieldClass == String.class) { + print("String "); + printFieldVarName(fieldInfo); + println(";"); + + println("if (lexer.isEnabled(Feature.InitStringFieldAsEmpty)) {"); + print("\t"); + printFieldVarName(fieldInfo); + println(" = lexer.stringDefaultValue();"); + print("\t"); + genSetFlag(i); + println("} else {"); + print("\t"); + printFieldVarName(fieldInfo); + println(" = null;"); + println("}"); + } else { + printClassName(fieldClass); + print(" "); + printFieldVarName(fieldInfo); + print(" = null;"); + println(); + } + } + } + + println("boolean endFlag = false, restFlag = false;"); + println(); + + for (int i = 0; i < fieldListSize; ++i) { + print("if ((!endFlag) && (!restFlag)) {"); + incrementIndent(); + println(); + + FieldInfo fieldInfo = fieldList[i]; + Class fieldClass = fieldInfo.fieldClass; + Type fieldType = fieldInfo.fieldType; + + if (fieldClass == boolean.class) { + printFieldVarName(fieldInfo); + print(" = lexer.scanFieldBoolean("); + printFieldPrefix(fieldInfo); + println(");"); + } else if (fieldClass == byte.class || fieldClass == short.class || fieldClass == int.class) { + printFieldVarName(fieldInfo); + print(" = lexer.scanFieldInt("); + printFieldPrefix(fieldInfo); + println(");"); + } else if (fieldClass == long.class) { + printFieldVarName(fieldInfo); + print(" = lexer.scanFieldLong("); + printFieldPrefix(fieldInfo); + println(");"); + } else if (fieldClass == float.class) { + printFieldVarName(fieldInfo); + print(" = lexer.scanFieldFloat("); + printFieldPrefix(fieldInfo); + println(");"); + } else if (fieldClass == double.class) { + printFieldVarName(fieldInfo); + print(" = lexer.scanFieldDouble("); + printFieldPrefix(fieldInfo); + println(");"); + } else if (fieldClass == String.class) { + printFieldVarName(fieldInfo); + print(" = lexer.scanFieldString("); + printFieldPrefix(fieldInfo); + println(");"); + } else if (fieldClass.isEnum()) { + print("String "); + printFieldVarEnumName(fieldInfo); + + print(" = lexer.scanFieldSymbol("); + printFieldPrefix(fieldInfo); + println(", parser.getSymbolTable());"); + + print("if ("); + printFieldVarEnumName(fieldInfo); + println(" == null) {"); + print("\t"); + printFieldVarName(fieldInfo); + print(" = "); + printClassName(fieldClass); + print(".valueOf("); + printFieldVarEnumName(fieldInfo); + println(");"); + println("}"); + } else if (Collection.class.isAssignableFrom(fieldClass)) { + Class itemClass = TypeUtils.getCollectionItemClass(fieldType); + + if (itemClass == String.class) { + printFieldVarName(fieldInfo); + print(" = ("); + printClassName(fieldClass); + print(") lexer.scanFieldStringArray("); + printFieldPrefix(fieldInfo); + print(", "); + printClassName(fieldClass); + print(".class);"); + println(); + } else { + genDeserialzeList(fieldInfo, i, itemClass); + if (i == fieldListSize - 1) { + genEndCheck(); + } + } + } else { + genDeserialzeObject(fieldInfo, i); + + if (i == fieldListSize - 1) { + genEndCheck(); + } + } + + println("if(lexer.matchStat > 0) {"); + print("\t"); + genSetFlag(i); + println("\tmatchedCount++;"); + println("}"); + + println("if(lexer.matchStat == JSONLexerBase.NOT_MATCH) {"); + println("\trestFlag = true;"); + println("}"); + + + println("if(lexer.matchStat != JSONLexerBase.END) {"); + println("\tendFlag = true;"); + println("}"); + + + decrementIndent(); + println(); + println("}"); + } + + genBatchSet(fieldList, true); + + println(); + println("if (restFlag) {"); + println("\treturn super.parseRest(parser, type, fieldName, instance);"); + println("}"); + + println(); + print("return instance;"); + println(); + + decrementIndent(); + println(); + print("}"); + } + + private void genBatchSet(FieldInfo[] fieldList, boolean flag) throws IOException { + for (int i = 0, size = fieldList.length; i < size; ++i) { + FieldInfo fieldInfo = fieldList[i]; + + String varName = "_asm_flag_" + (i / 32); + if (flag) { + print("if (("); + print(varName); + print(" & "); + print(Integer.toString(1 << i)); + print(") != 0) {"); + println(); + incrementIndent(); + } + + if (fieldInfo.method != null) { + print("\tinstance."); + print(fieldInfo.method.getName()); + print("("); + printFieldVarName(fieldInfo); + println(");"); + } else { + print("\tinstance."); + print(fieldInfo.field.getName()); + print(" = "); + printFieldVarName(fieldInfo); + println(";"); + } + + if (flag) { + decrementIndent(); + println(); + println("}"); + } + } + } + + private void genEndCheck() throws IOException { + println("if (matchedCount <= 0 || lexer.token() != JSONToken.RBRACE) {"); + println("\trestFlag = true;"); + println("} else if (lexer.token() == JSONToken.COMMA) {"); + println("\tlexer.nextToken();"); + println("}"); + } + + protected void genDeserialzeList(FieldInfo fieldInfo, int i, Class itemClass) throws IOException { + print("if (lexer.matchField("); + printFieldPrefix(fieldInfo); + print(")) {"); + println(); + print("\t"); + genSetFlag(i); + println("\tif (lexer.token() == JSONToken.NULL) {"); + println("\t\tlexer.nextToken(JSONToken.COMMA);"); + println("\t} else {"); + println("\t\tif (lexer.token() == JSONToken.LBRACKET) {"); + print("\t\t\tif("); + printListFieldItemDeser(fieldInfo); + print(" == null) {"); + println(); + + print("\t\t\t\t"); + printListFieldItemDeser(fieldInfo); + print(" = parser.getConfig().getDeserializer("); + printClassName(itemClass); + print(".class);"); + println(); + + print("\t\t\t}"); + println(); + + print("\t\t\tfinal int fastMatchToken = "); + printListFieldItemDeser(fieldInfo); + print(".getFastMatchToken();"); + println(); + println("\t\t\tlexer.nextToken(fastMatchToken);"); + + // _newCollection + print("\t\t\t"); + printFieldVarName(fieldInfo); + print(" = "); + Class fieldClass = fieldInfo.fieldClass; + if (fieldClass.isAssignableFrom(ArrayList.class)) { + print("new java.util.ArrayList();"); + } else if (fieldClass.isAssignableFrom(LinkedList.class)) { + print("new java.util.LinkedList();"); + } else if (fieldClass.isAssignableFrom(HashSet.class)) { + print("new java.util.HashSet();"); + } else if (fieldClass.isAssignableFrom(TreeSet.class)) { + print("new java.util.TreeSet();"); + } else { + print("new "); + printClassName(fieldClass); + print("();"); + } + println(); + + println("\t\t\tParseContext listContext = parser.getContext();"); + print("\t\t\tparser.setContext("); + printFieldVarName(fieldInfo); + print(", \""); + print(fieldInfo.name); + print("\");"); + println(); + + println(); + println("\t\t\tfor(int i = 0; ;++i) {"); + + println("\t\t\t\tif (lexer.token() == JSONToken.RBRACKET) {"); + println("\t\t\t\t\tbreak;"); + println("\t\t\t\t}"); + print("\t\t\t\t"); + printClassName(itemClass); + print(" itemValue = "); + printListFieldItemDeser(fieldInfo); + print(".deserialze(parser, "); + printListFieldItemType(fieldInfo); + println(", i);"); + + print("\t\t\t\t"); + printFieldVarName(fieldInfo); + println(".add(itemValue);"); + + print("\t\t\t\tparser.checkListResolve("); + printFieldVarName(fieldInfo); + println(");"); + + println("\t\t\t\tif (lexer.token() == JSONToken.COMMA) {"); + println("\t\t\t\t\tlexer.nextToken(fastMatchToken);"); + println("\t\t\t\t}"); + + // end for + println("\t\t\t}"); + + println("\t\t\tparser.setContext(listContext);"); + + println("\t\t\tif (lexer.token() != JSONToken.RBRACKET) {"); + println("\t\t\t\trestFlag = true;"); + println("\t\t\t}"); + println("\t\t\tlexer.nextToken(JSONToken.COMMA);"); + + println(); + println("\t\t} else {"); + println("\t\t\trestFlag = true;"); + println("\t\t}"); + println("\t}"); + println("}"); + } + + protected void genDeserialzeObject(FieldInfo fieldInfo, int i) throws IOException { + print("if (lexer.matchField("); + printFieldPrefix(fieldInfo); + print(")) {"); + println(); + print("\t"); + genSetFlag(i); + println("\tmatchedCount++;"); + + // _deserObject + print("if ("); + printFieldDeser(fieldInfo); + print(" == null) {"); + println(); + + print("\t"); + printFieldDeser(fieldInfo); + print(" = parser.getConfig().getDeserializer("); + printClassName(fieldInfo.fieldClass); + println(".class);"); + println("}"); + + print("\t"); + printFieldDeser(fieldInfo); + print(".deserialze(parser, "); + if (fieldInfo.fieldType instanceof Class) { + printClassName(fieldInfo.fieldClass); + print(".class"); + } else { + print("getFieldType(\""); + println(fieldInfo.name); + print("\")"); + } + print(",\""); + print(fieldInfo.name); + println("\");"); + + println("\tif(parser.getResolveStatus() == DefaultJSONParser.NeedToResolve) {"); + println("\t\tResolveTask resolveTask = parser.getLastResolveTask();"); + println("\t\tresolveTask.setOwnerContext(parser.getContext());"); + print("\t\tresolveTask.setFieldDeserializer(this.getFieldDeserializer(\""); + print(fieldInfo.name); + println("\"));"); + println("\t\tparser.setResolveStatus(DefaultJSONParser.NONE);"); + println("\t}"); + println("}"); + } + + private void printFieldVarName(FieldInfo fieldInfo) throws IOException { + print(fieldInfo.name); + print("_gen"); + } + + private void printFieldVarEnumName(FieldInfo fieldInfo) throws IOException { + print(fieldInfo.name); + print("_gen_enum_name"); + } + + private void printFieldPrefix(FieldInfo fieldInfo) throws IOException { + print(fieldInfo.name); + print("_gen_prefix__"); + } + + private void printListFieldItemDeser(FieldInfo fieldInfo) throws IOException { + print(fieldInfo.name); + print("_gen_list_item_deser__"); + } + + private void printFieldDeser(FieldInfo fieldInfo) throws IOException { + print(fieldInfo.name); + print("_gen_deser__"); + } + + private void printListFieldItemType(FieldInfo fieldInfo) throws IOException { + print(fieldInfo.name); + print("_gen_list_item_type__"); + } + + private void genSetFlag(int flag) throws IOException { + String varName = "_asm_flag_" + (flag / 32); + print(varName); + print(" |= "); + print(Integer.toString(1 << flag)); + print(";"); + println(); + } + + protected void genConstructor() throws IOException { + for (int i = 0, size = beanInfo.fields.length; i < size; ++i) { + FieldInfo fieldInfo = beanInfo.fields[i]; + print("private char[] "); + printFieldPrefix(fieldInfo); + print(" = \"\\\""); + print(fieldInfo.name); + print("\\\":\".toCharArray();"); + println(); + } + + println(); + + boolean fieldDeserFlag = false; + for (int i = 0, size = beanInfo.fields.length; i < size; ++i) { + FieldInfo fieldInfo = beanInfo.fields[i]; + Class fieldClass = fieldInfo.fieldClass; + + if (fieldClass.isPrimitive()) { + continue; + } + + if (fieldClass.isEnum()) { + continue; + } + + print("private ObjectDeserializer "); + + if (Collection.class.isAssignableFrom(fieldClass)) { + printListFieldItemDeser(fieldInfo); + } else { + printFieldDeser(fieldInfo); + } + println(";"); + fieldDeserFlag = true; + + if (Collection.class.isAssignableFrom(fieldClass)) { + print("private Type "); + printListFieldItemType(fieldInfo); + print(" = "); + Class fieldItemClass = TypeUtils.getCollectionItemClass(fieldInfo.fieldType); + printClassName(fieldItemClass); + println(".class;"); + } + } + + if (fieldDeserFlag) { + println(); + } + + // constructor + print("public "); + print(genClassName); + print(" (ParserConfig config, Class clazz) {"); + incrementIndent(); + println(); + + println("super(config, clazz);"); + + decrementIndent(); + println(); + print("}"); + println(); + } + +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/IgnoreTypeDeserializer.java b/src/test/java/com/alibaba/fastjson/deserializer/IgnoreTypeDeserializer.java new file mode 100644 index 0000000000..8282a05d54 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/IgnoreTypeDeserializer.java @@ -0,0 +1,55 @@ +package com.alibaba.fastjson.deserializer; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; + +import org.junit.Assert; +import org.junit.Test; + + +/** + * Created by jiangyu on 2017-03-03 11:33. + */ +public class IgnoreTypeDeserializer { + @Test(expected = JSONException.class) + public void parseObjectWithNotExistTypeThrowException() { + String s = "{\"@type\":\"com.alibaba.fastjson.ValueBean\",\"val\":1}"; + JSONObject.parseObject(s, ValueBean.class); + } + + @Test + public void parseObjectWithNotExistType() { + String s = "{\"@type\":\"com.alibaba.fastjson.ValueBean\",\"val\":1}"; + ValueBean v = JSONObject.parseObject(s, ValueBean.class, Feature.IgnoreAutoType); + Assert.assertNotNull(v); + Assert.assertEquals(new Integer(1), v.getVal()); + } + + @Test + public void parseWithNotExistType() { + String s = "{\"@type\":\"com.alibaba.fastjson.ValueBean\",\"val\":1}"; + Object object = JSONObject.parse(s); + Assert.assertNotNull(object); + Assert.assertTrue(object instanceof JSONObject); + Assert.assertEquals(new Integer(1), JSONObject.class.cast(object).getInteger("val")); + } + + @Test + public void parseWithExistType() { + String s = "{\"@type\":\"com.alibaba.fastjson.deserializer.ValueBean\",\"val\":1}"; + Object object = JSONObject.parse(s); + Assert.assertNotNull(object); + Assert.assertTrue(object instanceof ValueBean); + Assert.assertEquals(new Integer(1), ValueBean.class.cast(object).getVal()); + } + + @Test + public void parseObjectWithExistType() { + String s = "{\"@type\":\"com.alibaba.fastjson.deserializer.ValueBean\",\"val\":1}"; + ValueBean object = JSONObject.parseObject(s, ValueBean.class); + Assert.assertNotNull(object); + Assert.assertEquals(new Integer(1), object.getVal()); + } + +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/ValueBean.java b/src/test/java/com/alibaba/fastjson/deserializer/ValueBean.java new file mode 100644 index 0000000000..ff31794e45 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/ValueBean.java @@ -0,0 +1,18 @@ +package com.alibaba.fastjson.deserializer; + +/** + * Created by jiangyu on 2017-03-03 11:34. + */ +public class ValueBean { + + private Integer val; + + public Integer getVal() { + return val; + } + + public ValueBean setVal(Integer val) { + this.val = val; + return this; + } +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issue1463/TestIssue1463.java b/src/test/java/com/alibaba/fastjson/deserializer/issue1463/TestIssue1463.java new file mode 100644 index 0000000000..72478998f7 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issue1463/TestIssue1463.java @@ -0,0 +1,40 @@ +package com.alibaba.fastjson.deserializer.issue1463; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.deserializer.issue1463.beans.Person; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * + * @author LNAmp + * @since 2017年09月11日 + * + * https://github.com/alibaba/fastjson/issues/569 + */ +public class TestIssue1463 { + + private Person wenshao; + + @Before + public void setUp() { + wenshao = new Person("wenshao", 18); + } + + @Test + public void testIssue1463() { + String str = doubleDeserialization(wenshao); + try { + wenshao = JSON.parseObject(str, Person.class); + } catch (Throwable ex) { + Assert.assertEquals(ex.getCause() instanceof NullPointerException, false); + } + } + + private String doubleDeserialization(Person person) { + return JSON.toJSONString(JSON.toJSONString(person)); + } + +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issue1463/beans/Person.java b/src/test/java/com/alibaba/fastjson/deserializer/issue1463/beans/Person.java new file mode 100644 index 0000000000..3370d6228f --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issue1463/beans/Person.java @@ -0,0 +1,32 @@ +package com.alibaba.fastjson.deserializer.issue1463.beans; + +import java.io.Serializable; + +/** + * issue 1463 + * + * @author LNAmp + * @since 2017年09月11日 + * + */ +public class Person implements Serializable { + + private static final long serialVersionUID = 248616267815851026L; + + private String name; + + private Integer age; + + public Person(String name, Integer age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public Integer getAge() { + return age; + } +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/TestIssue1763_2.java b/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/TestIssue1763_2.java new file mode 100644 index 0000000000..b43948a4c2 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/TestIssue1763_2.java @@ -0,0 +1,51 @@ +package com.alibaba.fastjson.deserializer.issue1763_2; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.deserializer.issue1763_2.bean.BaseResult; +import com.alibaba.fastjson.deserializer.issue1763_2.bean.CouponResult; +import com.alibaba.fastjson.deserializer.issue1763_2.bean.PageResult; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Test Issue 1763_2 + * 如果有多层泛型且前面泛型已经实现的情况下,判断下一级泛型 + * @author cnlyml + */ +public class TestIssue1763_2 { + private String jsonStr; + private Class clazz; + + @Before + public void init() { + jsonStr = "{\"code\":0, \"message\":\"Success\", \"content\":{\"pageNum\":1, \"pageSize\":2, \"size\":2, \"startRow\":1, \"endRow\":1, \"total\":2, \"pages\":1, \"list\":[{\"id\":10000001, \"couponName\":\"Test1\"}, {\"id\":10000002, \"couponName\": \"Test2\"}]}}"; + clazz = (Class) CouponResult.class; + } + + // 修复test + @Test + public void testFixBug1763_2() { + BaseResult> data = JSON.parseObject(jsonStr, new TypeReference>>(clazz){}.getType()); + + Assert.assertTrue(data.isSuccess()); + Assert.assertTrue(data.getContent().getList().size() == 2); + Assert.assertTrue(data.getContent().getList().get(0).getId().equals(10000001L)); + Assert.assertEquals(CouponResult.class, data.getContent().getList().get(0).getClass()); + } + + // 复现BUG + @Test + public void testBug1763_2() { + BaseResult> data = JSON.parseObject(jsonStr, new TypeReferenceBug1763_2>>(clazz){}.getType()); + + Assert.assertTrue(data.isSuccess()); + Assert.assertTrue(data.getContent().getList().size() == 2); + try { + data.getContent().getList().get(0).getId(); + } catch (Throwable ex) { + Assert.assertEquals(ex.getCause() instanceof ClassCastException, false); + } + } +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/TypeReferenceBug1763_2.java b/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/TypeReferenceBug1763_2.java new file mode 100644 index 0000000000..0ed8f9056f --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/TypeReferenceBug1763_2.java @@ -0,0 +1,89 @@ +package com.alibaba.fastjson.deserializer.issue1763_2; + +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.util.ParameterizedTypeImpl; +import com.alibaba.fastjson.util.TypeUtils; + +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +public class TypeReferenceBug1763_2 { + + static ConcurrentMap classTypeCache + = new ConcurrentHashMap(16, 0.75f, 1); + + protected final Type type; + + /** + * Constructs a new type literal. Derives represented class from type + * parameter. + * + *

Clients create an empty anonymous subclass. Doing so embeds the type + * parameter in the anonymous class's type hierarchy so we can reconstitute it + * at runtime despite erasure. + */ + protected TypeReferenceBug1763_2(){ + Type superClass = getClass().getGenericSuperclass(); + + Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; + + Type cachedType = classTypeCache.get(type); + if (cachedType == null) { + classTypeCache.putIfAbsent(type, type); + cachedType = classTypeCache.get(type); + } + + this.type = cachedType; + } + + /** + * @since 1.2.9 + * @param actualTypeArguments + */ + protected TypeReferenceBug1763_2(Type... actualTypeArguments){ + Class thisClass = this.getClass(); + Type superClass = thisClass.getGenericSuperclass(); + + ParameterizedType argType = (ParameterizedType) ((ParameterizedType) superClass).getActualTypeArguments()[0]; + Type rawType = argType.getRawType(); + Type[] argTypes = argType.getActualTypeArguments(); + + int actualIndex = 0; + for (int i = 0; i < argTypes.length; ++i) { + if (argTypes[i] instanceof TypeVariable && + actualIndex < actualTypeArguments.length) { + argTypes[i] = actualTypeArguments[actualIndex++]; + } + // fix for openjdk and android env + if (argTypes[i] instanceof GenericArrayType) { + argTypes[i] = TypeUtils.checkPrimitiveArray( + (GenericArrayType) argTypes[i]); + } + + } + + Type key = new ParameterizedTypeImpl(argTypes, thisClass, rawType); + Type cachedType = classTypeCache.get(key); + if (cachedType == null) { + classTypeCache.putIfAbsent(key, key); + cachedType = classTypeCache.get(key); + } + + type = cachedType; + + } + + /** + * Gets underlying {@code Type} instance. + */ + public Type getType() { + return type; + } + + public final static Type LIST_STRING = new TypeReference>() {}.getType(); +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/bean/BaseResult.java b/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/bean/BaseResult.java new file mode 100644 index 0000000000..4157033416 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/bean/BaseResult.java @@ -0,0 +1,45 @@ +package com.alibaba.fastjson.deserializer.issue1763_2.bean; + +import com.alibaba.fastjson.annotation.JSONField; + +/** + * BaseResult + * + * @author cnlyml + */ +public class BaseResult { + private static final Integer SUCCESS_CODE = 0; + + private Integer code; + private String message; + @JSONField(name = "content") + private T content; + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public T getContent() { + return content; + } + + public void setContent(T content) { + this.content = content; + } + + public boolean isSuccess() { + return code.equals(SUCCESS_CODE); + } +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/bean/CouponResult.java b/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/bean/CouponResult.java new file mode 100644 index 0000000000..d790df14e0 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/bean/CouponResult.java @@ -0,0 +1,36 @@ +package com.alibaba.fastjson.deserializer.issue1763_2.bean; + + +/** + * + * @author cnlyml + */ +public class CouponResult{ + /** + * 优惠券ID + */ + private Long id; + + /** + * 优惠券名称 + */ + private String couponName; + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getCouponName() { + return couponName; + } + + public void setCouponName(String couponName) { + this.couponName = couponName; + } + +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/bean/PageResult.java b/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/bean/PageResult.java new file mode 100644 index 0000000000..af26bf5515 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issue1763_2/bean/PageResult.java @@ -0,0 +1,85 @@ +package com.alibaba.fastjson.deserializer.issue1763_2.bean; + +import java.util.List; + +/** + * 分页信息 + * @param + * + * @author cnlyml + */ +public class PageResult { + private Integer pageNum; + private Integer pageSize; + private Integer size; + private Integer startRow; + private Integer endRow; + private Integer total; + private Integer pages; + + private List list; + + public Integer getPageNum() { + return pageNum; + } + + public void setPageNum(Integer pageNum) { + this.pageNum = pageNum; + } + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } + + public Integer getSize() { + return size; + } + + public void setSize(Integer size) { + this.size = size; + } + + public Integer getStartRow() { + return startRow; + } + + public void setStartRow(Integer startRow) { + this.startRow = startRow; + } + + public Integer getEndRow() { + return endRow; + } + + public void setEndRow(Integer endRow) { + this.endRow = endRow; + } + + public Integer getTotal() { + return total; + } + + public void setTotal(Integer total) { + this.total = total; + } + + public Integer getPages() { + return pages; + } + + public void setPages(Integer pages) { + this.pages = pages; + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issues569/TestIssues569.java b/src/test/java/com/alibaba/fastjson/deserializer/issues569/TestIssues569.java new file mode 100644 index 0000000000..5587d09a58 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issues569/TestIssues569.java @@ -0,0 +1,76 @@ +package com.alibaba.fastjson.deserializer.issues569; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.deserializer.issues569.beans.Dept; +import com.alibaba.fastjson.deserializer.issues569.beans.MyResponse; +import com.alibaba.fastjson.deserializer.issues569.parser.ParserConfigBug569; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.lang.reflect.Type; +import java.util.*; + +/** + * Author : BlackShadowWalker + * Date : 2016-10-10 + * + * https://github.com/alibaba/fastjson/issues/569 + */ +public class TestIssues569 { + + private int featureValues = JSON.DEFAULT_PARSER_FEATURE; + private Feature[] features; + + private static final Feature[] EMPTY_SERIALIZER_FEATURES = new Feature[0]; + + private String jsonData = "{\"result\":[{\"id\":0,\"startDate\":1420041600000,\"name\":\"集团\",\"abbr\":\"集团\",\"endDate\":253402185600000,\"type\":\"1317967b-4a83-442c-a7b4-1ac9e7bf84d9\"},{\"id\":0,\"startDate\":1420041600000,\"name\":\"集团总裁办\",\"abbr\":\"集团总裁办\",\"endDate\":253402185600000,\"pcode\":\"4aa2817e-ae16-4355-a1cc-a73d0b8abc43\",\"type\":\"36e9bde9-2e94-4b91-8b9f-b1078296e3ad\"}],\"errCode\":0,\"success\":true}"; + + private Type mType1;//MyResponse + private Type mType;//MyResponse> + + ParserConfig config = ParserConfig.getGlobalInstance(); + ParserConfig configBug569 = new ParserConfigBug569();//这个是包含bug的代码 + + @Before + public void init() { + mType = new TypeReference>>() { + }.getType(); + mType1 = new TypeReference() { + }.getType(); + } + + //复现 + @Test + public void testBug569() { + //第一次反序列化是使用的 MyResponse, 没有指定泛型类型,貌似会缓存 MyResponse, 后面在调用的MyResponse反序列化就受影响了 + MyResponse resp1 = JSON.parseObject(jsonData, mType1, configBug569, featureValues, + features != null ? features : EMPTY_SERIALIZER_FEATURES); + + //expect MyResponse> + MyResponse resp = JSON.parseObject(jsonData, mType, configBug569, featureValues, + features != null ? features : EMPTY_SERIALIZER_FEATURES); + Assert.assertNotNull(resp); + Assert.assertNotNull(resp.getResult()); + Assert.assertEquals(JSONArray.class, resp.getResult().getClass());//这里会受到 resp1 的影响 + } + + //修复 + @Test + public void testFixBug569() { + MyResponse resp1 = JSON.parseObject(jsonData, mType1, config, featureValues, + features != null ? features : EMPTY_SERIALIZER_FEATURES); + + //expect MyResponse> + MyResponse resp = JSON.parseObject(jsonData, mType, config, featureValues, + features != null ? features : EMPTY_SERIALIZER_FEATURES); + Assert.assertNotNull(resp); + Assert.assertNotNull(resp.getResult()); + Assert.assertEquals(ArrayList.class, resp.getResult().getClass()); + } + +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issues569/beans/Dept.java b/src/test/java/com/alibaba/fastjson/deserializer/issues569/beans/Dept.java new file mode 100644 index 0000000000..f43017c606 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issues569/beans/Dept.java @@ -0,0 +1,45 @@ +package com.alibaba.fastjson.deserializer.issues569.beans; + +/** + * Author : BlackShadowWalker + * Date : 2016-10-10 + */ +public class Dept { + + Long id; + String code;//部门编号 + String name;//部门名称 + String abbr;//简称 + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAbbr() { + return abbr; + } + + public void setAbbr(String abbr) { + this.abbr = abbr; + } +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issues569/beans/MyResponse.java b/src/test/java/com/alibaba/fastjson/deserializer/issues569/beans/MyResponse.java new file mode 100644 index 0000000000..b9965d76b7 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issues569/beans/MyResponse.java @@ -0,0 +1,45 @@ +package com.alibaba.fastjson.deserializer.issues569.beans; + +/** + * Author : BlackShadowWalker + * Date : 2016-09-06 + */ +public class MyResponse { + + Boolean success; + Integer errCode; + String errDes; + T result; + + public Boolean getSuccess() { + return success; + } + + public void setSuccess(Boolean success) { + this.success = success; + } + + public Integer getErrCode() { + return errCode; + } + + public void setErrCode(Integer errCode) { + this.errCode = errCode; + } + + public String getErrDes() { + return errDes; + } + + public void setErrDes(String errDes) { + this.errDes = errDes; + } + + public T getResult() { + return result; + } + + public void setResult(T result) { + this.result = result; + } +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issues569/parser/DefaultFieldDeserializerBug569.java b/src/test/java/com/alibaba/fastjson/deserializer/issues569/parser/DefaultFieldDeserializerBug569.java new file mode 100644 index 0000000000..ea1546f52d --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issues569/parser/DefaultFieldDeserializerBug569.java @@ -0,0 +1,67 @@ +package com.alibaba.fastjson.deserializer.issues569.parser; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParseContext; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ContextObjectDeserializer; +import com.alibaba.fastjson.parser.deserializer.DefaultFieldDeserializer; +import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; +import com.alibaba.fastjson.util.FieldInfo; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Map; + +/** + * Author : BlackShadowWalker + * Date : 2016-10-10 + */ +public class DefaultFieldDeserializerBug569 extends DefaultFieldDeserializer { + public DefaultFieldDeserializerBug569(ParserConfig mapping, Class clazz, FieldInfo fieldInfo) { + super(mapping, clazz, fieldInfo); + } + + @Override + public void parseField(DefaultJSONParser parser, Object object, Type objectType, Map fieldValues) { + if (fieldValueDeserilizer == null) { + getFieldValueDeserilizer(parser.getConfig()); + } + + Type fieldType = fieldInfo.fieldType; + if (objectType instanceof ParameterizedType) { + ParseContext objContext = parser.getContext(); + objContext.type = objectType; + fieldType = FieldInfo.getFieldType(this.clazz, objectType, fieldType); + } + + // ContextObjectDeserializer + Object value; + if (fieldValueDeserilizer instanceof JavaBeanDeserializer) { + JavaBeanDeserializer javaBeanDeser = (JavaBeanDeserializer) fieldValueDeserilizer; + value = javaBeanDeser.deserialze(parser, fieldType, fieldInfo.name, fieldInfo.parserFeatures); + } else { + if (this.fieldInfo.format != null && fieldValueDeserilizer instanceof ContextObjectDeserializer) { + value = ((ContextObjectDeserializer) fieldValueDeserilizer) // + .deserialze(parser, fieldType, + fieldInfo.name, + fieldInfo.format, + fieldInfo.parserFeatures); + } else { + value = fieldValueDeserilizer.deserialze(parser, fieldType, fieldInfo.name); + } + } + if (parser.getResolveStatus() == DefaultJSONParser.NeedToResolve) { + DefaultJSONParser.ResolveTask task = parser.getLastResolveTask(); + task.fieldDeserializer = this; + task.ownerContext = parser.getContext(); + parser.setResolveStatus(DefaultJSONParser.NONE); + } else { + if (object == null) { + fieldValues.put(fieldInfo.name, value); + } else { + setValue(object, value); + } + } + } + +} diff --git a/src/test/java/com/alibaba/fastjson/deserializer/issues569/parser/ParserConfigBug569.java b/src/test/java/com/alibaba/fastjson/deserializer/issues569/parser/ParserConfigBug569.java new file mode 100644 index 0000000000..6ce58e407d --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/deserializer/issues569/parser/ParserConfigBug569.java @@ -0,0 +1,194 @@ +package com.alibaba.fastjson.deserializer.issues569.parser; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.*; +import com.alibaba.fastjson.serializer.AwtCodec; +import com.alibaba.fastjson.serializer.CollectionCodec; +import com.alibaba.fastjson.serializer.MiscCodec; +import com.alibaba.fastjson.serializer.ObjectArrayCodec; +import com.alibaba.fastjson.util.FieldInfo; +import com.alibaba.fastjson.util.JavaBeanInfo; +import com.alibaba.fastjson.util.ServiceLoader; +import com.alibaba.fastjson.util.TypeUtils; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; +import java.util.*; + +/** + * Author : BlackShadowWalker + * Date : 2016-10-10 + */ +public class ParserConfigBug569 extends ParserConfig { + + private static boolean awtError = false; + private static boolean jdk8Error = false; + private String[] denyList = new String[] { "java.lang.Thread" }; + + public FieldDeserializer createFieldDeserializer(ParserConfig mapping, // + JavaBeanInfo beanInfo, // + FieldInfo fieldInfo) { + Class clazz = beanInfo.clazz; + Class fieldClass = fieldInfo.fieldClass; + + Class deserializeUsing = null; + JSONField annotation = fieldInfo.getAnnotation(); + if (annotation != null) { + deserializeUsing = annotation.deserializeUsing(); + if (deserializeUsing == Void.class) { + deserializeUsing = null; + } + } + + if (deserializeUsing == null && (fieldClass == List.class || fieldClass == ArrayList.class)) { + return new ArrayListTypeFieldDeserializer(mapping, clazz, fieldInfo); + } + + return new DefaultFieldDeserializerBug569(mapping, clazz, fieldInfo); + } + + public ObjectDeserializer getDeserializer(Class clazz, Type type) { + com.alibaba.fastjson.util.IdentityHashMap derializers = super.getDeserializers(); + ObjectDeserializer derializer = derializers.get(type); + if (derializer != null) { + return derializer; + } + + if (type == null) { + type = clazz; + } + + derializer = derializers.get(type); + if (derializer != null) { + return derializer; + } + + { + JSONType annotation = TypeUtils.getAnnotation(clazz,JSONType.class); + if (annotation != null) { + Class mappingTo = annotation.mappingTo(); + if (mappingTo != Void.class) { + return getDeserializer(mappingTo, mappingTo); + } + } + } + + if (type instanceof WildcardType || type instanceof TypeVariable || type instanceof ParameterizedType) { + derializer = derializers.get(clazz); + } + + if (derializer != null) { + return derializer; + } + + String className = clazz.getName(); + className = className.replace('$', '.'); + for (int i = 0; i < denyList.length; ++i) { + String deny = denyList[i]; + if (className.startsWith(deny)) { + throw new JSONException("parser deny : " + className); + } + } + + if (className.startsWith("java.awt.") // + && AwtCodec.support(clazz)) { + if (!awtError) { + try { + derializers.put(Class.forName("java.awt.Point"), AwtCodec.instance); + derializers.put(Class.forName("java.awt.Font"), AwtCodec.instance); + derializers.put(Class.forName("java.awt.Rectangle"), AwtCodec.instance); + derializers.put(Class.forName("java.awt.Color"), AwtCodec.instance); + } catch (Throwable e) { + // skip + awtError = true; + } + + derializer = AwtCodec.instance; + } + } + + if (!jdk8Error) { + try { + if (className.startsWith("java.time.")) { + + derializers.put(Class.forName("java.time.LocalDateTime"), Jdk8DateCodec.instance); + derializers.put(Class.forName("java.time.LocalDate"), Jdk8DateCodec.instance); + derializers.put(Class.forName("java.time.LocalTime"), Jdk8DateCodec.instance); + derializers.put(Class.forName("java.time.ZonedDateTime"), Jdk8DateCodec.instance); + derializers.put(Class.forName("java.time.OffsetDateTime"), Jdk8DateCodec.instance); + derializers.put(Class.forName("java.time.OffsetTime"), Jdk8DateCodec.instance); + derializers.put(Class.forName("java.time.ZoneOffset"), Jdk8DateCodec.instance); + derializers.put(Class.forName("java.time.ZoneRegion"), Jdk8DateCodec.instance); + derializers.put(Class.forName("java.time.ZoneId"), Jdk8DateCodec.instance); + derializers.put(Class.forName("java.time.Period"), Jdk8DateCodec.instance); + derializers.put(Class.forName("java.time.Duration"), Jdk8DateCodec.instance); + derializers.put(Class.forName("java.time.Instant"), Jdk8DateCodec.instance); + + derializer = derializers.get(clazz); + } else if (className.startsWith("java.util.Optional")) { + + derializers.put(Class.forName("java.util.Optional"), OptionalCodec.instance); + derializers.put(Class.forName("java.util.OptionalDouble"), OptionalCodec.instance); + derializers.put(Class.forName("java.util.OptionalInt"), OptionalCodec.instance); + derializers.put(Class.forName("java.util.OptionalLong"), OptionalCodec.instance); + + derializer = derializers.get(clazz); + } + } catch (Throwable e) { + // skip + jdk8Error = true; + } + } + + if (className.equals("java.nio.file.Path")) { + derializers.put(clazz, MiscCodec.instance); + } + + final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + try { + for (AutowiredObjectDeserializer autowired : ServiceLoader.load(AutowiredObjectDeserializer.class, + classLoader)) { + for (Type forType : autowired.getAutowiredFor()) { + derializers.put(forType, autowired); + } + } + } catch (Exception ex) { + // skip + } + + if (derializer == null) { + derializer = derializers.get(type); + } + + if (derializer != null) { + return derializer; + } + + if (clazz.isEnum()) { + derializer = new EnumDeserializer(clazz); + } else if (clazz.isArray()) { + derializer = ObjectArrayCodec.instance; + } else if (clazz == Set.class || clazz == HashSet.class || clazz == Collection.class || clazz == List.class + || clazz == ArrayList.class) { + derializer = CollectionCodec.instance; + } else if (Collection.class.isAssignableFrom(clazz)) { + derializer = CollectionCodec.instance; + } else if (Map.class.isAssignableFrom(clazz)) { + derializer = MapDeserializer.instance; + } else if (Throwable.class.isAssignableFrom(clazz)) { + derializer = new ThrowableDeserializer(this, clazz); + } else { + derializer = createJavaBeanDeserializer(clazz, type); + } + + putDeserializer(type, derializer); + + return derializer; + } + +} diff --git a/src/test/java/com/alibaba/fastjson/serializer/SerializeWriterTest.java b/src/test/java/com/alibaba/fastjson/serializer/SerializeWriterTest.java new file mode 100644 index 0000000000..05fe403343 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/serializer/SerializeWriterTest.java @@ -0,0 +1,83 @@ +package com.alibaba.fastjson.serializer; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.util.logging.Logger; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.util.IOUtils; + +public class SerializeWriterTest { + + private final Logger logger = Logger.getLogger(SerializeWriterTest.class.getSimpleName()); + + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + private final SerializeWriter writer = new SerializeWriter(new OutputStreamWriter(baos)); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testWriteLiteBasicStr() throws UnsupportedEncodingException { + String targetStr = new String(IOUtils.DIGITS); + this.doTestWrite(targetStr); + } + + private String doTestWrite(String input) throws UnsupportedEncodingException { + writer.writeString(input, (char) 0); + writer.flush(); + String result = this.baos.toString("UTF-8"); + + Assert.assertEquals(input, JSON.parse(result)); + + logger.info(result); + + return result; + } + + @Test + public void testWriteLiteSpecilaStr() throws UnsupportedEncodingException { + this.doTestWrite(this.makeSpecialChars()); + } + + private String makeSpecialChars() { + StringBuilder strBuilder = new StringBuilder(128); + for (char c = 128; c <= 160; c++) { + strBuilder.append(c); + } + return strBuilder.toString(); + } + + @Test + public void testWriteLargeBasicStr() throws UnsupportedEncodingException { + String tmp = new String(IOUtils.DIGITS); + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < 200; i++) { + builder.append(tmp); + } + this.doTestWrite(builder.toString()); + } + + @Test + public void testWriteLargeSpecialStr() throws UnsupportedEncodingException { + + String tmp = this.makeSpecialChars(); + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < 200; i++) { + builder.append(tmp); + } + this.doTestWrite(builder.toString()); + } +} diff --git a/src/test/java/com/alibaba/fastjson/serializer/TestBean.java b/src/test/java/com/alibaba/fastjson/serializer/TestBean.java new file mode 100644 index 0000000000..a369c5f509 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/serializer/TestBean.java @@ -0,0 +1,28 @@ +package com.alibaba.fastjson.serializer; + +import com.alibaba.fastjson.JSONObject; + +/** + * java bean for test + * Created by yixian on 2016-02-25. + */ +class TestBean { + private JSONObject data; + private String name; + + public JSONObject getData() { + return data; + } + + public void setData(JSONObject data) { + this.data = data; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/src/test/java/com/alibaba/fastjson/serializer/TestParse.java b/src/test/java/com/alibaba/fastjson/serializer/TestParse.java new file mode 100644 index 0000000000..e805dd0976 --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/serializer/TestParse.java @@ -0,0 +1,37 @@ +package com.alibaba.fastjson.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.junit.Before; +import org.junit.Test; + +import java.util.logging.Logger; + +/** + * test parse json contains jsonobject in javabean + * Created by yixian on 2016-02-25. + */ +public class TestParse { + private final Logger logger = Logger.getLogger(TestParse.class.getSimpleName()); + + private String jsonString; + + @Before + public void prepareJsonString() { + TestBean bean = new TestBean(); + bean.setName("tester"); + JSONObject data = new JSONObject(); + data.put("key", "value"); + bean.setData(data); + jsonString = JSON.toJSONString(bean, SerializerFeature.WriteClassName); + } + + @Test + public void testParse() { + logger.info("parsing json string:" + jsonString); + TestBean testBean = (TestBean) JSON.parse(jsonString); + assert testBean.getData() != null; + assert "tester".equals(testBean.getName()); + assert "value".equals(testBean.getData().getString("key")); + } +} diff --git a/src/test/java/com/alibaba/fastjson/support/jaxrs/TestIssue885.java b/src/test/java/com/alibaba/fastjson/support/jaxrs/TestIssue885.java new file mode 100644 index 0000000000..62b430ddea --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/support/jaxrs/TestIssue885.java @@ -0,0 +1,79 @@ +package com.alibaba.fastjson.support.jaxrs; + + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.Test; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.core.Application; +import java.util.Date; + +import static org.junit.Assert.*; + +public class TestIssue885 extends JerseyTest { + + @Path("user") + public static class UserResource { + @GET + public User getUser() { + User user = new User(); + user.setId(12345L); + user.setName("smallnest"); + user.setCreatedOn(new Date()); + return user; + } + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(new FastJsonFeature()).register(FastJsonProvider.class); + } + + @Override + protected Application configure() { + enable(TestProperties.LOG_TRAFFIC); + enable(TestProperties.DUMP_ENTITY); + + ResourceConfig config = new ResourceConfig(); + //config.register(new FastJsonFeature()).register(FastJsonProvider.class); + config.register(new FastJsonFeature()).register(new FastJsonProvider().setPretty(true)); + config.packages("com.alibaba.fastjson"); + return config; + } + + @Test + public void testWriteTo() { + final String user = target("user").request().accept("application/json").get(String.class); + // {"createdOn":1412036891919,"id":12345,"name":"smallnest"}] + assertTrue(user.indexOf("createdOn") > 0); + assertTrue(user.indexOf("\"id\":12345") > 0); + assertTrue(user.indexOf("\"name\":\"smallnest\"") > 0); + } + + @Test + public void testWriteToWithPretty() { + //System.out.println("@@@@@Test Pretty"); + final String user = target("user").queryParam("pretty", "true").request().accept("application/json").get(String.class); + // {"createdOn":1412036891919,"id":12345,"name":"smallnest"}] + assertTrue(user.indexOf("createdOn") > 0); + assertTrue(user.indexOf("\"id\":12345") > 0); + assertTrue(user.indexOf("\"name\":\"smallnest\"") > 0); + //response does not contain a return character + //assertTrue(user.indexOf("\n\t") > 0); + + } + + @Test + public void testReadFrom() { + final User user = target("user").request().accept("application/json").get(User.class); + assertNotNull(user); + assertNotNull(user.getCreatedOn()); + assertEquals(user.getId().longValue(), 12345L); + assertEquals(user.getName(), "smallnest"); + } + +} diff --git a/src/test/java/com/alibaba/fastjson/support/jaxrs/User.java b/src/test/java/com/alibaba/fastjson/support/jaxrs/User.java new file mode 100644 index 0000000000..e82dadba3e --- /dev/null +++ b/src/test/java/com/alibaba/fastjson/support/jaxrs/User.java @@ -0,0 +1,38 @@ +package com.alibaba.fastjson.support.jaxrs; + +import com.alibaba.fastjson.annotation.JSONType; + +import java.util.Date; + +@JSONType +public class User { + + private Long id; + private String name; + private Date createdOn; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getCreatedOn() { + return createdOn; + } + + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } + +} \ No newline at end of file diff --git a/src/test/java/com/alibaba/json/ArrayRefTest2.java b/src/test/java/com/alibaba/json/ArrayRefTest2.java new file mode 100755 index 0000000000..45be1a77f7 --- /dev/null +++ b/src/test/java/com/alibaba/json/ArrayRefTest2.java @@ -0,0 +1,78 @@ +package com.alibaba.json; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class ArrayRefTest2 extends TestCase { + + public void test_0() throws Exception { + String text; + { + List groups = new ArrayList(); + + Group g0 = new Group(0); + Group g1 = new Group(1); + Group g2 = new Group(2); + + groups.add(g0); + groups.add(g1); + groups.add(g2); + groups.add(g0); + groups.add(g1); + groups.add(g2); + + text = JSON.toJSONString(groups); + } + + System.out.println(text); + + Group[] groups = JSON.parseObject(text, new TypeReference() {}); + Assert.assertEquals(6, groups.length); + + Assert.assertNotNull(groups[0]); + Assert.assertNotNull(groups[1]); + Assert.assertNotNull(groups[2]); + Assert.assertNotNull(groups[3]); + Assert.assertNotNull(groups[4]); + Assert.assertNotNull(groups[5]); + + Assert.assertEquals(0, groups[0].getId()); + Assert.assertEquals(1, groups[1].getId()); + Assert.assertEquals(2, groups[2].getId()); + Assert.assertEquals(0, groups[3].getId()); + Assert.assertEquals(1, groups[4].getId()); + Assert.assertEquals(2, groups[5].getId()); + } + + public static class Group { + + private int id; + + public Group(){ + + } + + public Group(int id){ + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String toString() { + return "{id:" + id + "}"; + } + + } +} diff --git a/src/test/java/com/alibaba/json/SerializerFeatureDistinctTest.java b/src/test/java/com/alibaba/json/SerializerFeatureDistinctTest.java new file mode 100644 index 0000000000..499998b0e8 --- /dev/null +++ b/src/test/java/com/alibaba/json/SerializerFeatureDistinctTest.java @@ -0,0 +1,24 @@ +package com.alibaba.json; + +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.HashSet; +import java.util.Set; + +/** + * Created by wenshao on 24/06/2017. + */ +public class SerializerFeatureDistinctTest extends TestCase { + public void test_allfeatures() throws Exception { + Set masks = new HashSet(); + for (SerializerFeature feature : SerializerFeature.values()) { + Object mask = feature.getMask(); + assertFalse(masks.contains(mask)); + masks.add(mask); + } + assertEquals(masks.size(), SerializerFeature.values().length); + + System.out.println(SerializerFeature.values().length); + } +} diff --git a/src/test/java/com/alibaba/json/TestGC.java b/src/test/java/com/alibaba/json/TestGC.java new file mode 100755 index 0000000000..44268377a8 --- /dev/null +++ b/src/test/java/com/alibaba/json/TestGC.java @@ -0,0 +1,14 @@ +package com.alibaba.json; + +import junit.framework.TestCase; + + +public class TestGC extends TestCase { + public void test_0 () throws Exception { + for (int i = 0; i < 1000 * 1000; ++i) { + StringBuilder buf = new StringBuilder(1000 * 1000 * 10); + buf.append(i); + Thread.sleep(10); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/AnnotationTest.java b/src/test/java/com/alibaba/json/bvt/AnnotationTest.java new file mode 100755 index 0000000000..4dd3eeddf2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/AnnotationTest.java @@ -0,0 +1,61 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class AnnotationTest extends TestCase { + + public void test_codec() throws Exception { + User user = new User(); + user.setId(1001); + user.setName("bob.panl"); + user.setDescrition("大黄牛"); + + String text = JSON.toJSONString(user); + System.out.println(text); + + User user1 = JSON.parseObject(text, User.class); + + Assert.assertEquals(user1.getId(), user.getId()); + Assert.assertEquals(user1.getName(), user.getName()); + } + + public static class User { + + private int id; + private String name; + private String descrition; + + @JSONField(name = "ID") + public int getId() { + return id; + } + + @JSONField(name = "ID") + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @JSONField(name = "desc") + public String getDescrition() { + return descrition; + } + + @JSONField(name = "desc") + public void setDescrition(String descrition) { + this.descrition = descrition; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/AnnotationTest2.java b/src/test/java/com/alibaba/json/bvt/AnnotationTest2.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/AnnotationTest2.java rename to src/test/java/com/alibaba/json/bvt/AnnotationTest2.java index b77d0a750f..c7415f5042 --- a/src/test/java/com/alibaba/json/test/bvt/AnnotationTest2.java +++ b/src/test/java/com/alibaba/json/bvt/AnnotationTest2.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/AnnotationTest3.java b/src/test/java/com/alibaba/json/bvt/AnnotationTest3.java new file mode 100755 index 0000000000..7c3140f14f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/AnnotationTest3.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class AnnotationTest3 extends TestCase { + + public void test_supperField() throws Exception { + C c = new C(); + c.setId(123); + c.setName("jobs"); + + String str = JSON.toJSONString(c); + Assert.assertEquals("{\"ID\":123,\"name\":\"jobs\"}", str); + } + + public static class S { + + @JSONField(name = "ID") + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } + + public static class C extends S { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/AppendableFieldTest.java b/src/test/java/com/alibaba/json/bvt/AppendableFieldTest.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/AppendableFieldTest.java rename to src/test/java/com/alibaba/json/bvt/AppendableFieldTest.java index 91883c4eb4..1d4679f432 --- a/src/test/java/com/alibaba/json/test/bvt/AppendableFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/AppendableFieldTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/ArmoryTest.java b/src/test/java/com/alibaba/json/bvt/ArmoryTest.java old mode 100644 new mode 100755 similarity index 76% rename from src/test/java/com/alibaba/json/test/bvt/ArmoryTest.java rename to src/test/java/com/alibaba/json/bvt/ArmoryTest.java index 9f7f0b3ed1..3f8387b5ed --- a/src/test/java/com/alibaba/json/test/bvt/ArmoryTest.java +++ b/src/test/java/com/alibaba/json/bvt/ArmoryTest.java @@ -1,25 +1,29 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.ArrayList; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; public class ArmoryTest extends TestCase { + + public void test_item() throws Exception { + Item item = new Item(); + String text = JSON.toJSONString(item, SerializerFeature.SortField, SerializerFeature.UseSingleQuotes); + Assert.assertEquals("{'id':0,'name':'xx'}", text); + } public void test_0() throws Exception { List message = new ArrayList(); - MessageHead head = new MessageHead(); - - MessageBody body = new MessageBody(); - body.getItems().add(new Item()); + Item item = new Item(); + body.getItems().add(item); - message.add(head); + message.add(new MessageHead()); message.add(body); String text = JSON.toJSONString(message, SerializerFeature.SortField, SerializerFeature.UseSingleQuotes); diff --git a/src/test/java/com/alibaba/json/bvt/ArrayListFieldTest.java b/src/test/java/com/alibaba/json/bvt/ArrayListFieldTest.java new file mode 100755 index 0000000000..638de152c2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ArrayListFieldTest.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt; + +import java.util.ArrayList; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class ArrayListFieldTest extends TestCase { + public void test_codec_null() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"value\":null}", text); + + ParserConfig config = new ParserConfig(); + config.setAsmEnable(false); + + V0 v1 = JSON.parseObject(text, V0.class, config, JSON.DEFAULT_PARSER_FEATURE); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + private static class V0 { + + private ArrayList value; + + public ArrayList getValue() { + return value; + } + + public void setValue(ArrayList value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ArrayListFieldTest_1.java b/src/test/java/com/alibaba/json/bvt/ArrayListFieldTest_1.java new file mode 100644 index 0000000000..2378110217 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ArrayListFieldTest_1.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt; + +import java.util.ArrayList; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class ArrayListFieldTest_1 extends TestCase { + + public void test_var() throws Exception { + JSON.parseObject("{\"value\":[{}]}", V0.class); + V0 v1 = JSON.parseObject("{\"value\":[{}]}", new TypeReference>() { + }); + Assert.assertTrue(v1.getValue().get(0) instanceof A); + + V0 v2 = JSON.parseObject("{\"value\":[{}]}", new TypeReference>() { + }); + Assert.assertTrue(v2.getValue().get(0) instanceof B); + } + + private static class V { + + } + + private static class V0 extends V { + + private ArrayList value; + + public ArrayList getValue() { + return value; + } + + public void setValue(ArrayList value) { + this.value = value; + } + } + + public static class A { + + } + + public static class B { + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/ArrayListFloatFieldTest.java b/src/test/java/com/alibaba/json/bvt/ArrayListFloatFieldTest.java old mode 100644 new mode 100755 similarity index 77% rename from src/test/java/com/alibaba/json/test/bvt/ArrayListFloatFieldTest.java rename to src/test/java/com/alibaba/json/bvt/ArrayListFloatFieldTest.java index cd5a9300ab..6897f63edb --- a/src/test/java/com/alibaba/json/test/bvt/ArrayListFloatFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/ArrayListFloatFieldTest.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.ArrayList; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -20,12 +20,16 @@ public void test_codec() throws Exception { User user1 = JSON.parseObject(text, User.class); - Assert.assertEquals(user1.getValue(), user.getValue()); + Assert.assertEquals(user.getValue(), user1.getValue()); } public static class User { private ArrayList value; + + public User() { + + } public List getValue() { return value; diff --git a/src/test/java/com/alibaba/json/bvt/ArrayRefTest.java b/src/test/java/com/alibaba/json/bvt/ArrayRefTest.java new file mode 100755 index 0000000000..d296713e07 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ArrayRefTest.java @@ -0,0 +1,71 @@ +package com.alibaba.json.bvt; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class ArrayRefTest extends TestCase { + + public void test_0() throws Exception { + String text; + { + List groups = new ArrayList(); + + Group g0 = new Group(0); + Group g1 = new Group(1); + Group g2 = new Group(2); + + groups.add(g0); + groups.add(g1); + groups.add(g2); + groups.add(g0); + groups.add(g1); + groups.add(g2); + + text = JSON.toJSONString(groups); + } + + System.out.println(text); + + List groups = JSON.parseObject(text, new TypeReference>() {}); + Assert.assertEquals(6, groups.size()); + + Assert.assertEquals(0, groups.get(0).getId()); + Assert.assertEquals(1, groups.get(1).getId()); + Assert.assertEquals(2, groups.get(2).getId()); + Assert.assertEquals(0, groups.get(3).getId()); + Assert.assertEquals(1, groups.get(4).getId()); + Assert.assertEquals(2, groups.get(5).getId()); + } + + public static class Group { + + private int id; + + public Group(){ + + } + + public Group(int id){ + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String toString() { + return "{id:" + id + "}"; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/Base64Test.java b/src/test/java/com/alibaba/json/bvt/Base64Test.java new file mode 100755 index 0000000000..a4ee32a822 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/Base64Test.java @@ -0,0 +1,15 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.util.IOUtils; + +import junit.framework.TestCase; + + +public class Base64Test extends TestCase { + public void test_base64() throws Exception { + Assert.assertEquals(IOUtils.decodeBase64(new char[0], 0, 0).length, 0); + Assert.assertEquals(IOUtils.decodeBase64("ABC".toCharArray(), 0, 3).length, 2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/Base64Test2.java b/src/test/java/com/alibaba/json/bvt/Base64Test2.java new file mode 100644 index 0000000000..2e972d507a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/Base64Test2.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.util.IOUtils; + +import junit.framework.TestCase; + +public class Base64Test2 extends TestCase { + + public void test_base64_2() throws Exception { + String text = ""; + for (int i = 0; i < 1000; ++i) { + byte[] bytes = text.getBytes("UTF-8"); + { + String str = com.alibaba.json.test.Base64.encodeToString(bytes, true); + Assert.assertEquals(text, new String(IOUtils.decodeBase64(str.toCharArray(), 0, str.length()), "UTF-8")); + Assert.assertEquals(text, new String(IOUtils.decodeBase64(str), "UTF-8")); + Assert.assertEquals(text, new String(IOUtils.decodeBase64(str, 0, str.length()), "UTF-8")); + } + { + String str = com.alibaba.json.test.Base64.encodeToString(bytes, false); + Assert.assertEquals(text, new String(IOUtils.decodeBase64(str.toCharArray(), 0, str.length()), "UTF-8")); + Assert.assertEquals(text, new String(IOUtils.decodeBase64(str), "UTF-8")); + Assert.assertEquals(text, new String(IOUtils.decodeBase64(str, 0, str.length()), "UTF-8")); + } + text += ((char) i); + + } + } + + public void test_illegal() throws Exception { + String text = "abc"; + byte[] bytes = text.getBytes("UTF-8"); + String str = "\0" + com.alibaba.json.test.Base64.encodeToString(bytes, false) + "\0"; + Assert.assertEquals(text, new String(IOUtils.decodeBase64(str.toCharArray(), 0, str.length()), "UTF-8")); + Assert.assertEquals(text, new String(IOUtils.decodeBase64(str), "UTF-8")); + Assert.assertEquals(text, new String(IOUtils.decodeBase64(str, 0, str.length()), "UTF-8")); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/BigDecimalFieldTest.java b/src/test/java/com/alibaba/json/bvt/BigDecimalFieldTest.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/BigDecimalFieldTest.java rename to src/test/java/com/alibaba/json/bvt/BigDecimalFieldTest.java index ca1b95d4a2..d57eadae41 --- a/src/test/java/com/alibaba/json/test/bvt/BigDecimalFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/BigDecimalFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.math.BigDecimal; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/BigIntegerFieldTest.java b/src/test/java/com/alibaba/json/bvt/BigIntegerFieldTest.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/BigIntegerFieldTest.java rename to src/test/java/com/alibaba/json/bvt/BigIntegerFieldTest.java index 76e157fc83..01fb2b24a1 --- a/src/test/java/com/alibaba/json/test/bvt/BigIntegerFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/BigIntegerFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.math.BigInteger; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/BooleanArrayFieldTest.java b/src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/BooleanArrayFieldTest.java rename to src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest.java index e1ef66b488..e133a2a13e --- a/src/test/java/com/alibaba/json/test/bvt/BooleanArrayFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/BooleanArrayFieldTest_primitive.java b/src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest_primitive.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/BooleanArrayFieldTest_primitive.java rename to src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest_primitive.java index acf54e0f14..448f2e73be --- a/src/test/java/com/alibaba/json/test/bvt/BooleanArrayFieldTest_primitive.java +++ b/src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest_primitive.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest_primitive_private.java b/src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest_primitive_private.java new file mode 100644 index 0000000000..bb09e7dfd6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest_primitive_private.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class BooleanArrayFieldTest_primitive_private extends TestCase { + + public void test_array() throws Exception { + Assert.assertEquals("[true]", JSON.toJSONString(new boolean[] { true })); + + } + + public void test_codec_null() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"value\":null}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_codec_null_1() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty); + Assert.assertEquals("{\"value\":[]}", text); + } + + private static class V0 { + + private boolean[] value; + + public boolean[] getValue() { + return value; + } + + public void setValue(boolean[] value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/Bug12.java b/src/test/java/com/alibaba/json/bvt/Bug12.java new file mode 100644 index 0000000000..553e66df57 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/Bug12.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt; + +import java.io.InputStream; +import java.io.InputStreamReader; + +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class Bug12 extends TestCase { + + public void test_0() throws Exception { + String resource = "2.json"; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); + String text = IOUtils.toString(new InputStreamReader(is, "UTF-8")); + is.close(); + + Object obj = JSON.parse(text); + Assert.assertNotNull(obj); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/Bug89.java b/src/test/java/com/alibaba/json/bvt/Bug89.java new file mode 100644 index 0000000000..e73346de3d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/Bug89.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import org.junit.Test; + +import static org.junit.Assert.fail; + +public class Bug89 { + @Test + public void testBug89() { + try { + String s = "{\"a\":з」∠)_,\"}"; + JSON.parseObject(s); + fail("Expect JSONException"); + } catch (JSONException e) { + // good + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/BuilderTest.java b/src/test/java/com/alibaba/json/bvt/BuilderTest.java new file mode 100755 index 0000000000..4ba83dcdf3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/BuilderTest.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class BuilderTest extends TestCase { + public void test_builder() throws Exception { + RainbowStats rainbowStats = JSON.parseObject("{\"id\":33}", RainbowStats.class); + Assert.assertEquals(33, rainbowStats.getId()); + } + + private static class RainbowStats { + private int id; + private String name; + + public int getId() { + return id; + } + + public RainbowStats setId(int id) { + this.id = id; + return this; + } + + public String getName() { + return name; + } + + public RainbowStats setName(String name) { + this.name = name; + return this; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_1.java b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_1.java new file mode 100755 index 0000000000..efd64ec38e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_1.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class ByteArrayFieldTest_1 extends TestCase { + + public void test_array() throws Exception { + Assert.assertEquals("\"AQ==\"", JSON.toJSONString(new byte[] { 1 })); + + } + + public void test_codec_null() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"value\":null}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_codec_null_1() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty); + Assert.assertEquals("{\"value\":[]}", text); + } + + public static class V0 { + + private byte[] value; + + public byte[] getValue() { + return value; + } + + public void setValue(byte[] value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_2.java b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_2.java new file mode 100755 index 0000000000..dd81f96e0a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_2.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt; + +import java.io.UnsupportedEncodingException; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.json.test.TestUtils; + +public class ByteArrayFieldTest_2 extends TestCase { + + public void test_0() throws Exception { + Entity entity = new Entity("中华人民共和国"); + String text = JSON.toJSONString(entity); + JSONObject json = JSON.parseObject(text); + Assert.assertEquals(TestUtils.encodeToBase64String(entity.getValue(), false), json.getString("value")); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals("中华人民共和国", new String(entity2.getValue(), "UTF-8")); + } + + public static class Entity { + + private byte[] value; + + public Entity(){ + + } + + public Entity(String value) throws UnsupportedEncodingException{ + this.value = value.getBytes("UTF-8"); + } + + public byte[] getValue() { + return value; + } + + public void setValue(byte[] value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_3.java b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_3.java new file mode 100755 index 0000000000..b47179fb7a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_3.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt; + +import java.io.UnsupportedEncodingException; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.json.test.TestUtils; + +public class ByteArrayFieldTest_3 extends TestCase { + + public void test_0() throws Exception { + Entity entity = new Entity("中华人民共和国"); + String text = JSON.toJSONString(entity); + JSONObject json = JSON.parseObject(text); + Assert.assertEquals(TestUtils.encodeToBase64String(entity.getValue(), false), json.getString("value")); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals("中华人民共和国", new String(entity2.getValue(), "UTF-8")); + } + + private static class Entity { + + private byte[] value; + + public Entity(){ + + } + + public Entity(String value) throws UnsupportedEncodingException{ + this.value = value.getBytes("UTF-8"); + } + + public byte[] getValue() { + return value; + } + + public void setValue(byte[] value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_4.java b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_4.java new file mode 100755 index 0000000000..2137746bff --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_4.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.json.test.TestUtils; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.io.UnsupportedEncodingException; + +public class ByteArrayFieldTest_4 extends TestCase { + + public void test_0() throws Exception { + Model model = new Model(); + + model.value = "ABCDEG".getBytes(); + + String json = JSON.toJSONString(model); + + assertEquals("{\"value\":x'414243444547'}", json); + + Model model1 = JSON.parseObject(json, Model.class); + Assert.assertArrayEquals(model.value, model1.value); + + } + + private static class Model { + + @JSONField(format = "hex") + public byte[] value; + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_5_base64.java b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_5_base64.java new file mode 100755 index 0000000000..7b1e333db0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_5_base64.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class ByteArrayFieldTest_5_base64 extends TestCase { + + public void test_0() throws Exception { + Model model = new Model(); + + model.value = "ABCDEG".getBytes(); + + String json = JSON.toJSONString(model); + + assertEquals("{\"value\":\"QUJDREVH\"}", json); + + Model model1 = JSON.parseObject(json, Model.class); + Assert.assertArrayEquals(model.value, model1.value); + } + + private static class Model { + + @JSONField(format = "base64") + public byte[] value; + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_6_gzip.java b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_6_gzip.java new file mode 100755 index 0000000000..de7fb9871f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_6_gzip.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class ByteArrayFieldTest_6_gzip extends TestCase { + + public void test_0() throws Exception { + Model model = new Model(); + + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < 1000; ++i) { + buf.append("0123456890"); + buf.append("ABCDEFGHIJ"); + } + + model.value = buf.toString().getBytes(); + + String json = JSON.toJSONString(model); + + assertEquals("{\"value\":\"H4sIAAAAAAAAAO3IsRGAIBAAsJVeUE5LBBXcfyC3sErKxJLyupX9iHq2ft3PmG8455xzzjnnnHPOOeecc84555xzzjnnnHPOOeecc84555xzzjnnnHPOOeecc84555z7/T6powiAIE4AAA==\"}", json); + + Model model1 = JSON.parseObject(json, Model.class); + Assert.assertArrayEquals(model.value, model1.value); + } + + public static class Model { + @JSONField(format = "gzip") + public byte[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_7_gzip_hex.java b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_7_gzip_hex.java new file mode 100755 index 0000000000..864ef36487 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_7_gzip_hex.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class ByteArrayFieldTest_7_gzip_hex extends TestCase { + + public void test_0() throws Exception { + Model model = new Model(); + + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < 1000; ++i) { + buf.append("0123456890"); + buf.append("ABCDEFGHIJ"); + } + + model.value = buf.toString().getBytes(); + + String json = JSON.toJSONString(model); + + assertEquals("{\"value\":\"H4sIAAAAAAAAAO3IsRGAIBAAsJVeUE5LBBXcfyC3sErKxJLyupX9iHq2ft3PmG8455xzzjnnnHPOOeecc84555xzzjnnnHPOOeecc84555xzzjnnnHPOOeecc84555z7/T6powiAIE4AAA==\"}", json); + + Model model1 = JSON.parseObject(json, Model.class); + Assert.assertArrayEquals(model.value, model1.value); + } + + private static class Model { + + @JSONField(format = "gzip,base64") + public byte[] value; + + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/ByteFieldTest.java b/src/test/java/com/alibaba/json/bvt/ByteFieldTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/ByteFieldTest.java rename to src/test/java/com/alibaba/json/bvt/ByteFieldTest.java index 04b06e0345..f8e24e94c5 --- a/src/test/java/com/alibaba/json/test/bvt/ByteFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/ByteFieldTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/CastTest.java b/src/test/java/com/alibaba/json/bvt/CastTest.java old mode 100644 new mode 100755 similarity index 84% rename from src/test/java/com/alibaba/json/test/bvt/CastTest.java rename to src/test/java/com/alibaba/json/bvt/CastTest.java index 485d55b06b..08064e3340 --- a/src/test/java/com/alibaba/json/test/bvt/CastTest.java +++ b/src/test/java/com/alibaba/json/bvt/CastTest.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.ArrayList; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -30,10 +30,10 @@ public void test_0() throws Exception { JSONArray array = JSON.parseArray(text); - Body body = array.getObject(1, Body.class); - Assert.assertEquals(1, body.getItems().size()); +// Body body = array.getObject(1, Body.class); +// Assert.assertEquals(1, body.getItems().size()); - Assert.assertEquals("张三", body.getName()); +// Assert.assertEquals("张三", body.getName()); } public static class Header { diff --git a/src/test/java/com/alibaba/json/test/bvt/CastTest2.java b/src/test/java/com/alibaba/json/bvt/CastTest2.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/CastTest2.java rename to src/test/java/com/alibaba/json/bvt/CastTest2.java index 2533edd2e6..43e42e6f27 --- a/src/test/java/com/alibaba/json/test/bvt/CastTest2.java +++ b/src/test/java/com/alibaba/json/bvt/CastTest2.java @@ -1,11 +1,11 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/CharTypesTest.java b/src/test/java/com/alibaba/json/bvt/CharTypesTest.java new file mode 100755 index 0000000000..00d8d3fad0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/CharTypesTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.util.IOUtils; + +public class CharTypesTest extends TestCase { + static byte[] specicalFlags_singleQuotes = IOUtils.specicalFlags_singleQuotes; + static byte[] specicalFlags_doubleQuotes = IOUtils.specicalFlags_doubleQuotes; + + public void test_0() throws Exception { + + Assert.assertTrue(isSpecial_doubleQuotes('\n')); + Assert.assertTrue(isSpecial_doubleQuotes('\r')); + Assert.assertTrue(isSpecial_doubleQuotes('\b')); + Assert.assertTrue(isSpecial_doubleQuotes('\f')); + Assert.assertTrue(isSpecial_doubleQuotes('\"')); + Assert.assertFalse(isSpecial_doubleQuotes('0')); + Assert.assertTrue(isSpecial_doubleQuotes('\0')); + Assert.assertFalse(isSpecial_doubleQuotes('中')); + Assert.assertFalse(isSpecial_doubleQuotes('中')); + } + + public static boolean isSpecial_doubleQuotes(char ch) { + return ch < specicalFlags_doubleQuotes.length && specicalFlags_doubleQuotes[ch] != 0; + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/CharsetFieldTest.java b/src/test/java/com/alibaba/json/bvt/CharsetFieldTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/CharsetFieldTest.java rename to src/test/java/com/alibaba/json/bvt/CharsetFieldTest.java index 9c3ef6e54d..b190b06667 --- a/src/test/java/com/alibaba/json/test/bvt/CharsetFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/CharsetFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.nio.charset.Charset; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/ChineseSpaceTest.java b/src/test/java/com/alibaba/json/bvt/ChineseSpaceTest.java new file mode 100644 index 0000000000..b24a99f118 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ChineseSpaceTest.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by wenshao on 2016/10/14. + */ +public class ChineseSpaceTest extends TestCase { + public void test_for_chinese_space() throws Exception { + Map map = Collections.singletonMap("v", " "); + String json = JSON.toJSONString(map); + assertEquals("{\"v\":\" \"}", json); + + JSONObject jsonObject = JSON.parseObject(json); + assertEquals(map.get("v"), jsonObject.get("v")); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/CircularReferenceTest.java b/src/test/java/com/alibaba/json/bvt/CircularReferenceTest.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/CircularReferenceTest.java rename to src/test/java/com/alibaba/json/bvt/CircularReferenceTest.java index 49b76c2d18..fcb050c342 --- a/src/test/java/com/alibaba/json/test/bvt/CircularReferenceTest.java +++ b/src/test/java/com/alibaba/json/bvt/CircularReferenceTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; diff --git a/src/test/java/com/alibaba/json/bvt/ClassFieldTest.java b/src/test/java/com/alibaba/json/bvt/ClassFieldTest.java new file mode 100755 index 0000000000..09eb244600 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ClassFieldTest.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.util.ASMClassLoader; + +public class ClassFieldTest extends TestCase { + + public void test_codec() throws Exception { + User user = new User(); + user.setValue(Object.class); + + String text = JSON.toJSONString(user); + + User user1 = JSON.parseObject(text, User.class); + + Assert.assertEquals(user1.getValue(), user.getValue()); + } + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":123}", User.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class User { + + private Class value; + + public Class getValue() { + return value; + } + + public void setValue(Class value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/CurrencyTest.java b/src/test/java/com/alibaba/json/bvt/CurrencyTest.java new file mode 100644 index 0000000000..1146641391 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/CurrencyTest.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt; + +import java.util.Currency; +import java.util.Locale; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class CurrencyTest extends TestCase { + + public void test_0() throws Exception { + VO vo = new VO(); + vo.setValue(Currency.getInstance(Locale.CHINA)); + String text = JSON.toJSONString(vo); + System.out.println(text); + JSON.parseObject(text, VO.class); + } + + public static class VO { + + private Currency value; + + public Currency getValue() { + return value; + } + + public void setValue(Currency value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/CurrencyTest3.java b/src/test/java/com/alibaba/json/bvt/CurrencyTest3.java new file mode 100644 index 0000000000..7ea4bc8043 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/CurrencyTest3.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt; + +import java.math.BigDecimal; +import java.util.Currency; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + + +public class CurrencyTest3 extends TestCase { + public static class Money { + public Currency currency; + public BigDecimal amount; + + @Override + public String toString() { + return "Money{currency=" + currency + ", amount=" + amount + '}'; + } + } + + public void testJson() throws Exception { + Money money = new Money(); + money.currency = Currency.getInstance("CNY"); + money.amount = new BigDecimal("10.03"); + + String json = JSON.toJSONString(money); + System.out.println("json = " + json); + + Money moneyBack = JSON.parseObject(json, Money.class); + System.out.println("money = " + moneyBack); + + JSONObject jsonObject = JSON.parseObject(json); + Money moneyCast = JSON.toJavaObject(jsonObject, Money.class); + System.out.printf("money = " + moneyCast); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/CurrencyTest4.java b/src/test/java/com/alibaba/json/bvt/CurrencyTest4.java new file mode 100644 index 0000000000..f174d4396e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/CurrencyTest4.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import junit.framework.TestCase; + +import java.util.Currency; +import java.util.Locale; + +public class CurrencyTest4 extends TestCase { + + public void test_0() throws Exception { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("currency", "CNY"); + + String text = JSON.toJSONString(jsonObject); + + Currency currency = JSON.parseObject(text, Currency.class); + + assertSame(Currency.getInstance("CNY"), currency); + } + + public void test_1() throws Exception { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("currencyCode", "CNY"); + + String text = JSON.toJSONString(jsonObject); + + Currency currency = JSON.parseObject(text, Currency.class); + + assertSame(Currency.getInstance("CNY"), currency); + } + + public static class VO { + public Currency value; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/CurrencyTest5.java b/src/test/java/com/alibaba/json/bvt/CurrencyTest5.java new file mode 100644 index 0000000000..eeb70dbd7a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/CurrencyTest5.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializeConfig; +import junit.framework.TestCase; + +import java.util.Currency; + +public class CurrencyTest5 extends TestCase { + + public void test_0() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.put(Currency.class + , config.createJavaBeanSerializer(Currency.class)); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("value", Currency.getInstance("CNY")); + + String text = JSON.toJSONString(jsonObject, config); + System.out.println(text); + String str1 = "{\"value\":{\"currencyCode\":\"CNY\",\"displayName\":\"Chinese Yuan\",\"symbol\":\"CNY\"}}"; + String str2 = "{\"value\":{\"currencyCode\":\"CNY\",\"displayName\":\"人民币\",\"symbol\":\"¥\"}}"; + String str3 = "{\"value\":{\"currencyCode\":\"CNY\",\"displayName\":\"Chinese Yuan\",\"numericCodeAsString\":\"156\",\"symbol\":\"CN¥\"}}"; + assertTrue(text.equals(str1) + || text.equals(str2) + || text.equals(str3)); + + Currency currency = JSON.parseObject(text, VO.class).value; + + assertSame(Currency.getInstance("CNY"), currency); + } + + public static class VO { + public Currency value; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/CurrencyTest_2.java b/src/test/java/com/alibaba/json/bvt/CurrencyTest_2.java new file mode 100644 index 0000000000..318ebf02c7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/CurrencyTest_2.java @@ -0,0 +1,43 @@ +package com.alibaba.json.bvt; + +import java.util.Currency; +import java.util.Locale; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class CurrencyTest_2 extends TestCase { + + public void test_0() throws Exception { + VO vo = new VO(); + vo.setValue(Currency.getInstance(Locale.CHINA)); + vo.setValue1(Currency.getInstance(Locale.CHINA)); + String text = JSON.toJSONString(vo); + System.out.println(text); + JSON.parseObject(text, VO.class); + } + + public static class VO { + + private Currency value; + private Currency value1; + + public Currency getValue() { + return value; + } + + public void setValue(Currency value) { + this.value = value; + } + + public Currency getValue1() { + return value1; + } + + public void setValue1(Currency value1) { + this.value1 = value1; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/DefaultJSONParserTest.java b/src/test/java/com/alibaba/json/bvt/DefaultJSONParserTest.java old mode 100644 new mode 100755 similarity index 83% rename from src/test/java/com/alibaba/json/test/bvt/DefaultJSONParserTest.java rename to src/test/java/com/alibaba/json/bvt/DefaultJSONParserTest.java index abc5d8eaa8..6c79b96112 --- a/src/test/java/com/alibaba/json/test/bvt/DefaultJSONParserTest.java +++ b/src/test/java/com/alibaba/json/bvt/DefaultJSONParserTest.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.HashMap; +import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.DefaultJSONParser; @@ -34,6 +35,14 @@ public void test_double() { Assert.assertEquals(3.4D, result); } + public void test_double_in_object() { + DefaultJSONParser parser = new DefaultJSONParser("{\"double\":3.4}"); + parser.config(Feature.UseBigDecimal, false); + Assert.assertEquals("{\"double\":3.4}", parser.getInput()); + Object result = parser.parse(); + Assert.assertEquals(3.4D, ((Map) result).get("double")); + } + public void test_error() { Exception error = null; try { diff --git a/src/test/java/com/alibaba/json/bvt/DefaultJSONParserTest_ref.java b/src/test/java/com/alibaba/json/bvt/DefaultJSONParserTest_ref.java new file mode 100644 index 0000000000..66a24bffc4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/DefaultJSONParserTest_ref.java @@ -0,0 +1,34 @@ +/* + * Copyright 1999-2017 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.json.bvt; + +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class DefaultJSONParserTest_ref extends TestCase { + + public void test_ref() { + Map obj = JSON.parseObject("{\"id\":{},\"value\":{\"$ref\":\"$\"}}", Map.class); + Assert.assertTrue(obj == obj.get("value")); + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/DeprecatedClassTest.java b/src/test/java/com/alibaba/json/bvt/DeprecatedClassTest.java new file mode 100644 index 0000000000..f57bf61c7f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/DeprecatedClassTest.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.JSONSerializerMap; + +import junit.framework.TestCase; + +@SuppressWarnings("deprecation") +public class DeprecatedClassTest extends TestCase { + @SuppressWarnings("resource") + public void test_0() throws Exception { + new DefaultExtJSONParser(""); + new DefaultExtJSONParser("", ParserConfig.getGlobalInstance(), 1); + new DefaultExtJSONParser("".toCharArray(), 0, ParserConfig.getGlobalInstance(), 1); + } + + public void test_1() throws Exception { + new JSONSerializerMap().put(Object.class, null); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/DisableSpecialKeyDetectTest.java b/src/test/java/com/alibaba/json/bvt/DisableSpecialKeyDetectTest.java new file mode 100644 index 0000000000..99a5377155 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/DisableSpecialKeyDetectTest.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt; + +import java.util.Map; +import java.util.Set; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.parser.Feature; + +public class DisableSpecialKeyDetectTest extends TestCase { + + public void test_0() throws Exception { + String json = "{\"schema\":{\"$ref\":{\"@title\":\"类目ID\",\"@type\":\"string\"},\"$\":{\"@\":\"类目名称\",\"type\":\"string\"},\"cat_desc\":{\"title\":\"类目描述\",\"type\":\"string\"}}}"; + JSONObject errorJson = JSON.parseObject(json, Feature.DisableSpecialKeyDetect); + JSONObject schema = errorJson.getJSONObject("schema"); + Set> es2 = schema.entrySet(); + for (Map.Entry entry : es2) { + System.out.println(entry.getKey() + "_" + entry.getValue()); + } + } + + public void test_1() throws Exception { + String text = "{\"@v1\":\"v1\",\"@type\":\"v2\", \"@\":\"v3\",\"$\":\"v4\",\"$ref\":\"v5\"}"; + JSONObject json = JSON.parseObject(text, Feature.DisableSpecialKeyDetect); + Assert.assertEquals("v1", json.getString("@v1")); + Assert.assertEquals("v2", json.getString("@type")); + Assert.assertEquals("v3", json.getString("@")); + Assert.assertEquals("v4", json.getString("$")); + Assert.assertEquals("v5", json.getString("$ref")); + } + + public void test_2() throws Exception { + String text = "{\"@v1\":\"v1\",\"@type\":\"v2\", \"@\":\"v3\",\"$\":\"v4\",\"$ref\":\"v5\"}"; + Map map = JSON.parseObject(text, new TypeReference>(){}, Feature.DisableSpecialKeyDetect); + Assert.assertEquals("v1", map.get("@v1")); + Assert.assertEquals("v2", map.get("@type")); + Assert.assertEquals("v3", map.get("@")); + Assert.assertEquals("v4", map.get("$")); + Assert.assertEquals("v5", map.get("$ref")); + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/DoubleArrayFieldTest_primitive.java b/src/test/java/com/alibaba/json/bvt/DoubleArrayFieldTest_primitive.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/DoubleArrayFieldTest_primitive.java rename to src/test/java/com/alibaba/json/bvt/DoubleArrayFieldTest_primitive.java index eebe0d77b4..1171616a76 --- a/src/test/java/com/alibaba/json/test/bvt/DoubleArrayFieldTest_primitive.java +++ b/src/test/java/com/alibaba/json/bvt/DoubleArrayFieldTest_primitive.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/DoubleFieldTest_A.java b/src/test/java/com/alibaba/json/bvt/DoubleFieldTest_A.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/DoubleFieldTest_A.java rename to src/test/java/com/alibaba/json/bvt/DoubleFieldTest_A.java index 1dea8c1a99..48d55ecbca --- a/src/test/java/com/alibaba/json/test/bvt/DoubleFieldTest_A.java +++ b/src/test/java/com/alibaba/json/bvt/DoubleFieldTest_A.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/EmptyArrayAsNullTest.java b/src/test/java/com/alibaba/json/bvt/EmptyArrayAsNullTest.java new file mode 100644 index 0000000000..6ecbec7dd0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/EmptyArrayAsNullTest.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 2016/10/15. + */ +public class EmptyArrayAsNullTest extends TestCase { + + public void test_emtpyAsNull() throws Exception { + String text = "{\"value\":[]}"; + + Model model = JSON.parseObject(text, Model.class); + assertNull(model.value); + } + + public static class Model { + public Value value; + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/EmptyObjectTest.java b/src/test/java/com/alibaba/json/bvt/EmptyObjectTest.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/EmptyObjectTest.java rename to src/test/java/com/alibaba/json/bvt/EmptyObjectTest.java index 2d2942d4a7..9400ca98ae --- a/src/test/java/com/alibaba/json/test/bvt/EmptyObjectTest.java +++ b/src/test/java/com/alibaba/json/bvt/EmptyObjectTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/EnumFieldTest.java b/src/test/java/com/alibaba/json/bvt/EnumFieldTest.java new file mode 100644 index 0000000000..f8bfe79d84 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/EnumFieldTest.java @@ -0,0 +1,80 @@ +package com.alibaba.json.bvt; + +import java.io.StringReader; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class EnumFieldTest extends TestCase { + + public void test_special() throws Exception { + JSONReader read = new JSONReader(new StringReader("{\"value\":1}")); + Model model = read.readObject(Model.class); + Assert.assertEquals(Type.B, model.value); + read.close(); + } + + public void test_1() throws Exception { + JSONReader read = new JSONReader(new StringReader("{\"value\":\"A\",\"value1\":\"B\"}")); + Model model = read.readObject(Model.class); + Assert.assertEquals(Type.A, model.value); + Assert.assertEquals(Type.B, model.value1); + read.close(); + } + + public void test_map() throws Exception { + JSONReader read = new JSONReader(new StringReader("{\"model\":{\"value\":\"A\",\"value1\":\"B\"}}")); + Map map = read.readObject(new TypeReference>(){}); + Model model = (Model) map.get("model"); + Assert.assertEquals(Type.A, model.value); + Assert.assertEquals(Type.B, model.value1); + read.close(); + } + + public void test_error() throws Exception { + JSONReader read = new JSONReader(new StringReader("{\"value\":\"a\\b\"}")); + Model model = read.readObject(Model.class); + assertNull(model.value); + } + + public void test_error_1() throws Exception { + Exception error = null; + try { + JSONReader read = new JSONReader(new StringReader("{\"value\":\"A\",\"value1\":\"B\"[")); + Model model = read.readObject(Model.class); + read.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + Exception error = null; + try { + JSONReader read = new JSONReader(new StringReader("{\"model\":{\"value\":\"A\",\"value1\":\"B\"}[")); + Map map = read.readObject(new TypeReference>(){}); + read.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Model { + + public Type value; + public Type value1; + + } + + public static enum Type { + A, B, C + } +} diff --git a/src/test/java/com/alibaba/json/bvt/EnumFieldTest2.java b/src/test/java/com/alibaba/json/bvt/EnumFieldTest2.java new file mode 100644 index 0000000000..b79dcd78d6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/EnumFieldTest2.java @@ -0,0 +1,104 @@ +package com.alibaba.json.bvt; + +import java.io.StringReader; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class EnumFieldTest2 extends TestCase { + + public void test_0() throws Exception { + JSONReader read = new JSONReader(new StringReader("[1,2]")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + Assert.assertEquals(Type.B, model.value); + Assert.assertEquals(Type.C, model.value1); + read.close(); + } + + public void test_1() throws Exception { + JSONReader read = new JSONReader(new StringReader("[\"A\",\"B\"]")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + Assert.assertEquals(Type.A, model.value); + Assert.assertEquals(Type.B, model.value1); + read.close(); + } + + public void test_2() throws Exception { + JSONReader read = new JSONReader(new StringReader("[null,null]")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + Assert.assertEquals(null, model.value); + Assert.assertEquals(null, model.value1); + read.close(); + } + + public void test_error_1() throws Exception { + Exception error = null; + try { + JSONReader read = new JSONReader(new StringReader("[null:null]")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + read.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_n() throws Exception { + Exception error = null; + try { + JSONReader read = new JSONReader(new StringReader("[n")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + read.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_nu() throws Exception { + Exception error = null; + try { + JSONReader read = new JSONReader(new StringReader("[nu")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + read.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_nul() throws Exception { + Exception error = null; + try { + JSONReader read = new JSONReader(new StringReader("[nul")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + read.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public Type value; + public Type value1; + + } + + public static enum Type { + A, B, C + } +} diff --git a/src/test/java/com/alibaba/json/bvt/EnumFieldTest2_private.java b/src/test/java/com/alibaba/json/bvt/EnumFieldTest2_private.java new file mode 100644 index 0000000000..6009fc6475 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/EnumFieldTest2_private.java @@ -0,0 +1,104 @@ +package com.alibaba.json.bvt; + +import java.io.StringReader; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class EnumFieldTest2_private extends TestCase { + + public void test_0() throws Exception { + JSONReader read = new JSONReader(new StringReader("[1,2]")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + Assert.assertEquals(Type.B, model.value); + Assert.assertEquals(Type.C, model.value1); + read.close(); + } + + public void test_1() throws Exception { + JSONReader read = new JSONReader(new StringReader("[\"A\",\"B\"]")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + Assert.assertEquals(Type.A, model.value); + Assert.assertEquals(Type.B, model.value1); + read.close(); + } + + public void test_2() throws Exception { + JSONReader read = new JSONReader(new StringReader("[null,null]")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + Assert.assertEquals(null, model.value); + Assert.assertEquals(null, model.value1); + read.close(); + } + + public void test_error_1() throws Exception { + Exception error = null; + try { + JSONReader read = new JSONReader(new StringReader("[null:null]")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + read.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_n() throws Exception { + Exception error = null; + try { + JSONReader read = new JSONReader(new StringReader("[n")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + read.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_nu() throws Exception { + Exception error = null; + try { + JSONReader read = new JSONReader(new StringReader("[nu")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + read.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_nul() throws Exception { + Exception error = null; + try { + JSONReader read = new JSONReader(new StringReader("[nul")); + read.config(Feature.SupportArrayToBean, true); + Model model = read.readObject(Model.class); + read.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Model { + + public Type value; + public Type value1; + + } + + public static enum Type { + A, B, C + } +} diff --git a/src/test/java/com/alibaba/json/bvt/EnumFieldTest3.java b/src/test/java/com/alibaba/json/bvt/EnumFieldTest3.java new file mode 100644 index 0000000000..1dc67e46ec --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/EnumFieldTest3.java @@ -0,0 +1,76 @@ +package com.alibaba.json.bvt; + +import java.io.StringWriter; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class EnumFieldTest3 extends TestCase { + + public void test_1() throws Exception { + Model[] array = new Model[2048]; + for (int i = 0; i < array.length; ++i) { + array[i] = new Model(); + array[i].value = Type.A; + } + + String text = JSON.toJSONString(array); + + Model[] array2 = JSON.parseObject(text, Model[].class); + + Assert.assertEquals(array.length, array2.length); + for (int i = 0; i < array.length; ++i) { + Assert.assertEquals(array[i].value, array2[i].value); + } + } + + public void test_1_writer() throws Exception { + Model[] array = new Model[2048]; + for (int i = 0; i < array.length; ++i) { + array[i] = new Model(); + array[i].value = Type.A; + } + + StringWriter writer = new StringWriter(); + JSON.writeJSONString(writer, array); + String text = writer.toString(); + + Model[] array2 = JSON.parseObject(text, Model[].class); + + Assert.assertEquals(array.length, array2.length); + for (int i = 0; i < array.length; ++i) { + Assert.assertEquals(array[i].value, array2[i].value); + } + } + + public void test_null() throws Exception { + Model[] array = new Model[2048]; + for (int i = 0; i < array.length; ++i) { + array[i] = new Model(); + array[i].value = null; + } + + String text = JSON.toJSONString(array, SerializerFeature.WriteMapNullValue); + + Model[] array2 = JSON.parseObject(text, Model[].class); + + Assert.assertEquals(array.length, array2.length); + for (int i = 0; i < array.length; ++i) { + Assert.assertEquals(array[i].value, array2[i].value); + } + } + + public static class Model { + + public Type value; + + } + + public static enum Type { + A, B, C + } +} diff --git a/src/test/java/com/alibaba/json/bvt/EnumFieldTest3_private.java b/src/test/java/com/alibaba/json/bvt/EnumFieldTest3_private.java new file mode 100644 index 0000000000..ee0bf70e85 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/EnumFieldTest3_private.java @@ -0,0 +1,76 @@ +package com.alibaba.json.bvt; + +import java.io.StringWriter; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class EnumFieldTest3_private extends TestCase { + + public void test_1() throws Exception { + Model[] array = new Model[2048]; + for (int i = 0; i < array.length; ++i) { + array[i] = new Model(); + array[i].value = Type.A; + } + + String text = JSON.toJSONString(array); + + Model[] array2 = JSON.parseObject(text, Model[].class); + + Assert.assertEquals(array.length, array2.length); + for (int i = 0; i < array.length; ++i) { + Assert.assertEquals(array[i].value, array2[i].value); + } + } + + public void test_1_writer() throws Exception { + Model[] array = new Model[2048]; + for (int i = 0; i < array.length; ++i) { + array[i] = new Model(); + array[i].value = Type.A; + } + + StringWriter writer = new StringWriter(); + JSON.writeJSONString(writer, array); + String text = writer.toString(); + + Model[] array2 = JSON.parseObject(text, Model[].class); + + Assert.assertEquals(array.length, array2.length); + for (int i = 0; i < array.length; ++i) { + Assert.assertEquals(array[i].value, array2[i].value); + } + } + + public void test_null() throws Exception { + Model[] array = new Model[2048]; + for (int i = 0; i < array.length; ++i) { + array[i] = new Model(); + array[i].value = null; + } + + String text = JSON.toJSONString(array, SerializerFeature.WriteMapNullValue); + + Model[] array2 = JSON.parseObject(text, Model[].class); + + Assert.assertEquals(array.length, array2.length); + for (int i = 0; i < array.length; ++i) { + Assert.assertEquals(array[i].value, array2[i].value); + } + } + + public static class Model { + + public Type value; + + } + + private static enum Type { + A, B, C + } +} diff --git a/src/test/java/com/alibaba/json/bvt/EnumerationTest.java b/src/test/java/com/alibaba/json/bvt/EnumerationTest.java new file mode 100755 index 0000000000..390812be31 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/EnumerationTest.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt; + +import java.util.Collections; +import java.util.Enumeration; +import java.util.Vector; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class EnumerationTest extends TestCase { + + public void test_enumeration() throws Exception { + Assert.assertEquals("[]", JSON.toJSONString(new Vector().elements())); + Assert.assertEquals("[null]", JSON.toJSONString(new Vector(Collections.singleton(null)).elements())); + + Assert.assertEquals("{\"value\":[]}", JSON.toJSONString(new VO(), SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); + } + + private static class VO { + + private Enumeration value; + + public Enumeration getValue() { + return value; + } + + public void setValue(Enumeration value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/FastJsonBigClassTest.java b/src/test/java/com/alibaba/json/bvt/FastJsonBigClassTest.java new file mode 100644 index 0000000000..99a26a84b9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/FastJsonBigClassTest.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.bvtVO.BigClass; + +import junit.framework.TestCase; + +public class FastJsonBigClassTest extends TestCase { + + public void test_big_class() { + BigClass bigObj = new BigClass(); + String json = JSON.toJSONString(bigObj, SerializerFeature.IgnoreNonFieldGetter); +// assertThat(json, not(containsString("skipme"))); + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/FileFieldTest.java b/src/test/java/com/alibaba/json/bvt/FileFieldTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/FileFieldTest.java rename to src/test/java/com/alibaba/json/bvt/FileFieldTest.java index a83fe15c31..c59f10ab24 --- a/src/test/java/com/alibaba/json/test/bvt/FileFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/FileFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.io.File; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/FinalTest.java b/src/test/java/com/alibaba/json/bvt/FinalTest.java new file mode 100644 index 0000000000..076be99210 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/FinalTest.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class FinalTest extends TestCase { + public void test_final() throws Exception { + VO vo = new VO(); + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"value\":1001}", text); + JSON.parseObject(text, VO.class); + JSON.parseObject("{\"id\":1001,\"value\":1001}", VO.class); + } + + + public static class VO { + public final static int id = 1001; + public final int value = 1001; + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/FloatArrayFieldTest_primitive.java b/src/test/java/com/alibaba/json/bvt/FloatArrayFieldTest_primitive.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/FloatArrayFieldTest_primitive.java rename to src/test/java/com/alibaba/json/bvt/FloatArrayFieldTest_primitive.java index 22c01f08d9..94cb213675 --- a/src/test/java/com/alibaba/json/test/bvt/FloatArrayFieldTest_primitive.java +++ b/src/test/java/com/alibaba/json/bvt/FloatArrayFieldTest_primitive.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/FloatFieldTest.java b/src/test/java/com/alibaba/json/bvt/FloatFieldTest.java old mode 100644 new mode 100755 similarity index 78% rename from src/test/java/com/alibaba/json/test/bvt/FloatFieldTest.java rename to src/test/java/com/alibaba/json/bvt/FloatFieldTest.java index 837d826b4e..1e5bac5d3d --- a/src/test/java/com/alibaba/json/test/bvt/FloatFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/FloatFieldTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -16,7 +16,7 @@ public void test_codec() throws Exception { User user1 = JSON.parseObject(text, User.class); - Assert.assertEquals(user1.getValue(), user.getValue()); + Assert.assertTrue(user1.getValue() == user.getValue()); } public static class User { diff --git a/src/test/java/com/alibaba/json/test/bvt/FloatFieldTest_A.java b/src/test/java/com/alibaba/json/bvt/FloatFieldTest_A.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/FloatFieldTest_A.java rename to src/test/java/com/alibaba/json/bvt/FloatFieldTest_A.java index 158799ef3d..59b24c42ae --- a/src/test/java/com/alibaba/json/test/bvt/FloatFieldTest_A.java +++ b/src/test/java/com/alibaba/json/bvt/FloatFieldTest_A.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/FluentSetterTest.java b/src/test/java/com/alibaba/json/bvt/FluentSetterTest.java new file mode 100644 index 0000000000..59eb26f651 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/FluentSetterTest.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class FluentSetterTest extends TestCase { + + public void test_fluent() throws Exception { + B b = new B(); + b.setId(1001); + b.setValue(1002); + + String text = JSON.toJSONString(b); + Assert.assertEquals("{\"id\":1001,\"value\":1002}", text); + + B b1 = JSON.parseObject(text, B.class); + Assert.assertEquals(b.getId(), b1.getId()); + Assert.assertEquals(b.getValue(), b1.getValue()); + } + + public static class A { + + private int id; + + public int getId() { + return id; + } + + public A setId(int id) { + this.id = id; + return this; + } + } + + public static class B extends A { + + private int value; + + public int getValue() { + return value; + } + + public B setValue(int value) { + this.value = value; + return this; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/GetSetNotMatchTest.java b/src/test/java/com/alibaba/json/bvt/GetSetNotMatchTest.java new file mode 100644 index 0000000000..85dc63d2d3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/GetSetNotMatchTest.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class GetSetNotMatchTest extends TestCase { + + public void test_0() throws Exception { + VO vo = new VO(); + vo.setValue(1); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"value\":true}", text); + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getValue(), vo1.getValue()); + } + + public static class VO { + + private int value; + + public boolean getValue() { + return value == 1; + } + + public void setValue(int value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/GroovyTest.java b/src/test/java/com/alibaba/json/bvt/GroovyTest.java new file mode 100755 index 0000000000..2861f2ac78 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/GroovyTest.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt; + +import groovy.lang.GroovyClassLoader; +import groovy.lang.GroovyObject; +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class GroovyTest extends TestCase { + + public void test_groovy() throws Exception { + ClassLoader parent = Thread.currentThread().getContextClassLoader(); + GroovyClassLoader loader = new GroovyClassLoader(parent); + + // A类 + Class AClass = loader.parseClass("class A {\n" + // + " int id\n" + // + "}"); + + // A实例 + GroovyObject a = (GroovyObject) AClass.newInstance(); + a.setProperty("id", 33); + String textA = JSON.toJSONString(a); + + GroovyObject aa = (GroovyObject) JSON.parseObject(textA, AClass); + Assert.assertEquals(a.getProperty("id"), aa.getProperty("id")); + + System.out.println(a); + + // B类,继承于A + Class BClass = loader.parseClass("class B extends A {\n" + // + " String name\n" + // + "}"); + + // B实例 + GroovyObject b = (GroovyObject) BClass.newInstance(); + b.setProperty("name", "jobs"); + String textB = JSON.toJSONString(b); + GroovyObject bb = (GroovyObject) JSON.parseObject(textB, BClass); + Assert.assertEquals(b.getProperty("id"), bb.getProperty("id")); + Assert.assertEquals(b.getProperty("name"), bb.getProperty("name")); + + + // 序列化失败 + System.out.println(JSON.toJSONString(b, true)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/IncomingDataPointTest.java b/src/test/java/com/alibaba/json/bvt/IncomingDataPointTest.java new file mode 100644 index 0000000000..7212460d2f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/IncomingDataPointTest.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvtVO.IncomingDataPoint; +import junit.framework.TestCase; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Created by wenshao on 03/08/2017. + */ +public class IncomingDataPointTest extends TestCase { + public void test_0() throws Exception { + Map tags = new LinkedHashMap(); + tags.put("site", "et2"); + tags.put("appname", "histore"); + tags.put("ip", "1.1.1.1"); + + IncomingDataPoint point = new IncomingDataPoint(); + point.setMetric("mem.usage.GB"); + point.setTimestamp(1501760861298L); + point.setTags(tags); + point.setValue("58.41"); + point.setTSUID(""); + point.setAggregator(""); + IncomingDataPoint[] array = new IncomingDataPoint[] {point}; + + String json = JSON.toJSONString(array); + System.out.println(json); + + JSON.parseArray(json, IncomingDataPoint.class); + + IncomingDataPoint p2 = JSON.parseObject("[\"mem.usage.GB\",1501833776283,\"58.41\",{\"site\":\"et2\",\"appname\":\"histore\",\"ip\":\"1.1.1.1\"}]", IncomingDataPoint.class); + IncomingDataPoint p3 = JSON.parseObject("[\"mem.usage.GB\",1501833776283,\"58.41\",{\"site\":\"et2\",\"appname\":\"histore\",\"ip\":\"1.1.1.1\"},null]", IncomingDataPoint.class); + System.out.println(JSON.toJSONString(p2)); +// JSON.parseObject(json, IncomingDataPoint[].class); + } + public void test_for_IncomingDataPoint() throws Exception { + // "metric", "timestamp", "value", "tags", "tsuid", "granularity", "aggregator" + String text = "[[\"DataAdaptor.LbMultiGroupPersonalityDataAdaptor.stddev.aggregate_sum\",\"1501812639932\",\"95.52667633256902\",{\"appName\":\"aladdin\",\"hostIdc\":\"et2\",\"hostunit\":\"CENTER\",\"nodegroup\":\"aladdin_prehost\",\"idc\":\"ET2\",\"agg_version\":\"100\",\"group\":\"DEFAULT\"},\"\",\"\",\"\"]]"; + System.out.println(text); + JSON.parseArray(text, IncomingDataPoint.class); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/InetAddressFieldTest.java b/src/test/java/com/alibaba/json/bvt/InetAddressFieldTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/InetAddressFieldTest.java rename to src/test/java/com/alibaba/json/bvt/InetAddressFieldTest.java index 72cffbd886..7dc6852dd2 --- a/src/test/java/com/alibaba/json/test/bvt/InetAddressFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/InetAddressFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.net.InetAddress; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/InetSocketAddressFieldTest.java b/src/test/java/com/alibaba/json/bvt/InetSocketAddressFieldTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/InetSocketAddressFieldTest.java rename to src/test/java/com/alibaba/json/bvt/InetSocketAddressFieldTest.java index 5469a40d19..06fb15b164 --- a/src/test/java/com/alibaba/json/test/bvt/InetSocketAddressFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/InetSocketAddressFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.net.InetSocketAddress; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/IntArrayFieldTest_primitive.java b/src/test/java/com/alibaba/json/bvt/IntArrayFieldTest_primitive.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/IntArrayFieldTest_primitive.java rename to src/test/java/com/alibaba/json/bvt/IntArrayFieldTest_primitive.java index c458577be2..59e1d669de --- a/src/test/java/com/alibaba/json/test/bvt/IntArrayFieldTest_primitive.java +++ b/src/test/java/com/alibaba/json/bvt/IntArrayFieldTest_primitive.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/IntKeyMapTest.java b/src/test/java/com/alibaba/json/bvt/IntKeyMapTest.java new file mode 100755 index 0000000000..fe09709ace --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/IntKeyMapTest.java @@ -0,0 +1,12 @@ +package com.alibaba.json.bvt; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class IntKeyMapTest extends TestCase { + + public void test_0() throws Exception { + JSON.parse("{1:\"AA\",2:{}}"); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/IntegerArrayFieldTest.java b/src/test/java/com/alibaba/json/bvt/IntegerArrayFieldTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/IntegerArrayFieldTest.java rename to src/test/java/com/alibaba/json/bvt/IntegerArrayFieldTest.java index aab4faf3e9..b287a8c5e2 --- a/src/test/java/com/alibaba/json/test/bvt/IntegerArrayFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/IntegerArrayFieldTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/Issue213Test.java b/src/test/java/com/alibaba/json/bvt/Issue213Test.java new file mode 100644 index 0000000000..a4b69f3be6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/Issue213Test.java @@ -0,0 +1,84 @@ +package com.alibaba.json.bvt; + +import java.io.Serializable; +import java.util.Date; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Issue213Test extends TestCase { + + public void test_0() throws Exception { + String text = "\t\t\t\t\t\t \u00A020:00-21:30
\r\n\r\n

\r\n

\r\n\t\r\n

\r\n

\r\n\t
\r\n

\r\n\t\t\t"; + Product e = new Product(); + e.setIntro(text); + byte[] r = JSON.toJSONBytes(e); + JSON.parseObject(r, Product.class); + } + + public static class Product implements Serializable { + + private static final long serialVersionUID = 5515785177596600948L; + + private String studyTargets; + + private String applicableUsers; + + private String intro; + + private Date createDateTime; + + private int createUserId; + + private int liveStatus; + + public String getStudyTargets() { + return studyTargets; + } + + public void setStudyTargets(String studyTargets) { + this.studyTargets = studyTargets; + } + + public String getApplicableUsers() { + return applicableUsers; + } + + public void setApplicableUsers(String applicableUsers) { + this.applicableUsers = applicableUsers; + } + + public String getIntro() { + return intro; + } + + public void setIntro(String intro) { + this.intro = intro; + } + + public int getCreateUserId() { + return createUserId; + } + + public void setCreateUserId(int createUserId) { + this.createUserId = createUserId; + } + + public int getLiveStatus() { + return liveStatus; + } + + public void setLiveStatus(int liveStatus) { + this.liveStatus = liveStatus; + } + + public Date getCreateDateTime() { + return createDateTime; + } + + public void setCreateDateTime(Date createDateTime) { + this.createDateTime = createDateTime; + } + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONArrayTest.java b/src/test/java/com/alibaba/json/bvt/JSONArrayTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/JSONArrayTest.java rename to src/test/java/com/alibaba/json/bvt/JSONArrayTest.java index 9bb749cf78..3128011434 --- a/src/test/java/com/alibaba/json/test/bvt/JSONArrayTest.java +++ b/src/test/java/com/alibaba/json/bvt/JSONArrayTest.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.io.StringWriter; import java.math.BigDecimal; @@ -25,7 +25,7 @@ import java.util.ListIterator; import java.util.concurrent.atomic.AtomicInteger; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -117,11 +117,11 @@ public void test_2() throws Exception { Assert.assertEquals(123, array.getShort(0).shortValue()); Assert.assertEquals(123, array.getShortValue(0)); - Assert.assertEquals(123F, array.getFloat(0).floatValue()); - Assert.assertEquals(123F, array.getFloatValue(0)); + Assert.assertTrue(123F == array.getFloat(0).floatValue()); + Assert.assertTrue(123F == array.getFloatValue(0)); - Assert.assertEquals(123D, array.getDouble(0).doubleValue()); - Assert.assertEquals(123D, array.getDoubleValue(0)); + Assert.assertTrue(123D == array.getDouble(0).doubleValue()); + Assert.assertTrue(123D == array.getDoubleValue(0)); Assert.assertEquals(123, array.getIntValue(0)); Assert.assertEquals(123, array.getLongValue(0)); diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONArrayTest2.java b/src/test/java/com/alibaba/json/bvt/JSONArrayTest2.java old mode 100644 new mode 100755 similarity index 80% rename from src/test/java/com/alibaba/json/test/bvt/JSONArrayTest2.java rename to src/test/java/com/alibaba/json/bvt/JSONArrayTest2.java index c5e79b1099..3eaaa5d0d7 --- a/src/test/java/com/alibaba/json/test/bvt/JSONArrayTest2.java +++ b/src/test/java/com/alibaba/json/bvt/JSONArrayTest2.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.math.BigInteger; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONArray; @@ -17,8 +17,8 @@ public void test_0() throws Exception { array.add(time); Assert.assertEquals(0, array.getByteValue(0)); Assert.assertEquals(0, array.getShortValue(0)); - Assert.assertEquals(0F, array.getFloatValue(0)); - Assert.assertEquals(0D, array.getDoubleValue(0)); + Assert.assertTrue(0F == array.getFloatValue(0)); + Assert.assertTrue(0D == array.getDoubleValue(0)); Assert.assertEquals(new BigInteger("1"), array.getBigInteger(1)); Assert.assertEquals("1", array.getString(1)); Assert.assertEquals(new java.util.Date(time), array.getDate(2)); @@ -28,8 +28,8 @@ public void test_0() throws Exception { JSONArray array2 = (JSONArray) array.clone(); Assert.assertEquals(0, array2.getByteValue(0)); Assert.assertEquals(0, array2.getShortValue(0)); - Assert.assertEquals(0F, array2.getFloatValue(0)); - Assert.assertEquals(0D, array2.getDoubleValue(0)); + Assert.assertTrue(0F == array2.getFloatValue(0)); + Assert.assertTrue(0D == array2.getDoubleValue(0)); Assert.assertEquals(new BigInteger("1"), array2.getBigInteger(1)); Assert.assertEquals("1", array2.getString(1)); Assert.assertEquals(new java.util.Date(time), array2.getDate(2)); diff --git a/src/test/java/com/alibaba/json/bvt/JSONArrayTest3.java b/src/test/java/com/alibaba/json/bvt/JSONArrayTest3.java new file mode 100644 index 0000000000..e3acf5f104 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONArrayTest3.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt; + +import java.util.Arrays; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONArray; + +import junit.framework.TestCase; + +public class JSONArrayTest3 extends TestCase { + public void test_0() throws Exception { + JSONArray array = new JSONArray(); + array.set(1, "1001"); + Assert.assertEquals(2, array.size()); + Assert.assertNull(array.get(0)); + Assert.assertEquals("1001", array.get(1)); + + array.clear(); + Assert.assertEquals(0, array.size()); + + array.set(-1, "1001"); + Assert.assertEquals(1, array.size()); + Assert.assertEquals("1001", array.get(0)); + + array.fluentAdd("1002").fluentClear(); + Assert.assertEquals(0, array.size()); + + array.fluentAdd("1002").fluentRemove("1002"); + Assert.assertEquals(0, array.size()); + + array.fluentAdd("1002").fluentRemove(0); + Assert.assertEquals(0, array.size()); + + array.fluentSet(1, "1001"); + Assert.assertEquals(2, array.size()); + Assert.assertNull(array.get(0)); + Assert.assertEquals("1001", array.get(1)); + + array.fluentRemoveAll(Arrays.asList(null, "1001")); + Assert.assertEquals(0, array.size()); + + array.fluentAddAll(Arrays.asList("1001", "1002", "1003")); + Assert.assertEquals(3, array.size()); + + array.retainAll(Arrays.asList("1002", "1004")); + Assert.assertEquals(1, array.size()); + Assert.assertEquals("1002", array.get(0)); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONArrayTest_hashCode.java b/src/test/java/com/alibaba/json/bvt/JSONArrayTest_hashCode.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/JSONArrayTest_hashCode.java rename to src/test/java/com/alibaba/json/bvt/JSONArrayTest_hashCode.java index 3e44286507..e8373bd4a3 --- a/src/test/java/com/alibaba/json/test/bvt/JSONArrayTest_hashCode.java +++ b/src/test/java/com/alibaba/json/bvt/JSONArrayTest_hashCode.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/JSONBytesTest.java b/src/test/java/com/alibaba/json/bvt/JSONBytesTest.java new file mode 100644 index 0000000000..27840ea94d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONBytesTest.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class JSONBytesTest extends TestCase { + + public void test_codec() throws Exception { + int len = (Character.MAX_VALUE - Character.MIN_VALUE) + 1; + char[] chars = new char[len]; + for (int i = 0; i < len; ++i) { + char ch = (char) ((int) Character.MAX_VALUE + i); + if (ch >= 55296 && ch <= 57344) { + continue; + } + chars[i] = ch; + } + + String text = new String(chars); + + byte[] bytes = JSON.toJSONBytes(text); + String text2 = (String) JSON.parse(bytes); + + Assert.assertEquals(text.length(), text2.length()); + for (int i = 0; i < len; ++i) { + char c1 = text.charAt(i); + char c2 = text2.charAt(i); + + Assert.assertEquals(c1, c2); + } + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONBytesTest2.java b/src/test/java/com/alibaba/json/bvt/JSONBytesTest2.java new file mode 100644 index 0000000000..d339b4c78d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONBytesTest2.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class JSONBytesTest2 extends TestCase { + + public void test_codec() throws Exception { + String text="𠜎𠜱𠝹𠱓𠱸𠲖𠳏𠳕𠴕𠵼𠵿𠸎𠸏𠹷𠺝𠺢𠻗𠻹𠻺𠼭𠼮𠽌𠾴𠾼𠿪𡁜𡁯𡁵𡁶𡁻𡃁𡃉𡇙𢃇𢞵𢫕𢭃𢯊𢱑𢱕𢳂𢴈𢵌𢵧𢺳𣲷𤓓𤶸𤷪𥄫𦉘𦟌𦧲𦧺𧨾𨅝𨈇𨋢𨳊𨳍𨳒𩶘"; + + byte[] bytes = JSON.toJSONBytes(text); + String text2 = (String) JSON.parse(bytes); + + Assert.assertEquals(text.length(), text2.length()); + for (int i = 0; i < text.length(); ++i) { + char c1 = text.charAt(i); + char c2 = text2.charAt(i); + + Assert.assertEquals(c1, c2); + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONBytesTest3.java b/src/test/java/com/alibaba/json/bvt/JSONBytesTest3.java new file mode 100644 index 0000000000..ee743fc849 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONBytesTest3.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt; + +import java.nio.charset.Charset; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class JSONBytesTest3 extends TestCase { + + public void test_codec() throws Exception { + Model model = new Model(); + model.value = "𠜎𠜱𠝹𠱓𠱸𠲖𠳏𠳕𠴕𠵼𠵿𠸎𠸏𠹷𠺝𠺢𠻗𠻹𠻺𠼭𠼮𠽌𠾴𠾼𠿪𡁜𡁯𡁵𡁶𡁻𡃁𡃉𡇙𢃇𢞵𢫕𢭃𢯊𢱑𢱕𢳂𢴈𢵌𢵧𢺳𣲷𤓓𤶸𤷪𥄫𦉘𦟌𦧲𦧺𧨾𨅝𨈇𨋢𨳊𨳍𨳒𩶘"; + + byte[] bytes = JSON.toJSONBytes(model); + Model model2 = JSON.parseObject(bytes, 0, bytes.length, Charset.forName("UTF8").newDecoder(), Model.class); + + Assert.assertEquals(model.value.length(), model2.value.length()); + for (int i = 0; i < model.value.length(); ++i) { + char c1 = model.value.charAt(i); + char c2 = model2.value.charAt(i); + + Assert.assertEquals(c1, c2); + } + } + + public static class Model { + public String value; + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONExceptionTest.java b/src/test/java/com/alibaba/json/bvt/JSONExceptionTest.java old mode 100644 new mode 100755 similarity index 88% rename from src/test/java/com/alibaba/json/test/bvt/JSONExceptionTest.java rename to src/test/java/com/alibaba/json/bvt/JSONExceptionTest.java index 8d45f560b1..ebcc3e0af6 --- a/src/test/java/com/alibaba/json/test/bvt/JSONExceptionTest.java +++ b/src/test/java/com/alibaba/json/bvt/JSONExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; diff --git a/src/test/java/com/alibaba/json/bvt/JSONFeidDemo2.java b/src/test/java/com/alibaba/json/bvt/JSONFeidDemo2.java new file mode 100755 index 0000000000..9d06b193e5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONFeidDemo2.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.List; + +public class JSONFeidDemo2 extends TestCase { + + public void test_0() throws Exception { + Z_OA_MM_PR_INFO_IN in = new Z_OA_MM_PR_INFO_IN(); + in.setIM_PREQ_NO("111111"); + TB_PR_INFO t1 = new TB_PR_INFO("t1"); + TB_PR_INFO t2 = new TB_PR_INFO("t2"); + List tb_pr_infos = new ArrayList(); + tb_pr_infos.add(t1); + tb_pr_infos.add(t2); + in.setTB_PR_INFO(tb_pr_infos); + + String text = JSON.toJSONString(in); + System.out.println(text); + + assertEquals( + "{\"IM_PREQ_NO\":\"111111\",\"TB_PR_INFO\":[{\"PREQ_NO\":\"t1\"},{\"PREQ_NO\":\"t2\"}]}", + text); + + } + + public void test_1() throws Exception { + String text = "{\"IM_PREQ_NO\":\"111111\",\"TB_PR_INFO\":[{\"pREQ_NO\":\"t1\"},{\"pREQ_NO\":\"t2\"}]}"; + Z_OA_MM_PR_INFO_IN in = JSON + .parseObject(text, Z_OA_MM_PR_INFO_IN.class); + assertEquals("111111", in.getIM_PREQ_NO()); + assertNotNull(in.getTB_PR_INFO()); + + } + + public static class Z_OA_MM_PR_INFO_IN { + @JSONField(name = "IM_PREQ_NO") + private String IM_PREQ_NO; + @JSONField(name = "TB_PR_INFO") + private List TB_PR_INFO; + + public List getTB_PR_INFO() { + return TB_PR_INFO; + } + + public void setTB_PR_INFO(List TB_PR_INFO) { + this.TB_PR_INFO = TB_PR_INFO; + } + + public String getIM_PREQ_NO() { + return IM_PREQ_NO; + } + + public void setIM_PREQ_NO(String IM_PREQ_NO) { + this.IM_PREQ_NO = IM_PREQ_NO; + } + } + + public static class TB_PR_INFO { + @JSONField(name = "PREQ_NO") + private String PREQ_NO; + + public TB_PR_INFO() { + } + + public TB_PR_INFO(String PREQ_NO) { + this.PREQ_NO = PREQ_NO; + } + @JSONField(name = "PREQ_NO") + public String getPREQ_NO() { + return PREQ_NO; + } + + public void setPREQ_NO(String PREQ_NO) { + this.PREQ_NO = PREQ_NO; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONFieldTest.java b/src/test/java/com/alibaba/json/bvt/JSONFieldTest.java new file mode 100644 index 0000000000..0b92214c13 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONFieldTest.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + + +public class JSONFieldTest extends TestCase { + + public void test_field() throws Exception { + Demo demo = new Demo(); + demo.setId(1009); + demo.setName("IT"); + demo.setAge(30); + System.out.println(JSON.toJSON(demo)); + } + + public static class Demo { + private int id; + + @JSONField(serialize = false) + private String name; + + private int age; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONFromObjectTest.java b/src/test/java/com/alibaba/json/bvt/JSONFromObjectTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/JSONFromObjectTest.java rename to src/test/java/com/alibaba/json/bvt/JSONFromObjectTest.java index b2fe8e9d11..10c396e22f --- a/src/test/java/com/alibaba/json/test/bvt/JSONFromObjectTest.java +++ b/src/test/java/com/alibaba/json/bvt/JSONFromObjectTest.java @@ -1,10 +1,10 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/JSONObjectFluentTest.java b/src/test/java/com/alibaba/json/bvt/JSONObjectFluentTest.java new file mode 100644 index 0000000000..88074a96a4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectFluentTest.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt; + +import java.util.Collections; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class JSONObjectFluentTest extends TestCase { + + public void test_fluent() throws Exception { + JSONObject object = new JSONObject() // + .fluentPut("1", 1001) // + .fluentPut("2", 1002); + + Assert.assertEquals(2, object.size()); + + object.fluentPutAll(Collections.singletonMap("3", 1003)) // + .fluentPutAll(Collections.singletonMap("4", 1004)); + + Assert.assertEquals(4, object.size()); + + object.fluentRemove("1") // + .fluentRemove("2"); + + Assert.assertEquals(2, object.size()); + + object.fluentClear().fluentClear(); + + Assert.assertEquals(0, object.size()); + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONObjectTest.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/JSONObjectTest.java rename to src/test/java/com/alibaba/json/bvt/JSONObjectTest.java index abd3b0dd53..7c89f0755f --- a/src/test/java/com/alibaba/json/test/bvt/JSONObjectTest.java +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.io.StringWriter; import java.math.BigDecimal; @@ -21,7 +21,7 @@ import java.util.Date; import java.util.HashMap; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONObject; @@ -156,10 +156,10 @@ public void test_all_2() throws Exception { Assert.assertEquals(new BigDecimal("222"), array.getBigDecimal("1")); Assert.assertEquals(true, array.getBooleanValue("4")); - Assert.assertEquals(2.0F, array.getFloat("5").floatValue()); - Assert.assertEquals(2.0F, array.getFloatValue("5")); - Assert.assertEquals(2.0D, array.getDouble("5").doubleValue()); - Assert.assertEquals(2.0D, array.getDoubleValue("5")); + Assert.assertTrue(2.0F == array.getFloat("5").floatValue()); + Assert.assertTrue(2.0F == array.getFloatValue("5")); + Assert.assertTrue(2.0D == array.getDouble("5").doubleValue()); + Assert.assertTrue(2.0D == array.getDoubleValue("5")); } public void test_getObject_null() throws Exception { @@ -168,6 +168,11 @@ public void test_getObject_null() throws Exception { Assert.assertTrue(json.getJSONObject("obj") == null); } + + public void test_bytes () throws Exception { + JSONObject object = new JSONObject(); + Assert.assertNull(object.getBytes("bytes")); + } public void test_getObject() throws Exception { JSONObject json = new JSONObject(); diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONObjectTest2.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest2.java old mode 100644 new mode 100755 similarity index 84% rename from src/test/java/com/alibaba/json/test/bvt/JSONObjectTest2.java rename to src/test/java/com/alibaba/json/bvt/JSONObjectTest2.java index 6c508b2d1f..601a015e82 --- a/src/test/java/com/alibaba/json/test/bvt/JSONObjectTest2.java +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest2.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.LinkedHashMap; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONArray; @@ -31,8 +31,8 @@ public void test_0() throws Exception { Assert.assertEquals(obj.getByteValue("d"), 0); Assert.assertEquals(obj.getShortValue("d"), 0); - Assert.assertEquals(obj.getFloatValue("d"), 0F); - Assert.assertEquals(obj.getDoubleValue("d"), 0D); + Assert.assertTrue(obj.getFloatValue("d") == 0F); + Assert.assertTrue(obj.getDoubleValue("d") == 0D); Assert.assertEquals(obj.getBigInteger("d"), null); Assert.assertEquals(obj.getSqlDate("d"), null); Assert.assertEquals(obj.getTimestamp("d"), null); diff --git a/src/test/java/com/alibaba/json/bvt/JSONObjectTest3.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest3.java new file mode 100755 index 0000000000..cfad9757f8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest3.java @@ -0,0 +1,182 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONField; + +public class JSONObjectTest3 extends TestCase { + + public void test_0() throws Exception { + String text = "{value:'123',big:false}"; + Bean bean = JSON.parseObject(text, Bean.class); + Assert.assertEquals("123", bean.getValue()); + Assert.assertEquals(false, bean.isBig()); + Assert.assertEquals(123, bean.getIntValue()); + + bean.setBig(true); + Assert.assertEquals(true, bean.isBig()); + + bean.setID(567); + Assert.assertEquals(567, bean.getID()); + + } + + public void test_error_0() throws Exception { + String text = "{value:'123',big:false}"; + Bean bean = JSON.parseObject(text, Bean.class); + + JSONException error = null; + try { + bean.f(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + String text = "{value:'123',big:false}"; + Bean bean = JSON.parseObject(text, Bean.class); + + JSONException error = null; + try { + bean.f(1); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + String text = "{value:'123',big:false}"; + Bean bean = JSON.parseObject(text, Bean.class); + + JSONException error = null; + try { + bean.get(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + String text = "{value:'123',big:false}"; + Bean bean = JSON.parseObject(text, Bean.class); + + JSONException error = null; + try { + bean.is(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_4() throws Exception { + String text = "{value:'123',big:false}"; + Bean bean = JSON.parseObject(text, Bean.class); + + Exception error = null; + try { + bean.f(1, 2); + } catch (UnsupportedOperationException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_5() throws Exception { + String text = "{value:'123',big:false}"; + Bean bean = JSON.parseObject(text, Bean.class); + + JSONException error = null; + try { + bean.getA(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_6() throws Exception { + String text = "{value:'123',big:false}"; + Bean bean = JSON.parseObject(text, Bean.class); + + JSONException error = null; + try { + bean.f1(1); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_7() throws Exception { + String text = "{value:'123',big:false}"; + Bean bean = JSON.parseObject(text, Bean.class); + + JSONException error = null; + try { + bean.set(1); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_8() throws Exception { + String text = "{value:'123',big:false}"; + Bean bean = JSON.parseObject(text, Bean.class); + + JSONException error = null; + try { + bean.xx(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static interface Bean { + + String getValue(); + + void setValue(String value); + + boolean isBig(); + + @JSONField + void setBig(boolean value); + + @JSONField(name = "value") + int getIntValue(); + + @JSONField(name = "id") + void setID(int value); + + @JSONField(name = "id") + int getID(); + + Object get(); + + Object xx(); + + void set(int i); + + boolean is(); + + void getA(); + + void f(); + + Object f(int a); + + void f1(int a); + + void f(int a, int b); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONObjectTest4.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest4.java new file mode 100644 index 0000000000..28e5e1ab13 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest4.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class JSONObjectTest4 extends TestCase { + + public void test_interface() throws Exception { + VO vo = JSON.parseObject("{id:123}", VO.class); + Assert.assertEquals(123, vo.getId()); + } + + public static interface VO { + @JSONField() + int getId(); + + @JSONField() + void setId(int val); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONObjectTest5.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest5.java new file mode 100644 index 0000000000..96254fc134 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest5.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class JSONObjectTest5 extends TestCase { + + public void test() throws Exception { + JSONObject jsonObject = new JSONObject(3, true); + jsonObject.put("name", "J.K.SAGE"); + jsonObject.put("age", 21); + jsonObject.put("msg", "Hello!"); + JSONObject cloneObject = (JSONObject) jsonObject.clone(); + assertEquals(JSON.toJSONString(jsonObject), JSON.toJSONString(cloneObject)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONObjectTest6.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest6.java new file mode 100644 index 0000000000..08ee84b8c5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest6.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class JSONObjectTest6 extends TestCase { + + public void test() throws Exception { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("value", 123); + + Model model = jsonObject.toJavaObject(Model.class); + assertEquals(123, model.value); + } + + public static class Model { + public int value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONObjectTest_get.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_get.java new file mode 100644 index 0000000000..b11739d3b3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_get.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class JSONObjectTest_get extends TestCase { + + public void test_get() throws Exception { + JSONObject obj = JSON.parseObject("{id:123}"); + Assert.assertEquals(123, obj.getObject("id", Object.class)); + } + + public static interface VO { + @JSONField() + int getId(); + + @JSONField() + void setId(int val); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getBigInteger.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getBigInteger.java new file mode 100644 index 0000000000..e4a72666bd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getBigInteger.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt; + +import java.math.BigInteger; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class JSONObjectTest_getBigInteger extends TestCase { + + public void test_get_float() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("value", 123.45F); + Assert.assertTrue(123.45F == ((Float) obj.get("value")).floatValue()); + Assert.assertEquals(new BigInteger("123"), obj.getBigInteger("value")); + } + + public void test_get_double() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("value", 123.45D); + Assert.assertTrue(123.45D == ((Double) obj.get("value")).doubleValue()); + Assert.assertEquals(new BigInteger("123"), obj.getBigInteger("value")); + } + + public void test_get_empty() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("value", ""); + Assert.assertEquals("", obj.get("value")); + Assert.assertNull(obj.getBigInteger("value")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getDate.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getDate.java new file mode 100644 index 0000000000..96049dbbd3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getDate.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class JSONObjectTest_getDate extends TestCase { + + public void test_get_empty() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("value", ""); + Assert.assertEquals("", obj.get("value")); + Assert.assertNull(obj.getDate("value")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getObj.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getObj.java new file mode 100644 index 0000000000..0363335e06 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getObj.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class JSONObjectTest_getObj extends TestCase { + + public void test_get_empty() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("value", ""); + Assert.assertEquals("", obj.get("value")); + Assert.assertNull(obj.getObject("value", Model.class)); + } + + public void test_get_null() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("value", "null"); + Assert.assertEquals("null", obj.get("value")); + Assert.assertNull(obj.getObject("value", Model.class)); + } + + public static class Model { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getObj_2.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getObj_2.java new file mode 100644 index 0000000000..69de4169ca --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_getObj_2.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt; + +import java.lang.reflect.Type; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.util.TypeUtils; + +import junit.framework.TestCase; + +public class JSONObjectTest_getObj_2 extends TestCase { + + public void test_get_empty() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("value", ""); + Assert.assertEquals("", obj.get("value")); + Assert.assertNull(obj.getObject("value", Model.class)); + } + + public void test_get_null() throws Exception { + TypeUtils.cast("null", getType(), ParserConfig.getGlobalInstance()); + TypeUtils.cast("", getType(), ParserConfig.getGlobalInstance()); + } + + public static class Model { + + } + + public static Type getType() { + return new TypeReference() {}.getType(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONObjectTest_get_2.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_get_2.java new file mode 100644 index 0000000000..c5d8b18262 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_get_2.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class JSONObjectTest_get_2 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.JSONObjectTest_get_2."); + } + + public void test_get() throws Exception { + JSONObject obj = JSON.parseObject("{\"value\":{}}"); + JSONObject value = (JSONObject) obj.getObject("value", Object.class); + Assert.assertEquals(0, value.size()); + } + + public void test_get_obj() throws Exception { + JSONObject obj = new JSONObject(); + { + Map value = new HashMap(); + value.put("@type", "com.alibaba.json.bvt.JSONObjectTest_get_2$VO"); + value.put("id", 1001); + obj.put("value", value); + } + VO value = (VO) obj.getObject("value", Object.class); + Assert.assertEquals(1001, value.getId()); + } + + public static interface VO { + @JSONField() + int getId(); + + @JSONField() + void setId(int val); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONObjectTest_hashCode.java b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_hashCode.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/JSONObjectTest_hashCode.java rename to src/test/java/com/alibaba/json/bvt/JSONObjectTest_hashCode.java index a86896b8a0..9e466cbc92 --- a/src/test/java/com/alibaba/json/test/bvt/JSONObjectTest_hashCode.java +++ b/src/test/java/com/alibaba/json/bvt/JSONObjectTest_hashCode.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONParseTest.java b/src/test/java/com/alibaba/json/bvt/JSONParseTest.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/JSONParseTest.java rename to src/test/java/com/alibaba/json/bvt/JSONParseTest.java index c13b336ec4..18addf9c2d --- a/src/test/java/com/alibaba/json/test/bvt/JSONParseTest.java +++ b/src/test/java/com/alibaba/json/bvt/JSONParseTest.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.ArrayList; diff --git a/src/test/java/com/alibaba/json/bvt/JSONTest.java b/src/test/java/com/alibaba/json/bvt/JSONTest.java new file mode 100755 index 0000000000..526e88d975 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONTest.java @@ -0,0 +1,159 @@ +/* + * Copyright 1999-2017 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.json.bvt; + +import java.io.IOException; +import java.io.StringWriter; +import java.math.BigDecimal; +import java.util.HashMap; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializeWriter; + +public class JSONTest extends TestCase { + + public void test_number() throws Exception { + Assert.assertEquals("3", JSON.parse("3").toString()); + Assert.assertEquals("34", JSON.parse("34").toString()); + Assert.assertEquals("922337203685477580755", JSON.parse("922337203685477580755").toString()); + Assert.assertEquals("-34", JSON.parse("-34").toString()); + Assert.assertEquals(new BigDecimal("9.223372036854776E18"), new BigDecimal(JSON.parse("9.223372036854776E18").toString())); + Assert.assertEquals(new BigDecimal("9.223372036854776E+18"), new BigDecimal(JSON.parse("9.223372036854776E+18").toString())); + Assert.assertEquals(new BigDecimal("9.223372036854776E-18"), new BigDecimal(JSON.parse("9.223372036854776E-18").toString())); + } + + public void test_string() throws Exception { + Assert.assertEquals("", JSON.parse("\"\"").toString()); + Assert.assertEquals("3", JSON.parse("\"3\"").toString()); + Assert.assertEquals("34", JSON.parse("\"34\"").toString()); + Assert.assertEquals("3\\4", JSON.parse("\"3\\\\4\"").toString()); + Assert.assertEquals("3\"4", JSON.parse("\"3\\\"4\"").toString()); + Assert.assertEquals("3\\b4", JSON.parse("\"3\\\\b4\"").toString()); + Assert.assertEquals("3\\f4", JSON.parse("\"3\\\\f4\"").toString()); + Assert.assertEquals("3\\n4", JSON.parse("\"3\\\\n4\"").toString()); + Assert.assertEquals("3\\r4", JSON.parse("\"3\\\\r4\"").toString()); + Assert.assertEquals("3\\t4", JSON.parse("\"3\\\\t4\"").toString()); + Assert.assertEquals("中国", JSON.parse("\"中国\"").toString()); + Assert.assertEquals("中国", JSON.parse("\"\\u4E2D\\u56FD\"").toString()); + Assert.assertEquals("\u001F", JSON.parse("\"\\u001F\"").toString()); + } + + public void test_for_jh() throws Exception { + String text = "[{\"I.13\":\"XEMwXFMweGEuMHhjOFxGy87M5VxUxOO6ww==\",\"I.18\":\"MA==\"},{\"I.13\":\"XEMwXFMweGEuMHhjOFxGy87M5VxUxOO6ww==\",\"I.18\":\"MA==\"}]"; + JSON.parse(text); + JSON.parseArray(text); + } + + public void test_value() throws Exception { + Assert.assertEquals(Boolean.TRUE, JSON.parse("true")); + Assert.assertEquals(Boolean.FALSE, JSON.parse("false")); + Assert.assertEquals(null, JSON.parse("null")); + } + + public void test_object() throws Exception { + Assert.assertTrue(JSON.parseObject("{}").size() == 0); + Assert.assertEquals(1, JSON.parseObject("{\"K\":3}").size()); + Assert.assertEquals(3, ((Number) JSON.parseObject("{\"K\":3}").get("K")).intValue()); + Assert.assertEquals(2, JSON.parseObject("{\"K1\":3,\"K2\":4}").size()); + Assert.assertEquals(3, ((Number) JSON.parseObject("{\"K1\":3,\"K2\":4}").get("K1")).intValue()); + Assert.assertEquals(4, ((Number) JSON.parseObject("{\"K1\":3,\"K2\":4}").get("K2")).intValue()); + Assert.assertEquals(1, JSON.parseObject("{\"K\":{}}").size()); + Assert.assertEquals(1, JSON.parseObject("{\"K\":[]}").size()); + } + + public void test_array() throws Exception { + Assert.assertEquals(0, JSON.parseArray("[]").size()); + Assert.assertEquals(1, JSON.parseArray("[1]").size()); + Assert.assertEquals(1, ((Number) JSON.parseArray("[1]").get(0)).intValue()); + Assert.assertEquals(3, JSON.parseArray("[1,2, 3]").size()); + Assert.assertEquals(1, ((Number) JSON.parseArray("[1,2, 3]").get(0)).intValue()); + Assert.assertEquals(2, ((Number) JSON.parseArray("[1,2, 3]").get(1)).intValue()); + Assert.assertEquals(3, ((Number) JSON.parseArray("[1,2, 3]").get(2)).intValue()); + } + + public void test_all() throws Exception { + Assert.assertEquals(null, JSON.parse(null)); + Assert.assertEquals("{}", JSON.toJSONString(new HashMap())); + Assert.assertEquals("{}", JSON.toJSONString(new HashMap(), true)); + Assert.assertEquals("{}", JSON.toJSONString(new HashMap(), true)); + Assert.assertEquals(null, JSON.parseObject(null)); + Assert.assertEquals(null, JSON.parseArray(null)); + Assert.assertEquals(null, JSON.parseObject(null, Object.class)); + Assert.assertEquals(null, JSON.parseArray(null, Object.class)); + } + + public void test_writeTo_0() throws Exception { + SerializeWriter out = new SerializeWriter(); + + JSONObject json = new JSONObject(); + json.writeJSONString(out); + + Assert.assertEquals("{}", out.toString()); + } + + public void test_writeTo_1() throws Exception { + StringWriter out = new StringWriter(); + + JSONObject json = new JSONObject(); + json.writeJSONString(out); + + Assert.assertEquals("{}", out.toString()); + } + + public void test_writeTo_2() throws Exception { + StringBuffer out = new StringBuffer(); + + JSONObject json = new JSONObject(); + json.writeJSONString(out); + + Assert.assertEquals("{}", out.toString()); + } + + public void test_writeTo_error() throws Exception { + JSONException error = null; + try { + JSONObject json = new JSONObject(); + json.writeJSONString(new ErrorAppendable()); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } + + public void test_fromJavaObject_null() throws Exception { + Assert.assertEquals(null, JSON.toJSON(null)); + } + + private final class ErrorAppendable implements Appendable { + + public Appendable append(CharSequence csq, int start, int end) throws IOException { + throw new IOException(""); + } + + public Appendable append(char c) throws IOException { + throw new IOException(""); + } + + public Appendable append(CharSequence csq) throws IOException { + throw new IOException(""); + } + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONTest2.java b/src/test/java/com/alibaba/json/bvt/JSONTest2.java old mode 100644 new mode 100755 similarity index 97% rename from src/test/java/com/alibaba/json/test/bvt/JSONTest2.java rename to src/test/java/com/alibaba/json/bvt/JSONTest2.java index 3eb2abc177..9fa3377689 --- a/src/test/java/com/alibaba/json/test/bvt/JSONTest2.java +++ b/src/test/java/com/alibaba/json/bvt/JSONTest2.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.io.ByteArrayInputStream; import java.io.InputStream; diff --git a/src/test/java/com/alibaba/json/bvt/JSONTest3.java b/src/test/java/com/alibaba/json/bvt/JSONTest3.java new file mode 100644 index 0000000000..373746ed51 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONTest3.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.deserializer.ExtraProcessor; + +import junit.framework.TestCase; + +public class JSONTest3 extends TestCase { + public void test_json() throws Exception { + ExtraProcessor extraProcessor = new ExtraProcessor() { + + public void processExtra(Object object, String key, Object value) { + Model model = (Model) object; + model.attributes.put(key, value); + } + }; + + Model model = JSON.parseObject("{\"id\":1001}", (Type) Model.class, extraProcessor); + Assert.assertEquals(1, model.attributes.size()); + Assert.assertEquals(1001, model.attributes.get("id")); + } + + public static class Model { + private Map attributes = new HashMap(); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONTest_Bytes.java b/src/test/java/com/alibaba/json/bvt/JSONTest_Bytes.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/JSONTest_Bytes.java rename to src/test/java/com/alibaba/json/bvt/JSONTest_Bytes.java index 0278cc0648..117d590f71 --- a/src/test/java/com/alibaba/json/test/bvt/JSONTest_Bytes.java +++ b/src/test/java/com/alibaba/json/bvt/JSONTest_Bytes.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/JSONTest_Bytes_1.java b/src/test/java/com/alibaba/json/bvt/JSONTest_Bytes_1.java new file mode 100644 index 0000000000..d03f02c65b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONTest_Bytes_1.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class JSONTest_Bytes_1 extends TestCase { + + public void test_bytes() throws Exception { + Assert.assertEquals("\"abc\"", new String(JSON.toJSONBytes("abc", SerializeConfig.getGlobalInstance()))); + Assert.assertEquals("'abc'", + new String(JSON.toJSONBytes("abc", SerializeConfig.getGlobalInstance(), + SerializerFeature.UseSingleQuotes))); + } + + public void test_bytes_2() throws Exception { + Assert.assertEquals("\"abc\"", new String(JSON.toJSONBytes("abc"))); + Assert.assertEquals("'abc'", new String(JSON.toJSONBytes("abc", SerializerFeature.UseSingleQuotes))); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONTest_null.java b/src/test/java/com/alibaba/json/bvt/JSONTest_null.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/JSONTest_null.java rename to src/test/java/com/alibaba/json/bvt/JSONTest_null.java index 407866abfe..7ed9881197 --- a/src/test/java/com/alibaba/json/test/bvt/JSONTest_null.java +++ b/src/test/java/com/alibaba/json/bvt/JSONTest_null.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.lang.reflect.Type; import java.nio.charset.Charset; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/JSONTest_overflow.java b/src/test/java/com/alibaba/json/bvt/JSONTest_overflow.java new file mode 100755 index 0000000000..7ed5e66448 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONTest_overflow.java @@ -0,0 +1,43 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.serializer.SerializeConfig; + +public class JSONTest_overflow extends TestCase { + + public void test_overflow() throws Exception { + Entity entity = new Entity(); + entity.setSelf(entity); + + String text = JSON.toJSONString(entity, SerializeConfig.getGlobalInstance()); + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertTrue(entity2 == entity2.getSelf()); + } + + public void test_overflow_1() throws Exception { + Entity entity = new Entity(); + entity.setSelf(entity); + + String text = JSON.toJSONStringZ(entity, SerializeConfig.getGlobalInstance()); + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertTrue(entity2 == entity2.getSelf()); + } + + public static class Entity { + + private Entity self; + + public Entity getSelf() { + return self; + } + + public void setSelf(Entity self) { + this.self = self; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JSONTokenTest.java b/src/test/java/com/alibaba/json/bvt/JSONTokenTest.java old mode 100644 new mode 100755 similarity index 85% rename from src/test/java/com/alibaba/json/test/bvt/JSONTokenTest.java rename to src/test/java/com/alibaba/json/bvt/JSONTokenTest.java index deab193cb6..aa246e6446 --- a/src/test/java/com/alibaba/json/test/bvt/JSONTokenTest.java +++ b/src/test/java/com/alibaba/json/bvt/JSONTokenTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.JSONToken; @@ -28,6 +28,8 @@ public void test_0 () throws Exception { Assert.assertEquals("ident", JSONToken.name(JSONToken.IDENTIFIER)); Assert.assertEquals("fieldName", JSONToken.name(JSONToken.FIELD_NAME)); Assert.assertEquals("EOF", JSONToken.name(JSONToken.EOF)); - Assert.assertEquals("Unkown", JSONToken.name(Integer.MAX_VALUE)); + Assert.assertEquals("Unknown", JSONToken.name(Integer.MAX_VALUE)); + Assert.assertEquals("Set", JSONToken.name(JSONToken.SET)); + Assert.assertEquals("TreeSet", JSONToken.name(JSONToken.TREE_SET)); } } diff --git a/src/test/java/com/alibaba/json/bvt/JSONTypeTest.java b/src/test/java/com/alibaba/json/bvt/JSONTypeTest.java new file mode 100755 index 0000000000..a49aa812f5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONTypeTest.java @@ -0,0 +1,132 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; + +public class JSONTypeTest extends TestCase { + public void test_0() throws Exception { + VO vo = new VO(); + vo.setId(1001); + vo.setName("xx"); + vo.setAge(33); + + Assert.assertEquals("{\"age\":33,\"id\":1001,\"name\":\"xx\"}", + JSON.toJSONString(vo)); + } + + public void test_1() throws Exception { + V1 vo = new V1(); + vo.setId(1001); + vo.setName("xx"); + vo.setAge(33); + + Assert.assertEquals("{\"id\":1001,\"name\":\"xx\",\"age\":33}", + JSON.toJSONString(vo)); + } + + public void test_2() throws Exception { + V1 vo = new V1(); + vo.setId(1001); + vo.setName("xx"); + vo.setAge(33); + + Assert.assertEquals("{\"id\":1001,\"name\":\"xx\",\"age\":33}", + JSON.toJSONString(vo)); + } + + @JSONType + public static class VO { + private int id; + private String name; + private int age; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + } + + @JSONType(orders = { "id", "name", "age" }) + public static class V1 { + private int id; + private String name; + private int age; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + } + + @JSONType(orders = { "id", "name", "age" },asm=false) + private class V2 { + private int id; + private String name; + private int age; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONTypeTest1.java b/src/test/java/com/alibaba/json/bvt/JSONTypeTest1.java new file mode 100755 index 0000000000..e201b1c9ce --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONTypeTest1.java @@ -0,0 +1,140 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; + +public class JSONTypeTest1 extends TestCase { + + public void test_ignores() throws Exception { + A a = new A(); + a.setF1(1001); + a.setF2(1002); + a.setF3(1003); + + Assert.assertEquals("{\"f1\":1001,\"f3\":1003}", JSON.toJSONString(a)); + } + + public void test_ignoresParent() throws Exception { + B b = new B(); + b.setF1(1001); + b.setF2(1002); + b.setF3(1003); + b.setF4(1004); + b.setF5(1005); + + Assert.assertEquals("{\"f1\":1001,\"f3\":1003,\"f5\":1005}", JSON.toJSONString(b)); + } + + public void test_ignoresParent2() throws Exception { + C c = new C(); + c.setF1(1001); + c.setF2(1002); + c.setF3(1003); + c.setF4(1004); + c.setF5(1005); + c.setF6(1006); + + Assert.assertEquals("{\"f1\":1001,\"f3\":1003,\"f5\":1005,\"f6\":1006}", JSON.toJSONString(c)); + } + + public void test_ignoresParent3() throws Exception { + D d = new D(); + d.setF1(1001); + d.setF2(1002); + d.setF3(1003); + d.setF4(1004); + d.setF5(1005); + d.setF6(1006); + d.setF7(1007); + + Assert.assertEquals("{\"f1\":1001,\"f3\":1003,\"f5\":1005,\"f6\":1006,\"f7\":1007}", JSON.toJSONString(d)); + } + + @JSONType(ignores = "f2") + public static class A { + + private int f1; + private int f2; + private int f3; + + public int getF1() { + return f1; + } + + public void setF1(int f1) { + this.f1 = f1; + } + + public int getF2() { + return f2; + } + + public void setF2(int f2) { + this.f2 = f2; + } + + public int getF3() { + return f3; + } + + public void setF3(int f3) { + this.f3 = f3; + } + + } + + @JSONType(ignores = { "f4" }) + public static class B extends A { + + private int f4; + private int f5; + + public int getF4() { + return f4; + } + + public void setF4(int f4) { + this.f4 = f4; + } + + public int getF5() { + return f5; + } + + public void setF5(int f5) { + this.f5 = f5; + } + + } + + public static class C extends B { + + private int f6; + + public int getF6() { + return f6; + } + + public void setF6(int f6) { + this.f6 = f6; + } + + } + + public static class D extends C { + + private int f7; + + public int getF7() { + return f7; + } + + public void setF7(int f7) { + this.f7 = f7; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONTypeTest_orders_arrayMapping.java b/src/test/java/com/alibaba/json/bvt/JSONTypeTest_orders_arrayMapping.java new file mode 100755 index 0000000000..5beed8c21e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONTypeTest_orders_arrayMapping.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +public class JSONTypeTest_orders_arrayMapping extends TestCase { + public void test_1() throws Exception { + Model vo = new Model(); + vo.setId(1001); + vo.setName("xx"); + vo.setAge(33); + + String json = JSON.toJSONString(vo, SerializerFeature.BeanToArray); + assertEquals("[1001,\"xx\",33]", json); + + JSON.parseObject(json, Model.class, Feature.SupportArrayToBean); + + Model[] array = new Model[] {vo}; + String json2 = JSON.toJSONString(array, SerializerFeature.BeanToArray); + JSON.parseObject(json2, Model[].class, Feature.SupportArrayToBean); + } + + @JSONType(orders = { "id", "name", "age" }) + public static class Model { + private int id; + private String name; + private int age; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/JSONTypeTest_orders_arrayMapping_2.java b/src/test/java/com/alibaba/json/bvt/JSONTypeTest_orders_arrayMapping_2.java new file mode 100755 index 0000000000..951d4c7a99 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JSONTypeTest_orders_arrayMapping_2.java @@ -0,0 +1,83 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +public class JSONTypeTest_orders_arrayMapping_2 extends TestCase { + public void test_1() throws Exception { + Model vo = new Model(); + vo.setId(1001); + vo.setName("xx"); + vo.setAge(33); + vo.setDvalue(0.1D); + + String json = JSON.toJSONString(vo); + assertEquals("[1001,\"xx\",33,0.0,0.1]", json); + + JSON.parseObject(json, Model.class); + + Model[] array = new Model[] {vo}; + String json2 = JSON.toJSONString(array); + JSON.parseObject(json2, Model[].class); + + String json3 = "[\"1001\",\"xx\",33,\"0.0\",\"0.1\"]"; + JSON.parseObject(json3, Model.class); + } + + @JSONType(orders = {"id", "name", "age", "value"} + , serialzeFeatures = SerializerFeature.BeanToArray + , parseFeatures = Feature.SupportArrayToBean + ) + public static class Model { + private int id; + private String name; + private int age; + private float value; + private double dvalue; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public float getValue() { + return value; + } + + public void setValue(float value) { + this.value = value; + } + + public double getDvalue() { + return dvalue; + } + + public void setDvalue(double dvalue) { + this.dvalue = dvalue; + } + } + + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JSON_toJSONStringTest.java b/src/test/java/com/alibaba/json/bvt/JSON_toJSONStringTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/JSON_toJSONStringTest.java rename to src/test/java/com/alibaba/json/bvt/JSON_toJSONStringTest.java index ec28af5298..92a5b7f113 --- a/src/test/java/com/alibaba/json/test/bvt/JSON_toJSONStringTest.java +++ b/src/test/java/com/alibaba/json/bvt/JSON_toJSONStringTest.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.Collections; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; diff --git a/src/test/java/com/alibaba/json/test/bvt/JSON_toJavaObject_test.java b/src/test/java/com/alibaba/json/bvt/JSON_toJavaObject_test.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/JSON_toJavaObject_test.java rename to src/test/java/com/alibaba/json/bvt/JSON_toJavaObject_test.java index 4ce968be19..8b4e3bf744 --- a/src/test/java/com/alibaba/json/test/bvt/JSON_toJavaObject_test.java +++ b/src/test/java/com/alibaba/json/bvt/JSON_toJavaObject_test.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/JavaBeanMappingTest.java b/src/test/java/com/alibaba/json/bvt/JavaBeanMappingTest.java new file mode 100755 index 0000000000..eb168bb11f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JavaBeanMappingTest.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.parser.ParserConfig; + +import junit.framework.TestCase; + +@SuppressWarnings("deprecation") +public class JavaBeanMappingTest extends TestCase { + + public void test_0 () throws Exception { + ParserConfig.getGlobalInstance(); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/JavaBeanTest.java b/src/test/java/com/alibaba/json/bvt/JavaBeanTest.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/JavaBeanTest.java rename to src/test/java/com/alibaba/json/bvt/JavaBeanTest.java index 970907ae0e..8ba1abd5f3 --- a/src/test/java/com/alibaba/json/test/bvt/JavaBeanTest.java +++ b/src/test/java/com/alibaba/json/bvt/JavaBeanTest.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/JsonValueTest.java b/src/test/java/com/alibaba/json/bvt/JsonValueTest.java new file mode 100755 index 0000000000..4fe69de324 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/JsonValueTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 1999-2017 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.json.bvt; + +import java.util.Date; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class JsonValueTest extends TestCase { + + public void test_toJSONString() throws Exception { + Assert.assertEquals("null", JSON.toJSONString(Double.NaN)); + Assert.assertEquals("3.0", JSON.toJSONString(3D)); + Assert.assertEquals("null", JSON.toJSONString(Float.NaN)); + Assert.assertEquals("3.0", JSON.toJSONString(3F)); + Assert.assertEquals("1292939095640", JSON.toJSONString(new Date(1292939095640L))); + Assert.assertEquals(new Date(1292939095640L), JSON.parse("new Date(1292939095640)")); + } + + public void test_bug_0() throws Exception { + String text = "[{\"S\":0,\"T\":\"Register\"},{\"HOST_NAME\":\"qa-qd-62-187\",\"IP\":[\"172.29.62.187\"],\"MAC_ADDR\":[\"00:16:3E:43:E5:1C\"],\"SERVICE_TAG\":\"NOSN00:16:3E:43:E5:1C\",\"VERSION\":\"2.5\"}] "; + JSON.parseArray(text); + } + + public void test_bug_1() throws Exception { + String text = "[{\"S\":2,\"T\":\"ConnectResp\"},\n\r \t{\"VAL\" :null}]\r\f"; + JSON.parseArray(text); + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/LexerTest.java b/src/test/java/com/alibaba/json/bvt/LexerTest.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/LexerTest.java rename to src/test/java/com/alibaba/json/bvt/LexerTest.java index 5fdb4b4882..77b10cd80d --- a/src/test/java/com/alibaba/json/test/bvt/LexerTest.java +++ b/src/test/java/com/alibaba/json/bvt/LexerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.math.BigDecimal; import java.math.BigInteger; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -70,7 +70,7 @@ public void test_string() throws Exception { String stringVal = lexer.stringVal(); - Assert.assertEquals("\"\\\\/\\b\\f\\n\\r\t中\"", JSON.toJSONString(stringVal)); + Assert.assertEquals("\"\\\\/\\b\\f\\n\\r\\t中\"", JSON.toJSONString(stringVal)); } diff --git a/src/test/java/com/alibaba/json/test/bvt/LinkedListFieldTest.java b/src/test/java/com/alibaba/json/bvt/LinkedListFieldTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/LinkedListFieldTest.java rename to src/test/java/com/alibaba/json/bvt/LinkedListFieldTest.java index ed217e89a9..b6cd8cc92b --- a/src/test/java/com/alibaba/json/test/bvt/LinkedListFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/LinkedListFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.LinkedList; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/ListFieldTest.java b/src/test/java/com/alibaba/json/bvt/ListFieldTest.java new file mode 100755 index 0000000000..327f4cc6b7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ListFieldTest.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt; + +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class ListFieldTest extends TestCase { + public void test_codec_null() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"value\":null}", text); + + ParserConfig config = new ParserConfig(); + config.setAutoTypeSupport(true); + config.setAsmEnable(false); + + V0 v1 = JSON.parseObject(text, V0.class, config, JSON.DEFAULT_PARSER_FEATURE); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public static class V0 { + + private List value; + + public List getValue() { + return value; + } + + public void setValue(List value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/ListFieldTest2.java b/src/test/java/com/alibaba/json/bvt/ListFieldTest2.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/ListFieldTest2.java rename to src/test/java/com/alibaba/json/bvt/ListFieldTest2.java index e44a392786..3fa264e8af --- a/src/test/java/com/alibaba/json/test/bvt/ListFieldTest2.java +++ b/src/test/java/com/alibaba/json/bvt/ListFieldTest2.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/ListFieldTest3.java b/src/test/java/com/alibaba/json/bvt/ListFieldTest3.java new file mode 100644 index 0000000000..980c576517 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ListFieldTest3.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +import data.media.MediaContent; + +public class ListFieldTest3 extends TestCase { + + public void test_typeRef() throws Exception { + String text = "{\"images\":[],\"media\":{\"width\":640}}"; + + MediaContent object = JSON.parseObject(text, MediaContent.class); + } + + public static class Root { + private List images = new ArrayList(); + private Entity media; + + public List getImages() { + return images; + } + + public void setImages(List images) { + this.images = images; + } + + public Entity getMedia() { + return media; + } + + public void setMedia(Entity media) { + this.media = media; + } + + } + + public static class Image { + public int width; + } + + public static class Entity { + public String title; // Can be null + public int width; + public int height; + public Size size; + } + + public enum Size { + SMALL, LARGE + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/ListFloatFieldTest.java b/src/test/java/com/alibaba/json/bvt/ListFloatFieldTest.java old mode 100644 new mode 100755 similarity index 88% rename from src/test/java/com/alibaba/json/test/bvt/ListFloatFieldTest.java rename to src/test/java/com/alibaba/json/bvt/ListFloatFieldTest.java index 8ba1fd98c6..302e3326b2 --- a/src/test/java/com/alibaba/json/test/bvt/ListFloatFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/ListFloatFieldTest.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.ArrayList; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/LocaleFieldTest.java b/src/test/java/com/alibaba/json/bvt/LocaleFieldTest.java new file mode 100755 index 0000000000..ceb578a23c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/LocaleFieldTest.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt; + +import java.util.Locale; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class LocaleFieldTest extends TestCase { + + public void test_codec() throws Exception { + User user = new User(); + user.setValue(Locale.CANADA); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + String text = JSON.toJSONString(user, mapping, SerializerFeature.WriteMapNullValue); + + User user1 = JSON.parseObject(text, User.class); + + Assert.assertEquals(user1.getValue(), user.getValue()); + } + + public void test_codec_null() throws Exception { + User user = new User(); + user.setValue(null); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + String text = JSON.toJSONString(user, mapping, SerializerFeature.WriteMapNullValue); + + User user1 = JSON.parseObject(text, User.class); + + Assert.assertEquals(user1.getValue(), user.getValue()); + } + + public static class User { + + private Locale value; + + public Locale getValue() { + return value; + } + + public void setValue(Locale value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/LongArrayFieldTest.java b/src/test/java/com/alibaba/json/bvt/LongArrayFieldTest.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/LongArrayFieldTest.java rename to src/test/java/com/alibaba/json/bvt/LongArrayFieldTest.java index 842a968dc4..4e21abd47f --- a/src/test/java/com/alibaba/json/test/bvt/LongArrayFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/LongArrayFieldTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/LongArrayFieldTest_primitive.java b/src/test/java/com/alibaba/json/bvt/LongArrayFieldTest_primitive.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/LongArrayFieldTest_primitive.java rename to src/test/java/com/alibaba/json/bvt/LongArrayFieldTest_primitive.java index 743fbe5d0a..1c60406c70 --- a/src/test/java/com/alibaba/json/test/bvt/LongArrayFieldTest_primitive.java +++ b/src/test/java/com/alibaba/json/bvt/LongArrayFieldTest_primitive.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/LongFieldTest.java b/src/test/java/com/alibaba/json/bvt/LongFieldTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/LongFieldTest.java rename to src/test/java/com/alibaba/json/bvt/LongFieldTest.java index 1e21afd73d..43e25a379e --- a/src/test/java/com/alibaba/json/test/bvt/LongFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/LongFieldTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/LongFieldTest_2.java b/src/test/java/com/alibaba/json/bvt/LongFieldTest_2.java new file mode 100644 index 0000000000..6193296049 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/LongFieldTest_2.java @@ -0,0 +1,117 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSONReader; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +import java.io.StringReader; + +public class LongFieldTest_2 extends TestCase { + + public void test_min() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_min_reader() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v); + + V0 v1 = new JSONReader(new StringReader(text)).readObject(V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_max() throws Exception { + V0 v = new V0(); + v.setValue(Long.MAX_VALUE); + + String text = JSON.toJSONString(v); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_max_reader() throws Exception { + V0 v = new V0(); + v.setValue(Long.MAX_VALUE); + + String text = JSON.toJSONString(v); + + V0 v1 = new JSONReader(new StringReader(text)).readObject(V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_min_array() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v, SerializerFeature.BeanToArray); + + V0 v1 = JSON.parseObject(text, V0.class, Feature.SupportArrayToBean); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_min_array_reader() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v, SerializerFeature.BeanToArray); + + V0 v1 = new JSONReader(new StringReader(text), Feature.SupportArrayToBean).readObject(V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_max_array() throws Exception { + V0 v = new V0(); + v.setValue(Long.MAX_VALUE); + + String text = JSON.toJSONString(v, SerializerFeature.BeanToArray); + + V0 v1 = JSON.parseObject(text, V0.class, Feature.SupportArrayToBean); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_max_array_reader() throws Exception { + V0 v = new V0(); + v.setValue(Long.MAX_VALUE); + + String text = JSON.toJSONString(v, SerializerFeature.BeanToArray); + + V0 v1 = new JSONReader(new StringReader(text), Feature.SupportArrayToBean).readObject(V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public static class V0 { + + private Long value; + + public Long getValue() { + return value; + } + + public void setValue(Long value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/LongFieldTest_2_private.java b/src/test/java/com/alibaba/json/bvt/LongFieldTest_2_private.java new file mode 100644 index 0000000000..e5d4b556cb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/LongFieldTest_2_private.java @@ -0,0 +1,71 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.bvt.LongFieldTest_2.V0; + +import junit.framework.TestCase; + +public class LongFieldTest_2_private extends TestCase { + + public void test_min() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_max() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_min_array() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v, SerializerFeature.BeanToArray); + + V0 v1 = JSON.parseObject(text, V0.class, Feature.SupportArrayToBean); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_max_array() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v, SerializerFeature.BeanToArray); + + V0 v1 = JSON.parseObject(text, V0.class, Feature.SupportArrayToBean); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + private static class V0 { + + private Long value; + + public Long getValue() { + return value; + } + + public void setValue(Long value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/LongFieldTest_2_stream.java b/src/test/java/com/alibaba/json/bvt/LongFieldTest_2_stream.java new file mode 100644 index 0000000000..8f1c2c1f98 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/LongFieldTest_2_stream.java @@ -0,0 +1,77 @@ +package com.alibaba.json.bvt; + +import java.io.StringReader; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class LongFieldTest_2_stream extends TestCase { + + public void test_min() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v); + + JSONReader reader = new JSONReader(new StringReader(text)); + V0 v1 = reader.readObject(V0.class); + Assert.assertEquals(v1.getValue(), v.getValue()); + reader.close(); + } + + public void test_max() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v); + + JSONReader reader = new JSONReader(new StringReader(text)); + V0 v1 = reader.readObject(V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_min_array() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v, SerializerFeature.BeanToArray); + + JSONReader reader = new JSONReader(new StringReader(text), Feature.SupportArrayToBean); + V0 v1 = reader.readObject(V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_max_array() throws Exception { + V0 v = new V0(); + v.setValue(Long.MIN_VALUE); + + String text = JSON.toJSONString(v, SerializerFeature.BeanToArray); + + JSONReader reader = new JSONReader(new StringReader(text), Feature.SupportArrayToBean); + V0 v1 = reader.readObject(V0.class); + + Assert.assertEquals(v.getValue(), v1.getValue()); + } + + public static class V0 { + + private Long value; + + public Long getValue() { + return value; + } + + public void setValue(Long value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/LongFieldTest_3.java b/src/test/java/com/alibaba/json/bvt/LongFieldTest_3.java new file mode 100644 index 0000000000..ccdb3bcd1b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/LongFieldTest_3.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt; + +import java.util.Random; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class LongFieldTest_3 extends TestCase { + + public void test_min() throws Exception { + Random random = new Random(); + Model[] array = new Model[2048]; + for (int i = 0; i < array.length; ++i) { + array[i] = new Model(); + array[i].value = random.nextLong(); + } + + String text = JSON.toJSONString(array); + + Model[] array2 = JSON.parseObject(text, Model[].class); + + Assert.assertEquals(array.length, array2.length); + for (int i = 0; i < array.length; ++i) { + Assert.assertEquals(array[i].value, array2[i].value); + } + } + + + public static class Model { + + public long value; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/LongFieldTest_3_private.java b/src/test/java/com/alibaba/json/bvt/LongFieldTest_3_private.java new file mode 100644 index 0000000000..1bff667c0f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/LongFieldTest_3_private.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt; + +import java.util.Random; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class LongFieldTest_3_private extends TestCase { + + public void test_min() throws Exception { + Random random = new Random(); + Model[] array = new Model[8192]; + for (int i = 0; i < array.length; ++i) { + array[i] = new Model(); + array[i].value = random.nextLong(); + } + + String text = JSON.toJSONString(array); + + Model[] array2 = JSON.parseObject(text, Model[].class); + + Assert.assertEquals(array.length, array2.length); + for (int i = 0; i < array.length; ++i) { + Assert.assertEquals(array[i].value, array2[i].value); + } + } + + + private static class Model { + + public long value; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/LongFieldTest_3_stream.java b/src/test/java/com/alibaba/json/bvt/LongFieldTest_3_stream.java new file mode 100644 index 0000000000..5af6b4e9d7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/LongFieldTest_3_stream.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt; + +import java.io.StringReader; +import java.util.Random; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; + +import junit.framework.TestCase; + +public class LongFieldTest_3_stream extends TestCase { + + public void test_min() throws Exception { + Random random = new Random(); + Model[] array = new Model[8192]; + for (int i = 0; i < array.length; ++i) { + array[i] = new Model(); + array[i].value = random.nextLong(); + } + + String text = JSON.toJSONString(array); + + JSONReader reader = new JSONReader(new StringReader(text)); + Model[] array2 = reader.readObject(Model[].class); + + Assert.assertEquals(array.length, array2.length); + for (int i = 0; i < array.length; ++i) { + Assert.assertEquals(array[i].value, array2[i].value); + } + reader.close(); + } + + + public static class Model { + + public long value; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/LongFieldTest_4.java b/src/test/java/com/alibaba/json/bvt/LongFieldTest_4.java new file mode 100644 index 0000000000..f891c91768 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/LongFieldTest_4.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt; + +import java.util.Random; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class LongFieldTest_4 extends TestCase { + + public void test_min() throws Exception { + Random random = new Random(); + Model[] array = new Model[2048]; + for (int i = 0; i < array.length; ++i) { + array[i] = new Model(); + array[i].value = random.nextLong(); + } + + String text = JSON.toJSONString(array); + + Model[] array2 = JSON.parseObject(text, Model[].class); + + Assert.assertEquals(array.length, array2.length); + for (int i = 0; i < array.length; ++i) { + Assert.assertEquals(array[i].value, array2[i].value); + } + } + + @JSONType(serialzeFeatures = SerializerFeature.BeanToArray, parseFeatures = Feature.SupportArrayToBean) + public static class Model { + + public long value; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/LongFieldTest_4_stream.java b/src/test/java/com/alibaba/json/bvt/LongFieldTest_4_stream.java new file mode 100644 index 0000000000..dac0846604 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/LongFieldTest_4_stream.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt; + +import java.io.StringReader; +import java.util.Random; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.bvt.LongFieldTest_3_stream.Model; + +import junit.framework.TestCase; + +public class LongFieldTest_4_stream extends TestCase { + + public void test_min() throws Exception { + Random random = new Random(); + Model[] array = new Model[2048]; + for (int i = 0; i < array.length; ++i) { + array[i] = new Model(); + array[i].value = random.nextLong(); + } + + String text = JSON.toJSONString(array); + + JSONReader reader = new JSONReader(new StringReader(text)); + Model[] array2 = reader.readObject(Model[].class); + + Assert.assertEquals(array.length, array2.length); + for (int i = 0; i < array.length; ++i) { + Assert.assertEquals(array[i].value, array2[i].value); + } + reader.close(); + } + + @JSONType(serialzeFeatures = SerializerFeature.BeanToArray, parseFeatures = Feature.SupportArrayToBean) + public static class Model { + + public long value; + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/LongFieldTest_primitive.java b/src/test/java/com/alibaba/json/bvt/LongFieldTest_primitive.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/LongFieldTest_primitive.java rename to src/test/java/com/alibaba/json/bvt/LongFieldTest_primitive.java index 0cf617a222..ed0786e56a --- a/src/test/java/com/alibaba/json/test/bvt/LongFieldTest_primitive.java +++ b/src/test/java/com/alibaba/json/bvt/LongFieldTest_primitive.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/MapRefTest.java b/src/test/java/com/alibaba/json/bvt/MapRefTest.java new file mode 100755 index 0000000000..9220f9f36b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/MapRefTest.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class MapRefTest extends TestCase { + + public void test_0() throws Exception { + String text; + { + Map map = new HashMap(); + + User user = new User(); + user.setId(123); + user.setName("wenshao"); + + map.put("u1", user); + map.put("u2", user); + + text = JSON.toJSONString(map); + } + + System.out.println(text); + Map map = JSON.parseObject(text, new TypeReference>() {}); + //Assert.assertEquals(map, map.get("this")); + Assert.assertEquals(map.get("u1"), map.get("u2")); + } + + public static class User { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/MapRefTest1.java b/src/test/java/com/alibaba/json/bvt/MapRefTest1.java new file mode 100755 index 0000000000..dbd439b705 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/MapRefTest1.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class MapRefTest1 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.MapRefTest1"); + } + + public void test_0() throws Exception { + String text; + { + Map map = new HashMap(); + + User user = new User(); + user.setId(123); + user.setName("wenshao"); + + map.put("u1", user); + map.put("u2", user); + + text = JSON.toJSONString(map, SerializerFeature.WriteClassName); + } + + System.out.println(text); + Map map = JSON.parseObject(text); + //Assert.assertEquals(map, map.get("this")); + Assert.assertEquals(map.get("u1"), map.get("u2")); + } + + public static class User { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/MapRefTest2.java b/src/test/java/com/alibaba/json/bvt/MapRefTest2.java new file mode 100755 index 0000000000..8a256472f4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/MapRefTest2.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class MapRefTest2 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.MapRefTest2"); + } + + public void test_0() throws Exception { + String text; + { + Map map = new HashMap(); + + User user = new User(); + user.setId(123); + user.setName("wenshao"); + + map.put("u1", user); + map.put("u2", user); + + text = JSON.toJSONString(map, SerializerFeature.WriteClassName); + } + + System.out.println(text); + Map map = JSON.parseObject(text, new TypeReference>() {}); + //Assert.assertEquals(map, map.get("this")); + Assert.assertEquals(map.get("u1"), map.get("u2")); + } + + public static class User { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/MapRefTest3.java b/src/test/java/com/alibaba/json/bvt/MapRefTest3.java new file mode 100755 index 0000000000..b72cadfdbd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/MapRefTest3.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class MapRefTest3 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.MapRefTest3"); + } + + public void test_0() throws Exception { + String text; + { + Map map = new HashMap(); + + User user = new User(); + user.setId(123); + user.setName("wenshao"); + + map.put("u1", user); + map.put("u2", user); + + text = JSON.toJSONString(map, SerializerFeature.WriteClassName); + } + + System.out.println(text); + Map map = JSON.parseObject(text, new TypeReference>() {}); + //Assert.assertEquals(map, map.get("this")); + Assert.assertEquals(map.get("u1"), map.get("u2")); + } + + public static class User { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/MapRefTest4.java b/src/test/java/com/alibaba/json/bvt/MapRefTest4.java new file mode 100644 index 0000000000..bd183d6202 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/MapRefTest4.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt; + +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class MapRefTest4 extends TestCase { + + public void test_0() throws Exception { + String text = "{\"u1\":{\"id\":123,\"name\":\"wenshao\"},\"u2\":{\"$ref\":\"..\"}}"; + Map map = JSON.parseObject(text, new TypeReference>() {}); + //Assert.assertEquals(map, map.get("this")); + Assert.assertSame(map, map.get("u2")); + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/MapRefTest5.java b/src/test/java/com/alibaba/json/bvt/MapRefTest5.java new file mode 100644 index 0000000000..ebaa8165a3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/MapRefTest5.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt; + +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class MapRefTest5 extends TestCase { + + public void test_0() throws Exception { + String text = "[{\"u1\":{\"id\":123,\"name\":\"wenshao\"},\"u2\":{\"$ref\":\"$\"}}]"; + List> list = JSON.parseObject(text, new TypeReference>>() {}); + //Assert.assertEquals(map, map.get("this")); + Assert.assertSame(list, list.get(0).get("u2")); + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/MapRefTest6.java b/src/test/java/com/alibaba/json/bvt/MapRefTest6.java new file mode 100644 index 0000000000..4a985d6540 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/MapRefTest6.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt; + +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class MapRefTest6 extends TestCase { + + public void test_0() throws Exception { + List> list = JSON.parseObject("[{},{\"$\":\"$[0]\"},{\"$001\":\"101\"},{\"$r01\":\"102\"},{\"$re1\":\"103\"}]", + new TypeReference>>() { + }); + Assert.assertEquals(5, list.size()); + Assert.assertEquals(true, ((Map)list.get(0)).isEmpty()); + Assert.assertEquals("$[0]", ((Map)list.get(1)).get("$")); + Assert.assertEquals("101", ((Map)list.get(2)).get("$001")); + Assert.assertEquals("102", ((Map)list.get(3)).get("$r01")); + Assert.assertEquals("103", ((Map)list.get(4)).get("$re1")); + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/MapTest.java b/src/test/java/com/alibaba/json/bvt/MapTest.java new file mode 100755 index 0000000000..317d4d492b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/MapTest.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class MapTest extends TestCase { + + public void test_null() throws Exception { + Map map = new HashMap(); + map.put(null, "123"); + String text = JSON.toJSONString(map); + Assert.assertEquals("{null:\"123\"}", text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/MapTest2.java b/src/test/java/com/alibaba/json/bvt/MapTest2.java new file mode 100755 index 0000000000..152324ade8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/MapTest2.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt; + +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + + +public class MapTest2 extends TestCase { + public void test_map () throws Exception { +Map map = JSON.parseObject("{1:\"2\",\"3\":4,'5':6}", new TypeReference>() {}); +Assert.assertEquals("2", map.get(1)); +Assert.assertEquals(4, map.get("3")); +Assert.assertEquals(6, map.get("5")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/MaterializedInterfaceTest.java b/src/test/java/com/alibaba/json/bvt/MaterializedInterfaceTest.java new file mode 100755 index 0000000000..74fecca5a8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/MaterializedInterfaceTest.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class MaterializedInterfaceTest extends TestCase { + + public void test_parse() throws Exception { + String text = "{\"id\":123, \"name\":\"chris\"}"; + Bean bean = JSON.parseObject(text, Bean.class); + + Assert.assertEquals(123, bean.getId()); + Assert.assertEquals("chris", bean.getName()); + + String text2 = JSON.toJSONString(bean); + System.out.println(text2); + } + + public static interface Bean { + int getId(); + + void setId(int value); + + String getName(); + + void setName(String value); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/MaterializedInterfaceTest2.java b/src/test/java/com/alibaba/json/bvt/MaterializedInterfaceTest2.java new file mode 100755 index 0000000000..ee41825d87 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/MaterializedInterfaceTest2.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.util.TypeUtils; + +public class MaterializedInterfaceTest2 extends TestCase { + + public void test_parse() throws Exception { + String text = "{\"id\":123, \"name\":\"chris\"}"; + JSONObject object = JSON.parseObject(text); + + Bean bean = TypeUtils.cast(object, Bean.class, null); + + Assert.assertEquals(123, bean.getId()); + Assert.assertEquals("chris", bean.getName()); + + String text2 = JSON.toJSONString(bean); + System.out.println(text2); + } + + public static interface Bean { + int getId(); + + void setId(int value); + + String getName(); + + void setName(String value); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/NotWriteRootClassNameTest.java b/src/test/java/com/alibaba/json/bvt/NotWriteRootClassNameTest.java new file mode 100755 index 0000000000..1eb1777e9b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/NotWriteRootClassNameTest.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import org.junit.Assert; +import junit.framework.TestCase; + + +public class NotWriteRootClassNameTest extends TestCase { + public void test_NotWriteRootClassName() throws Exception { + SerializerFeature[] features = new SerializerFeature[] {SerializerFeature.WriteClassName, SerializerFeature.NotWriteRootClassName}; + Assert.assertEquals("{}", JSON.toJSONString(new VO(), features)); + Assert.assertEquals("{}", JSON.toJSONString(new V1(), features)); + } + + public static class VO { + + } + + private static class V1 { + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/NumberFieldTest.java b/src/test/java/com/alibaba/json/bvt/NumberFieldTest.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/NumberFieldTest.java rename to src/test/java/com/alibaba/json/bvt/NumberFieldTest.java index 57ff6843af..858eff34f6 --- a/src/test/java/com/alibaba/json/test/bvt/NumberFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/NumberFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.math.BigDecimal; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/OOMTest.java b/src/test/java/com/alibaba/json/bvt/OOMTest.java new file mode 100755 index 0000000000..5ec08ef0e9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/OOMTest.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt; + +import java.lang.reflect.Field; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.SymbolTable; + +import junit.framework.TestCase; + +public class OOMTest extends TestCase { + public void test_oom() throws Exception { + + for (int i = 0; i < 1000 * 1000; ++i) { + String text = "{\"" + i + "\":0}"; + JSON.parse(text); + } + + Field field = SymbolTable.class.getDeclaredField("symbols"); + field.setAccessible(true); + Object[] symbols = (Object[]) field.get(ParserConfig.getGlobalInstance().symbolTable); + Assert.assertEquals(4096, symbols.length); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/ObjectArrayFieldTest.java b/src/test/java/com/alibaba/json/bvt/ObjectArrayFieldTest.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/ObjectArrayFieldTest.java rename to src/test/java/com/alibaba/json/bvt/ObjectArrayFieldTest.java index d8db375deb..072fde0566 --- a/src/test/java/com/alibaba/json/test/bvt/ObjectArrayFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/ObjectArrayFieldTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/ObjectFieldTest.java b/src/test/java/com/alibaba/json/bvt/ObjectFieldTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/ObjectFieldTest.java rename to src/test/java/com/alibaba/json/bvt/ObjectFieldTest.java index d48d3c0054..a25dad03bd --- a/src/test/java/com/alibaba/json/test/bvt/ObjectFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/ObjectFieldTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/OverriadeTest.java b/src/test/java/com/alibaba/json/bvt/OverriadeTest.java new file mode 100644 index 0000000000..264a9a8db7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/OverriadeTest.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class OverriadeTest extends TestCase { + + public void test_override() throws Exception { + JSON.parseObject("{\"id\":123}", B.class); + } + + public static class A { + + protected long id; + + public long getId() { + return id; + } + + public void setId(long id) { + throw new UnsupportedOperationException(); + } + + } + + public static class B extends A { + public void setId(String id) { + this.id = Long.parseLong(id); + } + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/ParseArrayTest.java b/src/test/java/com/alibaba/json/bvt/ParseArrayTest.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/ParseArrayTest.java rename to src/test/java/com/alibaba/json/bvt/ParseArrayTest.java index a621117c0f..d0ca757830 --- a/src/test/java/com/alibaba/json/test/bvt/ParseArrayTest.java +++ b/src/test/java/com/alibaba/json/bvt/ParseArrayTest.java @@ -1,11 +1,11 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.TreeMap; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/PatternFieldTest.java b/src/test/java/com/alibaba/json/bvt/PatternFieldTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/PatternFieldTest.java rename to src/test/java/com/alibaba/json/bvt/PatternFieldTest.java index 3dd2a544d2..d36ab51751 --- a/src/test/java/com/alibaba/json/test/bvt/PatternFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/PatternFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.regex.Pattern; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/PointTest.java b/src/test/java/com/alibaba/json/bvt/PointTest.java new file mode 100755 index 0000000000..981f6a2d40 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/PointTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt; + +import java.awt.Point; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.AwtCodec; +import com.alibaba.fastjson.serializer.JSONSerializer; + +import junit.framework.TestCase; + +public class PointTest extends TestCase { + + public void test_color() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Point.class).getClass()); + + Point point = new Point(3, 4); + String text = JSON.toJSONString(point); + + Point point2 = JSON.parseObject(text, Point.class); + + Assert.assertEquals(point, point2); + } + + public void test_color_2() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Point.class).getClass()); + + Point point = new Point(5, 6); + String text = JSON.toJSONString(point); + + Point point2 = JSON.parseObject(text, Point.class); + + Assert.assertEquals(point, point2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/PointTest2.java b/src/test/java/com/alibaba/json/bvt/PointTest2.java new file mode 100755 index 0000000000..b6568ba669 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/PointTest2.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt; + +import java.awt.Point; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.AwtCodec; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class PointTest2 extends TestCase { + + public void test_point() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Point.class).getClass()); + + Point point = new Point(3, 4); + String text = JSON.toJSONString(point, SerializerFeature.WriteClassName); + + System.out.println(text); + Object obj = JSON.parse(text); + Point point2 = (Point) obj; + + Assert.assertEquals(point, point2); + + Point point3 = (Point) JSON.parseObject(text, Point.class); + + Assert.assertEquals(point, point3); + } + + public void test_point2() throws Exception { + JSON.parseObject("{}", Point.class); + JSON.parseArray("[null,null]", Point.class); + Assert.assertNull(JSON.parseObject("null", Point.class)); + JSON.parseObject("{\"@type\":\"java.awt.Point\"}", Point.class); + JSON.parseObject("{\"value\":null}", VO.class); + } + + public static class VO { + + private Point value; + + public Point getValue() { + return value; + } + + public void setValue(Point value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/PublicFieldDoubleTest.java b/src/test/java/com/alibaba/json/bvt/PublicFieldDoubleTest.java new file mode 100755 index 0000000000..9cf758bcd3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/PublicFieldDoubleTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class PublicFieldDoubleTest extends TestCase { + + public static class VO { + + public double id; + } + + public void test_codec() throws Exception { + VO vo = new VO(); + vo.id = 12.34; + + String str = JSON.toJSONString(vo); + + VO vo1 = JSON.parseObject(str, VO.class); + + Assert.assertTrue(vo1.id == vo.id); + } + + public void test_nan() throws Exception { + JSON.parseObject("{\"id\":NaN}", VO.class); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/PublicFieldFloatTest.java b/src/test/java/com/alibaba/json/bvt/PublicFieldFloatTest.java new file mode 100755 index 0000000000..c44e4a2647 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/PublicFieldFloatTest.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class PublicFieldFloatTest extends TestCase { + + public static class VO { + + public float id; + } + + public void test_codec() throws Exception { + VO vo = new VO(); + vo.id = 123.4F; + + String str = JSON.toJSONString(vo); + + VO vo1 = JSON.parseObject(str, VO.class); + + Assert.assertTrue(vo1.id == vo.id); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/PublicFieldLongTest.java b/src/test/java/com/alibaba/json/bvt/PublicFieldLongTest.java new file mode 100755 index 0000000000..d3856d3762 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/PublicFieldLongTest.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class PublicFieldLongTest extends TestCase { + + public static class VO { + + public long id; + } + + public void test_codec() throws Exception { + VO vo = new VO(); + vo.id = 1234; + + String str = JSON.toJSONString(vo); + + VO vo1 = JSON.parseObject(str, VO.class); + + Assert.assertEquals(vo1.id, vo.id); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/PublicFieldStringTest.java b/src/test/java/com/alibaba/json/bvt/PublicFieldStringTest.java new file mode 100755 index 0000000000..b1fa0cbd31 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/PublicFieldStringTest.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class PublicFieldStringTest extends TestCase { + + public static class VO { + + public String id; + } + + public void test_codec() throws Exception { + VO vo = new VO(); + vo.id = "x12345"; + + String str = JSON.toJSONString(vo); + + VO vo1 = JSON.parseObject(str, VO.class); + + Assert.assertEquals(vo1.id, vo.id); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/RectangleTest.java b/src/test/java/com/alibaba/json/bvt/RectangleTest.java new file mode 100755 index 0000000000..ea06325a59 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/RectangleTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt; + +import java.awt.Rectangle; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.AwtCodec; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class RectangleTest extends TestCase { + + public void test_color() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Rectangle.class).getClass()); + + Rectangle v = new Rectangle(3, 4, 100, 200); + String text = JSON.toJSONString(v, SerializerFeature.WriteClassName); + + System.out.println(text); + + Rectangle v2 = (Rectangle) JSON.parse(text); + + Assert.assertEquals(v, v2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest.java b/src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest.java new file mode 100644 index 0000000000..2d37512477 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; + +/** + * Created by wenshao on 08/01/2017. + */ +public class SerializeEnumAsJavaBeanTest extends TestCase { + public void test_serializeEnumAsJavaBean() throws Exception { + String text = JSON.toJSONString(OrderType.PayOrder); + assertEquals("{\"remark\":\"支付订单\",\"value\":1}", text); + } + + public void test_field() throws Exception { + Model model = new Model(); + model.orderType = OrderType.SettleBill; + String text = JSON.toJSONString(model); + assertEquals("{\"orderType\":{\"remark\":\"结算单\",\"value\":2}}", text); + } + + public void test_field_2() throws Exception { + Model model = new Model(); + model.orderType = OrderType.SettleBill; + model.orderType1 = OrderType.SettleBill; + String text = JSON.toJSONString(model); + assertEquals("{\"orderType\":{\"remark\":\"结算单\",\"value\":2},\"orderType1\":{\"remark\":\"结算单\",\"value\":2}}", text); + } + + @JSONType(serializeEnumAsJavaBean = true) + public static enum OrderType { + PayOrder(1, "支付订单"), // + SettleBill(2, "结算单"); + + public final int value; + public final String remark; + + private OrderType(int value, String remark) { + this.value = value; + this.remark = remark; + } + } + + public static class Model { + public OrderType orderType; + public OrderType orderType1; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest_manual.java b/src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest_manual.java new file mode 100644 index 0000000000..f6be916bc5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest_manual.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializeConfig; +import junit.framework.TestCase; + +/** + * Created by wenshao on 08/01/2017. + */ +public class SerializeEnumAsJavaBeanTest_manual extends TestCase { + protected void setUp() throws Exception { + SerializeConfig serializeConfig = SerializeConfig.globalInstance; + serializeConfig.configEnumAsJavaBean(OrderType.class); + } + + public void test_serializeEnumAsJavaBean() throws Exception { + String text = JSON.toJSONString(OrderType.PayOrder); + assertEquals("{\"remark\":\"支付订单\",\"value\":1}", text); + } + + public void test_field() throws Exception { + + Model model = new Model(); + model.orderType = OrderType.SettleBill; + String text = JSON.toJSONString(model); + assertEquals("{\"orderType\":{\"remark\":\"结算单\",\"value\":2}}", text); + } + + public static enum OrderType { + PayOrder(1, "支付订单"), // + SettleBill(2, "结算单"); + + public final int value; + public final String remark; + + private OrderType(int value, String remark) { + this.value = value; + this.remark = remark; + } + } + + public static class Model { + public OrderType orderType; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest_private.java b/src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest_private.java new file mode 100644 index 0000000000..2fd7ea105a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest_private.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializeConfig; +import junit.framework.TestCase; + +/** + * Created by wenshao on 08/01/2017. + */ +public class SerializeEnumAsJavaBeanTest_private extends TestCase { + public void test_serializeEnumAsJavaBean() throws Exception { + String text = JSON.toJSONString(OrderType.PayOrder); + assertEquals("{\"remark\":\"支付订单\",\"value\":1}", text); + } + + public void test_field() throws Exception { + Model model = new Model(); + model.orderType = OrderType.SettleBill; + String text = JSON.toJSONString(model); + assertEquals("{\"orderType\":{\"remark\":\"结算单\",\"value\":2}}", text); + } + + public void test_field_2() throws Exception { + Model model = new Model(); + model.orderType = OrderType.SettleBill; + model.orderType1 = OrderType.SettleBill; + String text = JSON.toJSONString(model); + assertEquals("{\"orderType\":{\"remark\":\"结算单\",\"value\":2},\"orderType1\":{\"remark\":\"结算单\",\"value\":2}}", text); + } + + @JSONType(serializeEnumAsJavaBean = true) + private static enum OrderType { + PayOrder(1, "支付订单"), // + SettleBill(2, "结算单"); + + public final int value; + public final String remark; + + private OrderType(int value, String remark) { + this.value = value; + this.remark = remark; + } + } + + private static class Model { + public OrderType orderType; + public OrderType orderType1; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/SerializeWriterTest.java b/src/test/java/com/alibaba/json/bvt/SerializeWriterTest.java new file mode 100755 index 0000000000..4d4b56b363 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/SerializeWriterTest.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.serializer.SerializeWriter; + +public class SerializeWriterTest extends TestCase { + + public void test_0() throws Exception { + SerializeWriter writer = new SerializeWriter(); + writer.append('A'); + writer.writeInt(156); + Assert.assertEquals("A156", writer.toString()); + writer.writeLong(345); + Assert.assertEquals("A156345", writer.toString()); + + } + + public void test_1() throws Exception { + SerializeWriter writer = new SerializeWriter(); + writer.writeInt(-1); + Assert.assertEquals("-1", writer.toString()); + } + + public void test_4() throws Exception { + SerializeWriter writer = new SerializeWriter(); + writer.writeInt(-1); + writer.write(','); + Assert.assertEquals("-1,", writer.toString()); + } + + public void test_5() throws Exception { + SerializeWriter writer = new SerializeWriter(); + writer.writeLong(-1L); + Assert.assertEquals("-1", writer.toString()); + } + + public void test_6() throws Exception { + SerializeWriter writer = new SerializeWriter(); + writer.writeLong(-1L); + writer.write(','); + Assert.assertEquals("-1,", writer.toString()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ServiceLoaderTest.java b/src/test/java/com/alibaba/json/bvt/ServiceLoaderTest.java new file mode 100644 index 0000000000..3643edf8a1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ServiceLoaderTest.java @@ -0,0 +1,12 @@ +package com.alibaba.json.bvt; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.util.ServiceLoader; + + +public class ServiceLoaderTest extends TestCase { + public void test_0() throws Exception { + new ServiceLoader(); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/ShortArrayFieldTest_primitive.java b/src/test/java/com/alibaba/json/bvt/ShortArrayFieldTest_primitive.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/ShortArrayFieldTest_primitive.java rename to src/test/java/com/alibaba/json/bvt/ShortArrayFieldTest_primitive.java index 7bae14f5bd..356bf2ffd0 --- a/src/test/java/com/alibaba/json/test/bvt/ShortArrayFieldTest_primitive.java +++ b/src/test/java/com/alibaba/json/bvt/ShortArrayFieldTest_primitive.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/SlashTest.java b/src/test/java/com/alibaba/json/bvt/SlashTest.java old mode 100644 new mode 100755 similarity index 88% rename from src/test/java/com/alibaba/json/test/bvt/SlashTest.java rename to src/test/java/com/alibaba/json/bvt/SlashTest.java index 84448c819a..70fd2a5942 --- a/src/test/java/com/alibaba/json/test/bvt/SlashTest.java +++ b/src/test/java/com/alibaba/json/bvt/SlashTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/SpecialKeyTest.java b/src/test/java/com/alibaba/json/bvt/SpecialKeyTest.java new file mode 100755 index 0000000000..8744818fb0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/SpecialKeyTest.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class SpecialKeyTest extends TestCase { + + public void test_0() throws Exception { + Map map = new HashMap(); + map.put(1, "a"); + map.put(2, "b"); + + String text = JSON.toJSONString(map); + System.out.println(text); + + Map map2 = JSON.parseObject(text, new TypeReference>() {}); + Assert.assertEquals(map, map2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/SpecialKeyTest2.java b/src/test/java/com/alibaba/json/bvt/SpecialKeyTest2.java new file mode 100644 index 0000000000..af94d5fcbe --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/SpecialKeyTest2.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt; + +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class SpecialKeyTest2 extends TestCase { + public void test_0() throws Exception { + Model model = JSON.parseObject("{\"items\":{\"1\":{},\"1001\":{}},\"items1\":{\"$ref\":\"$.items\"}}", Model.class); + Assert.assertEquals(2, model.items.size()); + Assert.assertNotNull(model.items.get(1L)); + Assert.assertNotNull(model.items.get(1001L)); + Assert.assertSame(model.items, model.items1); + } + + public static class Model { + public Map items; + public Map items1; + } + + public static class Item { + } +} diff --git a/src/test/java/com/alibaba/json/bvt/SqlDateTest1.java b/src/test/java/com/alibaba/json/bvt/SqlDateTest1.java new file mode 100644 index 0000000000..cf7a42a486 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/SqlDateTest1.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt; + +import java.sql.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class SqlDateTest1 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = new Locale("zh_CN"); + } + + public void test_date() throws Exception { + long millis = 1324138987429L; + Date date = new Date(millis); + + Assert.assertEquals("1324138987429", JSON.toJSONString(date)); + Assert.assertEquals("{\"@type\":\"java.sql.Date\",\"val\":1324138987429}", JSON.toJSONString(date, SerializerFeature.WriteClassName)); + Assert.assertEquals(1324138987429L, ((java.util.Date)JSON.parse("{\"@type\":\"java.util.Date\",\"val\":1324138987429}")).getTime()); + + Assert.assertEquals("\"2011-12-18 00:23:07\"", + JSON.toJSONString(date, SerializerFeature.WriteDateUseDateFormat)); + Assert.assertEquals("\"2011-12-18 00:23:07.429\"", + JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss.SSS")); + Assert.assertEquals("'2011-12-18 00:23:07.429'", + JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss.SSS", + SerializerFeature.UseSingleQuotes)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/StringBufferFieldTest.java b/src/test/java/com/alibaba/json/bvt/StringBufferFieldTest.java new file mode 100644 index 0000000000..b004b5cbff --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/StringBufferFieldTest.java @@ -0,0 +1,86 @@ +package com.alibaba.json.bvt; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class StringBufferFieldTest extends TestCase { + + public void test_codec_null() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"value\":null}", text); + + ParserConfig config = new ParserConfig(); + config.setAsmEnable(false); + + V0 v1 = JSON.parseObject(text, V0.class, config, JSON.DEFAULT_PARSER_FEATURE); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_codec_null_1() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, + SerializerFeature.WriteNullStringAsEmpty); + Assert.assertEquals("{\"value\":\"\"}", text); + } + + public void test_deserialize_1() throws Exception { + String json = "{\"value\":\"\"}"; + + V0 vo = JSON.parseObject(json, V0.class); + Assert.assertNotNull(vo.getValue()); + Assert.assertEquals("", vo.getValue().toString()); + } + + public void test_deserialize_2() throws Exception { + String json = "{\"value\":null}"; + + V0 vo = JSON.parseObject(json, V0.class); + Assert.assertNull(vo.getValue()); + } + + public void test_deserialize_3() throws Exception { + String json = "{\"value\":\"true\"}"; + + V0 vo = JSON.parseObject(json, V0.class); + Assert.assertNotNull(vo.getValue()); + Assert.assertEquals("true", vo.getValue().toString()); + } + + public void test_deserialize_4() throws Exception { + String json = "{\"value\":\"123\"}"; + + V0 vo = JSON.parseObject(json, V0.class); + Assert.assertNotNull(vo.getValue()); + Assert.assertEquals("123", vo.getValue().toString()); + } + + public static class V0 { + + private StringBuffer value; + + public StringBuffer getValue() { + return value; + } + + public void setValue(StringBuffer value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/StringBuilderFieldTest.java b/src/test/java/com/alibaba/json/bvt/StringBuilderFieldTest.java new file mode 100644 index 0000000000..4081db4579 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/StringBuilderFieldTest.java @@ -0,0 +1,86 @@ +package com.alibaba.json.bvt; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class StringBuilderFieldTest extends TestCase { + + public void test_codec_null() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"value\":null}", text); + + ParserConfig config = new ParserConfig(); + config.setAsmEnable(false); + + V0 v1 = JSON.parseObject(text, V0.class, config, JSON.DEFAULT_PARSER_FEATURE); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_codec_null_1() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, + SerializerFeature.WriteNullStringAsEmpty); + Assert.assertEquals("{\"value\":\"\"}", text); + } + + public void test_deserialize_1() throws Exception { + String json = "{\"value\":\"\"}"; + + V0 vo = JSON.parseObject(json, V0.class); + Assert.assertNotNull(vo.getValue()); + Assert.assertEquals("", vo.getValue().toString()); + } + + public void test_deserialize_2() throws Exception { + String json = "{\"value\":null}"; + + V0 vo = JSON.parseObject(json, V0.class); + Assert.assertNull(vo.getValue()); + } + + public void test_deserialize_3() throws Exception { + String json = "{\"value\":\"true\"}"; + + V0 vo = JSON.parseObject(json, V0.class); + Assert.assertNotNull(vo.getValue()); + Assert.assertEquals("true", vo.getValue().toString()); + } + + public void test_deserialize_4() throws Exception { + String json = "{\"value\":\"123\"}"; + + V0 vo = JSON.parseObject(json, V0.class); + Assert.assertNotNull(vo.getValue()); + Assert.assertEquals("123", vo.getValue().toString()); + } + + public static class V0 { + + private StringBuilder value; + + public StringBuilder getValue() { + return value; + } + + public void setValue(StringBuilder value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/StringDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/StringDeserializerTest.java new file mode 100755 index 0000000000..f98e027904 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/StringDeserializerTest.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class StringDeserializerTest extends TestCase { + + public void test_0() throws Exception { + Assert.assertEquals("123", JSON.parseObject("123", String.class)); + Assert.assertEquals("true", JSON.parseObject("true", String.class)); + Assert.assertEquals(null, JSON.parseObject("null", String.class)); + } + + public void test_StringBuffer() throws Exception { + Assert.assertTrue(equals(new StringBuffer("123"), JSON.parseObject("123", StringBuffer.class))); + Assert.assertTrue(equals(new StringBuffer("true"), JSON.parseObject("true", StringBuffer.class))); + Assert.assertEquals(null, JSON.parseObject("null", StringBuffer.class)); + } + + public void test_StringBuilder() throws Exception { + Assert.assertTrue(equals(new StringBuilder("123"), JSON.parseObject("123", StringBuilder.class))); + Assert.assertTrue(equals(new StringBuilder("true"), JSON.parseObject("true", StringBuilder.class))); + Assert.assertEquals(null, JSON.parseObject("null", StringBuilder.class)); + } + + private boolean equals(StringBuffer sb1, StringBuffer sb2) { + if (sb1 == null && sb2 == null) { + return true; + } + if ((sb1 == null && sb2 != null) || (sb1 != null && sb2 == null)) { + return false; + } + + return sb1.toString().equals(sb2.toString()); + } + + private boolean equals(StringBuilder sb1, StringBuilder sb2) { + if (sb1 == null && sb2 == null) { + return true; + } + if ((sb1 == null && sb2 != null) || (sb1 != null && sb2 == null)) { + return false; + } + + return sb1.toString().equals(sb2.toString()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/StringFieldTest.java b/src/test/java/com/alibaba/json/bvt/StringFieldTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/StringFieldTest.java rename to src/test/java/com/alibaba/json/bvt/StringFieldTest.java index fae180fea1..d9c82e183a --- a/src/test/java/com/alibaba/json/test/bvt/StringFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/StringFieldTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/StringFieldTest2.java b/src/test/java/com/alibaba/json/bvt/StringFieldTest2.java new file mode 100644 index 0000000000..4835132612 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/StringFieldTest2.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class StringFieldTest2 extends TestCase { + + public void test_codec_null_1() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"value\":\"\"}", text); + } + + public static class V0 { + + @JSONField(serialzeFeatures=SerializerFeature.WriteNullStringAsEmpty) + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/StringFieldTest_special.java b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special.java new file mode 100644 index 0000000000..8c3c7612bf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt; + +import java.io.StringReader; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; + +import junit.framework.TestCase; + +public class StringFieldTest_special extends TestCase { + public void test_special() throws Exception { + Model model = new Model(); + model.name = "a\\bc"; + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"name\":\"a\\\\bc\"}", text); + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model2 = reader.readObject(Model.class); + Assert.assertEquals(model.name, model2.name); + reader.close(); + } + + public void test_special_2() throws Exception { + Model model = new Model(); + model.name = "a\\bc\""; + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"name\":\"a\\\\bc\\\"\"}", text); + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model2 = reader.readObject(Model.class); + Assert.assertEquals(model.name, model2.name); + reader.close(); + } + + public static class Model { + + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_1.java b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_1.java new file mode 100644 index 0000000000..554b622380 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_1.java @@ -0,0 +1,59 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class StringFieldTest_special_1 extends TestCase { + public void test_special() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + String text = JSON.toJSONString(model); + + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.name, model2.name); + } + + public void test_special_browsecue() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + String text = JSON.toJSONString(model, SerializerFeature.BrowserSecure); + text = text.replaceAll("<", "<"); + text = text.replaceAll(">", ">"); + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.name, model2.name); + } + + public void test_special_browsecompatible() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + String text = JSON.toJSONString(model, SerializerFeature.BrowserCompatible); + + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.name, model2.name); + } + + public static class Model { + + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_2.java b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_2.java new file mode 100644 index 0000000000..89c0016796 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_2.java @@ -0,0 +1,72 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class StringFieldTest_special_2 extends TestCase { + public void test_special() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + String text = JSON.toJSONString(model); + + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.name, model2.name); + } + + public void test_special_browsecue() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + String text = JSON.toJSONString(model, SerializerFeature.BrowserSecure); + text = text.replaceAll("<", "<"); + text = text.replaceAll(">", ">"); +// text = text.replaceAll("\\\\/", "/"); + Model model2 = JSON.parseObject(text, Model.class); + + for (int i = 0; i < model.name.length() && i < model2.name.length(); ++i) { + char c1 = model.name.charAt(i); + char c2 = model.name.charAt(i); + if (c1 != c2) { + System.out.println("diff : " + c1 + " -> " + c2); + break; + } + } +// String str = model2.name.substring(65535); +// System.out.println(str); + Assert.assertEquals(model.name.length(), model2.name.length()); + Assert.assertEquals(model.name, model2.name); + } + + public void test_special_browsecompatible() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + String text = JSON.toJSONString(model, SerializerFeature.BrowserCompatible); + + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.name, model2.name); + } + + private static class Model { + + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_3.java b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_3.java new file mode 100644 index 0000000000..b3b0f1a29f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_3.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt; + +import java.io.StringWriter; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class StringFieldTest_special_3 extends TestCase { + public void test_special() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + StringWriter writer = new StringWriter(); + JSON.writeJSONString(writer, model); + + String json = writer.toString(); + Model model2 = JSON.parseObject(json, Model.class); + Assert.assertEquals(model.name, model2.name); + } + + public void test_special_browsecue() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + StringWriter writer = new StringWriter(); + JSON.writeJSONString(writer, model, SerializerFeature.BrowserSecure); + + String text = writer.toString(); + + text = text.replaceAll("<", "<"); + text = text.replaceAll(">", ">"); + + Model model2 = JSON.parseObject(text, Model.class); + assertEquals(model.name, model2.name); + } + + public void test_special_browsecompatible() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + StringWriter writer = new StringWriter(); + JSON.writeJSONString(writer, model, SerializerFeature.BrowserCompatible); + + Model model2 = JSON.parseObject(writer.toString(), Model.class); + Assert.assertEquals(model.name, model2.name); + } + + private static class Model { + + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_reader.java b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_reader.java new file mode 100644 index 0000000000..717bdd5e10 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_reader.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class StringFieldTest_special_reader extends TestCase { + public void test_special() throws Exception { + Model model = new Model(); + model.name = "a\\bc"; + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"name\":\"a\\\\bc\"}", text); + + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.name, model2.name); + } + + public void test_special_2() throws Exception { + Model model = new Model(); + model.name = "a\\bc\""; + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"name\":\"a\\\\bc\\\"\"}", text); + + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.name, model2.name); + } + + public static class Model { + + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_singquote.java b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_singquote.java new file mode 100644 index 0000000000..1ecced91ab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/StringFieldTest_special_singquote.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt; + +import java.io.StringWriter; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class StringFieldTest_special_singquote extends TestCase { + public void test_special() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + StringWriter writer = new StringWriter(); + JSON.writeJSONString(writer, model); + + Model model2 = JSON.parseObject(writer.toString(), Model.class); + Assert.assertEquals(model.name, model2.name); + } + + public void test_special_browsecue() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + StringWriter writer = new StringWriter(); + JSON.writeJSONString(writer, model, SerializerFeature.UseSingleQuotes); + + Model model2 = JSON.parseObject(writer.toString(), Model.class); + Assert.assertEquals(model.name, model2.name); + } + + public void test_special_browsecompatible() throws Exception { + Model model = new Model(); + StringBuilder buf = new StringBuilder(); + for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; ++i) { + buf.append((char) i); + } + model.name = buf.toString(); + + StringWriter writer = new StringWriter(); + JSON.writeJSONString(writer, model, SerializerFeature.UseSingleQuotes); + + Model model2 = JSON.parseObject(writer.toString(), Model.class); + Assert.assertEquals(model.name, model2.name); + } + + private static class Model { + + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/SymbolTableTest.java b/src/test/java/com/alibaba/json/bvt/SymbolTableTest.java new file mode 100755 index 0000000000..927f6e96a1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/SymbolTableTest.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.parser.SymbolTable; + +public class SymbolTableTest extends TestCase { + + protected String[] symbols = new String[] { "EffectedRowCount", "DataSource", "BatchSizeMax", "BatchSizeTotal", "ConcurrentMax", "ErrorCount", + "ExecuteCount", "FetchRowCount", "File", "ID", "LastError", "LastTime", "MaxTimespan", "MaxTimespanOccurTime", "Name", "RunningCount", "SQL", + "TotalTime" }; + char[][] symbols_char = new char[symbols.length][]; + final int COUNT = 1000 * 1000; + + protected void setUp() throws Exception { + for (int i = 0; i < symbols.length; ++i) { + symbols_char[i] = symbols[i].toCharArray(); + } + } + + public void test_symbol() throws Exception { + + char[][] symbols_char = new char[symbols.length][]; + for (int i = 0; i < symbols.length; ++i) { + symbols_char[i] = symbols[i].toCharArray(); + } + + + + SymbolTable table = new SymbolTable(512); + for (int i = 0; i < symbols.length; ++i) { + String symbol = symbols[i]; + char[] charArray = symbol.toCharArray(); + table.addSymbol(charArray, 0, charArray.length); + //System.out.println((table.hash(symbol) & table.getIndexMask()) + "\t\t:" + symbol + "\t\t" + table.hash(symbol)); + } + + String symbol = "name"; + table.addSymbol(symbol.toCharArray(), 0, symbol.length()); + table.addSymbol(symbol.toCharArray(), 0, symbol.length()); + + Assert.assertTrue(symbol == table.addSymbol("name".toCharArray(), 0, 4)); + Assert.assertTrue(symbol == table.addSymbol(" name".toCharArray(), 1, 4)); + Assert.assertTrue(symbol == table.addSymbol(" name ".toCharArray(), 1, 4)); + Assert.assertTrue(symbol != table.addSymbol(" namf ".toCharArray(), 1, 4)); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/TabCharTest.java b/src/test/java/com/alibaba/json/bvt/TabCharTest.java new file mode 100755 index 0000000000..3116d7c693 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TabCharTest.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class TabCharTest extends TestCase { + + @SuppressWarnings("deprecation") + public void test_0() throws Exception { + JSONObject json = new JSONObject(); + json.put("hello\t", "World\t!"); + Assert.assertEquals("{\"hello\\t\":\"World\\t!\"}", JSON.toJSONString(json)); + Assert.assertEquals("{\"hello\\t\":\"World\\t!\"}", JSON.toJSONStringZ(json, SerializeConfig.getGlobalInstance())); + Assert.assertEquals("{'hello\\t':'World\\t!'}", JSON.toJSONString(json, SerializerFeature.WriteTabAsSpecial, SerializerFeature.UseSingleQuotes)); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/TestDeprecate.java b/src/test/java/com/alibaba/json/bvt/TestDeprecate.java new file mode 100755 index 0000000000..163c61f706 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestDeprecate.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class TestDeprecate extends TestCase { + + public void test_0() throws Exception { + VO vo = new VO(); + vo.setId(123); + + String text = JSON.toJSONString(vo); + } + + public static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + /** + * @deprecated + * @return + */ + public int getId2() { + return this.id; + } + + @Deprecated + public int getId3() { + return this.id; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/TestExternal.java b/src/test/java/com/alibaba/json/bvt/TestExternal.java new file mode 100755 index 0000000000..1ccc3ed8a3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestExternal.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; + +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; + +import com.alibaba.fastjson.JSON; + + +public class TestExternal extends TestCase { + public void test_0 () throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("external.VO"); + Method method = clazz.getMethod("setName", new Class[] {String.class}); + Object obj = clazz.newInstance(); + method.invoke(obj, "jobs"); + + String text = JSON.toJSONString(obj); + System.out.println(text); + JSON.parseObject(text, clazz); + } + + public static class ExtClassLoader extends ClassLoader { + public ExtClassLoader() throws IOException{ + super(Thread.currentThread().getContextClassLoader()); + + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("external/VO.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("external.VO", bytes, 0, bytes.length); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestExternal2.java b/src/test/java/com/alibaba/json/bvt/TestExternal2.java new file mode 100755 index 0000000000..6fd6e7b7d6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestExternal2.java @@ -0,0 +1,80 @@ +package com.alibaba.json.bvt; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; + +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class TestExternal2 extends TestCase { + + public void test_0() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + + Class theClass = classLoader.loadClass("com.alibaba.mock.demo.service.MockDemoService"); + Method[] methods = theClass.getMethods(); + + //基本类型 + if (void.class.isPrimitive()) { + System.out.println("void"); + } + if (boolean.class.isPrimitive()) { + System.out.println("boolean"); + } + + for (Method method : methods) { + System.out.println("name: " + method.getName()); + + Class[] paraClassArray = method.getParameterTypes(); + for (Class paraClass : paraClassArray) { + System.out.println("parameters: " + paraClass); + + Package pkg = paraClass.getPackage(); + if (pkg == null || !pkg.getName().equals("java.lang")) { + Object obj = paraClass.newInstance(); + // System.out.println(obj); + + String kaka = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue); + System.out.println(kaka); + System.out.println(kaka); + +// ObjectMapper objectMapper = new ObjectMapper(); +// String tt = objectMapper.writeValueAsString(obj); +// System.out.println(tt); + } + } + //System.out.println("return: " + method.getReturnType()); + //System.out.println("description: " + method.toGenericString()); + System.out.println(); + } + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException{ + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("external/Demo.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("com.alibaba.mock.demo.api.Demo", bytes, 0, bytes.length); + } + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("external/MockDemoService.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("com.alibaba.mock.demo.service.MockDemoService", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestExternal3.java b/src/test/java/com/alibaba/json/bvt/TestExternal3.java new file mode 100755 index 0000000000..e4c2dc513b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestExternal3.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + + +public class TestExternal3 extends TestCase { + ParserConfig confg = ParserConfig.global; + protected void setUp() throws Exception { + confg.addAccept("external.VO"); + } + + public void test_0 () throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("external.VO"); + Method method = clazz.getMethod("setName", new Class[] {String.class}); + Object obj = clazz.newInstance(); + method.invoke(obj, "jobs"); + + String text = JSON.toJSONString(obj, SerializerFeature.WriteClassName); + System.out.println(text); + JSON.parseObject(text, clazz, confg); + String clazzName = JSON.parse(text, confg).getClass().getName(); + Assert.assertEquals(clazz.getName(), clazzName); + } + + public static class ExtClassLoader extends ClassLoader { + public ExtClassLoader() throws IOException{ + super(Thread.currentThread().getContextClassLoader()); + + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("external/VO.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("external.VO", bytes, 0, bytes.length); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestExternal4.java b/src/test/java/com/alibaba/json/bvt/TestExternal4.java new file mode 100755 index 0000000000..702af08068 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestExternal4.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.HashMap; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class TestExternal4 extends TestCase { + ParserConfig confg = ParserConfig.global; + protected void setUp() throws Exception { + confg.addAccept("external.VO2"); + } + + public void test_0() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("external.VO2"); + Method method = clazz.getMethod("setName", new Class[] { String.class }); + Method methodSetValue = clazz.getMethod("setValue", new Class[] { Serializable.class }); + + Object obj = clazz.newInstance(); + method.invoke(obj, "jobs"); + methodSetValue.invoke(obj, obj); + + { + String text = JSON.toJSONString(obj); + System.out.println(text); + } + + String text = JSON.toJSONString(obj, SerializerFeature.WriteClassName); + System.out.println(text); + JSON.parseObject(text, clazz, confg); + String clazzName = JSON.parse(text, confg).getClass().getName(); + Assert.assertEquals(clazz.getName(), clazzName); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException{ + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("external/VO2.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("external.VO2", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestExternal5.java b/src/test/java/com/alibaba/json/bvt/TestExternal5.java new file mode 100755 index 0000000000..529c5fe09c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestExternal5.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.HashMap; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class TestExternal5 extends TestCase { + ParserConfig confg = ParserConfig.global; + protected void setUp() throws Exception { + confg.addAccept("com.alibaba.dubbo.demo"); + } + + public void test_0() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("com.alibaba.dubbo.demo.MyEsbResultModel2"); + Method method = clazz.getMethod("setReturnValue", new Class[] { Serializable.class }); + + Object obj = clazz.newInstance(); + method.invoke(obj, "AAAA"); + + { + String text = JSON.toJSONString(obj); + System.out.println(text); + } + + String text = JSON.toJSONString(obj, SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue); + System.out.println(text); + Object object = JSON.parseObject(text, clazz, confg); + assertEquals("a1", clazz.getName(), object.getClass().getName()); + + Object object2 = JSON.parse(text, confg); + assertEquals("a2 " + text, clazz.getName(), object2.getClass().getName()); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException{ + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("external/MyEsbResultModel2.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("com.alibaba.dubbo.demo.MyEsbResultModel2", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestExternal6.java b/src/test/java/com/alibaba/json/bvt/TestExternal6.java new file mode 100755 index 0000000000..4d836c1586 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestExternal6.java @@ -0,0 +1,78 @@ +package com.alibaba.json.bvt; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.HashMap; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class TestExternal6 extends TestCase { + ParserConfig confg = ParserConfig.global; + + protected void setUp() throws Exception { + confg.addAccept("org.mule.esb.model"); + } + + public void test_0() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("org.mule.esb.model.tcc.result.EsbResultModel"); + Method[] methods = clazz.getMethods(); + Method method = clazz.getMethod("setReturnValue", new Class[] { Serializable.class }); + + Object obj = clazz.newInstance(); +// method.invoke(obj, "AAAA"); + + { + String text = JSON.toJSONString(obj); + System.out.println(text); + } + + String text = JSON.toJSONString(obj, SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue); + System.out.println(text); + JSON.parseObject(text, clazz, confg); + String clazzName = JSON.parse(text, confg).getClass().getName(); + Assert.assertEquals(clazz.getName(), clazzName); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException{ + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("external/EsbResultModel.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("org.mule.esb.model.tcc.result.EsbResultModel", bytes, 0, bytes.length); + } + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("external/EsbListBean.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("org.esb.crm.tools.EsbListBean", bytes, 0, bytes.length); + } + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("external/EsbHashMapBean.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("org.esb.crm.tools.EsbHashMapBean", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestFlase.java b/src/test/java/com/alibaba/json/bvt/TestFlase.java new file mode 100644 index 0000000000..a474756d89 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestFlase.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class TestFlase extends TestCase { + + public void test_0() throws Exception { + Object obj = JSON.parseObject("[{\"data\":{\"@type\":\"java.util.TreeMap\",false:21L},\"dataType\":2,\"dis\":0,\"length\":24,\"maxNum\":100,\"size\":3600000,\"version\":0}]", VO[].class); + System.out.println(JSON.toJSONString(obj)); + } + + public static class VO { + + private Object data; + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestForEmoji.java b/src/test/java/com/alibaba/json/bvt/TestForEmoji.java new file mode 100755 index 0000000000..786ff5385a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestForEmoji.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import org.junit.Assert; +import junit.framework.TestCase; + + +public class TestForEmoji extends TestCase { + public void test_0 () throws Exception { + Assert.assertEquals("\"\\uE507\"", JSON.toJSONString("\uE507", SerializerFeature.BrowserCompatible)); + Assert.assertEquals("\"\\uE501\"", JSON.toJSONString("\uE501", SerializerFeature.BrowserCompatible)); + Assert.assertEquals("\"\\uE44C\"", JSON.toJSONString("\uE44C", SerializerFeature.BrowserCompatible)); + Assert.assertEquals("\"\\uE401\"", JSON.toJSONString("\uE401", SerializerFeature.BrowserCompatible)); + Assert.assertEquals("\"\\uE253\"", JSON.toJSONString("\uE253", SerializerFeature.BrowserCompatible)); + Assert.assertEquals("\"\\uE201\"", JSON.toJSONString("\uE201", SerializerFeature.BrowserCompatible)); + Assert.assertEquals("\"\\uE15A\"", JSON.toJSONString("\uE15A", SerializerFeature.BrowserCompatible)); + Assert.assertEquals("\"\\uE101\"", JSON.toJSONString("\uE101", SerializerFeature.BrowserCompatible)); + Assert.assertEquals("\"\\uE05A\"", JSON.toJSONString("\uE05A", SerializerFeature.BrowserCompatible)); + Assert.assertEquals("\"\\uE001\"", JSON.toJSONString("\uE001", SerializerFeature.BrowserCompatible)); + //E507 + } + + public void test_zh() throws Exception { + Assert.assertEquals("\"\\u4E2D\\u56FD\"", JSON.toJSONString("中国", SerializerFeature.BrowserCompatible)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestForPascalStyle.java b/src/test/java/com/alibaba/json/bvt/TestForPascalStyle.java new file mode 100755 index 0000000000..0ced5dc389 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestForPascalStyle.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class TestForPascalStyle extends TestCase { + + public void test_for_pascal_style() throws Exception { + String text = "{\"ID\":12,\"Name\":\"Jobs\"}"; + VO vo = JSON.parseObject(text, VO.class); + Assert.assertEquals(vo.getId(), 12); + Assert.assertEquals(vo.getName(), "Jobs"); + } + + public static class VO { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestMultiLevelClass.java b/src/test/java/com/alibaba/json/bvt/TestMultiLevelClass.java new file mode 100755 index 0000000000..fe6dbe7adc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestMultiLevelClass.java @@ -0,0 +1,61 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class TestMultiLevelClass extends TestCase { + + public static class A { + + private B b; + + public B getB() { + return b; + } + + public void setB(B b) { + this.b = b; + } + + public static class B { + + private C c; + + public C getC() { + return c; + } + + public void setC(C c) { + this.c = c; + } + + static class C { + + private int value; + + + public int getValue() { + return value; + } + + + public void setValue(int value) { + this.value = value; + } + } + } + } + + public void test_codec() throws Exception { + A a = new A(); + a.setB(new A.B()); + a.getB().setC(new A.B.C()); + a.getB().getC().setValue(123); + + String text = JSON.toJSONString(a); + System.out.println(text); + + A a2 = JSON.parseObject(text, A.class); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestMultiLevelClass2.java b/src/test/java/com/alibaba/json/bvt/TestMultiLevelClass2.java new file mode 100755 index 0000000000..639d7e0416 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestMultiLevelClass2.java @@ -0,0 +1,61 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class TestMultiLevelClass2 extends TestCase { + + public static class A { + + private B b; + + public B getB() { + return b; + } + + public void setB(B b) { + this.b = b; + } + + public class B { + + private C c; + + public C getC() { + return c; + } + + public void setC(C c) { + this.c = c; + } + + class C { + + private int value; + + + public int getValue() { + return value; + } + + + public void setValue(int value) { + this.value = value; + } + } + } + } + + public void test_codec() throws Exception { + A a = new A(); + a.setB(a.new B()); + a.getB().setC(a.b.new C()); + a.getB().getC().setValue(123); + + String text = JSON.toJSONString(a); + System.out.println(text); + + A a2 = JSON.parseObject(text, A.class); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestNullKeyMap.java b/src/test/java/com/alibaba/json/bvt/TestNullKeyMap.java new file mode 100755 index 0000000000..e0375a6bf4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestNullKeyMap.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt; + +import java.util.HashMap; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class TestNullKeyMap extends TestCase { + public void test_0 () throws Exception { + HashMap map = new HashMap(); + map.put(null, 123); + + String text = JSON.toJSONString(map); + + Assert.assertEquals("{null:123}", text); + + HashMap map2 = JSON.parseObject(text, HashMap.class); + Assert.assertEquals(map.get(null), map2.get(null)); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestSerializable.java b/src/test/java/com/alibaba/json/bvt/TestSerializable.java new file mode 100755 index 0000000000..a483c59f7a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestSerializable.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt; + +import java.io.Serializable; +import java.util.ArrayList; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class TestSerializable extends TestCase { + public void test_codec() throws Exception { + VO vo = new VO(); + vo.setValue(new ArrayList()); + + JSON.toJSONString(vo); + } + + public static class VO { + + private long id; + private Serializable value; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Serializable getValue() { + return value; + } + + public void setValue(Serializable value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/TestTimeUnit.java b/src/test/java/com/alibaba/json/bvt/TestTimeUnit.java new file mode 100755 index 0000000000..35cffd2866 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TestTimeUnit.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt; + +import java.util.concurrent.TimeUnit; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class TestTimeUnit extends TestCase { + public void test_0 () throws Exception { + String text = JSON.toJSONString(TimeUnit.DAYS); + Assert.assertEquals(TimeUnit.DAYS, JSON.parseObject(text, TimeUnit.class)); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/TimeZoneFieldTest.java b/src/test/java/com/alibaba/json/bvt/TimeZoneFieldTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/TimeZoneFieldTest.java rename to src/test/java/com/alibaba/json/bvt/TimeZoneFieldTest.java index aa1f67a513..a800b07577 --- a/src/test/java/com/alibaba/json/test/bvt/TimeZoneFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/TimeZoneFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.TimeZone; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/TimestampTest.java b/src/test/java/com/alibaba/json/bvt/TimestampTest.java new file mode 100755 index 0000000000..2a5ccc4dcd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/TimestampTest.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt; + + +import java.sql.Timestamp; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class TimestampTest extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_0 () throws Exception { + long millis = (System.currentTimeMillis() / 1000) * 1000; + + SimpleDateFormat format = new SimpleDateFormat(JSON.DEFFAULT_DATE_FORMAT, JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + String text = "\"" + format.format(new Date(millis)) + "\""; + System.out.println(text); + Assert.assertEquals(new Timestamp(millis), JSON.parseObject("" + millis, Timestamp.class)); + Assert.assertEquals(new Timestamp(millis), JSON.parseObject("\"" + millis + "\"", Timestamp.class)); + Assert.assertEquals(new Timestamp(millis), JSON.parseObject(text, Timestamp.class)); + Assert.assertEquals(new java.sql.Date(millis), JSON.parseObject(text, java.sql.Date.class)); + Assert.assertEquals(new java.util.Date(millis), JSON.parseObject(text, java.util.Date.class)); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/TypeUtilstTest.java b/src/test/java/com/alibaba/json/bvt/TypeUtilstTest.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/TypeUtilstTest.java rename to src/test/java/com/alibaba/json/bvt/TypeUtilstTest.java index 00b9920e0b..c072f1ada4 --- a/src/test/java/com/alibaba/json/test/bvt/TypeUtilstTest.java +++ b/src/test/java/com/alibaba/json/bvt/TypeUtilstTest.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.math.BigDecimal; import java.math.BigInteger; diff --git a/src/test/java/com/alibaba/json/test/bvt/URIFieldTest.java b/src/test/java/com/alibaba/json/bvt/URIFieldTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/URIFieldTest.java rename to src/test/java/com/alibaba/json/bvt/URIFieldTest.java index 6a7dc7d971..c64e1a8667 --- a/src/test/java/com/alibaba/json/test/bvt/URIFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/URIFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.net.URI; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/URLFieldTest.java b/src/test/java/com/alibaba/json/bvt/URLFieldTest.java old mode 100644 new mode 100755 similarity index 85% rename from src/test/java/com/alibaba/json/test/bvt/URLFieldTest.java rename to src/test/java/com/alibaba/json/bvt/URLFieldTest.java index 0d3bfc34d2..57add69509 --- a/src/test/java/com/alibaba/json/test/bvt/URLFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/URLFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.net.URL; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -18,10 +18,11 @@ public void test_codec() throws Exception { SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(user, mapping, SerializerFeature.WriteMapNullValue); + System.out.println(text); User user1 = JSON.parseObject(text, User.class); - Assert.assertEquals(user1.getValue(), user.getValue()); + Assert.assertEquals(user1.getValue().toString(), user.getValue().toString()); } public void test_codec_null() throws Exception { diff --git a/src/test/java/com/alibaba/json/test/bvt/UUIDFieldTest.java b/src/test/java/com/alibaba/json/bvt/UUIDFieldTest.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/UUIDFieldTest.java rename to src/test/java/com/alibaba/json/bvt/UUIDFieldTest.java index d5ded9bfc0..5b1628bc94 --- a/src/test/java/com/alibaba/json/test/bvt/UUIDFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/UUIDFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt; import java.util.UUID; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/UnQuoteFieldNamesTest.java b/src/test/java/com/alibaba/json/bvt/UnQuoteFieldNamesTest.java new file mode 100644 index 0000000000..ffa615362b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/UnQuoteFieldNamesTest.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.Collections; +import java.util.Map; + +/** + * Created by wenshao on 11/01/2017. + */ +public class UnQuoteFieldNamesTest extends TestCase { + public void test_for_issue() throws Exception { + Map map = Collections.singletonMap("value", 123); + + String json = JSON.toJSONString(map + , SerializeConfig.globalInstance + , new SerializeFilter[0] + , null + , JSON.DEFAULT_GENERATE_FEATURE & ~SerializerFeature.QuoteFieldNames.mask + ); + assertEquals("{value:123}", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/WildcardTypeTest.java b/src/test/java/com/alibaba/json/bvt/WildcardTypeTest.java new file mode 100644 index 0000000000..57021d1913 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/WildcardTypeTest.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +public class WildcardTypeTest extends TestCase { + public void test_for_wildcardType() throws Exception { + TestType b = new TestType(); + b.value = new B(2001, "BBBB"); + b.superType = new TestType(new A(101)); + + String json = JSON.toJSONString(b); + + assertEquals("{\"superType\":{\"value\":{\"id\":101}},\"value\":{\"id\":2001,\"name\":\"BBBB\"}}", json); + + TestType b1 = JSON.parseObject(json, new TypeReference>() {}); + String json2 = JSON.toJSONString(b1); + + assertEquals(json, json2); + } + + public static class TestType { + public X value; + public TestType superType; + + public TestType() { + + } + + public TestType(X value) { + this.value = value; + } + } + + public static class TestType2 { + TestType2 superReversedType; + } + + public static class A { + public int id; + + public A(int id) { + this.id = id; + } + } + + public static class B extends A { + public String name; + + public B(int id, String name) { + super(id); + this.name = name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/WriteClassNameTest.java b/src/test/java/com/alibaba/json/bvt/WriteClassNameTest.java new file mode 100755 index 0000000000..c10ee7e30c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/WriteClassNameTest.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class WriteClassNameTest extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.WriteClassNameTest."); + } + + public void test_0() throws Exception { + Entity entity = new Entity(3, "jobs"); + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + + Entity entity2 = (Entity) JSON.parseObject(text, Object.class); + + Assert.assertEquals(entity.getId(), entity2.getId()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public static class Entity { + + private int id; + private String name; + + public Entity(){ + } + + public Entity(int id, String name){ + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/WriteClassNameTest2.java b/src/test/java/com/alibaba/json/bvt/WriteClassNameTest2.java new file mode 100755 index 0000000000..dae25de13c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/WriteClassNameTest2.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class WriteClassNameTest2 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.WriteClassNameTest2"); + } + + public void test_0() throws Exception { + Entity entity = new Entity(3, "jobs"); + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName, SerializerFeature.PrettyFormat); + System.out.println(text); + + Entity entity2 = (Entity) JSON.parseObject(text, Object.class); + + Assert.assertEquals(entity.getId(), entity2.getId()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public static class Entity { + + private int id; + private String name; + + public Entity(){ + } + + public Entity(int id, String name){ + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/XX01.java b/src/test/java/com/alibaba/json/bvt/XX01.java new file mode 100644 index 0000000000..1067ec0287 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/XX01.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +/** + * Created by wenshao on 14/08/2017. + */ +public class XX01 extends TestCase { + public void test_for_xx() throws Exception { + String text = "{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}"; + JSONObject test = JSON.parseObject(text); + + String text2 = test.toJSONString(); + assertEquals("{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}", text2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/annotation/AnnotationTest.java b/src/test/java/com/alibaba/json/bvt/annotation/AnnotationTest.java new file mode 100644 index 0000000000..7a1443aa80 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/annotation/AnnotationTest.java @@ -0,0 +1,92 @@ +package com.alibaba.json.bvt.annotation; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Created by Helly on 2017/04/10. + */ +public class AnnotationTest extends TestCase { + + public void test_annoation() throws Exception { + Bob bob = new Bob("Bob", 30, true); +// JSONObject obj = (JSONObject) JSON.toJSON(bob); +// assertEquals(3, obj.size()); +// assertEquals(Boolean.TRUE, obj.get("sex")); +// assertEquals("Bob", obj.get("name")); +// assertEquals(new Integer(30), obj.get("age")); + + PersonInfo info = Bob.class.getAnnotation(PersonInfo.class); + JSONObject obj = (JSONObject) JSON.toJSON(info); + + assertEquals(3, obj.size()); + assertEquals(Boolean.TRUE, obj.get("sex")); + assertEquals("Bob", obj.get("name")); + assertEquals(new Integer(30), obj.get("age")); + } + + @PersonInfo(name = "Bob", age = 30, sex = true) + public static class Bob implements Person { + private String name; + private int age; + private boolean sex; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public boolean isSex() { + return sex; + } + + public void setSex(boolean sex) { + this.sex = sex; + } + + public Bob() { + } + + public Bob(String name, int age, boolean sex) { + this(); + this.name = name; + this.age = age; + this.sex = sex; + } + + public void hello() { + System.out.println("world"); + } + } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + public static @interface PersonInfo { + String name(); + int age(); + boolean sex(); + } + + + public static interface Person { + void hello(); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/annotation/CustomDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/annotation/CustomDeserializerTest.java new file mode 100644 index 0000000000..79a7cd02fa --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/annotation/CustomDeserializerTest.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.annotation; + +import java.lang.reflect.Type; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +import junit.framework.TestCase; + +public class CustomDeserializerTest extends TestCase { + public void test_0() throws Exception { + String text = "{\"xid\":1001}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(1001, model.id); + } + + @JSONType(deserializer=ModelDeserializer.class) + public static class Model { + public int id; + } + + public static class ModelDeserializer implements ObjectDeserializer { + @Override + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + JSONReader reader = new JSONReader(parser); + + reader.startObject(); + + String key = reader.readString(); + Integer value = reader.readInteger(); + + Model model = new Model(); + model.id = value; + + reader.endObject(); + // TODO Auto-generated method stub + return (T) model; + } + + @Override + public int getFastMatchToken() { + return 0; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/annotation/CustomSerializerTest.java b/src/test/java/com/alibaba/json/bvt/annotation/CustomSerializerTest.java new file mode 100644 index 0000000000..3f015dcae9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/annotation/CustomSerializerTest.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.annotation; + +import java.io.IOException; +import java.lang.reflect.Type; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; + +import junit.framework.TestCase; + +public class CustomSerializerTest extends TestCase { + public void test_0() throws Exception { + Model model = new Model(); + model.id = 1001; + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"ID\":1001}", text); + } + + @JSONType(serializer=ModelSerializer.class) + public static class Model { + public int id; + } + + public static class ModelSerializer implements ObjectSerializer { + + @Override + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, + int features) throws IOException { + Model model = (Model) object; + SerializeWriter out = serializer.getWriter(); + out.writeFieldValue('{', "ID", model.id); + out.write('}'); + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/annotation/CustomSerializerTest_enum.java b/src/test/java/com/alibaba/json/bvt/annotation/CustomSerializerTest_enum.java new file mode 100644 index 0000000000..0697113a77 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/annotation/CustomSerializerTest_enum.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.annotation; + +import java.io.IOException; +import java.lang.reflect.Type; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.JSONSerializable; +import com.alibaba.fastjson.serializer.JSONSerializer; + +import junit.framework.TestCase; + +public class CustomSerializerTest_enum extends TestCase { + + public void test_0() throws Exception { + Model model = new Model(); + model.id = 1001; + model.orderType = OrderType.PayOrder; + String text = JSON.toJSONString(model); +// Assert.assertEquals("{\"id\":1001,\"orderType\":{\"remark\":\"支付订单\",\"value\":1}}", text); + } + + public static class Model { + public int id; + public OrderType orderType; + } + + public static enum OrderType implements JSONSerializable { + PayOrder(1, "支付订单"), // + SettleBill(2, "结算单"); + + public final int value; + public final String remark; + + private OrderType(int value, String remark){ + this.value = value; + this.remark = remark; + } + + @Override + public void write(JSONSerializer serializer, Object fieldName, Type fieldType, + int features) throws IOException { + JSONObject json = new JSONObject(); + json.put("value", value); + json.put("remark", remark); + serializer.write(json); + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/annotation/DeserializeUsingTest.java b/src/test/java/com/alibaba/json/bvt/annotation/DeserializeUsingTest.java new file mode 100644 index 0000000000..f3140843e3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/annotation/DeserializeUsingTest.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt.annotation; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import junit.framework.TestCase; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wenshao on 16/9/25. + */ +public class DeserializeUsingTest extends TestCase { + + public void test_deserializeUsing() throws Exception { + String jsonStr = "{'subjectList':['CHINESE','MATH']}"; + Teacher teacher = JSON.parseObject(jsonStr, Teacher.class); + assertEquals(SubjectEnum.CHINESE.ordinal(), teacher.getSubjectList().get(0).intValue()); + assertEquals(SubjectEnum.MATH.ordinal(), teacher.getSubjectList().get(1).intValue()); + } + + public static class Teacher { + + @JSONField(deserializeUsing = SubjectListDeserializer.class) + private List subjectList; + public List getSubjectList() { + return subjectList; + } + public void setSubjectList(List subjectList) { + this.subjectList = subjectList; + } + + } + + public static class SubjectListDeserializer implements ObjectDeserializer { + + @SuppressWarnings("unchecked") + + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + List parseObjectList = parser.parseArray(String.class); + if(parseObjectList != null) { + List resultVoList = new ArrayList(); + for(String parseObject : parseObjectList) { + resultVoList.add(SubjectEnum.valueOf(parseObject).ordinal()); + } + return (T)resultVoList; + } + throw new IllegalStateException(); + } + + + public int getFastMatchToken() { + return 0; + } + } + + public static enum SubjectEnum { + CHINESE, MATH + } +} diff --git a/src/test/java/com/alibaba/json/bvt/annotation/JSONTypejsonType_alphabetic_Test.java b/src/test/java/com/alibaba/json/bvt/annotation/JSONTypejsonType_alphabetic_Test.java new file mode 100755 index 0000000000..a26db38591 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/annotation/JSONTypejsonType_alphabetic_Test.java @@ -0,0 +1,114 @@ +package com.alibaba.json.bvt.annotation; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; + +public class JSONTypejsonType_alphabetic_Test extends TestCase { + + public void test_alphabetic_true() throws Exception { + A a = new A(); + a.setF0(101); + a.setF1(102); + + Assert.assertEquals("{\"f0\":101,\"f1\":102}", JSON.toJSONString(a)); + } + +// public void test_alphabetic_false() throws Exception { +// B b = new B(); +// b.setF0(101); +// b.setF1(102); +// +// Assert.assertFalse("{\"f2\":0,\"f1\":102,\"f0\":101}".equals(JSON.toJSONString(b))); +// } + + public void test_alphabetic_notSet() throws Exception { + C c = new C(); + c.setF0(101); + c.setF1(102); + + Assert.assertEquals("{\"f0\":101,\"f1\":102}", JSON.toJSONString(c)); + } + + @JSONType(alphabetic = true) + public static class A { + + private int f1; + private int f0; + + public int getF1() { + return f1; + } + + public void setF1(int f1) { + this.f1 = f1; + } + + public int getF0() { + return f0; + } + + public void setF0(int f0) { + this.f0 = f0; + } + + } + + @JSONType(alphabetic = false) + public static class B { + + private int f2; + private int f1; + private int f0; + + public int getF2() { + return f2; + } + + public void setF2(int f2) { + this.f2 = f2; + } + + public int getF1() { + return f1; + } + + public void setF1(int f1) { + this.f1 = f1; + } + + public int getF0() { + return f0; + } + + public void setF0(int f0) { + this.f0 = f0; + } + + } + + public static class C { + + private int f1; + private int f0; + + public int getF1() { + return f1; + } + + public void setF1(int f1) { + this.f1 = f1; + } + + public int getF0() { + return f0; + } + + public void setF0(int f0) { + this.f0 = f0; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/annotation/JsonSeeAlsoTest.java b/src/test/java/com/alibaba/json/bvt/annotation/JsonSeeAlsoTest.java new file mode 100644 index 0000000000..1a20123bf1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/annotation/JsonSeeAlsoTest.java @@ -0,0 +1,73 @@ +package com.alibaba.json.bvt.annotation; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class JsonSeeAlsoTest extends TestCase { + + public void test_seeAlso_dog() throws Exception { + Dog dog = new Dog(); + dog.dogName = "dog1001"; + + String text = JSON.toJSONString(dog, SerializerFeature.WriteClassName); + Assert.assertEquals("{\"@type\":\"dog\",\"dogName\":\"dog1001\"}", text); + + Dog dog2 = (Dog) JSON.parseObject(text, Animal.class); + + Assert.assertEquals(dog.dogName, dog2.dogName); + } + + public void test_seeAlso_cat() throws Exception { + Cat cat = new Cat(); + cat.catName = "cat2001"; + + String text = JSON.toJSONString(cat, SerializerFeature.WriteClassName); + Assert.assertEquals("{\"@type\":\"cat\",\"catName\":\"cat2001\"}", text); + + Cat cat2 = (Cat) JSON.parseObject(text, Animal.class); + + Assert.assertEquals(cat.catName, cat2.catName); + } + + public void test_seeAlso_tidy() throws Exception { + Tidy tidy = new Tidy(); + tidy.dogName = "dog2001"; + tidy.tidySpecific = "tidy1001"; + + String text = JSON.toJSONString(tidy, SerializerFeature.WriteClassName); + Assert.assertEquals("{\"@type\":\"tidy\",\"dogName\":\"dog2001\",\"tidySpecific\":\"tidy1001\"}", text); + + Tidy tidy2 = (Tidy) JSON.parseObject(text, Animal.class); + + Assert.assertEquals(tidy.dogName, tidy2.dogName); + } + + @JSONType(seeAlso = { Dog.class, Cat.class }) + public static class Animal { + } + + @JSONType(typeName = "dog", seeAlso={Tidy.class, Labrador.class}) + public static class Dog extends Animal { + public String dogName; + } + + @JSONType(typeName = "cat") + public static class Cat extends Animal { + public String catName; + } + + @JSONType(typeName = "tidy") + public static class Tidy extends Dog { + public String tidySpecific; + } + + @JSONType(typeName = "labrador") + public static class Labrador extends Dog { + public String tidySpecific; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/annotation/SerializeUsingTest.java b/src/test/java/com/alibaba/json/bvt/annotation/SerializeUsingTest.java new file mode 100644 index 0000000000..3240060834 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/annotation/SerializeUsingTest.java @@ -0,0 +1,61 @@ +package com.alibaba.json.bvt.annotation; + +import java.io.IOException; +import java.lang.reflect.Type; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; + +import junit.framework.TestCase; + +public class SerializeUsingTest extends TestCase { + + public void test_annotation() throws Exception { + Model model = new Model(); + model.value = 100; + String json = JSON.toJSONString(model); + Assert.assertEquals("{\"value\":\"100元\"}", json); + + Model model2 = JSON.parseObject(json, Model.class); + Assert.assertEquals(model.value, model2.value); + } + + public static class Model { + + @JSONField(serializeUsing = ModelValueSerializer.class, deserializeUsing = ModelValueDeserializer.class) + public int value; + } + + public static class ModelValueSerializer implements ObjectSerializer { + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, + int features) throws IOException { + Integer value = (Integer) object; + String text = value + "元"; + serializer.write(text); + } + } + + public static class ModelValueDeserializer implements ObjectDeserializer { + + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + String text = (String) parser.parse(); + if (text != null) { + text = text.replaceAll("元", ""); + } + return (T) Integer.valueOf(Integer.parseInt(text)); + } + + @Override + public int getFastMatchToken() { + return 0; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/annotation/SerializeUsingWhenString.java b/src/test/java/com/alibaba/json/bvt/annotation/SerializeUsingWhenString.java new file mode 100644 index 0000000000..ea1a33f7d8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/annotation/SerializeUsingWhenString.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.annotation; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.io.IOException; +import java.lang.reflect.Type; + +/** + * @author by laugh on 16/9/28 12:08. + */ +public class SerializeUsingWhenString extends TestCase { + public void test_annotation() throws Exception { + Model model = new Model(); + model.value = "100"; + Assert.assertEquals("{\"value\":\"100元\"}", JSON.toJSONString(model)); + + ModelWithOutJsonField modelWithOutJsonField = new ModelWithOutJsonField(); + modelWithOutJsonField.value = "100"; + Assert.assertEquals("{\"value\":\"100\"}", JSON.toJSONString(modelWithOutJsonField)); + } + + public static class Model { + + @JSONField(serializeUsing = ModelValueSerializer.class) + public String value; + } + + public static class ModelWithOutJsonField { + + public String value; + } + + public static class ModelValueSerializer implements ObjectSerializer { + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, + int features) throws IOException { + String value = (String) object; + String text = value + "元"; + serializer.write(text); + } + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/asm/ASMDeserTest.java b/src/test/java/com/alibaba/json/bvt/asm/ASMDeserTest.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/asm/ASMDeserTest.java rename to src/test/java/com/alibaba/json/bvt/asm/ASMDeserTest.java index c3bec3e0e1..29aa78a4bc --- a/src/test/java/com/alibaba/json/test/bvt/asm/ASMDeserTest.java +++ b/src/test/java/com/alibaba/json/bvt/asm/ASMDeserTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.asm; +package com.alibaba.json.bvt.asm; import java.util.ArrayList; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/asm/ASMDeserTest2.java b/src/test/java/com/alibaba/json/bvt/asm/ASMDeserTest2.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/asm/ASMDeserTest2.java rename to src/test/java/com/alibaba/json/bvt/asm/ASMDeserTest2.java index ca1dfd4710..2338f89691 --- a/src/test/java/com/alibaba/json/test/bvt/asm/ASMDeserTest2.java +++ b/src/test/java/com/alibaba/json/bvt/asm/ASMDeserTest2.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.asm; +package com.alibaba.json.bvt.asm; import java.util.ArrayList; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/asm/ASMUtilsTest.java b/src/test/java/com/alibaba/json/bvt/asm/ASMUtilsTest.java new file mode 100755 index 0000000000..a751843cfa --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/asm/ASMUtilsTest.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.asm; + +import junit.framework.TestCase; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.ParseContext; +import com.alibaba.fastjson.util.ASMUtils; + +public class ASMUtilsTest extends TestCase { + + public void test_isAnroid() throws Exception { + Assert.assertTrue(ASMUtils.isAndroid("Dalvik")); + } + + public void test_getDescs() throws Exception { + Assert.assertEquals("Lcom/alibaba/fastjson/parser/ParseContext;", ASMUtils.desc(ParseContext.class)); + } + + public void test_getType_null() throws Exception { + Assert.assertNull(ASMUtils.getMethodType(ParseContext.class, "XX")); + } + + public static Type getMethodType(Class clazz, String methodName) { + try { + Method method = clazz.getMethod(methodName); + + return method.getGenericReturnType(); + } catch (Exception ex) { + return null; + } + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/asm/Case0.java b/src/test/java/com/alibaba/json/bvt/asm/Case0.java old mode 100644 new mode 100755 similarity index 89% rename from src/test/java/com/alibaba/json/test/bvt/asm/Case0.java rename to src/test/java/com/alibaba/json/bvt/asm/Case0.java index c1f1ebd163..a0a5f23d4c --- a/src/test/java/com/alibaba/json/test/bvt/asm/Case0.java +++ b/src/test/java/com/alibaba/json/bvt/asm/Case0.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.asm; +package com.alibaba.json.bvt.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/asm/Case_Eishay.java b/src/test/java/com/alibaba/json/bvt/asm/Case_Eishay.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/asm/Case_Eishay.java rename to src/test/java/com/alibaba/json/bvt/asm/Case_Eishay.java index fbe389fcc3..985c96d4e7 --- a/src/test/java/com/alibaba/json/test/bvt/asm/Case_Eishay.java +++ b/src/test/java/com/alibaba/json/bvt/asm/Case_Eishay.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.asm; +package com.alibaba.json.bvt.asm; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/bvt/asm/Huge_200_ClassTest.java b/src/test/java/com/alibaba/json/bvt/asm/Huge_200_ClassTest.java new file mode 100755 index 0000000000..14a1b7884f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/asm/Huge_200_ClassTest.java @@ -0,0 +1,1826 @@ +package com.alibaba.json.bvt.asm; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Huge_200_ClassTest extends TestCase { + public void test_huge() { + JSON.parseObject("{}", VO.class); + } + + public static class VO { + + private Integer f000; + private Integer f001; + private Integer f002; + private Integer f003; + private Integer f004; + private Integer f005; + private Integer f006; + private Integer f007; + private Integer f008; + private Integer f009; + + private Integer f010; + private Integer f011; + private Integer f012; + private Integer f013; + private Integer f014; + private Integer f015; + private Integer f016; + private Integer f017; + private Integer f018; + private Integer f019; + + private Integer f020; + private Integer f021; + private Integer f022; + private Integer f023; + private Integer f024; + private Integer f025; + private Integer f026; + private Integer f027; + private Integer f028; + private Integer f029; + + private Integer f030; + private Integer f031; + private Integer f032; + private Integer f033; + private Integer f034; + private Integer f035; + private Integer f036; + private Integer f037; + private Integer f038; + private Integer f039; + + private Integer f040; + private Integer f041; + private Integer f042; + private Integer f043; + private Integer f044; + private Integer f045; + private Integer f046; + private Integer f047; + private Integer f048; + private Integer f049; + + private Integer f050; + private Integer f051; + private Integer f052; + private Integer f053; + private Integer f054; + private Integer f055; + private Integer f056; + private Integer f057; + private Integer f058; + private Integer f059; + + private Integer f060; + private Integer f061; + private Integer f062; + private Integer f063; + private Integer f064; + private Integer f065; + private Integer f066; + private Integer f067; + private Integer f068; + private Integer f069; + + private Integer f070; + private Integer f071; + private Integer f072; + private Integer f073; + private Integer f074; + private Integer f075; + private Integer f076; + private Integer f077; + private Integer f078; + private Integer f079; + + private Integer f080; + private Integer f081; + private Integer f082; + private Integer f083; + private Integer f084; + private Integer f085; + private Integer f086; + private Integer f087; + private Integer f088; + private Integer f089; + + private Integer f090; + private Integer f091; + private Integer f092; + private Integer f093; + private Integer f094; + private Integer f095; + private Integer f096; + private Integer f097; + private Integer f098; + private Integer f099; + + private Integer f100; + private Integer f101; + private Integer f102; + private Integer f103; + private Integer f104; + private Integer f105; + private Integer f106; + private Integer f107; + private Integer f108; + private Integer f109; + private Integer f110; + private Integer f111; + private Integer f112; + private Integer f113; + private Integer f114; + private Integer f115; + private Integer f116; + private Integer f117; + private Integer f118; + private Integer f119; + private Integer f120; + private Integer f121; + private Integer f122; + private Integer f123; + private Integer f124; + private Integer f125; + private Integer f126; + private Integer f127; + private Integer f128; + private Integer f129; + private Integer f130; + private Integer f131; + private Integer f132; + private Integer f133; + private Integer f134; + private Integer f135; + private Integer f136; + private Integer f137; + private Integer f138; + private Integer f139; + private Integer f140; + private Integer f141; + private Integer f142; + private Integer f143; + private Integer f144; + private Integer f145; + private Integer f146; + private Integer f147; + private Integer f148; + private Integer f149; + private Integer f150; + private Integer f151; + private Integer f152; + private Integer f153; + private Integer f154; + private Integer f155; + private Integer f156; + private Integer f157; + private Integer f158; + private Integer f159; + private Integer f160; + private Integer f161; + private Integer f162; + private Integer f163; + private Integer f164; + private Integer f165; + private Integer f166; + private Integer f167; + private Integer f168; + private Integer f169; + private Integer f170; + private Integer f171; + private Integer f172; + private Integer f173; + private Integer f174; + private Integer f175; + private Integer f176; + private Integer f177; + private Integer f178; + private Integer f179; + private Integer f180; + private Integer f181; + private Integer f182; + private Integer f183; + private Integer f184; + private Integer f185; + private Integer f186; + private Integer f187; + private Integer f188; + private Integer f189; + private Integer f190; + private Integer f191; + private Integer f192; + private Integer f193; + private Integer f194; + private Integer f195; + private Integer f196; + private Integer f197; + private Integer f198; + private Integer f199; + + public Integer getF000() { + return f000; + } + + public void setF000(Integer f000) { + this.f000 = f000; + } + + public Integer getF001() { + return f001; + } + + public void setF001(Integer f001) { + this.f001 = f001; + } + + public Integer getF002() { + return f002; + } + + public void setF002(Integer f002) { + this.f002 = f002; + } + + public Integer getF003() { + return f003; + } + + public void setF003(Integer f003) { + this.f003 = f003; + } + + public Integer getF004() { + return f004; + } + + public void setF004(Integer f004) { + this.f004 = f004; + } + + public Integer getF005() { + return f005; + } + + public void setF005(Integer f005) { + this.f005 = f005; + } + + public Integer getF006() { + return f006; + } + + public void setF006(Integer f006) { + this.f006 = f006; + } + + public Integer getF007() { + return f007; + } + + public void setF007(Integer f007) { + this.f007 = f007; + } + + public Integer getF008() { + return f008; + } + + public void setF008(Integer f008) { + this.f008 = f008; + } + + public Integer getF009() { + return f009; + } + + public void setF009(Integer f009) { + this.f009 = f009; + } + + public Integer getF010() { + return f010; + } + + public void setF010(Integer f010) { + this.f010 = f010; + } + + public Integer getF011() { + return f011; + } + + public void setF011(Integer f011) { + this.f011 = f011; + } + + public Integer getF012() { + return f012; + } + + public void setF012(Integer f012) { + this.f012 = f012; + } + + public Integer getF013() { + return f013; + } + + public void setF013(Integer f013) { + this.f013 = f013; + } + + public Integer getF014() { + return f014; + } + + public void setF014(Integer f014) { + this.f014 = f014; + } + + public Integer getF015() { + return f015; + } + + public void setF015(Integer f015) { + this.f015 = f015; + } + + public Integer getF016() { + return f016; + } + + public void setF016(Integer f016) { + this.f016 = f016; + } + + public Integer getF017() { + return f017; + } + + public void setF017(Integer f017) { + this.f017 = f017; + } + + public Integer getF018() { + return f018; + } + + public void setF018(Integer f018) { + this.f018 = f018; + } + + public Integer getF019() { + return f019; + } + + public void setF019(Integer f019) { + this.f019 = f019; + } + + public Integer getF020() { + return f020; + } + + public void setF020(Integer f020) { + this.f020 = f020; + } + + public Integer getF021() { + return f021; + } + + public void setF021(Integer f021) { + this.f021 = f021; + } + + public Integer getF022() { + return f022; + } + + public void setF022(Integer f022) { + this.f022 = f022; + } + + public Integer getF023() { + return f023; + } + + public void setF023(Integer f023) { + this.f023 = f023; + } + + public Integer getF024() { + return f024; + } + + public void setF024(Integer f024) { + this.f024 = f024; + } + + public Integer getF025() { + return f025; + } + + public void setF025(Integer f025) { + this.f025 = f025; + } + + public Integer getF026() { + return f026; + } + + public void setF026(Integer f026) { + this.f026 = f026; + } + + public Integer getF027() { + return f027; + } + + public void setF027(Integer f027) { + this.f027 = f027; + } + + public Integer getF028() { + return f028; + } + + public void setF028(Integer f028) { + this.f028 = f028; + } + + public Integer getF029() { + return f029; + } + + public void setF029(Integer f029) { + this.f029 = f029; + } + + public Integer getF030() { + return f030; + } + + public void setF030(Integer f030) { + this.f030 = f030; + } + + public Integer getF031() { + return f031; + } + + public void setF031(Integer f031) { + this.f031 = f031; + } + + public Integer getF032() { + return f032; + } + + public void setF032(Integer f032) { + this.f032 = f032; + } + + public Integer getF033() { + return f033; + } + + public void setF033(Integer f033) { + this.f033 = f033; + } + + public Integer getF034() { + return f034; + } + + public void setF034(Integer f034) { + this.f034 = f034; + } + + public Integer getF035() { + return f035; + } + + public void setF035(Integer f035) { + this.f035 = f035; + } + + public Integer getF036() { + return f036; + } + + public void setF036(Integer f036) { + this.f036 = f036; + } + + public Integer getF037() { + return f037; + } + + public void setF037(Integer f037) { + this.f037 = f037; + } + + public Integer getF038() { + return f038; + } + + public void setF038(Integer f038) { + this.f038 = f038; + } + + public Integer getF039() { + return f039; + } + + public void setF039(Integer f039) { + this.f039 = f039; + } + + public Integer getF040() { + return f040; + } + + public void setF040(Integer f040) { + this.f040 = f040; + } + + public Integer getF041() { + return f041; + } + + public void setF041(Integer f041) { + this.f041 = f041; + } + + public Integer getF042() { + return f042; + } + + public void setF042(Integer f042) { + this.f042 = f042; + } + + public Integer getF043() { + return f043; + } + + public void setF043(Integer f043) { + this.f043 = f043; + } + + public Integer getF044() { + return f044; + } + + public void setF044(Integer f044) { + this.f044 = f044; + } + + public Integer getF045() { + return f045; + } + + public void setF045(Integer f045) { + this.f045 = f045; + } + + public Integer getF046() { + return f046; + } + + public void setF046(Integer f046) { + this.f046 = f046; + } + + public Integer getF047() { + return f047; + } + + public void setF047(Integer f047) { + this.f047 = f047; + } + + public Integer getF048() { + return f048; + } + + public void setF048(Integer f048) { + this.f048 = f048; + } + + public Integer getF049() { + return f049; + } + + public void setF049(Integer f049) { + this.f049 = f049; + } + + public Integer getF050() { + return f050; + } + + public void setF050(Integer f050) { + this.f050 = f050; + } + + public Integer getF051() { + return f051; + } + + public void setF051(Integer f051) { + this.f051 = f051; + } + + public Integer getF052() { + return f052; + } + + public void setF052(Integer f052) { + this.f052 = f052; + } + + public Integer getF053() { + return f053; + } + + public void setF053(Integer f053) { + this.f053 = f053; + } + + public Integer getF054() { + return f054; + } + + public void setF054(Integer f054) { + this.f054 = f054; + } + + public Integer getF055() { + return f055; + } + + public void setF055(Integer f055) { + this.f055 = f055; + } + + public Integer getF056() { + return f056; + } + + public void setF056(Integer f056) { + this.f056 = f056; + } + + public Integer getF057() { + return f057; + } + + public void setF057(Integer f057) { + this.f057 = f057; + } + + public Integer getF058() { + return f058; + } + + public void setF058(Integer f058) { + this.f058 = f058; + } + + public Integer getF059() { + return f059; + } + + public void setF059(Integer f059) { + this.f059 = f059; + } + + public Integer getF060() { + return f060; + } + + public void setF060(Integer f060) { + this.f060 = f060; + } + + public Integer getF061() { + return f061; + } + + public void setF061(Integer f061) { + this.f061 = f061; + } + + public Integer getF062() { + return f062; + } + + public void setF062(Integer f062) { + this.f062 = f062; + } + + public Integer getF063() { + return f063; + } + + public void setF063(Integer f063) { + this.f063 = f063; + } + + public Integer getF064() { + return f064; + } + + public void setF064(Integer f064) { + this.f064 = f064; + } + + public Integer getF065() { + return f065; + } + + public void setF065(Integer f065) { + this.f065 = f065; + } + + public Integer getF066() { + return f066; + } + + public void setF066(Integer f066) { + this.f066 = f066; + } + + public Integer getF067() { + return f067; + } + + public void setF067(Integer f067) { + this.f067 = f067; + } + + public Integer getF068() { + return f068; + } + + public void setF068(Integer f068) { + this.f068 = f068; + } + + public Integer getF069() { + return f069; + } + + public void setF069(Integer f069) { + this.f069 = f069; + } + + public Integer getF070() { + return f070; + } + + public void setF070(Integer f070) { + this.f070 = f070; + } + + public Integer getF071() { + return f071; + } + + public void setF071(Integer f071) { + this.f071 = f071; + } + + public Integer getF072() { + return f072; + } + + public void setF072(Integer f072) { + this.f072 = f072; + } + + public Integer getF073() { + return f073; + } + + public void setF073(Integer f073) { + this.f073 = f073; + } + + public Integer getF074() { + return f074; + } + + public void setF074(Integer f074) { + this.f074 = f074; + } + + public Integer getF075() { + return f075; + } + + public void setF075(Integer f075) { + this.f075 = f075; + } + + public Integer getF076() { + return f076; + } + + public void setF076(Integer f076) { + this.f076 = f076; + } + + public Integer getF077() { + return f077; + } + + public void setF077(Integer f077) { + this.f077 = f077; + } + + public Integer getF078() { + return f078; + } + + public void setF078(Integer f078) { + this.f078 = f078; + } + + public Integer getF079() { + return f079; + } + + public void setF079(Integer f079) { + this.f079 = f079; + } + + public Integer getF080() { + return f080; + } + + public void setF080(Integer f080) { + this.f080 = f080; + } + + public Integer getF081() { + return f081; + } + + public void setF081(Integer f081) { + this.f081 = f081; + } + + public Integer getF082() { + return f082; + } + + public void setF082(Integer f082) { + this.f082 = f082; + } + + public Integer getF083() { + return f083; + } + + public void setF083(Integer f083) { + this.f083 = f083; + } + + public Integer getF084() { + return f084; + } + + public void setF084(Integer f084) { + this.f084 = f084; + } + + public Integer getF085() { + return f085; + } + + public void setF085(Integer f085) { + this.f085 = f085; + } + + public Integer getF086() { + return f086; + } + + public void setF086(Integer f086) { + this.f086 = f086; + } + + public Integer getF087() { + return f087; + } + + public void setF087(Integer f087) { + this.f087 = f087; + } + + public Integer getF088() { + return f088; + } + + public void setF088(Integer f088) { + this.f088 = f088; + } + + public Integer getF089() { + return f089; + } + + public void setF089(Integer f089) { + this.f089 = f089; + } + + public Integer getF090() { + return f090; + } + + public void setF090(Integer f090) { + this.f090 = f090; + } + + public Integer getF091() { + return f091; + } + + public void setF091(Integer f091) { + this.f091 = f091; + } + + public Integer getF092() { + return f092; + } + + public void setF092(Integer f092) { + this.f092 = f092; + } + + public Integer getF093() { + return f093; + } + + public void setF093(Integer f093) { + this.f093 = f093; + } + + public Integer getF094() { + return f094; + } + + public void setF094(Integer f094) { + this.f094 = f094; + } + + public Integer getF095() { + return f095; + } + + public void setF095(Integer f095) { + this.f095 = f095; + } + + public Integer getF096() { + return f096; + } + + public void setF096(Integer f096) { + this.f096 = f096; + } + + public Integer getF097() { + return f097; + } + + public void setF097(Integer f097) { + this.f097 = f097; + } + + public Integer getF098() { + return f098; + } + + public void setF098(Integer f098) { + this.f098 = f098; + } + + public Integer getF099() { + return f099; + } + + public void setF099(Integer f099) { + this.f099 = f099; + } + + public Integer getF100() { + return f100; + } + + public void setF100(Integer f100) { + this.f100 = f100; + } + + public Integer getF101() { + return f101; + } + + public void setF101(Integer f101) { + this.f101 = f101; + } + + public Integer getF102() { + return f102; + } + + public void setF102(Integer f102) { + this.f102 = f102; + } + + public Integer getF103() { + return f103; + } + + public void setF103(Integer f103) { + this.f103 = f103; + } + + public Integer getF104() { + return f104; + } + + public void setF104(Integer f104) { + this.f104 = f104; + } + + public Integer getF105() { + return f105; + } + + public void setF105(Integer f105) { + this.f105 = f105; + } + + public Integer getF106() { + return f106; + } + + public void setF106(Integer f106) { + this.f106 = f106; + } + + public Integer getF107() { + return f107; + } + + public void setF107(Integer f107) { + this.f107 = f107; + } + + public Integer getF108() { + return f108; + } + + public void setF108(Integer f108) { + this.f108 = f108; + } + + public Integer getF109() { + return f109; + } + + public void setF109(Integer f109) { + this.f109 = f109; + } + + public Integer getF110() { + return f110; + } + + public void setF110(Integer f110) { + this.f110 = f110; + } + + public Integer getF111() { + return f111; + } + + public void setF111(Integer f111) { + this.f111 = f111; + } + + public Integer getF112() { + return f112; + } + + public void setF112(Integer f112) { + this.f112 = f112; + } + + public Integer getF113() { + return f113; + } + + public void setF113(Integer f113) { + this.f113 = f113; + } + + public Integer getF114() { + return f114; + } + + public void setF114(Integer f114) { + this.f114 = f114; + } + + public Integer getF115() { + return f115; + } + + public void setF115(Integer f115) { + this.f115 = f115; + } + + public Integer getF116() { + return f116; + } + + public void setF116(Integer f116) { + this.f116 = f116; + } + + public Integer getF117() { + return f117; + } + + public void setF117(Integer f117) { + this.f117 = f117; + } + + public Integer getF118() { + return f118; + } + + public void setF118(Integer f118) { + this.f118 = f118; + } + + public Integer getF119() { + return f119; + } + + public void setF119(Integer f119) { + this.f119 = f119; + } + + public Integer getF120() { + return f120; + } + + public void setF120(Integer f120) { + this.f120 = f120; + } + + public Integer getF121() { + return f121; + } + + public void setF121(Integer f121) { + this.f121 = f121; + } + + public Integer getF122() { + return f122; + } + + public void setF122(Integer f122) { + this.f122 = f122; + } + + public Integer getF123() { + return f123; + } + + public void setF123(Integer f123) { + this.f123 = f123; + } + + public Integer getF124() { + return f124; + } + + public void setF124(Integer f124) { + this.f124 = f124; + } + + public Integer getF125() { + return f125; + } + + public void setF125(Integer f125) { + this.f125 = f125; + } + + public Integer getF126() { + return f126; + } + + public void setF126(Integer f126) { + this.f126 = f126; + } + + public Integer getF127() { + return f127; + } + + public void setF127(Integer f127) { + this.f127 = f127; + } + + public Integer getF128() { + return f128; + } + + public void setF128(Integer f128) { + this.f128 = f128; + } + + public Integer getF129() { + return f129; + } + + public void setF129(Integer f129) { + this.f129 = f129; + } + + public Integer getF130() { + return f130; + } + + public void setF130(Integer f130) { + this.f130 = f130; + } + + public Integer getF131() { + return f131; + } + + public void setF131(Integer f131) { + this.f131 = f131; + } + + public Integer getF132() { + return f132; + } + + public void setF132(Integer f132) { + this.f132 = f132; + } + + public Integer getF133() { + return f133; + } + + public void setF133(Integer f133) { + this.f133 = f133; + } + + public Integer getF134() { + return f134; + } + + public void setF134(Integer f134) { + this.f134 = f134; + } + + public Integer getF135() { + return f135; + } + + public void setF135(Integer f135) { + this.f135 = f135; + } + + public Integer getF136() { + return f136; + } + + public void setF136(Integer f136) { + this.f136 = f136; + } + + public Integer getF137() { + return f137; + } + + public void setF137(Integer f137) { + this.f137 = f137; + } + + public Integer getF138() { + return f138; + } + + public void setF138(Integer f138) { + this.f138 = f138; + } + + public Integer getF139() { + return f139; + } + + public void setF139(Integer f139) { + this.f139 = f139; + } + + public Integer getF140() { + return f140; + } + + public void setF140(Integer f140) { + this.f140 = f140; + } + + public Integer getF141() { + return f141; + } + + public void setF141(Integer f141) { + this.f141 = f141; + } + + public Integer getF142() { + return f142; + } + + public void setF142(Integer f142) { + this.f142 = f142; + } + + public Integer getF143() { + return f143; + } + + public void setF143(Integer f143) { + this.f143 = f143; + } + + public Integer getF144() { + return f144; + } + + public void setF144(Integer f144) { + this.f144 = f144; + } + + public Integer getF145() { + return f145; + } + + public void setF145(Integer f145) { + this.f145 = f145; + } + + public Integer getF146() { + return f146; + } + + public void setF146(Integer f146) { + this.f146 = f146; + } + + public Integer getF147() { + return f147; + } + + public void setF147(Integer f147) { + this.f147 = f147; + } + + public Integer getF148() { + return f148; + } + + public void setF148(Integer f148) { + this.f148 = f148; + } + + public Integer getF149() { + return f149; + } + + public void setF149(Integer f149) { + this.f149 = f149; + } + + public Integer getF150() { + return f150; + } + + public void setF150(Integer f150) { + this.f150 = f150; + } + + public Integer getF151() { + return f151; + } + + public void setF151(Integer f151) { + this.f151 = f151; + } + + public Integer getF152() { + return f152; + } + + public void setF152(Integer f152) { + this.f152 = f152; + } + + public Integer getF153() { + return f153; + } + + public void setF153(Integer f153) { + this.f153 = f153; + } + + public Integer getF154() { + return f154; + } + + public void setF154(Integer f154) { + this.f154 = f154; + } + + public Integer getF155() { + return f155; + } + + public void setF155(Integer f155) { + this.f155 = f155; + } + + public Integer getF156() { + return f156; + } + + public void setF156(Integer f156) { + this.f156 = f156; + } + + public Integer getF157() { + return f157; + } + + public void setF157(Integer f157) { + this.f157 = f157; + } + + public Integer getF158() { + return f158; + } + + public void setF158(Integer f158) { + this.f158 = f158; + } + + public Integer getF159() { + return f159; + } + + public void setF159(Integer f159) { + this.f159 = f159; + } + + public Integer getF160() { + return f160; + } + + public void setF160(Integer f160) { + this.f160 = f160; + } + + public Integer getF161() { + return f161; + } + + public void setF161(Integer f161) { + this.f161 = f161; + } + + public Integer getF162() { + return f162; + } + + public void setF162(Integer f162) { + this.f162 = f162; + } + + public Integer getF163() { + return f163; + } + + public void setF163(Integer f163) { + this.f163 = f163; + } + + public Integer getF164() { + return f164; + } + + public void setF164(Integer f164) { + this.f164 = f164; + } + + public Integer getF165() { + return f165; + } + + public void setF165(Integer f165) { + this.f165 = f165; + } + + public Integer getF166() { + return f166; + } + + public void setF166(Integer f166) { + this.f166 = f166; + } + + public Integer getF167() { + return f167; + } + + public void setF167(Integer f167) { + this.f167 = f167; + } + + public Integer getF168() { + return f168; + } + + public void setF168(Integer f168) { + this.f168 = f168; + } + + public Integer getF169() { + return f169; + } + + public void setF169(Integer f169) { + this.f169 = f169; + } + + public Integer getF170() { + return f170; + } + + public void setF170(Integer f170) { + this.f170 = f170; + } + + public Integer getF171() { + return f171; + } + + public void setF171(Integer f171) { + this.f171 = f171; + } + + public Integer getF172() { + return f172; + } + + public void setF172(Integer f172) { + this.f172 = f172; + } + + public Integer getF173() { + return f173; + } + + public void setF173(Integer f173) { + this.f173 = f173; + } + + public Integer getF174() { + return f174; + } + + public void setF174(Integer f174) { + this.f174 = f174; + } + + public Integer getF175() { + return f175; + } + + public void setF175(Integer f175) { + this.f175 = f175; + } + + public Integer getF176() { + return f176; + } + + public void setF176(Integer f176) { + this.f176 = f176; + } + + public Integer getF177() { + return f177; + } + + public void setF177(Integer f177) { + this.f177 = f177; + } + + public Integer getF178() { + return f178; + } + + public void setF178(Integer f178) { + this.f178 = f178; + } + + public Integer getF179() { + return f179; + } + + public void setF179(Integer f179) { + this.f179 = f179; + } + + public Integer getF180() { + return f180; + } + + public void setF180(Integer f180) { + this.f180 = f180; + } + + public Integer getF181() { + return f181; + } + + public void setF181(Integer f181) { + this.f181 = f181; + } + + public Integer getF182() { + return f182; + } + + public void setF182(Integer f182) { + this.f182 = f182; + } + + public Integer getF183() { + return f183; + } + + public void setF183(Integer f183) { + this.f183 = f183; + } + + public Integer getF184() { + return f184; + } + + public void setF184(Integer f184) { + this.f184 = f184; + } + + public Integer getF185() { + return f185; + } + + public void setF185(Integer f185) { + this.f185 = f185; + } + + public Integer getF186() { + return f186; + } + + public void setF186(Integer f186) { + this.f186 = f186; + } + + public Integer getF187() { + return f187; + } + + public void setF187(Integer f187) { + this.f187 = f187; + } + + public Integer getF188() { + return f188; + } + + public void setF188(Integer f188) { + this.f188 = f188; + } + + public Integer getF189() { + return f189; + } + + public void setF189(Integer f189) { + this.f189 = f189; + } + + public Integer getF190() { + return f190; + } + + public void setF190(Integer f190) { + this.f190 = f190; + } + + public Integer getF191() { + return f191; + } + + public void setF191(Integer f191) { + this.f191 = f191; + } + + public Integer getF192() { + return f192; + } + + public void setF192(Integer f192) { + this.f192 = f192; + } + + public Integer getF193() { + return f193; + } + + public void setF193(Integer f193) { + this.f193 = f193; + } + + public Integer getF194() { + return f194; + } + + public void setF194(Integer f194) { + this.f194 = f194; + } + + public Integer getF195() { + return f195; + } + + public void setF195(Integer f195) { + this.f195 = f195; + } + + public Integer getF196() { + return f196; + } + + public void setF196(Integer f196) { + this.f196 = f196; + } + + public Integer getF197() { + return f197; + } + + public void setF197(Integer f197) { + this.f197 = f197; + } + + public Integer getF198() { + return f198; + } + + public void setF198(Integer f198) { + this.f198 = f198; + } + + public Integer getF199() { + return f199; + } + + public void setF199(Integer f199) { + this.f199 = f199; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/asm/Huge_300_ClassTest.java b/src/test/java/com/alibaba/json/bvt/asm/Huge_300_ClassTest.java new file mode 100755 index 0000000000..e30ec5c042 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/asm/Huge_300_ClassTest.java @@ -0,0 +1,2930 @@ +package com.alibaba.json.bvt.asm; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Huge_300_ClassTest extends TestCase { + + public void test_huge() { + JSON.parseObject("{}", VO.class); + } + + public static class VO { + + private Integer f000; + private Integer f001; + private Integer f002; + private Integer f003; + private Integer f004; + private Integer f005; + private Integer f006; + private Integer f007; + private Integer f008; + private Integer f009; + + private Integer f010; + private Integer f011; + private Integer f012; + private Integer f013; + private Integer f014; + private Integer f015; + private Integer f016; + private Integer f017; + private Integer f018; + private Integer f019; + + private Integer f020; + private Integer f021; + private Integer f022; + private Integer f023; + private Integer f024; + private Integer f025; + private Integer f026; + private Integer f027; + private Integer f028; + private Integer f029; + + private Integer f030; + private Integer f031; + private Integer f032; + private Integer f033; + private Integer f034; + private Integer f035; + private Integer f036; + private Integer f037; + private Integer f038; + private Integer f039; + + private Integer f040; + private Integer f041; + private Integer f042; + private Integer f043; + private Integer f044; + private Integer f045; + private Integer f046; + private Integer f047; + private Integer f048; + private Integer f049; + + private Integer f050; + private Integer f051; + private Integer f052; + private Integer f053; + private Integer f054; + private Integer f055; + private Integer f056; + private Integer f057; + private Integer f058; + private Integer f059; + + private Integer f060; + private Integer f061; + private Integer f062; + private Integer f063; + private Integer f064; + private Integer f065; + private Integer f066; + private Integer f067; + private Integer f068; + private Integer f069; + + private Integer f070; + private Integer f071; + private Integer f072; + private Integer f073; + private Integer f074; + private Integer f075; + private Integer f076; + private Integer f077; + private Integer f078; + private Integer f079; + + private Integer f080; + private Integer f081; + private Integer f082; + private Integer f083; + private Integer f084; + private Integer f085; + private Integer f086; + private Integer f087; + private Integer f088; + private Integer f089; + + private Integer f090; + private Integer f091; + private Integer f092; + private Integer f093; + private Integer f094; + private Integer f095; + private Integer f096; + private Integer f097; + private Integer f098; + private Integer f099; + + private Integer f100; + private Integer f101; + private Integer f102; + private Integer f103; + private Integer f104; + private Integer f105; + private Integer f106; + private Integer f107; + private Integer f108; + private Integer f109; + private Integer f110; + private Integer f111; + private Integer f112; + private Integer f113; + private Integer f114; + private Integer f115; + private Integer f116; + private Integer f117; + private Integer f118; + private Integer f119; + private Integer f120; + private Integer f121; + private Integer f122; + private Integer f123; + private Integer f124; + private Integer f125; + private Integer f126; + private Integer f127; + private Integer f128; + private Integer f129; + private Integer f130; + private Integer f131; + private Integer f132; + private Integer f133; + private Integer f134; + private Integer f135; + private Integer f136; + private Integer f137; + private Integer f138; + private Integer f139; + private Integer f140; + private Integer f141; + private Integer f142; + private Integer f143; + private Integer f144; + private Integer f145; + private Integer f146; + private Integer f147; + private Integer f148; + private Integer f149; + private Integer f150; + private Integer f151; + private Integer f152; + private Integer f153; + private Integer f154; + private Integer f155; + private Integer f156; + private Integer f157; + private Integer f158; + private Integer f159; + private Integer f160; + private Integer f161; + private Integer f162; + private Integer f163; + private Integer f164; + private Integer f165; + private Integer f166; + private Integer f167; + private Integer f168; + private Integer f169; + private Integer f170; + private Integer f171; + private Integer f172; + private Integer f173; + private Integer f174; + private Integer f175; + private Integer f176; + private Integer f177; + private Integer f178; + private Integer f179; + private Integer f180; + private Integer f181; + private Integer f182; + private Integer f183; + private Integer f184; + private Integer f185; + private Integer f186; + private Integer f187; + private Integer f188; + private Integer f189; + private Integer f190; + private Integer f191; + private Integer f192; + private Integer f193; + private Integer f194; + private Integer f195; + private Integer f196; + private Integer f197; + private Integer f198; + private Integer f199; + + private Integer f200; + private Integer f201; + private Integer f202; + private Integer f203; + private Integer f204; + private Integer f205; + private Integer f206; + private Integer f207; + private Integer f208; + private Integer f209; + private Integer f210; + private Integer f211; + private Integer f212; + private Integer f213; + private Integer f214; + private Integer f215; + private Integer f216; + private Integer f217; + private Integer f218; + private Integer f219; + private Integer f220; + private Integer f221; + private Integer f222; + private Integer f223; + private Integer f224; + private Integer f225; + private Integer f226; + private Integer f227; + private Integer f228; + private Integer f229; + private Integer f230; + private Integer f231; + private Integer f232; + private Integer f233; + private Integer f234; + private Integer f235; + private Integer f236; + private Integer f237; + private Integer f238; + private Integer f239; + private Integer f240; + private Integer f241; + private Integer f242; + private Integer f243; + private Integer f244; + private Integer f245; + private Integer f246; + private Integer f247; + private Integer f248; + private Integer f249; + private Integer f250; + private Integer f251; + private Integer f252; + private Integer f253; + private Integer f254; + private Integer f255; + private Integer f256; + private Integer f257; + private Integer f258; + private Integer f259; + private Integer f260; + private Integer f261; + private Integer f262; + private Integer f263; + private Integer f264; + private Integer f265; + private Integer f266; + private Integer f267; + private Integer f268; + private Integer f269; + private Integer f270; + private Integer f271; + private Integer f272; + private Integer f273; + private Integer f274; + private Integer f275; + private Integer f276; + private Integer f277; + private Integer f278; + private Integer f279; + private Integer f280; + private Integer f281; + private Integer f282; + private Integer f283; + private Integer f284; + private Integer f285; + private Integer f286; + private Integer f287; + private Integer f288; + private Integer f289; + private Integer f290; + private Integer f291; + private Integer f292; + private Integer f293; + private Integer f294; + private Integer f295; + private Integer f296; + private Integer f297; + private Integer f298; + private Integer f299; + + public Integer getF000() { + return f000; + } + + public void setF000(Integer f000) { + this.f000 = f000; + } + + public Integer getF001() { + return f001; + } + + public void setF001(Integer f001) { + this.f001 = f001; + } + + public Integer getF002() { + return f002; + } + + public void setF002(Integer f002) { + this.f002 = f002; + } + + public Integer getF003() { + return f003; + } + + public void setF003(Integer f003) { + this.f003 = f003; + } + + public Integer getF004() { + return f004; + } + + public void setF004(Integer f004) { + this.f004 = f004; + } + + public Integer getF005() { + return f005; + } + + public void setF005(Integer f005) { + this.f005 = f005; + } + + public Integer getF006() { + return f006; + } + + public void setF006(Integer f006) { + this.f006 = f006; + } + + public Integer getF007() { + return f007; + } + + public void setF007(Integer f007) { + this.f007 = f007; + } + + public Integer getF008() { + return f008; + } + + public void setF008(Integer f008) { + this.f008 = f008; + } + + public Integer getF009() { + return f009; + } + + public void setF009(Integer f009) { + this.f009 = f009; + } + + public Integer getF010() { + return f010; + } + + public void setF010(Integer f010) { + this.f010 = f010; + } + + public Integer getF011() { + return f011; + } + + public void setF011(Integer f011) { + this.f011 = f011; + } + + public Integer getF012() { + return f012; + } + + public void setF012(Integer f012) { + this.f012 = f012; + } + + public Integer getF013() { + return f013; + } + + public void setF013(Integer f013) { + this.f013 = f013; + } + + public Integer getF014() { + return f014; + } + + public void setF014(Integer f014) { + this.f014 = f014; + } + + public Integer getF015() { + return f015; + } + + public void setF015(Integer f015) { + this.f015 = f015; + } + + public Integer getF016() { + return f016; + } + + public void setF016(Integer f016) { + this.f016 = f016; + } + + public Integer getF017() { + return f017; + } + + public void setF017(Integer f017) { + this.f017 = f017; + } + + public Integer getF018() { + return f018; + } + + public void setF018(Integer f018) { + this.f018 = f018; + } + + public Integer getF019() { + return f019; + } + + public void setF019(Integer f019) { + this.f019 = f019; + } + + public Integer getF020() { + return f020; + } + + public void setF020(Integer f020) { + this.f020 = f020; + } + + public Integer getF021() { + return f021; + } + + public void setF021(Integer f021) { + this.f021 = f021; + } + + public Integer getF022() { + return f022; + } + + public void setF022(Integer f022) { + this.f022 = f022; + } + + public Integer getF023() { + return f023; + } + + public void setF023(Integer f023) { + this.f023 = f023; + } + + public Integer getF024() { + return f024; + } + + public void setF024(Integer f024) { + this.f024 = f024; + } + + public Integer getF025() { + return f025; + } + + public void setF025(Integer f025) { + this.f025 = f025; + } + + public Integer getF026() { + return f026; + } + + public void setF026(Integer f026) { + this.f026 = f026; + } + + public Integer getF027() { + return f027; + } + + public void setF027(Integer f027) { + this.f027 = f027; + } + + public Integer getF028() { + return f028; + } + + public void setF028(Integer f028) { + this.f028 = f028; + } + + public Integer getF029() { + return f029; + } + + public void setF029(Integer f029) { + this.f029 = f029; + } + + public Integer getF030() { + return f030; + } + + public void setF030(Integer f030) { + this.f030 = f030; + } + + public Integer getF031() { + return f031; + } + + public void setF031(Integer f031) { + this.f031 = f031; + } + + public Integer getF032() { + return f032; + } + + public void setF032(Integer f032) { + this.f032 = f032; + } + + public Integer getF033() { + return f033; + } + + public void setF033(Integer f033) { + this.f033 = f033; + } + + public Integer getF034() { + return f034; + } + + public void setF034(Integer f034) { + this.f034 = f034; + } + + public Integer getF035() { + return f035; + } + + public void setF035(Integer f035) { + this.f035 = f035; + } + + public Integer getF036() { + return f036; + } + + public void setF036(Integer f036) { + this.f036 = f036; + } + + public Integer getF037() { + return f037; + } + + public void setF037(Integer f037) { + this.f037 = f037; + } + + public Integer getF038() { + return f038; + } + + public void setF038(Integer f038) { + this.f038 = f038; + } + + public Integer getF039() { + return f039; + } + + public void setF039(Integer f039) { + this.f039 = f039; + } + + public Integer getF040() { + return f040; + } + + public void setF040(Integer f040) { + this.f040 = f040; + } + + public Integer getF041() { + return f041; + } + + public void setF041(Integer f041) { + this.f041 = f041; + } + + public Integer getF042() { + return f042; + } + + public void setF042(Integer f042) { + this.f042 = f042; + } + + public Integer getF043() { + return f043; + } + + public void setF043(Integer f043) { + this.f043 = f043; + } + + public Integer getF044() { + return f044; + } + + public void setF044(Integer f044) { + this.f044 = f044; + } + + public Integer getF045() { + return f045; + } + + public void setF045(Integer f045) { + this.f045 = f045; + } + + public Integer getF046() { + return f046; + } + + public void setF046(Integer f046) { + this.f046 = f046; + } + + public Integer getF047() { + return f047; + } + + public void setF047(Integer f047) { + this.f047 = f047; + } + + public Integer getF048() { + return f048; + } + + public void setF048(Integer f048) { + this.f048 = f048; + } + + public Integer getF049() { + return f049; + } + + public void setF049(Integer f049) { + this.f049 = f049; + } + + public Integer getF050() { + return f050; + } + + public void setF050(Integer f050) { + this.f050 = f050; + } + + public Integer getF051() { + return f051; + } + + public void setF051(Integer f051) { + this.f051 = f051; + } + + public Integer getF052() { + return f052; + } + + public void setF052(Integer f052) { + this.f052 = f052; + } + + public Integer getF053() { + return f053; + } + + public void setF053(Integer f053) { + this.f053 = f053; + } + + public Integer getF054() { + return f054; + } + + public void setF054(Integer f054) { + this.f054 = f054; + } + + public Integer getF055() { + return f055; + } + + public void setF055(Integer f055) { + this.f055 = f055; + } + + public Integer getF056() { + return f056; + } + + public void setF056(Integer f056) { + this.f056 = f056; + } + + public Integer getF057() { + return f057; + } + + public void setF057(Integer f057) { + this.f057 = f057; + } + + public Integer getF058() { + return f058; + } + + public void setF058(Integer f058) { + this.f058 = f058; + } + + public Integer getF059() { + return f059; + } + + public void setF059(Integer f059) { + this.f059 = f059; + } + + public Integer getF060() { + return f060; + } + + public void setF060(Integer f060) { + this.f060 = f060; + } + + public Integer getF061() { + return f061; + } + + public void setF061(Integer f061) { + this.f061 = f061; + } + + public Integer getF062() { + return f062; + } + + public void setF062(Integer f062) { + this.f062 = f062; + } + + public Integer getF063() { + return f063; + } + + public void setF063(Integer f063) { + this.f063 = f063; + } + + public Integer getF064() { + return f064; + } + + public void setF064(Integer f064) { + this.f064 = f064; + } + + public Integer getF065() { + return f065; + } + + public void setF065(Integer f065) { + this.f065 = f065; + } + + public Integer getF066() { + return f066; + } + + public void setF066(Integer f066) { + this.f066 = f066; + } + + public Integer getF067() { + return f067; + } + + public void setF067(Integer f067) { + this.f067 = f067; + } + + public Integer getF068() { + return f068; + } + + public void setF068(Integer f068) { + this.f068 = f068; + } + + public Integer getF069() { + return f069; + } + + public void setF069(Integer f069) { + this.f069 = f069; + } + + public Integer getF070() { + return f070; + } + + public void setF070(Integer f070) { + this.f070 = f070; + } + + public Integer getF071() { + return f071; + } + + public void setF071(Integer f071) { + this.f071 = f071; + } + + public Integer getF072() { + return f072; + } + + public void setF072(Integer f072) { + this.f072 = f072; + } + + public Integer getF073() { + return f073; + } + + public void setF073(Integer f073) { + this.f073 = f073; + } + + public Integer getF074() { + return f074; + } + + public void setF074(Integer f074) { + this.f074 = f074; + } + + public Integer getF075() { + return f075; + } + + public void setF075(Integer f075) { + this.f075 = f075; + } + + public Integer getF076() { + return f076; + } + + public void setF076(Integer f076) { + this.f076 = f076; + } + + public Integer getF077() { + return f077; + } + + public void setF077(Integer f077) { + this.f077 = f077; + } + + public Integer getF078() { + return f078; + } + + public void setF078(Integer f078) { + this.f078 = f078; + } + + public Integer getF079() { + return f079; + } + + public void setF079(Integer f079) { + this.f079 = f079; + } + + public Integer getF080() { + return f080; + } + + public void setF080(Integer f080) { + this.f080 = f080; + } + + public Integer getF081() { + return f081; + } + + public void setF081(Integer f081) { + this.f081 = f081; + } + + public Integer getF082() { + return f082; + } + + public void setF082(Integer f082) { + this.f082 = f082; + } + + public Integer getF083() { + return f083; + } + + public void setF083(Integer f083) { + this.f083 = f083; + } + + public Integer getF084() { + return f084; + } + + public void setF084(Integer f084) { + this.f084 = f084; + } + + public Integer getF085() { + return f085; + } + + public void setF085(Integer f085) { + this.f085 = f085; + } + + public Integer getF086() { + return f086; + } + + public void setF086(Integer f086) { + this.f086 = f086; + } + + public Integer getF087() { + return f087; + } + + public void setF087(Integer f087) { + this.f087 = f087; + } + + public Integer getF088() { + return f088; + } + + public void setF088(Integer f088) { + this.f088 = f088; + } + + public Integer getF089() { + return f089; + } + + public void setF089(Integer f089) { + this.f089 = f089; + } + + public Integer getF090() { + return f090; + } + + public void setF090(Integer f090) { + this.f090 = f090; + } + + public Integer getF091() { + return f091; + } + + public void setF091(Integer f091) { + this.f091 = f091; + } + + public Integer getF092() { + return f092; + } + + public void setF092(Integer f092) { + this.f092 = f092; + } + + public Integer getF093() { + return f093; + } + + public void setF093(Integer f093) { + this.f093 = f093; + } + + public Integer getF094() { + return f094; + } + + public void setF094(Integer f094) { + this.f094 = f094; + } + + public Integer getF095() { + return f095; + } + + public void setF095(Integer f095) { + this.f095 = f095; + } + + public Integer getF096() { + return f096; + } + + public void setF096(Integer f096) { + this.f096 = f096; + } + + public Integer getF097() { + return f097; + } + + public void setF097(Integer f097) { + this.f097 = f097; + } + + public Integer getF098() { + return f098; + } + + public void setF098(Integer f098) { + this.f098 = f098; + } + + public Integer getF099() { + return f099; + } + + public void setF099(Integer f099) { + this.f099 = f099; + } + + public Integer getF100() { + return f100; + } + + public void setF100(Integer f100) { + this.f100 = f100; + } + + public Integer getF101() { + return f101; + } + + public void setF101(Integer f101) { + this.f101 = f101; + } + + public Integer getF102() { + return f102; + } + + public void setF102(Integer f102) { + this.f102 = f102; + } + + public Integer getF103() { + return f103; + } + + public void setF103(Integer f103) { + this.f103 = f103; + } + + public Integer getF104() { + return f104; + } + + public void setF104(Integer f104) { + this.f104 = f104; + } + + public Integer getF105() { + return f105; + } + + public void setF105(Integer f105) { + this.f105 = f105; + } + + public Integer getF106() { + return f106; + } + + public void setF106(Integer f106) { + this.f106 = f106; + } + + public Integer getF107() { + return f107; + } + + public void setF107(Integer f107) { + this.f107 = f107; + } + + public Integer getF108() { + return f108; + } + + public void setF108(Integer f108) { + this.f108 = f108; + } + + public Integer getF109() { + return f109; + } + + public void setF109(Integer f109) { + this.f109 = f109; + } + + public Integer getF110() { + return f110; + } + + public void setF110(Integer f110) { + this.f110 = f110; + } + + public Integer getF111() { + return f111; + } + + public void setF111(Integer f111) { + this.f111 = f111; + } + + public Integer getF112() { + return f112; + } + + public void setF112(Integer f112) { + this.f112 = f112; + } + + public Integer getF113() { + return f113; + } + + public void setF113(Integer f113) { + this.f113 = f113; + } + + public Integer getF114() { + return f114; + } + + public void setF114(Integer f114) { + this.f114 = f114; + } + + public Integer getF115() { + return f115; + } + + public void setF115(Integer f115) { + this.f115 = f115; + } + + public Integer getF116() { + return f116; + } + + public void setF116(Integer f116) { + this.f116 = f116; + } + + public Integer getF117() { + return f117; + } + + public void setF117(Integer f117) { + this.f117 = f117; + } + + public Integer getF118() { + return f118; + } + + public void setF118(Integer f118) { + this.f118 = f118; + } + + public Integer getF119() { + return f119; + } + + public void setF119(Integer f119) { + this.f119 = f119; + } + + public Integer getF120() { + return f120; + } + + public void setF120(Integer f120) { + this.f120 = f120; + } + + public Integer getF121() { + return f121; + } + + public void setF121(Integer f121) { + this.f121 = f121; + } + + public Integer getF122() { + return f122; + } + + public void setF122(Integer f122) { + this.f122 = f122; + } + + public Integer getF123() { + return f123; + } + + public void setF123(Integer f123) { + this.f123 = f123; + } + + public Integer getF124() { + return f124; + } + + public void setF124(Integer f124) { + this.f124 = f124; + } + + public Integer getF125() { + return f125; + } + + public void setF125(Integer f125) { + this.f125 = f125; + } + + public Integer getF126() { + return f126; + } + + public void setF126(Integer f126) { + this.f126 = f126; + } + + public Integer getF127() { + return f127; + } + + public void setF127(Integer f127) { + this.f127 = f127; + } + + public Integer getF128() { + return f128; + } + + public void setF128(Integer f128) { + this.f128 = f128; + } + + public Integer getF129() { + return f129; + } + + public void setF129(Integer f129) { + this.f129 = f129; + } + + public Integer getF130() { + return f130; + } + + public void setF130(Integer f130) { + this.f130 = f130; + } + + public Integer getF131() { + return f131; + } + + public void setF131(Integer f131) { + this.f131 = f131; + } + + public Integer getF132() { + return f132; + } + + public void setF132(Integer f132) { + this.f132 = f132; + } + + public Integer getF133() { + return f133; + } + + public void setF133(Integer f133) { + this.f133 = f133; + } + + public Integer getF134() { + return f134; + } + + public void setF134(Integer f134) { + this.f134 = f134; + } + + public Integer getF135() { + return f135; + } + + public void setF135(Integer f135) { + this.f135 = f135; + } + + public Integer getF136() { + return f136; + } + + public void setF136(Integer f136) { + this.f136 = f136; + } + + public Integer getF137() { + return f137; + } + + public void setF137(Integer f137) { + this.f137 = f137; + } + + public Integer getF138() { + return f138; + } + + public void setF138(Integer f138) { + this.f138 = f138; + } + + public Integer getF139() { + return f139; + } + + public void setF139(Integer f139) { + this.f139 = f139; + } + + public Integer getF140() { + return f140; + } + + public void setF140(Integer f140) { + this.f140 = f140; + } + + public Integer getF141() { + return f141; + } + + public void setF141(Integer f141) { + this.f141 = f141; + } + + public Integer getF142() { + return f142; + } + + public void setF142(Integer f142) { + this.f142 = f142; + } + + public Integer getF143() { + return f143; + } + + public void setF143(Integer f143) { + this.f143 = f143; + } + + public Integer getF144() { + return f144; + } + + public void setF144(Integer f144) { + this.f144 = f144; + } + + public Integer getF145() { + return f145; + } + + public void setF145(Integer f145) { + this.f145 = f145; + } + + public Integer getF146() { + return f146; + } + + public void setF146(Integer f146) { + this.f146 = f146; + } + + public Integer getF147() { + return f147; + } + + public void setF147(Integer f147) { + this.f147 = f147; + } + + public Integer getF148() { + return f148; + } + + public void setF148(Integer f148) { + this.f148 = f148; + } + + public Integer getF149() { + return f149; + } + + public void setF149(Integer f149) { + this.f149 = f149; + } + + public Integer getF150() { + return f150; + } + + public void setF150(Integer f150) { + this.f150 = f150; + } + + public Integer getF151() { + return f151; + } + + public void setF151(Integer f151) { + this.f151 = f151; + } + + public Integer getF152() { + return f152; + } + + public void setF152(Integer f152) { + this.f152 = f152; + } + + public Integer getF153() { + return f153; + } + + public void setF153(Integer f153) { + this.f153 = f153; + } + + public Integer getF154() { + return f154; + } + + public void setF154(Integer f154) { + this.f154 = f154; + } + + public Integer getF155() { + return f155; + } + + public void setF155(Integer f155) { + this.f155 = f155; + } + + public Integer getF156() { + return f156; + } + + public void setF156(Integer f156) { + this.f156 = f156; + } + + public Integer getF157() { + return f157; + } + + public void setF157(Integer f157) { + this.f157 = f157; + } + + public Integer getF158() { + return f158; + } + + public void setF158(Integer f158) { + this.f158 = f158; + } + + public Integer getF159() { + return f159; + } + + public void setF159(Integer f159) { + this.f159 = f159; + } + + public Integer getF160() { + return f160; + } + + public void setF160(Integer f160) { + this.f160 = f160; + } + + public Integer getF161() { + return f161; + } + + public void setF161(Integer f161) { + this.f161 = f161; + } + + public Integer getF162() { + return f162; + } + + public void setF162(Integer f162) { + this.f162 = f162; + } + + public Integer getF163() { + return f163; + } + + public void setF163(Integer f163) { + this.f163 = f163; + } + + public Integer getF164() { + return f164; + } + + public void setF164(Integer f164) { + this.f164 = f164; + } + + public Integer getF165() { + return f165; + } + + public void setF165(Integer f165) { + this.f165 = f165; + } + + public Integer getF166() { + return f166; + } + + public void setF166(Integer f166) { + this.f166 = f166; + } + + public Integer getF167() { + return f167; + } + + public void setF167(Integer f167) { + this.f167 = f167; + } + + public Integer getF168() { + return f168; + } + + public void setF168(Integer f168) { + this.f168 = f168; + } + + public Integer getF169() { + return f169; + } + + public void setF169(Integer f169) { + this.f169 = f169; + } + + public Integer getF170() { + return f170; + } + + public void setF170(Integer f170) { + this.f170 = f170; + } + + public Integer getF171() { + return f171; + } + + public void setF171(Integer f171) { + this.f171 = f171; + } + + public Integer getF172() { + return f172; + } + + public void setF172(Integer f172) { + this.f172 = f172; + } + + public Integer getF173() { + return f173; + } + + public void setF173(Integer f173) { + this.f173 = f173; + } + + public Integer getF174() { + return f174; + } + + public void setF174(Integer f174) { + this.f174 = f174; + } + + public Integer getF175() { + return f175; + } + + public void setF175(Integer f175) { + this.f175 = f175; + } + + public Integer getF176() { + return f176; + } + + public void setF176(Integer f176) { + this.f176 = f176; + } + + public Integer getF177() { + return f177; + } + + public void setF177(Integer f177) { + this.f177 = f177; + } + + public Integer getF178() { + return f178; + } + + public void setF178(Integer f178) { + this.f178 = f178; + } + + public Integer getF179() { + return f179; + } + + public void setF179(Integer f179) { + this.f179 = f179; + } + + public Integer getF180() { + return f180; + } + + public void setF180(Integer f180) { + this.f180 = f180; + } + + public Integer getF181() { + return f181; + } + + public void setF181(Integer f181) { + this.f181 = f181; + } + + public Integer getF182() { + return f182; + } + + public void setF182(Integer f182) { + this.f182 = f182; + } + + public Integer getF183() { + return f183; + } + + public void setF183(Integer f183) { + this.f183 = f183; + } + + public Integer getF184() { + return f184; + } + + public void setF184(Integer f184) { + this.f184 = f184; + } + + public Integer getF185() { + return f185; + } + + public void setF185(Integer f185) { + this.f185 = f185; + } + + public Integer getF186() { + return f186; + } + + public void setF186(Integer f186) { + this.f186 = f186; + } + + public Integer getF187() { + return f187; + } + + public void setF187(Integer f187) { + this.f187 = f187; + } + + public Integer getF188() { + return f188; + } + + public void setF188(Integer f188) { + this.f188 = f188; + } + + public Integer getF189() { + return f189; + } + + public void setF189(Integer f189) { + this.f189 = f189; + } + + public Integer getF190() { + return f190; + } + + public void setF190(Integer f190) { + this.f190 = f190; + } + + public Integer getF191() { + return f191; + } + + public void setF191(Integer f191) { + this.f191 = f191; + } + + public Integer getF192() { + return f192; + } + + public void setF192(Integer f192) { + this.f192 = f192; + } + + public Integer getF193() { + return f193; + } + + public void setF193(Integer f193) { + this.f193 = f193; + } + + public Integer getF194() { + return f194; + } + + public void setF194(Integer f194) { + this.f194 = f194; + } + + public Integer getF195() { + return f195; + } + + public void setF195(Integer f195) { + this.f195 = f195; + } + + public Integer getF196() { + return f196; + } + + public void setF196(Integer f196) { + this.f196 = f196; + } + + public Integer getF197() { + return f197; + } + + public void setF197(Integer f197) { + this.f197 = f197; + } + + public Integer getF198() { + return f198; + } + + public void setF198(Integer f198) { + this.f198 = f198; + } + + public Integer getF199() { + return f199; + } + + public void setF199(Integer f199) { + this.f199 = f199; + } + + + public Integer getF200() { + return f200; + } + + + public void setF200(Integer f200) { + this.f200 = f200; + } + + + public Integer getF201() { + return f201; + } + + + public void setF201(Integer f201) { + this.f201 = f201; + } + + + public Integer getF202() { + return f202; + } + + + public void setF202(Integer f202) { + this.f202 = f202; + } + + + public Integer getF203() { + return f203; + } + + + public void setF203(Integer f203) { + this.f203 = f203; + } + + + public Integer getF204() { + return f204; + } + + + public void setF204(Integer f204) { + this.f204 = f204; + } + + + public Integer getF205() { + return f205; + } + + + public void setF205(Integer f205) { + this.f205 = f205; + } + + + public Integer getF206() { + return f206; + } + + + public void setF206(Integer f206) { + this.f206 = f206; + } + + + public Integer getF207() { + return f207; + } + + + public void setF207(Integer f207) { + this.f207 = f207; + } + + + public Integer getF208() { + return f208; + } + + + public void setF208(Integer f208) { + this.f208 = f208; + } + + + public Integer getF209() { + return f209; + } + + + public void setF209(Integer f209) { + this.f209 = f209; + } + + + public Integer getF210() { + return f210; + } + + + public void setF210(Integer f210) { + this.f210 = f210; + } + + + public Integer getF211() { + return f211; + } + + + public void setF211(Integer f211) { + this.f211 = f211; + } + + + public Integer getF212() { + return f212; + } + + + public void setF212(Integer f212) { + this.f212 = f212; + } + + + public Integer getF213() { + return f213; + } + + + public void setF213(Integer f213) { + this.f213 = f213; + } + + + public Integer getF214() { + return f214; + } + + + public void setF214(Integer f214) { + this.f214 = f214; + } + + + public Integer getF215() { + return f215; + } + + + public void setF215(Integer f215) { + this.f215 = f215; + } + + + public Integer getF216() { + return f216; + } + + + public void setF216(Integer f216) { + this.f216 = f216; + } + + + public Integer getF217() { + return f217; + } + + + public void setF217(Integer f217) { + this.f217 = f217; + } + + + public Integer getF218() { + return f218; + } + + + public void setF218(Integer f218) { + this.f218 = f218; + } + + + public Integer getF219() { + return f219; + } + + + public void setF219(Integer f219) { + this.f219 = f219; + } + + + public Integer getF220() { + return f220; + } + + + public void setF220(Integer f220) { + this.f220 = f220; + } + + + public Integer getF221() { + return f221; + } + + + public void setF221(Integer f221) { + this.f221 = f221; + } + + + public Integer getF222() { + return f222; + } + + + public void setF222(Integer f222) { + this.f222 = f222; + } + + + public Integer getF223() { + return f223; + } + + + public void setF223(Integer f223) { + this.f223 = f223; + } + + + public Integer getF224() { + return f224; + } + + + public void setF224(Integer f224) { + this.f224 = f224; + } + + + public Integer getF225() { + return f225; + } + + + public void setF225(Integer f225) { + this.f225 = f225; + } + + + public Integer getF226() { + return f226; + } + + + public void setF226(Integer f226) { + this.f226 = f226; + } + + + public Integer getF227() { + return f227; + } + + + public void setF227(Integer f227) { + this.f227 = f227; + } + + + public Integer getF228() { + return f228; + } + + + public void setF228(Integer f228) { + this.f228 = f228; + } + + + public Integer getF229() { + return f229; + } + + + public void setF229(Integer f229) { + this.f229 = f229; + } + + + public Integer getF230() { + return f230; + } + + + public void setF230(Integer f230) { + this.f230 = f230; + } + + + public Integer getF231() { + return f231; + } + + + public void setF231(Integer f231) { + this.f231 = f231; + } + + + public Integer getF232() { + return f232; + } + + + public void setF232(Integer f232) { + this.f232 = f232; + } + + + public Integer getF233() { + return f233; + } + + + public void setF233(Integer f233) { + this.f233 = f233; + } + + + public Integer getF234() { + return f234; + } + + + public void setF234(Integer f234) { + this.f234 = f234; + } + + + public Integer getF235() { + return f235; + } + + + public void setF235(Integer f235) { + this.f235 = f235; + } + + + public Integer getF236() { + return f236; + } + + + public void setF236(Integer f236) { + this.f236 = f236; + } + + + public Integer getF237() { + return f237; + } + + + public void setF237(Integer f237) { + this.f237 = f237; + } + + + public Integer getF238() { + return f238; + } + + + public void setF238(Integer f238) { + this.f238 = f238; + } + + + public Integer getF239() { + return f239; + } + + + public void setF239(Integer f239) { + this.f239 = f239; + } + + + public Integer getF240() { + return f240; + } + + + public void setF240(Integer f240) { + this.f240 = f240; + } + + + public Integer getF241() { + return f241; + } + + + public void setF241(Integer f241) { + this.f241 = f241; + } + + + public Integer getF242() { + return f242; + } + + + public void setF242(Integer f242) { + this.f242 = f242; + } + + + public Integer getF243() { + return f243; + } + + + public void setF243(Integer f243) { + this.f243 = f243; + } + + + public Integer getF244() { + return f244; + } + + + public void setF244(Integer f244) { + this.f244 = f244; + } + + + public Integer getF245() { + return f245; + } + + + public void setF245(Integer f245) { + this.f245 = f245; + } + + + public Integer getF246() { + return f246; + } + + + public void setF246(Integer f246) { + this.f246 = f246; + } + + + public Integer getF247() { + return f247; + } + + + public void setF247(Integer f247) { + this.f247 = f247; + } + + + public Integer getF248() { + return f248; + } + + + public void setF248(Integer f248) { + this.f248 = f248; + } + + + public Integer getF249() { + return f249; + } + + + public void setF249(Integer f249) { + this.f249 = f249; + } + + + public Integer getF250() { + return f250; + } + + + public void setF250(Integer f250) { + this.f250 = f250; + } + + + public Integer getF251() { + return f251; + } + + + public void setF251(Integer f251) { + this.f251 = f251; + } + + + public Integer getF252() { + return f252; + } + + + public void setF252(Integer f252) { + this.f252 = f252; + } + + + public Integer getF253() { + return f253; + } + + + public void setF253(Integer f253) { + this.f253 = f253; + } + + + public Integer getF254() { + return f254; + } + + + public void setF254(Integer f254) { + this.f254 = f254; + } + + + public Integer getF255() { + return f255; + } + + + public void setF255(Integer f255) { + this.f255 = f255; + } + + + public Integer getF256() { + return f256; + } + + + public void setF256(Integer f256) { + this.f256 = f256; + } + + + public Integer getF257() { + return f257; + } + + + public void setF257(Integer f257) { + this.f257 = f257; + } + + + public Integer getF258() { + return f258; + } + + + public void setF258(Integer f258) { + this.f258 = f258; + } + + + public Integer getF259() { + return f259; + } + + + public void setF259(Integer f259) { + this.f259 = f259; + } + + + public Integer getF260() { + return f260; + } + + + public void setF260(Integer f260) { + this.f260 = f260; + } + + + public Integer getF261() { + return f261; + } + + + public void setF261(Integer f261) { + this.f261 = f261; + } + + + public Integer getF262() { + return f262; + } + + + public void setF262(Integer f262) { + this.f262 = f262; + } + + + public Integer getF263() { + return f263; + } + + + public void setF263(Integer f263) { + this.f263 = f263; + } + + + public Integer getF264() { + return f264; + } + + + public void setF264(Integer f264) { + this.f264 = f264; + } + + + public Integer getF265() { + return f265; + } + + + public void setF265(Integer f265) { + this.f265 = f265; + } + + + public Integer getF266() { + return f266; + } + + + public void setF266(Integer f266) { + this.f266 = f266; + } + + + public Integer getF267() { + return f267; + } + + + public void setF267(Integer f267) { + this.f267 = f267; + } + + + public Integer getF268() { + return f268; + } + + + public void setF268(Integer f268) { + this.f268 = f268; + } + + + public Integer getF269() { + return f269; + } + + + public void setF269(Integer f269) { + this.f269 = f269; + } + + + public Integer getF270() { + return f270; + } + + + public void setF270(Integer f270) { + this.f270 = f270; + } + + + public Integer getF271() { + return f271; + } + + + public void setF271(Integer f271) { + this.f271 = f271; + } + + + public Integer getF272() { + return f272; + } + + + public void setF272(Integer f272) { + this.f272 = f272; + } + + + public Integer getF273() { + return f273; + } + + + public void setF273(Integer f273) { + this.f273 = f273; + } + + + public Integer getF274() { + return f274; + } + + + public void setF274(Integer f274) { + this.f274 = f274; + } + + + public Integer getF275() { + return f275; + } + + + public void setF275(Integer f275) { + this.f275 = f275; + } + + + public Integer getF276() { + return f276; + } + + + public void setF276(Integer f276) { + this.f276 = f276; + } + + + public Integer getF277() { + return f277; + } + + + public void setF277(Integer f277) { + this.f277 = f277; + } + + + public Integer getF278() { + return f278; + } + + + public void setF278(Integer f278) { + this.f278 = f278; + } + + + public Integer getF279() { + return f279; + } + + + public void setF279(Integer f279) { + this.f279 = f279; + } + + + public Integer getF280() { + return f280; + } + + + public void setF280(Integer f280) { + this.f280 = f280; + } + + + public Integer getF281() { + return f281; + } + + + public void setF281(Integer f281) { + this.f281 = f281; + } + + + public Integer getF282() { + return f282; + } + + + public void setF282(Integer f282) { + this.f282 = f282; + } + + + public Integer getF283() { + return f283; + } + + + public void setF283(Integer f283) { + this.f283 = f283; + } + + + public Integer getF284() { + return f284; + } + + + public void setF284(Integer f284) { + this.f284 = f284; + } + + + public Integer getF285() { + return f285; + } + + + public void setF285(Integer f285) { + this.f285 = f285; + } + + + public Integer getF286() { + return f286; + } + + + public void setF286(Integer f286) { + this.f286 = f286; + } + + + public Integer getF287() { + return f287; + } + + + public void setF287(Integer f287) { + this.f287 = f287; + } + + + public Integer getF288() { + return f288; + } + + + public void setF288(Integer f288) { + this.f288 = f288; + } + + + public Integer getF289() { + return f289; + } + + + public void setF289(Integer f289) { + this.f289 = f289; + } + + + public Integer getF290() { + return f290; + } + + + public void setF290(Integer f290) { + this.f290 = f290; + } + + + public Integer getF291() { + return f291; + } + + + public void setF291(Integer f291) { + this.f291 = f291; + } + + + public Integer getF292() { + return f292; + } + + + public void setF292(Integer f292) { + this.f292 = f292; + } + + + public Integer getF293() { + return f293; + } + + + public void setF293(Integer f293) { + this.f293 = f293; + } + + + public Integer getF294() { + return f294; + } + + + public void setF294(Integer f294) { + this.f294 = f294; + } + + + public Integer getF295() { + return f295; + } + + + public void setF295(Integer f295) { + this.f295 = f295; + } + + + public Integer getF296() { + return f296; + } + + + public void setF296(Integer f296) { + this.f296 = f296; + } + + + public Integer getF297() { + return f297; + } + + + public void setF297(Integer f297) { + this.f297 = f297; + } + + + public Integer getF298() { + return f298; + } + + + public void setF298(Integer f298) { + this.f298 = f298; + } + + + public Integer getF299() { + return f299; + } + + + public void setF299(Integer f299) { + this.f299 = f299; + } + + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/asm/JSONASMUtilTest.java b/src/test/java/com/alibaba/json/bvt/asm/JSONASMUtilTest.java new file mode 100755 index 0000000000..a0cfdce868 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/asm/JSONASMUtilTest.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.asm; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.util.ASMUtils; + +public class JSONASMUtilTest extends TestCase { + + public void test_1() throws Exception { + Assert.assertEquals("V", ASMUtils.desc(Void.TYPE)); + Assert.assertEquals("J", ASMUtils.desc(Long.TYPE)); + Assert.assertEquals("[J", ASMUtils.desc(long[].class)); + Assert.assertEquals("[Ljava/lang/Long;", ASMUtils.desc(Long[].class)); + } + + public void test_error_1() throws Exception { + new ASMUtils(); + + Exception error = null; + try { + ASMUtils.getPrimitiveLetter(Long.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/asm/LoopTest.java b/src/test/java/com/alibaba/json/bvt/asm/LoopTest.java old mode 100644 new mode 100755 similarity index 96% rename from src/test/java/com/alibaba/json/test/bvt/asm/LoopTest.java rename to src/test/java/com/alibaba/json/bvt/asm/LoopTest.java index 286534d86c..7f8f4cad45 --- a/src/test/java/com/alibaba/json/test/bvt/asm/LoopTest.java +++ b/src/test/java/com/alibaba/json/bvt/asm/LoopTest.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt.asm; +package com.alibaba.json.bvt.asm; import java.util.ArrayList; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/asm/SortFieldTest.java b/src/test/java/com/alibaba/json/bvt/asm/SortFieldTest.java old mode 100644 new mode 100755 similarity index 96% rename from src/test/java/com/alibaba/json/test/bvt/asm/SortFieldTest.java rename to src/test/java/com/alibaba/json/bvt/asm/SortFieldTest.java index e2ad9086a9..afed089283 --- a/src/test/java/com/alibaba/json/test/bvt/asm/SortFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/asm/SortFieldTest.java @@ -1,8 +1,10 @@ -package com.alibaba.json.test.bvt.asm; +package com.alibaba.json.bvt.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; +import java.util.LinkedHashMap; + import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; @@ -16,7 +18,7 @@ public void test_0() throws Exception { Assert.assertEquals("{'f0':0,'f1':0,'f10':0,'f11':0,'f12':0,'f13':0,'f14':0,'f2':0,'f3':0,'f4':0,'f5':0,'f6':0,'f7':0,'f8':0,'f9':0}", text); - JSONObject object = JSON.parseObject(text); + LinkedHashMap object = JSON.parseObject(text, LinkedHashMap.class); text = JSON.toJSONString(object, SerializerFeature.UseSingleQuotes, SerializerFeature.SortField); Assert.assertEquals("{'f0':0,'f1':0,'f10':0,'f11':0,'f12':0,'f13':0,'f14':0,'f2':0,'f3':0,'f4':0,'f5':0,'f6':0,'f7':0,'f8':0,'f9':0}", text); diff --git a/src/test/java/com/alibaba/json/test/bvt/asm/TestList.java b/src/test/java/com/alibaba/json/bvt/asm/TestList.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/asm/TestList.java rename to src/test/java/com/alibaba/json/bvt/asm/TestList.java index 29fd5d3c06..3bb094b136 --- a/src/test/java/com/alibaba/json/test/bvt/asm/TestList.java +++ b/src/test/java/com/alibaba/json/bvt/asm/TestList.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.asm; +package com.alibaba.json.bvt.asm; import java.util.ArrayList; import java.util.Arrays; @@ -6,7 +6,7 @@ import java.util.List; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/asm/TestNonASM.java b/src/test/java/com/alibaba/json/bvt/asm/TestNonASM.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/asm/TestNonASM.java rename to src/test/java/com/alibaba/json/bvt/asm/TestNonASM.java index bc09823979..395f1ca595 --- a/src/test/java/com/alibaba/json/test/bvt/asm/TestNonASM.java +++ b/src/test/java/com/alibaba/json/bvt/asm/TestNonASM.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.asm; +package com.alibaba.json.bvt.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.ParserConfig; diff --git a/src/test/java/com/alibaba/json/bvt/asm/TestType.java b/src/test/java/com/alibaba/json/bvt/asm/TestType.java new file mode 100755 index 0000000000..66b04c5973 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/asm/TestType.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.asm; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.asm.Type; +import com.alibaba.fastjson.util.ASMUtils; + +public class TestType extends TestCase { + + public void test_getType() throws Exception { + Assert.assertEquals(Type.VOID_TYPE, Type.getType(ASMUtils.desc(void.class))); + + Assert.assertEquals(Type.BOOLEAN_TYPE, Type.getType(ASMUtils.desc(boolean.class))); + + Assert.assertEquals(Type.CHAR_TYPE, Type.getType(ASMUtils.desc(char.class))); + + Assert.assertEquals(Type.BYTE_TYPE, Type.getType(ASMUtils.desc(byte.class))); + + Assert.assertEquals(Type.SHORT_TYPE, Type.getType(ASMUtils.desc(short.class))); + + Assert.assertEquals(Type.INT_TYPE, Type.getType(ASMUtils.desc(int.class))); + + Assert.assertEquals(Type.LONG_TYPE, Type.getType(ASMUtils.desc(long.class))); + + Assert.assertEquals(Type.FLOAT_TYPE, Type.getType(ASMUtils.desc(float.class))); + + Assert.assertEquals(Type.DOUBLE_TYPE, Type.getType(ASMUtils.desc(double.class))); + + Assert.assertEquals("[D", Type.getType(ASMUtils.desc(double[].class)).getInternalName()); + Assert.assertEquals("[[D", Type.getType(ASMUtils.desc(double[][].class)).getInternalName()); + Assert.assertEquals("[Ljava/lang/Double;", Type.getType(ASMUtils.desc(Double[].class)).getInternalName()); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/atomic/AtomicBooleanReadOnlyTest.java b/src/test/java/com/alibaba/json/bvt/atomic/AtomicBooleanReadOnlyTest.java new file mode 100644 index 0000000000..75e56ab277 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/atomic/AtomicBooleanReadOnlyTest.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.atomic; + +import java.util.concurrent.atomic.AtomicBoolean; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class AtomicBooleanReadOnlyTest extends TestCase { + + public void test_codec_null() throws Exception { + V0 v = new V0(true); + + String text = JSON.toJSONString(v); + Assert.assertEquals("{\"value\":true}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue().get(), v.getValue().get()); + } + + public static class V0 { + + private final AtomicBoolean value; + + public V0(){ + this(false); + } + + public V0(boolean value){ + this.value = new AtomicBoolean(value); + } + + public AtomicBoolean getValue() { + return value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/AtomicIntegerArrayFieldTest.java b/src/test/java/com/alibaba/json/bvt/atomic/AtomicIntegerArrayFieldTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/AtomicIntegerArrayFieldTest.java rename to src/test/java/com/alibaba/json/bvt/atomic/AtomicIntegerArrayFieldTest.java index d284a9c988..8bb8113e19 --- a/src/test/java/com/alibaba/json/test/bvt/AtomicIntegerArrayFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/atomic/AtomicIntegerArrayFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt.atomic; import java.util.concurrent.atomic.AtomicIntegerArray; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/atomic/AtomicIntegerReadOnlyTest.java b/src/test/java/com/alibaba/json/bvt/atomic/AtomicIntegerReadOnlyTest.java new file mode 100644 index 0000000000..8d7c3ad9af --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/atomic/AtomicIntegerReadOnlyTest.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.atomic; + +import java.util.concurrent.atomic.AtomicInteger; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class AtomicIntegerReadOnlyTest extends TestCase { + + public void test_codec_null() throws Exception { + V0 v = new V0(123); + + String text = JSON.toJSONString(v); + Assert.assertEquals("{\"value\":123}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue().intValue(), v.getValue().intValue()); + } + + public static class V0 { + + private final AtomicInteger value; + + public V0(){ + this(0); + } + + public V0(int value){ + this.value = new AtomicInteger(value); + } + + public AtomicInteger getValue() { + return value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/AtomicLongArrayFieldTest.java b/src/test/java/com/alibaba/json/bvt/atomic/AtomicLongArrayFieldTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/AtomicLongArrayFieldTest.java rename to src/test/java/com/alibaba/json/bvt/atomic/AtomicLongArrayFieldTest.java index 2e67259da4..6ad5461258 --- a/src/test/java/com/alibaba/json/test/bvt/AtomicLongArrayFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/atomic/AtomicLongArrayFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt.atomic; import java.util.concurrent.atomic.AtomicLongArray; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/atomic/AtomicLongReadOnlyTest.java b/src/test/java/com/alibaba/json/bvt/atomic/AtomicLongReadOnlyTest.java new file mode 100644 index 0000000000..5448f27c49 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/atomic/AtomicLongReadOnlyTest.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.atomic; + +import java.util.concurrent.atomic.AtomicLong; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class AtomicLongReadOnlyTest extends TestCase { + + public void test_codec_null() throws Exception { + V0 v = new V0(123); + + String text = JSON.toJSONString(v); + Assert.assertEquals("{\"value\":123}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue().intValue(), v.getValue().intValue()); + } + + public static class V0 { + + private final AtomicLong value; + + public V0(){ + this(0); + } + + public V0(int value){ + this.value = new AtomicLong(value); + } + + public AtomicLong getValue() { + return value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/awt/ColorTest.java b/src/test/java/com/alibaba/json/bvt/awt/ColorTest.java new file mode 100755 index 0000000000..69ca84b78e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/awt/ColorTest.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.awt; + +import java.awt.Color; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.AwtCodec; +import com.alibaba.fastjson.serializer.JSONSerializer; + +import junit.framework.TestCase; + + +public class ColorTest extends TestCase { + public void test_color() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Color.class).getClass()); + + Color color = Color.RED; + String text = JSON.toJSONString(color); + System.out.println(text); + + Color color2 = JSON.parseObject(text, Color.class); + + Assert.assertEquals(color, color2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/awt/ColorTest2.java b/src/test/java/com/alibaba/json/bvt/awt/ColorTest2.java new file mode 100755 index 0000000000..527178c7cf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/awt/ColorTest2.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.awt; + +import java.awt.Color; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.AwtCodec; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + + +public class ColorTest2 extends TestCase { + public void test_color() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Color.class).getClass()); + + Color color = Color.RED; + String text = JSON.toJSONString(color, SerializerFeature.WriteClassName); + System.out.println(text); + + Color color2 = (Color) JSON.parse(text); + + Assert.assertEquals(color, color2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/awt/FontTest.java b/src/test/java/com/alibaba/json/bvt/awt/FontTest.java new file mode 100755 index 0000000000..12edc9cbf7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/awt/FontTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.awt; + +import java.awt.Font; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class FontTest extends TestCase { + + public void test_color() throws Exception { + Font[] fonts = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); + for (Font font : fonts) { + String text = JSON.toJSONString(font); + + Font font2 = JSON.parseObject(text, Font.class); + + Assert.assertEquals(font, font2); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/awt/FontTest2.java b/src/test/java/com/alibaba/json/bvt/awt/FontTest2.java new file mode 100755 index 0000000000..8dba52b2c4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/awt/FontTest2.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.awt; + +import java.awt.Font; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class FontTest2 extends TestCase { + + public void test_color() throws Exception { + Font[] fonts = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); + for (Font font : fonts) { + String text = JSON.toJSONString(font, SerializerFeature.WriteClassName); + + Font font2 = (Font) JSON.parse(text); + + Assert.assertEquals(font, font2); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/DoubleNullTest.java b/src/test/java/com/alibaba/json/bvt/basicType/DoubleNullTest.java new file mode 100644 index 0000000000..ca05186996 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/DoubleNullTest.java @@ -0,0 +1,61 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +import java.io.StringReader; + +/** + * Created by wenshao on 10/08/2017. + */ +public class DoubleNullTest extends TestCase { + public void test_null() throws Exception { + Model model = JSON.parseObject("{\"v1\":null,\"v2\":null}", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_quote() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\",\"v2\":\"null\"}", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_1() throws Exception { + Model model = JSON.parseObject("{\"v1\":null ,\"v2\":null }", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_1_quote() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\" ,\"v2\":\"null\" }", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_array() throws Exception { + Model model = JSON.parseObject("[\"null\" ,\"null\"]", Model.class, Feature.SupportArrayToBean); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_array_reader() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[\"null\" ,\"null\"]"), Feature.SupportArrayToBean); + Model model = reader.readObject(Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public static class Model { + public Double v1; + public Double v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/DoubleNullTest_primitive.java b/src/test/java/com/alibaba/json/bvt/basicType/DoubleNullTest_primitive.java new file mode 100644 index 0000000000..963bf8a43c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/DoubleNullTest_primitive.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 10/08/2017. + */ +public class DoubleNullTest_primitive extends TestCase { + public void test_null() throws Exception { + Model model = JSON.parseObject("{\"v1\":null,\"v2\":null}", Model.class); + assertNotNull(model); + assertEquals(0D, model.v1); + assertEquals(0D,model.v2); + } + + public void test_null_1() throws Exception { + Model model = JSON.parseObject("{\"v1\":null ,\"v2\":null }", Model.class); + assertNotNull(model); + assertEquals(0D,model.v1); + assertEquals(0D,model.v2); + } + + public void test_null_2() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\",\"v2\":\"null\" }", Model.class); + assertNotNull(model); + assertEquals(0D,model.v1); + assertEquals(0D,model.v2); + } + + public static class Model { + public double v1; + public double v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/DoubleTest.java b/src/test/java/com/alibaba/json/bvt/basicType/DoubleTest.java new file mode 100644 index 0000000000..88fbeb3ce8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/DoubleTest.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 04/08/2017. + */ +public class DoubleTest extends TestCase { + public void test_obj() throws Exception { + String json = "{\"v1\":-0.012671709,\"v2\":0.22676692048907365,\"v3\":0.13231707,\"v4\":0.80090785,\"v5\":0.6192943}"; + String json2 = "{\"v1\":\"-0.012671709\",\"v2\":\"0.22676692048907365\",\"v3\":\"0.13231707\",\"v4\":\"0.80090785\",\"v5\":\"0.6192943\"}"; + + Model m1 = JSON.parseObject(json, Model.class); + Model m2 = JSON.parseObject(json2, Model.class); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-0.012671709D, m1.v1); + assertEquals(0.22676692048907365D, m1.v2); + assertEquals(0.13231707D, m1.v3); + assertEquals(0.80090785D, m1.v4); + assertEquals(0.6192943D, m1.v5); + + assertEquals(-0.012671709D, m2.v1); + assertEquals(0.22676692048907365D, m2.v2); + assertEquals(0.13231707D, m2.v3); + assertEquals(0.80090785D, m2.v4); + assertEquals(0.6192943D, m2.v5); + } + + public void test_array_mapping() throws Exception { + String json = "[-0.012671709,0.22676692048907365,0.13231707,0.80090785,0.6192943]"; + String json2 = "[\"-0.012671709\",\"0.22676692048907365\",\"0.13231707\",\"0.80090785\",\"0.6192943\"]"; + + Model m1 = JSON.parseObject(json, Model.class, Feature.SupportArrayToBean); + Model m2 = JSON.parseObject(json2, Model.class, Feature.SupportArrayToBean); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-0.012671709D, m1.v1); + assertEquals(0.22676692048907365D, m1.v2); + assertEquals(0.13231707D, m1.v3); + assertEquals(0.80090785D, m1.v4); + assertEquals(0.6192943D, m1.v5); + + assertEquals(-0.012671709D, m2.v1); + assertEquals(0.22676692048907365D, m2.v2); + assertEquals(0.13231707D, m2.v3); + assertEquals(0.80090785D, m2.v4); + assertEquals(0.6192943D, m2.v5); + } + + public static class Model { + public double v1; + public double v2; + public double v3; + public double v4; + public double v5; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/DoubleTest2_obj.java b/src/test/java/com/alibaba/json/bvt/basicType/DoubleTest2_obj.java new file mode 100644 index 0000000000..bc5a6fe41a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/DoubleTest2_obj.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 04/08/2017. + */ +public class DoubleTest2_obj extends TestCase { + public void test_obj() throws Exception { + String json = "{\"v1\":-0.012671709,\"v2\":0.22676692048907365,\"v3\":0.13231707,\"v4\":0.80090785,\"v5\":0.6192943}"; + String json2 = "{\"v1\":\"-0.012671709\",\"v2\":\"0.22676692048907365\",\"v3\":\"0.13231707\",\"v4\":\"0.80090785\",\"v5\":\"0.6192943\"}"; + + Model m1 = JSON.parseObject(json, Model.class); + Model m2 = JSON.parseObject(json2, Model.class); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-0.012671709D, m1.v1); + assertEquals(0.22676692048907365D, m1.v2); + assertEquals(0.13231707D, m1.v3); + assertEquals(0.80090785D, m1.v4); + assertEquals(0.6192943D, m1.v5); + + assertEquals(-0.012671709D, m2.v1); + assertEquals(0.22676692048907365D, m2.v2); + assertEquals(0.13231707D, m2.v3); + assertEquals(0.80090785D, m2.v4); + assertEquals(0.6192943D, m2.v5); + } + + public void test_array_mapping() throws Exception { + String json = "[-0.012671709,0.22676692048907365,0.13231707,0.80090785,0.6192943]"; + String json2 = "[\"-0.012671709\",\"0.22676692048907365\",\"0.13231707\",\"0.80090785\",\"0.6192943\"]"; + + Model m1 = JSON.parseObject(json, Model.class, Feature.SupportArrayToBean); + Model m2 = JSON.parseObject(json2, Model.class, Feature.SupportArrayToBean); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-0.012671709D, m1.v1); + assertEquals(0.22676692048907365D, m1.v2); + assertEquals(0.13231707D, m1.v3); + assertEquals(0.80090785D, m1.v4); + assertEquals(0.6192943D, m1.v5); + + assertEquals(-0.012671709D, m2.v1); + assertEquals(0.22676692048907365D, m2.v2); + assertEquals(0.13231707D, m2.v3); + assertEquals(0.80090785D, m2.v4); + assertEquals(0.6192943D, m2.v5); + } + + public static class Model { + public Double v1; + public Double v2; + public Double v3; + public Double v4; + public Double v5; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/FloatNullTest.java b/src/test/java/com/alibaba/json/bvt/basicType/FloatNullTest.java new file mode 100644 index 0000000000..4d4ebe3224 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/FloatNullTest.java @@ -0,0 +1,61 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +import java.io.StringReader; + +/** + * Created by wenshao on 10/08/2017. + */ +public class FloatNullTest extends TestCase { + public void test_null() throws Exception { + Model model = JSON.parseObject("{\"v1\":null,\"v2\":null}", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_quote() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\",\"v2\":\"null\"}", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_1() throws Exception { + Model model = JSON.parseObject("{\"v1\":null ,\"v2\":null }", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_1_quote() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\" ,\"v2\":\"null\" }", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_array() throws Exception { + Model model = JSON.parseObject("[\"null\" ,\"null\"]", Model.class, Feature.SupportArrayToBean); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_array_reader() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[\"null\" ,\"null\"]"), Feature.SupportArrayToBean); + Model model = reader.readObject(Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public static class Model { + public Float v1; + public Float v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/FloatNullTest_primitive.java b/src/test/java/com/alibaba/json/bvt/basicType/FloatNullTest_primitive.java new file mode 100644 index 0000000000..443221f09d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/FloatNullTest_primitive.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 10/08/2017. + */ +public class FloatNullTest_primitive extends TestCase { + public void test_null() throws Exception { + Model model = JSON.parseObject("{\"v1\":null,\"v2\":null}", Model.class); + assertNotNull(model); + assertEquals(0F, model.v1); + assertEquals(0F,model.v2); + } + + public void test_null_1() throws Exception { + Model model = JSON.parseObject("{\"v1\":null ,\"v2\":null }", Model.class); + assertNotNull(model); + assertEquals(0F,model.v1); + assertEquals(0F,model.v2); + } + + public void test_null_2() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\",\"v2\":\"null\" }", Model.class); + assertNotNull(model); + assertEquals(0F,model.v1); + assertEquals(0F,model.v2); + } + + public static class Model { + public float v1; + public float v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/FloatTest.java b/src/test/java/com/alibaba/json/bvt/basicType/FloatTest.java new file mode 100644 index 0000000000..15c713ee4f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/FloatTest.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 04/08/2017. + */ +public class FloatTest extends TestCase { + public void test_0() throws Exception { + String json = "{\"v1\":-0.012671709,\"v2\":0.6042485,\"v3\":0.13231707,\"v4\":0.80090785,\"v5\":0.6192943}"; + String json2 = "{\"v1\":\"-0.012671709\",\"v2\":\"0.6042485\",\"v3\":\"0.13231707\",\"v4\":\"0.80090785\",\"v5\":\"0.6192943\"}"; + + Model m1 = JSON.parseObject(json, Model.class); + Model m2 = JSON.parseObject(json2, Model.class); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-0.012671709f, m1.v1); + assertEquals(0.6042485f, m1.v2); + assertEquals(0.13231707f, m1.v3); + assertEquals(0.80090785f, m1.v4); + assertEquals(0.6192943f, m1.v5); + + assertEquals(-0.012671709f, m2.v1); + assertEquals(0.6042485f, m2.v2); + assertEquals(0.13231707f, m2.v3); + assertEquals(0.80090785f, m2.v4); + assertEquals(0.6192943f, m2.v5); + } + + public void test_array_mapping() throws Exception { + String json = "[-0.012671709,0.6042485,0.13231707,0.80090785,0.6192943]"; + String json2 = "[\"-0.012671709\",\"0.6042485\",\"0.13231707\",\"0.80090785\",\"0.6192943\"]"; + + Model m1 = JSON.parseObject(json, Model.class, Feature.SupportArrayToBean); + Model m2 = JSON.parseObject(json2, Model.class, Feature.SupportArrayToBean); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-0.012671709f, m1.v1); + assertEquals(0.6042485f, m1.v2); + assertEquals(0.13231707f, m1.v3); + assertEquals(0.80090785f, m1.v4); + assertEquals(0.6192943f, m1.v5); + + assertEquals(-0.012671709f, m2.v1); + assertEquals(0.6042485f, m2.v2); + assertEquals(0.13231707f, m2.v3); + assertEquals(0.80090785f, m2.v4); + assertEquals(0.6192943f, m2.v5); + } + + public static class Model { + public float v1; + public float v2; + public float v3; + public float v4; + public float v5; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/FloatTest2_obj.java b/src/test/java/com/alibaba/json/bvt/basicType/FloatTest2_obj.java new file mode 100644 index 0000000000..04849762a6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/FloatTest2_obj.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 04/08/2017. + */ +public class FloatTest2_obj extends TestCase { + public void test_0() throws Exception { + String json = "{\"v1\":-0.012671709,\"v2\":0.6042485,\"v3\":0.13231707,\"v4\":0.80090785,\"v5\":0.6192943}"; + String json2 = "{\"v1\":\"-0.012671709\",\"v2\":\"0.6042485\",\"v3\":\"0.13231707\",\"v4\":\"0.80090785\",\"v5\":\"0.6192943\"}"; + + Model m1 = JSON.parseObject(json, Model.class); + Model m2 = JSON.parseObject(json2, Model.class); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-0.012671709f, m1.v1); + assertEquals(0.6042485f, m1.v2); + assertEquals(0.13231707f, m1.v3); + assertEquals(0.80090785f, m1.v4); + assertEquals(0.6192943f, m1.v5); + + assertEquals(-0.012671709f, m2.v1); + assertEquals(0.6042485f, m2.v2); + assertEquals(0.13231707f, m2.v3); + assertEquals(0.80090785f, m2.v4); + assertEquals(0.6192943f, m2.v5); + } + + public void test_array_mapping() throws Exception { + String json = "[-0.012671709,0.6042485,0.13231707,0.80090785,0.6192943]"; + String json2 = "[\"-0.012671709\",\"0.6042485\",\"0.13231707\",\"0.80090785\",\"0.6192943\"]"; + + Model m1 = JSON.parseObject(json, Model.class, Feature.SupportArrayToBean); + Model m2 = JSON.parseObject(json2, Model.class, Feature.SupportArrayToBean); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-0.012671709f, m1.v1); + assertEquals(0.6042485f, m1.v2); + assertEquals(0.13231707f, m1.v3); + assertEquals(0.80090785f, m1.v4); + assertEquals(0.6192943f, m1.v5); + + assertEquals(-0.012671709f, m2.v1); + assertEquals(0.6042485f, m2.v2); + assertEquals(0.13231707f, m2.v3); + assertEquals(0.80090785f, m2.v4); + assertEquals(0.6192943f, m2.v5); + } + + public static class Model { + public Float v1; + public Float v2; + public Float v3; + public Float v4; + public Float v5; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/IntNullTest_primitive.java b/src/test/java/com/alibaba/json/bvt/basicType/IntNullTest_primitive.java new file mode 100644 index 0000000000..da6670b021 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/IntNullTest_primitive.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 10/08/2017. + */ +public class IntNullTest_primitive extends TestCase { + public void test_null() throws Exception { + Model model = JSON.parseObject("{\"v1\":null,\"v2\":null}", Model.class); + assertNotNull(model); + assertEquals(0, model.v1); + assertEquals(0,model.v2); + } + + public void test_null_1() throws Exception { + Model model = JSON.parseObject("{\"v1\":null ,\"v2\":null }", Model.class); + assertNotNull(model); + assertEquals(0,model.v1); + assertEquals(0,model.v2); + } + + public void test_null_2() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\",\"v2\":\"null\" }", Model.class); + assertNotNull(model); + assertEquals(0,model.v1); + assertEquals(0,model.v2); + } + + public static class Model { + public int v1; + public int v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/IntTest.java b/src/test/java/com/alibaba/json/bvt/basicType/IntTest.java new file mode 100644 index 0000000000..fbf6fc0a2c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/IntTest.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.basicType; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class IntTest extends TestCase { + public void test_array() throws Exception { + int[] values = new int[] {Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE}; + String text = JSON.toJSONString(values); + long[] values_2 = JSON.parseObject(text, long[].class); + assertEquals(values_2.length, values.length); + for (int i = 0; i < values.length; ++i) { + assertEquals(values[i], values_2[i]); + } + } + + public void test_map() throws Exception { + int[] values = new int[] {Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE}; + Map map = new HashMap(); + for (int i = 0; i < values.length; ++i) { + map.put(Integer.toString(i), values[i]); + } + + String text = JSON.toJSONString(map); + JSONObject obj = JSON.parseObject(text); + for (int i = 0; i < values.length; ++i) { + assertEquals(values[i], ((Number) obj.get(Integer.toString(i))).intValue()); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/IntegerNullTest.java b/src/test/java/com/alibaba/json/bvt/basicType/IntegerNullTest.java new file mode 100644 index 0000000000..4c1a9ad803 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/IntegerNullTest.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +import java.io.StringReader; + +/** + * Created by wenshao on 10/08/2017. + */ +public class IntegerNullTest extends TestCase { + public void test_null() throws Exception { + Model model = JSON.parseObject("{\"v1\":null,\"v2\":null}", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_quote() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\",\"v2\":\"null\"}", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_1() throws Exception { + Model model = JSON.parseObject("{\"v1\":null ,\"v2\":null }", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_1_quote() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\" ,\"v2\":\"null\" }", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_array() throws Exception { + Model model = JSON.parseObject("[\"null\" ,\"null\"]", Model.class, Feature.SupportArrayToBean); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_array_reader() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[\"null\" ,\"null\"]"), Feature.SupportArrayToBean); + Model model = reader.readObject(Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_array_reader_1() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[null ,null]"), Feature.SupportArrayToBean); + Model model = reader.readObject(Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public static class Model { + public Integer v1; + public Integer v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/LongNullTest.java b/src/test/java/com/alibaba/json/bvt/basicType/LongNullTest.java new file mode 100644 index 0000000000..2403f6b820 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/LongNullTest.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +import java.io.StringReader; + +/** + * Created by wenshao on 10/08/2017. + */ +public class LongNullTest extends TestCase { + public void test_null() throws Exception { + Model model = JSON.parseObject("{\"v1\":null,\"v2\":null}", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_quote() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\",\"v2\":\"null\"}", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_1() throws Exception { + Model model = JSON.parseObject("{\"v1\":null ,\"v2\":null }", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_1_quote() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\" ,\"v2\":\"null\" }", Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_array() throws Exception { + Model model = JSON.parseObject("[\"null\" ,\"null\"]", Model.class, Feature.SupportArrayToBean); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_array_reader() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[\"null\" ,\"null\"]"), Feature.SupportArrayToBean); + Model model = reader.readObject(Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public void test_null_array_reader_1() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[null ,null]"), Feature.SupportArrayToBean); + Model model = reader.readObject(Model.class); + assertNotNull(model); + assertNull(model.v1); + assertNull(model.v2); + } + + public static class Model { + public Long v1; + public Long v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/LongNullTest_primitive.java b/src/test/java/com/alibaba/json/bvt/basicType/LongNullTest_primitive.java new file mode 100644 index 0000000000..9219b5cc51 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/LongNullTest_primitive.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 10/08/2017. + */ +public class LongNullTest_primitive extends TestCase { + public void test_null() throws Exception { + Model model = JSON.parseObject("{\"v1\":null,\"v2\":null}", Model.class); + assertNotNull(model); + assertEquals(0, model.v1); + assertEquals(0,model.v2); + } + + public void test_null_1() throws Exception { + Model model = JSON.parseObject("{\"v1\":null ,\"v2\":null }", Model.class); + assertNotNull(model); + assertEquals(0,model.v1); + assertEquals(0,model.v2); + } + + public void test_null_2() throws Exception { + Model model = JSON.parseObject("{\"v1\":\"null\",\"v2\":\"null\" }", Model.class); + assertNotNull(model); + assertEquals(0,model.v1); + assertEquals(0,model.v2); + } + + public static class Model { + public long v1; + public long v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/LongTest.java b/src/test/java/com/alibaba/json/bvt/basicType/LongTest.java new file mode 100644 index 0000000000..deba9f9279 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/LongTest.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.basicType; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class LongTest extends TestCase { + public void test_array() throws Exception { + long[] values = new long[] {Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE}; + String text = JSON.toJSONString(values); + long[] values_2 = JSON.parseObject(text, long[].class); + Assert.assertEquals(values_2.length, values.length); + for (int i = 0; i < values.length; ++i) { + Assert.assertEquals(values[i], values_2[i]); + } + } + + public void test_map() throws Exception { + long[] values = new long[] {Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE}; + Map map = new HashMap(); + for (int i = 0; i < values.length; ++i) { + map.put(Long.toString(i), values[i]); + } + + String text = JSON.toJSONString(map); + JSONObject obj = JSON.parseObject(text); + for (int i = 0; i < values.length; ++i) { + Assert.assertEquals(values[i], ((Number) obj.get(Long.toString(i))).longValue()); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/LongTest2.java b/src/test/java/com/alibaba/json/bvt/basicType/LongTest2.java new file mode 100644 index 0000000000..9c5d3d75f1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/LongTest2.java @@ -0,0 +1,90 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +import java.io.StringReader; + +/** + * Created by wenshao on 11/08/2017. + */ +public class LongTest2 extends TestCase { + public void test_0() throws Exception { + String json = "{\"v1\":-1883391953414482124,\"v2\":-3019416596934963650,\"v3\":6497525620823745793,\"v4\":2136224289077142499,\"v5\":-2090575024006307745}"; + String json2 = "{\"v1\":\"-1883391953414482124\",\"v2\":\"-3019416596934963650\",\"v3\":\"6497525620823745793\",\"v4\":\"2136224289077142499\",\"v5\":\"-2090575024006307745\"}"; + + Model m1 = JSON.parseObject(json, Model.class); + Model m2 = JSON.parseObject(json2, Model.class); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-1883391953414482124L, m1.v1); + assertEquals(-3019416596934963650L, m1.v2); + assertEquals(6497525620823745793L, m1.v3); + assertEquals(2136224289077142499L, m1.v4); + assertEquals(-2090575024006307745L, m1.v5); + + assertEquals(-1883391953414482124L, m2.v1); + assertEquals(-3019416596934963650L, m2.v2); + assertEquals(6497525620823745793L, m2.v3); + assertEquals(2136224289077142499L, m2.v4); + assertEquals(-2090575024006307745L, m2.v5); + } + + public void test_1() throws Exception { + String json = "{\"v1\":-1883391953414482124,\"v2\":-3019416596934963650,\"v3\":6497525620823745793,\"v4\":2136224289077142499,\"v5\":-2090575024006307745}"; + String json2 = "{\"v1\":\"-1883391953414482124\",\"v2\":\"-3019416596934963650\",\"v3\":\"6497525620823745793\",\"v4\":\"2136224289077142499\",\"v5\":\"-2090575024006307745\"}"; + + Model m1 = new JSONReader(new StringReader(json)).readObject(Model.class); + Model m2 = new JSONReader(new StringReader(json2)).readObject(Model.class); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-1883391953414482124L, m1.v1); + assertEquals(-3019416596934963650L, m1.v2); + assertEquals(6497525620823745793L, m1.v3); + assertEquals(2136224289077142499L, m1.v4); + assertEquals(-2090575024006307745L, m1.v5); + + assertEquals(-1883391953414482124L, m2.v1); + assertEquals(-3019416596934963650L, m2.v2); + assertEquals(6497525620823745793L, m2.v3); + assertEquals(2136224289077142499L, m2.v4); + assertEquals(-2090575024006307745L, m2.v5); + } + + public void test_2() throws Exception { + String json = "[-1883391953414482124,-3019416596934963650,6497525620823745793,2136224289077142499,-2090575024006307745]"; + String json2 = "[\"-1883391953414482124\",\"-3019416596934963650\",\"6497525620823745793\",\"2136224289077142499\",\"-2090575024006307745\"]"; + + Model m1 = new JSONReader(new StringReader(json), Feature.SupportArrayToBean).readObject(Model.class); + Model m2 = new JSONReader(new StringReader(json2), Feature.SupportArrayToBean).readObject(Model.class); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-1883391953414482124L, m1.v1); + assertEquals(-3019416596934963650L, m1.v2); + assertEquals(6497525620823745793L, m1.v3); + assertEquals(2136224289077142499L, m1.v4); + assertEquals(-2090575024006307745L, m1.v5); + + assertEquals(-1883391953414482124L, m2.v1); + assertEquals(-3019416596934963650L, m2.v2); + assertEquals(6497525620823745793L, m2.v3); + assertEquals(2136224289077142499L, m2.v4); + assertEquals(-2090575024006307745L, m2.v5); + } + + public static class Model { + public long v1; + public long v2; + public long v3; + public long v4; + public long v5; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/LongTest2_obj.java b/src/test/java/com/alibaba/json/bvt/basicType/LongTest2_obj.java new file mode 100644 index 0000000000..11b5063966 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/LongTest2_obj.java @@ -0,0 +1,90 @@ +package com.alibaba.json.bvt.basicType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +import java.io.StringReader; + +/** + * Created by wenshao on 11/08/2017. + */ +public class LongTest2_obj extends TestCase { + public void test_0() throws Exception { + String json = "{\"v1\":-1883391953414482124,\"v2\":-3019416596934963650,\"v3\":6497525620823745793,\"v4\":2136224289077142499,\"v5\":-2090575024006307745}"; + String json2 = "{\"v1\":\"-1883391953414482124\",\"v2\":\"-3019416596934963650\",\"v3\":\"6497525620823745793\",\"v4\":\"2136224289077142499\",\"v5\":\"-2090575024006307745\"}"; + + Model m1 = JSON.parseObject(json, Model.class); + Model m2 = JSON.parseObject(json2, Model.class); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-1883391953414482124L, m1.v1.longValue()); + assertEquals(-3019416596934963650L, m1.v2.longValue()); + assertEquals(6497525620823745793L, m1.v3.longValue()); + assertEquals(2136224289077142499L, m1.v4.longValue()); + assertEquals(-2090575024006307745L, m1.v5.longValue()); + + assertEquals(-1883391953414482124L, m2.v1.longValue()); + assertEquals(-3019416596934963650L, m2.v2.longValue()); + assertEquals(6497525620823745793L, m2.v3.longValue()); + assertEquals(2136224289077142499L, m2.v4.longValue()); + assertEquals(-2090575024006307745L, m2.v5.longValue()); + } + + public void test_1() throws Exception { + String json = "{\"v1\":-1883391953414482124,\"v2\":-3019416596934963650,\"v3\":6497525620823745793,\"v4\":2136224289077142499,\"v5\":-2090575024006307745}"; + String json2 = "{\"v1\":\"-1883391953414482124\",\"v2\":\"-3019416596934963650\",\"v3\":\"6497525620823745793\",\"v4\":\"2136224289077142499\",\"v5\":\"-2090575024006307745\"}"; + + Model m1 = new JSONReader(new StringReader(json)).readObject(Model.class); + Model m2 = new JSONReader(new StringReader(json2)).readObject(Model.class); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-1883391953414482124L, m1.v1.longValue()); + assertEquals(-3019416596934963650L, m1.v2.longValue()); + assertEquals(6497525620823745793L, m1.v3.longValue()); + assertEquals(2136224289077142499L, m1.v4.longValue()); + assertEquals(-2090575024006307745L, m1.v5.longValue()); + + assertEquals(-1883391953414482124L, m2.v1.longValue()); + assertEquals(-3019416596934963650L, m2.v2.longValue()); + assertEquals(6497525620823745793L, m2.v3.longValue()); + assertEquals(2136224289077142499L, m2.v4.longValue()); + assertEquals(-2090575024006307745L, m2.v5.longValue()); + } + + public void test_2() throws Exception { + String json = "[-1883391953414482124,-3019416596934963650,6497525620823745793,2136224289077142499,-2090575024006307745]"; + String json2 = "[\"-1883391953414482124\",\"-3019416596934963650\",\"6497525620823745793\",\"2136224289077142499\",\"-2090575024006307745\"]"; + + Model m1 = new JSONReader(new StringReader(json), Feature.SupportArrayToBean).readObject(Model.class); + Model m2 = new JSONReader(new StringReader(json2), Feature.SupportArrayToBean).readObject(Model.class); + + assertNotNull(m1); + assertNotNull(m2); + + assertEquals(-1883391953414482124L, m1.v1.longValue()); + assertEquals(-3019416596934963650L, m1.v2.longValue()); + assertEquals(6497525620823745793L, m1.v3.longValue()); + assertEquals(2136224289077142499L, m1.v4.longValue()); + assertEquals(-2090575024006307745L, m1.v5.longValue()); + + assertEquals(-1883391953414482124L, m2.v1.longValue()); + assertEquals(-3019416596934963650L, m2.v2.longValue()); + assertEquals(6497525620823745793L, m2.v3.longValue()); + assertEquals(2136224289077142499L, m2.v4.longValue()); + assertEquals(-2090575024006307745L, m2.v5.longValue()); + } + + public static class Model { + public Long v1; + public Long v2; + public Long v3; + public Long v4; + public Long v5; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/basicType/LongTest_browserCompatible.java b/src/test/java/com/alibaba/json/bvt/basicType/LongTest_browserCompatible.java new file mode 100644 index 0000000000..f84e1099ab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/basicType/LongTest_browserCompatible.java @@ -0,0 +1,70 @@ +package com.alibaba.json.bvt.basicType; + +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class LongTest_browserCompatible extends TestCase { + public void test_array() throws Exception { + long[] values = new long[] {Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE}; + String text = JSON.toJSONString(values, SerializerFeature.BrowserCompatible); + long[] values_2 = JSON.parseObject(text, long[].class); + Assert.assertEquals(values_2.length, values.length); + for (int i = 0; i < values.length; ++i) { + Assert.assertEquals(values[i], values_2[i]); + } + } + + public void test_array_writer() throws Exception { + long[] values = new long[] {Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE}; + + StringWriter writer = new StringWriter(); + JSON.writeJSONString(writer, values, SerializerFeature.BrowserCompatible); + String text = writer.toString(); + long[] values_2 = JSON.parseObject(text, long[].class); + Assert.assertEquals(values_2.length, values.length); + for (int i = 0; i < values.length; ++i) { + Assert.assertEquals(values[i], values_2[i]); + } + } + + public void test_array_writer_2() throws Exception { + Random random = new Random(); + long[] values = new long[2048]; + for (int i = 0; i < values.length; ++i) { + values[i] = random.nextLong(); + } + + StringWriter writer = new StringWriter(); + JSON.writeJSONString(writer, values, SerializerFeature.BrowserCompatible); + String text = writer.toString(); + long[] values_2 = JSON.parseObject(text, long[].class); + Assert.assertEquals(values_2.length, values.length); + for (int i = 0; i < values.length; ++i) { + Assert.assertEquals(values[i], values_2[i]); + } + } + + public void test_map() throws Exception { + long[] values = new long[] {Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE}; + Map map = new HashMap(); + for (int i = 0; i < values.length; ++i) { + map.put(Long.toString(i), values[i]); + } + + String text = JSON.toJSONString(map, SerializerFeature.BrowserCompatible); + JSONObject obj = JSON.parseObject(text); + for (int i = 0; i < values.length; ++i) { + Assert.assertEquals(values[i], ((Number) obj.getLong(Long.toString(i))).longValue()); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug1.java new file mode 100755 index 0000000000..16a44d3ef2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug1.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.json.bvt.bug.JSONTest.InnerEntry; +import com.alibaba.json.bvt.bug.JSONTest.OuterEntry; + +public class Bug1 extends TestCase { + + public void testToEntry2() { + InnerEntry inner1 = null;// 出错 + String source1 = JSONObject.toJSONString(inner1); + System.out.println(source1); + OuterEntry inner2 = JSONObject.parseObject(source1, OuterEntry.class);// 出错 + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/bug/Bug11.java b/src/test/java/com/alibaba/json/bvt/bug/Bug11.java old mode 100644 new mode 100755 similarity index 88% rename from src/test/java/com/alibaba/json/test/bvt/bug/Bug11.java rename to src/test/java/com/alibaba/json/bvt/bug/Bug11.java index fbbb648511..4d711b6c6d --- a/src/test/java/com/alibaba/json/test/bvt/bug/Bug11.java +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug11.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.bug; +package com.alibaba.json.bvt.bug; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug13.java b/src/test/java/com/alibaba/json/bvt/bug/Bug13.java new file mode 100755 index 0000000000..57a477e6bc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug13.java @@ -0,0 +1,57 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class Bug13 extends TestCase { + public void test_0() throws Exception { + User user = new User("name1", "11"); + String object = JSON.toJSONString(user); + System.out.println(object); + user = JSON.parseObject(object, User.class);//报错 + } + + public static class User { + public User() { + } + + private String name, age; + private List group = new ArrayList(2); + + public List getGroup() { + return group; + } + + public void setGroup(List group) { + this.group = group; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAge() { + return age; + } + + public void setAge(String age) { + this.age = age; + } + + public User(String name, String age) { + this.name = name; + this.age = age; + group.add("1"); + group.add("2"); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug14.java b/src/test/java/com/alibaba/json/bvt/bug/Bug14.java new file mode 100755 index 0000000000..fc9f013b7e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug14.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.bug; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug14 extends TestCase { + + public void test_0() throws Exception { + double f = -5.5000009; + Long i = 4294967295l; + System.out.println(BigInteger.valueOf(i)); + System.out.println(Math.round(f)); + List list = new ArrayList(); + list.add(new AB("2a", "3b")); + list.add(new AB("4a", "6b")); + list.add(new AB("6a", "7{sdf<>jgh\n}b")); + list.add(new AB("8a", "9b")); + list.add(new AB("10a", "11ba")); + list.add(new AB("12a", "13b")); + String[] abc = new String[] { "sf", "sdf", "dsffds", "sdfsdf{fds}" }; + Map map = new LinkedHashMap(); + int k = 0; + for (AB a : list) { + map.put(String.valueOf(k++), a); + } + System.out.println(JSON.toJSON(list)); + System.out.println(JSON.toJSON(abc)); + System.out.println(JSON.toJSON(new AB("10a", "11ba"))); + System.out.println(JSON.toJSON(map)); + + } + + private static class AB { + + private String a; + private String b; + + public AB(){ + super(); + } + + public AB(String a, String b){ + super(); + this.a = a; + this.b = b; + } + + public String getA() { + return a; + } + + public String getB() { + return b; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug2.java new file mode 100755 index 0000000000..8740c54f2a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug2.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug2 extends TestCase { + + public void test_0() throws Exception { + Entity entity = new Entity(); + + entity.setArticles(Collections.singletonList(new Article())); + + String jsonString = JSON.toJSONString(entity); + + System.out.println(jsonString); + + Entity entity2 = JSON.parseObject(jsonString, Entity.class); + Assert.assertEquals(entity.getArticles().size(), entity2.getArticles().size()); + } + + public static class Entity { + + private List> list = new ArrayList>(); + private List
articles = null; + + public List> getList() { + return list; + } + + public void setList(List> list) { + this.list = list; + } + + public List
getArticles() { + return articles; + } + + public void setArticles(List
articles) { + this.articles = articles; + } + + } + + public static class Article { + + private long id; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_10.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_10.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/bug/Bug_10.java rename to src/test/java/com/alibaba/json/bvt/bug/Bug_10.java index e7a1865d00..642034e632 --- a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_10.java +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_10.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.bug; +package com.alibaba.json.bvt.bug; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin.java new file mode 100755 index 0000000000..14d1fdb05b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin.java @@ -0,0 +1,66 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_101_for_rongganlin extends TestCase { + + public void test_for_bug() throws Exception { + Structure structure = new Structure(); + List groups = new ArrayList(); + + List elemA = new ArrayList(); + elemA.add(new Text().set("t.a", "v.t.a")); + elemA.add(new Image().set("i.a", "v.i.a")); + groups.add(new Group().set(elemA)); + + List elemB = new ArrayList(); + elemB.add(new Text().set("t.b", "v.t.b")); + elemB.add(new Image().set("i.b", "v.i.b")); + groups.add(new Group().set(elemB)); + + structure.groups = groups; + + System.out.println(JSON.toJSON(structure)); + System.out.println(JSON.toJSONString(structure)); + } + + class Structure { + + public List groups; + } + + class Group implements Object { + + public List elements; + + public Group set(List items) { + this.elements = items; + return this; + } + } + + interface Object { + } + + abstract class Element { + + public String key, value; + + public Element set(String key, String value) { + this.key = key; + this.value = value; + return this; + } + } + + class Text extends Element { + } + + class Image extends Element { + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin_case2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin_case2.java new file mode 100755 index 0000000000..43254d0c95 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin_case2.java @@ -0,0 +1,71 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_101_for_rongganlin_case2 extends TestCase { + + public void test_for_bug() throws Exception { + Structure structure = new Structure(); + List groups = new ArrayList(); + + List elemA = new ArrayList(); + elemA.add(new Text().set("t.a", "v.t.a")); + elemA.add(new Image().set("i.a", "v.i.a")); + groups.add(new Group().set(elemA)); + + List elemB = new ArrayList(); + elemB.add(new Text().set("t.b", "v.t.b")); + elemB.add(new Image().set("i.b", "v.i.b")); + groups.add(new Group().set(elemB)); + + structure.groups = groups; + + String text = JSON.toJSONString(structure); + System.out.println(text); + Structure structure2 = JSON.parseObject(text, Structure.class); + + Assert.assertEquals(structure.groups.size(), structure2.groups.size()); + System.out.println(JSON.toJSONString(structure2)); + } + + public static class Structure { + + public List groups; + } + + public static class Group implements Object { + + public List elements; + + public Group set(List items) { + this.elements = items; + return this; + } + } + + public static interface Object { + } + + public static abstract class Element { + + public String key, value; + + public Element set(String key, String value) { + this.key = key; + this.value = value; + return this; + } + } + + public static class Text extends Element { + } + + public static class Image extends Element { + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin_case3.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin_case3.java new file mode 100755 index 0000000000..bee4529a8e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin_case3.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +public class Bug_101_for_rongganlin_case3 extends TestCase { + + public void test_for_bug() throws Exception { + Entity entity = new Entity(); + entity.setHolder(new Holder("AAA")); + + JSONObject json = (JSONObject) JSON.toJSON(entity); + Entity entity2 = JSON.toJavaObject(json, Entity.class); + Assert.assertEquals(JSON.toJSONString(entity), JSON.toJSONString(entity2)); + } + + public static class Entity { + + private Holder holder; + + public Holder getHolder() { + return holder; + } + + public void setHolder(Holder holder) { + this.holder = holder; + } + + } + + public static class Holder { + + private T value; + + public Holder() { + + } + + public Holder(T value) { + this.value = value; + } + + public T getValue() { + return value; + } + + public void setValue(T value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_102_for_rongganlin.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_102_for_rongganlin.java new file mode 100755 index 0000000000..11ee358bcf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_102_for_rongganlin.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.util.TypeUtils; + +public class Bug_102_for_rongganlin extends TestCase { + + public void test_bug() throws Exception { + TestBean testProcessInfo = new TestBean(); + com.alibaba.fastjson.JSONObject jo = new com.alibaba.fastjson.JSONObject(); + jo.put("id", 121); + ParserConfig config = new ParserConfig(); + testProcessInfo = TypeUtils.cast(jo, TestBean.class, config); + } + + public static class TestBean { + + private double id; + private double name; + + public double getId() { + return id; + } + + public void setId(double id) { + this.id = id; + } + + public double getName() { + return name; + } + + public void setName(double name) { + this.name = name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_105_for_SpitFire.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_105_for_SpitFire.java new file mode 100755 index 0000000000..9b91cfd1f5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_105_for_SpitFire.java @@ -0,0 +1,43 @@ +package com.alibaba.json.bvt.bug; + +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_105_for_SpitFire extends TestCase { + + static private class Foo { + + private List names; + private List codes; + + public List getNames() { + return names; + } + + public void setNames(List names) { + this.names = names; + } + + public List getCodes() { + return codes; + } + + public void setCodes(List codes) { + this.codes = codes; + } + + } + + public void test_listErrorTest() { + Foo foo = new Foo(); + String json = JSON.toJSONString(foo, SerializerFeature.WriteMapNullValue); + System.out.println(json); + Foo f = JSON.parseObject(json, Foo.class); + System.out.println(f); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_127_for_qiuyan81.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_127_for_qiuyan81.java new file mode 100644 index 0000000000..d2024e2c43 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_127_for_qiuyan81.java @@ -0,0 +1,90 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_127_for_qiuyan81 extends TestCase { + + public void test_parserUndefined() { + String jsonString = "{PayStatus:0,RunEmpId:undefined}"; + Object json = JSON.parse(jsonString); + Assert.assertEquals("{\"PayStatus\":0}", json.toString()); + } + + public void test_parserUndefined_space() { + String jsonString = "{PayStatus:0,RunEmpId:undefined }"; + Object json = JSON.parse(jsonString); + Assert.assertEquals("{\"PayStatus\":0}", json.toString()); + } + + public void test_parserUndefined_comma() { + String jsonString = "{PayStatus:0,RunEmpId:undefined,ext:1001}"; + JSONObject json = (JSONObject) JSON.parse(jsonString); + Assert.assertEquals(1001, json.get("ext")); + Assert.assertEquals(0, json.get("PayStatus")); + Assert.assertEquals(3, json.size()); + } + + public void test_parserUndefined_array() { + String jsonString = "[0,undefined]"; + Object json = JSON.parse(jsonString); + Assert.assertEquals("[0,null]", json.toString()); + } + + public void test_parserUndefined_n() { + String jsonString = "{PayStatus:0,RunEmpId:undefined\n}"; + Object json = JSON.parse(jsonString); + Assert.assertEquals("{\"PayStatus\":0}", json.toString()); + } + + public void test_parserUndefined_r() { + String jsonString = "{PayStatus:0,RunEmpId:undefined\r}"; + Object json = JSON.parse(jsonString); + Assert.assertEquals("{\"PayStatus\":0}", json.toString()); + } + + public void test_parserUndefined_t() { + String jsonString = "{PayStatus:0,RunEmpId:undefined\t}"; + Object json = JSON.parse(jsonString); + Assert.assertEquals("{\"PayStatus\":0}", json.toString()); + } + + public void test_parserUndefined_f() { + String jsonString = "{PayStatus:0,RunEmpId:undefined\f}"; + Object json = JSON.parse(jsonString); + Assert.assertEquals("{\"PayStatus\":0}", json.toString()); + } + + public void test_parserUndefined_b() { + String jsonString = "{PayStatus:0,RunEmpId:undefined\b}"; + Object json = JSON.parse(jsonString); + Assert.assertEquals("{\"PayStatus\":0}", json.toString()); + } + + public void test_parserUndefined_single() { + String jsonString = "undefined"; + Object json = JSON.parse(jsonString); + Assert.assertNull(json); + } + + public void test_parserUndefined_field() { + String jsonString = "{undefined:1001}"; + Object json = JSON.parse(jsonString); + Assert.assertEquals(1001, ((JSONObject)json).get("undefined")); + } + + public void test_parserError() { + Exception error = null; + try { + String jsonString = "{PayStatus:0,RunEmpId:undefinedaa}"; + JSON.parse(jsonString); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_376_for_iso8601.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_376_for_iso8601.java new file mode 100644 index 0000000000..ddb902b8f4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_376_for_iso8601.java @@ -0,0 +1,54 @@ +/* + * Copyright 2015 Alibaba.com All right reserved. This software is the + * confidential and proprietary information of Alibaba.com ("Confidential + * Information"). You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Alibaba.com. + */ +package com.alibaba.json.bvt.bug; + +import java.text.DateFormat; +import java.util.Date; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class Bug_376_for_iso8601 extends TestCase { + + public void test_fix() { + + String s = "{date: \"2015-07-22T19:13:42Z\"}"; + String s2 = "{date: \"2015-07-22T19:13:42.000Z\"}"; + + MyObj o = JSON.parseObject(s, MyObj.class, Feature.AllowISO8601DateFormat); + MyObj o2 = JSON.parseObject(s2, MyObj.class, Feature.AllowISO8601DateFormat); + + System.out.println(DateFormat.getDateTimeInstance().format(o.getDate())); + System.out.println(DateFormat.getDateTimeInstance().format(o2.getDate())); + + // 修复之前输出 + // 2015-7-22 19:13:42 + // 2015-7-23 3:13:42 + + // 修复之后输出 + // 2015-7-23 3:13:42 + // 2015-7-23 3:13:42 + + } + + static class MyObj { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_6.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_6.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/bug/Bug_6.java rename to src/test/java/com/alibaba/json/bvt/bug/Bug_6.java index 82210e7ad9..5ce2ad9ce0 --- a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_6.java +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_6.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.bug; +package com.alibaba.json.bvt.bug; import java.util.HashMap; import java.util.List; diff --git a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_7.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_7.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/bug/Bug_7.java rename to src/test/java/com/alibaba/json/bvt/bug/Bug_7.java index 08faa8235a..bda39152e4 --- a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_7.java +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_7.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.bug; +package com.alibaba.json.bvt.bug; import java.math.BigInteger; import java.util.concurrent.atomic.AtomicIntegerArray; diff --git a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_8.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_8.java old mode 100644 new mode 100755 similarity index 83% rename from src/test/java/com/alibaba/json/test/bvt/bug/Bug_8.java rename to src/test/java/com/alibaba/json/bvt/bug/Bug_8.java index 666e1a3ded..4d83c14176 --- a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_8.java +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_8.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.bug; +package com.alibaba.json.bvt.bug; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONArray; diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_KimShen.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_KimShen.java new file mode 100755 index 0000000000..7545e96273 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_KimShen.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Set; +import java.util.TreeSet; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_KimShen extends TestCase { + + public void test_0() throws Exception { + String text = JSON.toJSONString(new Entity()); + JSON.parseObject(text, Entity.class); + } + + public static class Entity { + + private Set value = new HashSet(); + private TreeSet treeSet = new TreeSet(); + private LinkedList linkedList = new LinkedList(); + private MySet mySet = new MySet(); + + public MySet getMySet() { + return mySet; + } + + public void setMySet(MySet mySet) { + this.mySet = mySet; + } + + public LinkedList getLinkedList() { + return linkedList; + } + + public void setLinkedList(LinkedList linkedList) { + this.linkedList = linkedList; + } + + public Set getValue() { + return value; + } + + public void setValue(Set value) { + this.value = value; + } + + public TreeSet getTreeSet() { + return treeSet; + } + + public void setTreeSet(TreeSet treeSet) { + this.treeSet = treeSet; + } + + } + + public static class MySet extends TreeSet { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_42283905.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_42283905.java new file mode 100755 index 0000000000..2de0159db6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_42283905.java @@ -0,0 +1,122 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class Bug_for_42283905 extends TestCase { + + public void test_0() throws Exception { + + String text; + { + List groups = new ArrayList(); + + Command c0 = new Command(1); + Command c1 = new Command(2); + Command c2 = new Command(3); + + c1.setPre(c0); + c2.setPre(c1); + + { + Group group = new Group("g0"); + group.getBattleCommandList().add(c0); + groups.add(group); + } + + { + Group group = new Group("g1"); + group.getBattleCommandList().add(c1); + groups.add(group); + } + + { + Group group = new Group("g2"); + group.getBattleCommandList().add(c2); + groups.add(group); + } + text = JSON.toJSONString(groups); + } + + System.out.println(text); + + List groups = JSON.parseObject(text, new TypeReference>() { + }); + Group g0 = groups.get(0); + Group g1 = groups.get(1); + + System.out.println(JSON.toJSONString(groups)); + } + + public static class Group { + + private String name; + + private List battleCommandList = new ArrayList(); + + public Group(){ + + } + + public Group(String name){ + this.name = name; + } + + public List getBattleCommandList() { + return battleCommandList; + } + + public void setBattleCommandList(List battleCommandList) { + this.battleCommandList = battleCommandList; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + + public static class Command { + + private int id; + + public Command(){ + + } + + public Command(int id){ + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + private Command pre; + + public Command getPre() { + return pre; + } + + public void setPre(Command pre) { + this.pre = pre; + } + + public String toString() { + return "{id:" + id + "}"; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_42283905_1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_42283905_1.java new file mode 100755 index 0000000000..28173d577c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_42283905_1.java @@ -0,0 +1,122 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class Bug_for_42283905_1 extends TestCase { + + public void test_0() throws Exception { + + String text; + { + List groups = new ArrayList(); + + Command c0 = new Command(1); + Command c1 = new Command(2); + Command c2 = new Command(3); + + c1.setPre(c0); + c2.setPre(c1); + + { + Group group = new Group("g0"); + group.getBattleCommandList().add(c0); + groups.add(group); + } + + { + Group group = new Group("g1"); + group.getBattleCommandList().add(c1); + groups.add(group); + } + + { + Group group = new Group("g2"); + group.getBattleCommandList().add(c2); + groups.add(group); + } + text = JSON.toJSONString(groups); + } + + System.out.println(text); + + Group[] groups = JSON.parseObject(text, new TypeReference() { + }); + Group g0 = groups[0]; + Group g1 = groups[1]; + + System.out.println(JSON.toJSONString(groups)); + } + + public static class Group { + + private String name; + + private List battleCommandList = new ArrayList(); + + public Group(){ + + } + + public Group(String name){ + this.name = name; + } + + public List getBattleCommandList() { + return battleCommandList; + } + + public void setBattleCommandList(List battleCommandList) { + this.battleCommandList = battleCommandList; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + + public static class Command { + + private int id; + + public Command(){ + + } + + public Command(int id){ + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + private Command pre; + + public Command getPre() { + return pre; + } + + public void setPre(Command pre) { + this.pre = pre; + } + + public String toString() { + return "{id:" + id + "}"; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_80108116.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_80108116.java new file mode 100755 index 0000000000..478801defd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_80108116.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.bug; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class Bug_for_80108116 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_dateFormat() throws Exception { + VO vo = new VO(); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + vo.setDate(dateFormat.parse("2012-07-12")); + + List voList = new ArrayList(); + voList.add(vo); + + String text = JSON.toJSONString(voList); + Assert.assertEquals("[{\"date\":\"2012-07-12\"}]", text); + } + + public static class VO { + + private Date date; + + @JSONField(format = "yyyy-MM-dd") + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ArrayMember.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ArrayMember.java new file mode 100755 index 0000000000..ce80bbd7d9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ArrayMember.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class Bug_for_ArrayMember extends TestCase { + public void test_arrayMember() throws Exception { + A a = new A(); + a.setValues(new B[] {new B()}); + + String text = JSON.toJSONString(a); + + Assert.assertEquals("{\"values\":[{}]}", text); + Assert.assertEquals("{}", JSON.toJSONString(new A())); + Assert.assertEquals("null", JSON.toJSONString(new A().getValues())); + + Assert.assertEquals("[]", JSON.toJSONString(new A[0])); + Assert.assertEquals("[{},{}]", JSON.toJSONString(new A[] {new A(), new A()})); + } + + public static class A { + + private B[] values; + + public B[] getValues() { + return values; + } + + public void setValues(B[] values) { + this.values = values; + } + + } + + public static class B { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_BlankRain_Issue_502.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_BlankRain_Issue_502.java new file mode 100644 index 0000000000..675e6e3d61 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_BlankRain_Issue_502.java @@ -0,0 +1,107 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_BlankRain_Issue_502 extends TestCase { + + public void test_for_issue() throws Exception { + People a1 = new People(); + a1.set姓名("A"); + a1.set类型("B"); + a1.set状态("C"); + a1.set满意度("D"); + a1.set统计("E"); + a1.set时间("F"); + + String text = JSON.toJSONString(a1); + Assert.assertEquals("{\"姓名\":\"A\",\"时间\":\"F\",\"满意度\":\"D\",\"状态\":\"C\",\"类型\":\"B\",\"统计\":\"E\"}", text); + System.out.println(text); + + People a2 = JSON.parseObject(text, People.class); + Assert.assertEquals(a1.get姓名(), a2.get姓名()); + Assert.assertEquals(a1.get类型(), a2.get类型()); + Assert.assertEquals(a1.get状态(), a2.get状态()); + Assert.assertEquals(a1.get满意度(), a2.get满意度()); + Assert.assertEquals(a1.get统计(), a2.get统计()); + Assert.assertEquals(a1.get时间(), a2.get时间()); + } + + public static class People { + + private String 姓名; + private String 类型; + private String 状态; + private String 满意度; + private String 统计; + private String 时间; + + static List head() { + List h = new ArrayList(); + + h.add("姓名"); + h.add("类型"); + h.add("状态"); + h.add("满意度"); + h.add("统计"); + h.add("时间"); + return h; + } + + public String get姓名() { + return 姓名; + } + + public void set姓名(String 姓名) { + this.姓名 = 姓名; + } + + public String get类型() { + return 类型; + } + + public void set类型(String 类型) { + this.类型 = 类型; + } + + public String get状态() { + return 状态; + } + + public void set状态(String 状态) { + this.状态 = 状态; + } + + public String get满意度() { + return 满意度; + } + + public void set满意度(String 满意度) { + this.满意度 = 满意度; + } + + public String get统计() { + return 统计; + } + + public void set统计(String 统计) { + this.统计 = 统计; + } + + public String get时间() { + return 时间; + } + + public void set时间(String 时间) { + this.时间 = 时间; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_DiffType.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_DiffType.java new file mode 100644 index 0000000000..37f2438c6f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_DiffType.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_DiffType extends TestCase { + public void test_for_diff_type() throws Exception { + Model model = new Model(); + model.setValue(1001); + + String text = JSON.toJSONString(model); + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.value, model2.value); + } + + public static class Model { + public String value; + + public long getValue() { + return Long.parseLong(value); + } + + public void setValue(long value) { + this.value = Long.toString(value); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Double2Tag.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Double2Tag.java new file mode 100755 index 0000000000..43b71012ec --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Double2Tag.java @@ -0,0 +1,95 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_Double2Tag extends TestCase { + public void test_double() throws Exception { + Double2Tag tag = new Double2Tag(); + String str = JSON.toJSONString(tag); + JSON.parseObject(str, Double2Tag.class); + } + + public static class Double2Tag { + public String data_time; + public String data_id; + public String hour_id; + public String minute_id; + public String tag3_id; + public double ali_fee; + public double total_ali_fee; + public long seller_cnt; + + public Double2Tag() { + ali_fee = 0.0; + total_ali_fee = 0.0; + seller_cnt = 0; + } + + public String getData_time() { + return data_time; + } + + public void setData_time(String data_time) { + this.data_time = data_time; + } + + public String getData_id() { + return data_id; + } + + public void setData_id(String data_id) { + this.data_id = data_id; + } + + public String getHour_id() { + return hour_id; + } + + public void setHour_id(String hour_id) { + this.hour_id = hour_id; + } + + public String getMinute_id() { + return minute_id; + } + + public void setMinute_id(String minute_id) { + this.minute_id = minute_id; + } + + public String getTag3_id() { + return tag3_id; + } + + public void setTag3_id(String tag3_id) { + this.tag3_id = tag3_id; + } + + public double getAli_fee() { + return ali_fee; + } + + public void setAli_fee(double ali_fee) { + this.ali_fee = ali_fee; + } + + public double getTotal_ali_fee() { + return total_ali_fee; + } + + public void setTotal_ali_fee(double total_ali_fee) { + this.total_ali_fee = total_ali_fee; + } + + public long getSeller_cnt() { + return seller_cnt; + } + + public void setSeller_cnt(long seller_cnt) { + this.seller_cnt = seller_cnt; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Exception.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Exception.java new file mode 100755 index 0000000000..a062ca8be6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Exception.java @@ -0,0 +1,15 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_Exception extends TestCase { + public void test_exception() throws Exception { + RuntimeException ex = new RuntimeException("e1"); + String text = JSON.toJSONString(ex); + System.out.println(text); + + RuntimeException ex2 = (RuntimeException) JSON.parse(text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_519.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_519.java new file mode 100644 index 0000000000..5d95d81714 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_519.java @@ -0,0 +1,12 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_Issue_519 extends TestCase { + public void test_issue() throws Exception { + String json = "{\"accomTypes\":[1],\"address\":\"\",\"airportIds\":[],\"airportrailwayIds\":[],\"areaIds\":[0,14,673],\"avgPrice\":0,\"avgScore\":3.8,\"baseScore\":-0.0035256863871981348,\"brandId\":23762,\"brandLogo\":\"\",\"brandName\":\"\",\"brandStory\":\"\",\"campaignsScore\":0,\"cates\":[392,20,79],\"cityIds\":[1],\"collegeIds\":[58],\"competeDiffPrice\":0,\"couponCount\":990,\"customAvgScore\":76.00890238508207,\"declineScore\":0,\"distance\":0,\"drLowestPrice\":289,\"festCanuse\":0,\"hasDR\":1,\"hasDRGroup\":0,\"hasGroup\":1,\"hasHR\":0,\"hasHRGroup\":0,\"hasInvoice\":0,\"hospitalIds\":[23599],\"hotelTypes\":[1,0,888],\"hrLowestPrice\":0,\"inBlackList\":0,\"innCates\":[],\"introduction\":\"\",\"landmarkScore\":0,\"lastModifyTime\":1457924599643,\"latitude\":39.997828,\"location\":\"39.997828,116.466004\",\"longitude\":116.466004,\"lowestPrice\":289,\"mapSmartPartScore\":69.74729610098822,\"markNumbers\":270,\"name\":\"布丁酒店(北京望京店)\",\"newDealScore\":0,\"phone\":\"010-64728973\",\"poiid\":52209391,\"prds\":[{\"areaIds\":[14,673],\"beginTime\":1436371200,\"bookingType\":0,\"cates\":[0,1],\"cityIds\":[1],\"dateCantUse\":[\"20160313\",\"20160314\",\"20160315\",\"20160316\",\"20160317\",\"20160318\",\"20160319\",\"20160320\",\"20160321\",\"20160322\",\"20160323\",\"20160324\",\"20160325\",\"20160326\",\"20160327\",\"20160328\",\"20160329\",\"20160330\",\"20160331\",\"20160401\",\"20160402\",\"20160403\",\"20160404\",\"20160405\",\"20160406\",\"20160407\",\"20160408\",\"20160409\"],\"did\":30513601,\"endTime\":1460131199,\"gid\":749878,\"hasCampaigns\":0,\"hasInvoice\":0,\"nobooking\":0,\"poiids\":[],\"price\":59,\"soldQuantity\":535,\"value\":80},{\"areaIds\":[14,673],\"beginTime\":1438531200,\"bookingType\":0,\"cates\":[0,1],\"cityIds\":[1],\"dateCantUse\":[\"20160313\",\"20160314\",\"20160315\",\"20160316\",\"20160317\",\"20160318\",\"20160319\",\"20160320\",\"20160321\",\"20160322\",\"20160323\",\"20160324\",\"20160325\",\"20160326\",\"20160327\",\"20160328\",\"20160329\",\"20160330\",\"20160331\",\"20160401\",\"20160402\",\"20160403\",\"20160404\"],\"did\":31035361,\"endTime\":1459699199,\"gid\":858227,\"hasCampaigns\":0,\"hasInvoice\":0,\"nobooking\":0,\"poiids\":[],\"price\":309,\"soldQuantity\":60,\"value\":319},{\"areaIds\":[14,673],\"beginTime\":1438531200,\"bookingType\":0,\"cates\":[0,1],\"cityIds\":[1],\"dateCantUse\":[\"20160313\",\"20160314\",\"20160315\",\"20160316\",\"20160317\",\"20160318\",\"20160319\",\"20160320\",\"20160321\",\"20160322\",\"20160323\",\"20160324\",\"20160325\",\"20160326\",\"20160327\",\"20160328\",\"20160329\",\"20160330\",\"20160331\",\"20160401\",\"20160402\",\"20160403\",\"20160404\"],\"did\":31035397,\"endTime\":1459699199,\"gid\":858226,\"hasCampaigns\":0,\"hasInvoice\":0,\"nobooking\":0,\"poiids\":[],\"price\":289,\"soldQuantity\":157,\"value\":309}],\"railwayStationIds\":[],\"roomSizes\":[0,1,3,4],\"roomStates\":{},\"scenicSpotIds\":[5655],\"showFlag\":1,\"smartAvgBaseScore\":5.7669880413567585,\"smartPartScore\":58.21997185816042,\"smartSoldBaseScore\":1.6134262836027502,\"subwayLineIds\":[3,75],\"subwayStationIds\":[1490,1485,147],\"yfSourceTypes\":[],\"zlSourceType\":0}"; + JSON.parse(json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_534.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_534.java new file mode 100644 index 0000000000..8098757397 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_534.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_Issue_534 extends TestCase { + public void test_for_issue() throws Exception { + Value value = new Value(); + value.aLong = 2459838341588L; + + String text = JSON.toJSONString(value); + Assert.assertEquals("{\"aLong\":2459838341588}", text); + } + + public void test_for_issue_1() throws Exception { + Long value = 2459838341588L; + + String text = JSON.toJSONString(value); + Assert.assertEquals("2459838341588", text); + } + + class Value { + + private Long aLong; + + public Long getaLong() { + return aLong; + } + + public void setaLong(Long aLong) { + this.aLong = aLong; + } + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_535.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_535.java new file mode 100644 index 0000000000..c423aa0acf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_535.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.bug; + +import java.math.BigDecimal; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class Bug_for_Issue_535 extends TestCase { + public void test_for_issue() throws Exception { + TestPOJO testPOJO = new TestPOJO(); + testPOJO.setA("a"); + testPOJO.setB(new BigDecimal("1234512312312312312312")); + String s = JSON.toJSONString(testPOJO); + System.out.println(s); + + TestPOJO vo2 = JSON.parseObject(s, TestPOJO.class, Feature.UseBigDecimal); + Assert.assertEquals(testPOJO.getB(), vo2.getB()); + } + + public static class TestPOJO { + + private String a; + private BigDecimal b; + // getter and setter + + public String getA() { + return a; + } + + public void setA(String a) { + this.a = a; + } + + public BigDecimal getB() { + return b; + } + + public void setB(BigDecimal b) { + this.b = b; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_603.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_603.java new file mode 100644 index 0000000000..1db3df5778 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_603.java @@ -0,0 +1,68 @@ +package com.alibaba.json.bvt.bug; + +import java.lang.reflect.Type; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +import junit.framework.TestCase; + +public class Bug_for_Issue_603 extends TestCase { + + public void test_for_issue() throws Exception { + ParserConfig.getGlobalInstance().putDeserializer(OrderActionEnum.class, new OrderActionEnumDeser()); + + { + Msg msg = JSON.parseObject("{\"actionEnum\":1,\"body\":\"A\"}", Msg.class); + Assert.assertEquals(msg.body, "A"); + Assert.assertEquals(msg.actionEnum, OrderActionEnum.FAIL); + } + { + Msg msg = JSON.parseObject("{\"actionEnum\":0,\"body\":\"B\"}", Msg.class); + Assert.assertEquals(msg.body, "B"); + Assert.assertEquals(msg.actionEnum, OrderActionEnum.SUCC); + } + } + + public static class OrderActionEnumDeser implements ObjectDeserializer { + + @SuppressWarnings("unchecked") + @Override + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + Integer intValue = parser.parseObject(int.class); + if (intValue == 1) { + return (T) OrderActionEnum.FAIL; + } else if (intValue == 0) { + return (T) OrderActionEnum.SUCC; + } + throw new IllegalStateException(); + } + + @Override + public int getFastMatchToken() { + return JSONToken.LITERAL_INT; + } + + } + + public static enum OrderActionEnum { + FAIL(1), SUCC(0); + + private int code; + + OrderActionEnum(int code){ + this.code = code; + } + } + + public static class Msg { + + public OrderActionEnum actionEnum; + public String body; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_JSONObject.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_JSONObject.java new file mode 100755 index 0000000000..153759c18d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_JSONObject.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializerFeature; + + +public class Bug_for_JSONObject extends TestCase { + public void test_0 () throws Exception { + JSONSerializer ser = new JSONSerializer(); + ser.config(SerializerFeature.WriteClassName, true); + ser.write(new JSONObject()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Jay.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Jay.java new file mode 100755 index 0000000000..0133a9fd0e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Jay.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_Jay extends TestCase { + + public void test_for_jay() throws Exception { + JSON.toJSONString(new B(), true); + } + + public class A { + + String nameA; + } + + public class B extends A { + String nameB; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Jay_1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Jay_1.java new file mode 100755 index 0000000000..2fc8bfeff8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Jay_1.java @@ -0,0 +1,11 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_Jay_1 extends TestCase { + public void test_bug() throws Exception { + JSON.parseObject("{\"body\":{\"coupons\":[{\"couponTypeId\":\"81c07c7c-7b88-4f5c-9d1e-e6f16e2ae36d\",\"editor\":\"ADMIN\",\"organizationPartyId\":\"00\",\"statusId\":\"COUPON_CREATED\",\"editorName\":\"超级管理员\",\"couponCode\":\"02\",\"creatorName\":\"超级管理员\",\"id\":\"d686bc04-a9d5-4f84-977a-8bfbb4fa9fe3\",\"fromDate\":\"2013-03-11 00:00:00\",\"creator\":\"ADMIN\",\"displayName\":\"02\",\"createTime\":\"2013-03-12 13:14:05\",\"updateTime\":\"2013-03-12 13:14:05\",\"organizationName\":\"X、X\"}],\"event\":\"activate\"}}"); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_JeryZeng.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_JeryZeng.java new file mode 100644 index 0000000000..b5d68a9d53 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_JeryZeng.java @@ -0,0 +1,12 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class Bug_for_JeryZeng extends TestCase { + public void test_0() throws Exception { + System.out.println(JSON.parseObject("{123:123,124:true,\"value\":{123:\"abc\"}}")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Johnny.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Johnny.java new file mode 100755 index 0000000000..46cea43dc2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Johnny.java @@ -0,0 +1,245 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_Johnny extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_Johnny."); + } + + public void test_bug()throws Exception { + MyObject myObject = new MyObject(); + List listObj = new LinkedList(); + Set setObj = new HashSet(); + Map mapObj = new HashMap(); + listObj.add("aaa"); + listObj.add("bbb"); + setObj.add("aaa"); + setObj.add("bbb"); + mapObj.put("key", "value"); + myObject.setBoolType(true); + myObject.setByteType(Byte.MIN_VALUE); + myObject.setCharType(Character.MIN_VALUE); + myObject.setDoubleType(Double.MIN_VALUE); + myObject.setFloatType(Float.MIN_VALUE); + myObject.setIntType(Integer.MIN_VALUE); + myObject.setLongType(Long.MIN_VALUE); + myObject.setShortType(Short.MIN_VALUE); + myObject.setEnumType(EnumType.MD5); + myObject.setStringType("aadf"); + myObject.setMapType(mapObj); + myObject.setSetType(setObj); + myObject.setListType(listObj); + + String text = JSON.toJSONString(myObject, SerializerFeature.WriteClassName); + System.out.println(text); + MyObject myObject2 = (MyObject) JSON.parse(text); + Assert.assertEquals(myObject2.getMapType(), myObject.getMapType()); + } + + public static enum EnumType { + MD5, SHA1 + } + + public static class MyObject { + + private String stringType; + private byte byteType; + private short shortType; + private int intType; + private long longType; + private char charType; + private float floatType; + private double doubleType; + private boolean boolType; + private List ListType; + private Map mapType; + private Set setType; + private EnumType enumType; + + public Set getSetType() { + return setType; + } + + public void setSetType(Set setType) { + this.setType = setType; + } + + /** + * @return the stringType + */ + public String getStringType() { + return stringType; + } + + public EnumType getEnumType() { + return enumType; + } + + public void setEnumType(EnumType enumType) { + this.enumType = enumType; + } + + public List getListType() { + return ListType; + } + + public void setListType(List listType) { + ListType = listType; + } + + public Map getMapType() { + return mapType; + } + + public void setMapType(Map mapType) { + this.mapType = mapType; + } + + /** + * @param stringType + * the stringType to set + */ + public void setStringType(String stringType) { + this.stringType = stringType; + } + + /** + * @return the byteType + */ + public byte getByteType() { + return byteType; + } + + /** + * @param byteType + * the byteType to set + */ + public void setByteType(byte byteType) { + this.byteType = byteType; + } + + /** + * @return the shortType + */ + public short getShortType() { + return shortType; + } + + /** + * @param shortType + * the shortType to set + */ + public void setShortType(short shortType) { + this.shortType = shortType; + } + + /** + * @return the intType + */ + public int getIntType() { + return intType; + } + + /** + * @param intType + * the intType to set + */ + public void setIntType(int intType) { + this.intType = intType; + } + + /** + * @return the longType + */ + public long getLongType() { + return longType; + } + + /** + * @param longType + * the longType to set + */ + public void setLongType(long longType) { + this.longType = longType; + } + + /** + * @return the charType + */ + public char getCharType() { + return charType; + } + + /** + * @param charType + * the charType to set + */ + public void setCharType(char charType) { + this.charType = charType; + } + + /** + * @return the floatType + */ + public float getFloatType() { + return floatType; + } + + /** + * @param floatType + * the floatType to set + */ + public void setFloatType(float floatType) { + this.floatType = floatType; + } + + /** + * @return the doubleType + */ + public double getDoubleType() { + return doubleType; + } + + /** + * @param doubleType + * the doubleType to set + */ + public void setDoubleType(double doubleType) { + this.doubleType = doubleType; + } + + /** + * @return the boolType + */ + public boolean isBoolType() { + return boolType; + } + + /** + * @param boolType + * the boolType to set + */ + public void setBoolType(boolean boolType) { + this.boolType = boolType; + } + + /** + * Constructs a GroupEntity
+ */ + public MyObject() { + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Next.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Next.java new file mode 100644 index 0000000000..5bbac9647c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_Next.java @@ -0,0 +1,292 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +import java.util.*; + + +public class Bug_for_Next extends TestCase { + + public static void main(String[] args) throws Exception { + Result result = JUnitCore.runClasses(Bug_for_Next.class); + for (Failure fail : result.getFailures()) { + System.out.println(fail.toString()); + } + if (result.wasSuccessful()) { + System.out.println("All tests finished successfully..."); + } + } + + public void testPrimitiveArray() throws Exception { + + showTitle("1====================================="); + String text= JSON.toJSONString("testbytearray".getBytes()); + showMesg("text : " + text); + byte[] byteArray = JSON.parseObject(text, byte[].class); + showMesg("byteArray : " + byteArrayToHexString(byteArray)); + + int[][] ii = new int[][]{ + new int[]{ 1, 2, 3}, + new int[]{ 2, 3, 4, 5} + }; + + text = JSON.toJSONString(ii); + showMesg("text : " + text); + int[][] pii = JSON.parseObject(text, int[][].class); + showMesg("pii : " + Arrays.toString(pii)); + showMesg("pii0 : " + Arrays.toString(pii[0])); + showMesg("pii1 : " + Arrays.toString(pii[1])); + + showTitle("2====================================="); + List blist = new ArrayList(); + blist.add("byte[]".getBytes()); + blist.add("blist".getBytes()); + text = JSON.toJSONString(blist); + showMesg("text : " + text); + blist = JSON.parseObject(text, new TypeReference>(byte[].class){}.getType()); + showMesg("blist : " + blist); + showMesg("blist1 : " + byteArrayToHexString(blist.get(0))); + showMesg("blist2 : " + byteArrayToHexString(blist.get(1))); + + List clist = new ArrayList(); + clist.add(new char[]{'1',',','2'}); + clist.add(new char[]{'2',',','1'}); + text = JSON.toJSONString(clist); + showMesg("text " + text); + clist = JSON.parseObject(text, new TypeReference>(char[].class){}); + showMesg("clist : " + clist); + showMesg("clist1 : " + Arrays.toString(clist.get(0))); + showMesg("clist2 : " + Arrays.toString(clist.get(1))); + + List ilist = new ArrayList(); + ilist.add(new int[]{11,22,33}); + ilist.add(new int[]{33,22,11}); + text = JSON.toJSONString(ilist); + showMesg("text " + text); + ilist = JSON.parseObject(text, new TypeReference>(int[].class){}); + showMesg("ilist : " + ilist); + showMesg("ilist1 : " + Arrays.toString(ilist.get(0))); + showMesg("ilist2 : " + Arrays.toString(ilist.get(1))); + + List flist = new ArrayList(); + flist.add(new float[]{11.2f,22.3f,33.4f}); + flist.add(new float[]{33.1f,22.2f,11.3f}); + text = JSON.toJSONString(flist); + showMesg("text " + text); + flist = JSON.parseObject(text, new TypeReference>(float[].class){}); + showMesg("flist : " + flist); + showMesg("flist1 : " + Arrays.toString(flist.get(0))); + showMesg("flist2 : " + Arrays.toString(flist.get(1))); + + List iilist = new ArrayList(); + iilist.add(new int[][] { + new int[]{9,6,3}, + new int[]{8,5,2} + }); + iilist.add(new int[][] { + new int[]{7,4,1}, + new int[]{0} + }); + text = JSON.toJSONString(iilist); + showMesg("text : " + text); + iilist = JSON.parseObject(text, new TypeReference>(int[][].class){}); + showMesg("iilist : " + iilist); + showMesg("iilist1 : " + Arrays.toString(iilist.get(0)[0])); + showMesg("iilist2 : " + Arrays.toString(iilist.get(1)[0])); + + showTitle("3====================================="); + Map sbmap = new HashMap(); + sbmap.put("key1", "key1".getBytes()); + sbmap.put("key2", "key2".getBytes()); + text = JSON.toJSONString(sbmap); + showMesg("sbmap : " + text); + sbmap = JSON.parseObject(text, new TypeReference>(String.class, byte[].class){}); + showMesg("sbmap : " + sbmap); + showMesg("sbmap key1 : " + byteArrayToHexString(sbmap.get("key1"))); + showMesg("sbmap key2 : " + byteArrayToHexString(sbmap.get("key2"))); + + showTitle("4====================================="); + Map sbcmap = new HashMap(); + sbcmap.put("key1", new Byte[]{ 1, 2, 3 }); + sbcmap.put("key2", new Byte[]{ 3, 2, 1 }); + text = JSON.toJSONString(sbcmap); + showMesg("sbcmap json : " + text); + sbcmap = JSON.parseObject(text, new TypeReference>(String.class, Byte[].class){}); + showMesg("sbcmap : " + sbcmap); + showMesg("sbcmap key1 : " + Arrays.toString(sbcmap.get("key1"))); + showMesg("sbcmap key1 : " + Arrays.toString(sbcmap.get("key2"))); + + showTitle("5====================================="); + int[] intArray = new int[]{ 11, 22, 33 }; + text = JSON.toJSONString(intArray); + showMesg("intArray json : " + text); + intArray = JSON.parseObject(text, int[].class); + showMesg("intArray : " + Arrays.toString(intArray)); + + showTitle("6====================================="); + Map simap = new HashMap(); + simap.put("key1", new int[]{ 11, 22, 33 }); + simap.put("key2", new int[]{ 33, 22, 11 }); + text = JSON.toJSONString(simap, SerializerFeature.WriteClassName); + showMesg("simap json : " + text); + simap = JSON.parseObject(text, new TypeReference>(String.class, int[].class){}); + showMesg("simap : " + simap); + showMesg("simap key1 : " + Arrays.toString(simap.get("key1"))); + showMesg("simap key1 : " + Arrays.toString(simap.get("key2"))); + + showTitle("7====================================="); + Map sicmap = new HashMap(); + sicmap.put("key1", new Integer[]{ 12, 23, 34 }); + sicmap.put("key2", new Integer[]{ 34, 23, 12 }); + text = JSON.toJSONString(sicmap, SerializerFeature.WriteClassName); + showMesg("sicmap json : " + text); + sicmap = JSON.parseObject(text, new TypeReference>(String.class, Integer[].class){}); + showMesg("sicmap : " + sicmap); + showMesg("sicmap key1 : " + Arrays.toString(sicmap.get("key1"))); + showMesg("sicmap key1 : " + Arrays.toString(sicmap.get("key2"))); + + showTitle("8====================================="); + HashMap bsmap = new HashMap(); + bsmap.put("testbytearray".getBytes(), "testbytearray"); + bsmap.put(new byte[] { 0, 1, 2}, "012"); + text = JSON.toJSONString(bsmap); + showMesg("text : " + text); + bsmap = JSON.parseObject(text, new TypeReference>(byte[].class, String.class){}.getType()); + showMesg("bsmap : " + bsmap); + + Iterator it = bsmap.keySet().iterator(); + int i = 0; + while (it.hasNext()) { + byte[] bs = it.next(); + showMesg("bsmap key" + i++ + " : " + byteArrayToHexString(bs)); + } + + Map stmap = new HashMap(); + stmap.put("key1", new TestBean[]{ new TestBean(), new TestBean()}); + stmap.put("key2", new TestBean[]{ new TestBean(), new TestBean(), new TestBean()}); + text = JSON.toJSONString(stmap); + showMesg("stmap json : " + text); + stmap = JSON.parseObject(text, new TypeReference>(String.class, TestBean[].class){}); + showMesg("stmap : " + stmap); + showMesg("key1 : " + Arrays.toString(stmap.get("key1"))); + showMesg("key2 : " + Arrays.toString(stmap.get("key2"))); + + } + + private void showTitle(String title) { + System.out.println("test " + title); + } + + private void showMesg(String mesg) { + System.out.println(" " + mesg); + } + + private static String byteArrayToHexString(byte[] data) { + return byteArrayToHexString(data, 0, data.length); + } + + private static String byteArrayToHexString(byte[] data, int offest, int len) { + if (data == null) { + return ""; + } + + StringBuilder sb = new StringBuilder(); + + if(offest < 0 || offest > data.length){ + offest = 0; + } + + int total = Math.min(len, data.length); + + int index = offest; + + while (total > 0) { + if (total >= 16) { + sb.append(String.format("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x ", + data[index], data[index + 1], data[index + 2], + data[index + 3], data[index + 4], + data[index + 5], data[index + 6], + data[index + 7], data[index + 8], + data[index + 9], data[index + 10], + data[index + 11], data[index + 12], + data[index + 13], data[index + 14], + data[index + 15])); + index += 16; + total -= 16; + } else { + for (int i = 0; i < total; i++) { + sb.append(String.format("%02x ", data[index])); + index++; + } + total = 0; + } + } + + return sb.toString(); + } + + static class TestBean { + byte b; + byte[] bs = "bs".getBytes(); + int i; + int[] is = new int[]{ 753, 159 }; + String s; + + public byte getB() { + return b; + } + + public void setB(byte b) { + this.b = b; + } + + public byte[] getBs() { + return bs; + } + + public void setBs(byte[] bs) { + this.bs = bs; + } + + public int getI() { + return i; + } + + public void setI(int i) { + this.i = i; + } + + public int[] getIs() { + return is; + } + + public void setIs(int[] is) { + this.is = is; + } + + public String getS() { + return s; + } + + public void setS(String s) { + this.s = s; + } + + @Override + public String toString() { + return "TestBean{" + + "b=" + b + + ", bs=" + Arrays.toString(bs) + + ", i=" + i + + ", is=" + Arrays.toString(is) + + ", s='" + s + '\'' + + '}'; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_NonStringKeyMap.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_NonStringKeyMap.java new file mode 100755 index 0000000000..63f6d21d5d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_NonStringKeyMap.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_NonStringKeyMap extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_NonStringKeyMap."); + } + + public void test_bug() throws Exception { + VO vo = new VO(); + vo.getMap().put(1L, new VAL()); + + String text = JSON.toJSONString(vo, SerializerFeature.WriteClassName); + System.out.println(text); + + JSON.parse(text); + } + + public void test_1() throws Exception { + Map, String> map = new HashMap, String>(); + Map submap = new HashMap(); + submap.put("subkey", "subvalue"); + map.put(submap, "value"); + String jsonString = JSON.toJSONString(map, SerializerFeature.WriteClassName); + System.out.println(jsonString); + Object object = JSON.parse(jsonString); + System.out.println(object.toString()); + } + + public static class VO { + + private Map map = new HashMap(); + + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + } + + public static class VAL { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_O_I_See_you.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_O_I_See_you.java new file mode 100755 index 0000000000..f5f0c01d61 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_O_I_See_you.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_O_I_See_you extends TestCase { + + public void test_bug() throws Exception { + Object[] arra = { "aa", "bb" }; + + Object[] arr = { "sssss", arra }; + + String s = JSON.toJSONString(arr); + + Object[] ar = JSON.parseObject(s, Object[].class); + System.out.println(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire.java new file mode 100755 index 0000000000..302c753fc6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_SpitFire extends TestCase { + + public void test_for_spitFire() throws Exception { + GenericDTO object = new GenericDTO(); + object.setFiled(new MyDTO()); + + String text = JSON.toJSONString(object, SerializerFeature.WriteClassName); + + GenericDTO object2 = (GenericDTO) JSON.parseObject(text, GenericDTO.class); + + Assert.assertEquals(object.getName(), object2.getName()); + Assert.assertEquals(object.getFiled().getId(), object2.getFiled().getId()); + } + + public static class GenericDTO extends AbstractDTO { + + private String name; + private T filed; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public T getFiled() { + return filed; + } + + public void setFiled(T filed) { + this.filed = filed; + } + } + + public abstract static class AbstractDTO { + + } + + public static class MyDTO extends AbstractDTO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_2.java new file mode 100755 index 0000000000..da7bd3fb29 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_2.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_SpitFire_2 extends TestCase { + + public void test_for_SpringFire() { + Generic q = new Generic(); + String text = JSON.toJSONString(q, SerializerFeature.WriteClassName); + System.out.println(text); + JSON.parseObject(text, Generic.class); + } + + public static class Generic { + + String header; + T payload; + + public String getHeader() { + return header; + } + + public void setHeader(String header) { + this.header = header; + } + + public T getPayload() { + return payload; + } + + public void setPayload(T payload) { + this.payload = payload; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_3.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_3.java new file mode 100755 index 0000000000..628608fca4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_3.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_SpitFire_3 extends TestCase { + + public void test_for_SpitFire() { + Generic q = new Generic(); + q.setHeader("Sdfdf"); + q.setPayload(new Payload()); + String text = JSON.toJSONString(q, SerializerFeature.WriteClassName); + System.out.println(text); + JSON.parseObject(text, Generic.class); + } + + public static abstract class AbstractDTO { + + private String test; + + public String getTest() { + return test; + } + + public void setTest(String test) { + this.test = test; + } + } + + public static class Payload extends AbstractDTO { + + } + + public static class Generic extends AbstractDTO { + + String header; + T payload; + + public String getHeader() { + return header; + } + + public void setHeader(String header) { + this.header = header; + } + + public T getPayload() { + return payload; + } + + public void setPayload(T payload) { + this.payload = payload; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_4.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_4.java new file mode 100755 index 0000000000..977de20a5c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_4.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_SpitFire_4 extends TestCase { + + public void test_for_SpitFire() { + Generic q = new Generic(); + q.setHeader(new Header()); + q.setPayload(new Payload()); + String text = JSON.toJSONString(q, SerializerFeature.WriteClassName); + System.out.println(text); + Generic o = (Generic) JSON.parseObject(text, q.getClass()); + Assert.assertNotNull(o.getPayload()); + } + + public static abstract class AbstractDTO { + } + + public static class Header { + + } + + public static class Payload extends AbstractDTO { + + } + + public static class Generic extends AbstractDTO { + + Header header; + T payload; + + public Header getHeader() { + return header; + } + + public void setHeader(Header header) { + this.header = header; + } + + public T getPayload() { + return payload; + } + + public void setPayload(T payload) { + this.payload = payload; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_5.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_5.java new file mode 100755 index 0000000000..767b2cb6f0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_5.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_SpitFire_5 extends TestCase { + + public void test_for_SpitFire() { + Generic q = new Generic(); + q.setHeader(new Header()); + q.setPayload(new Payload()); + String text = JSON.toJSONString(q, SerializerFeature.WriteClassName); + System.out.println(text); + Generic o = (Generic) JSON.parseObject(text, q.getClass()); + Assert.assertNotNull(o.getPayload()); + } + + public static abstract class AbstractDTO { + } + + public static class Header { + + } + + public static class Payload extends AbstractDTO { + + private String field; + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } + } + + public static class Generic extends AbstractDTO { + + Header header; + T payload; + + public Header getHeader() { + return header; + } + + public void setHeader(Header header) { + this.header = header; + } + + public T getPayload() { + return payload; + } + + public void setPayload(T payload) { + this.payload = payload; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_6.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_6.java new file mode 100755 index 0000000000..ba3b34f32d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_6.java @@ -0,0 +1,78 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_SpitFire_6 extends TestCase { + protected void setUp() throws Exception { + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_SpitFire_6."); + } + + public void test_ref() throws Exception { + GenericRS rs = new GenericRS(); + HotelAvailRS availRs = new HotelAvailRS(); + AvailRoomStayDTO stay = new AvailRoomStayDTO(); + availRs.getHotelAvailRoomStay().getRoomStays().add(stay); + availRs.getHotelAvailRoomStay().getRoomStays().add(stay); + availRs.getHotelAvailRoomStay().getRoomStays().add(stay); + availRs.getHotelAvailRoomStay().getRoomStays().add(stay); + rs.setPayload(availRs); + + String text = JSON.toJSONString(rs, SerializerFeature.WriteClassName, SerializerFeature.PrettyFormat); + System.out.println(text); + + JSON.parseObject(text, GenericRS.class); + } + + public static class GenericRS { + + private T payload; + + public T getPayload() { + return payload; + } + + public void setPayload(T payload) { + this.payload = payload; + } + + } + + public static class HotelAvailRS { + + private HotelAvailRoomStayDTO hotelAvailRoomStay = new HotelAvailRoomStayDTO(); + + public HotelAvailRoomStayDTO getHotelAvailRoomStay() { + return hotelAvailRoomStay; + } + + public void setHotelAvailRoomStay(HotelAvailRoomStayDTO hotelAvailRoomStay) { + this.hotelAvailRoomStay = hotelAvailRoomStay; + } + + } + + public static class HotelAvailRoomStayDTO { + + private List roomStays = new ArrayList(); + + public List getRoomStays() { + return roomStays; + } + + public void setRoomStays(List roomStays) { + this.roomStays = roomStays; + } + + } + + public static class AvailRoomStayDTO { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_agapple.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_agapple.java new file mode 100755 index 0000000000..c58f8d6a4b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_agapple.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Properties; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_agapple extends TestCase { + + public void test_for_agapple() throws Exception { + Entity entity = new Entity(); + entity.setProperties(new Properties()); + String text = JSON.toJSONString(entity); + + JSON.parseObject(text, Entity.class); + } + + private static class Entity { + + private Properties properties; + + public Properties getProperties() { + return properties; + } + + public void setProperties(Properties properties) { + this.properties = properties; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_agapple_2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_agapple_2.java new file mode 100755 index 0000000000..e9af774947 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_agapple_2.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +public class Bug_for_agapple_2 extends TestCase { + + public void test_bug() throws Exception { + DbMediaSource obj = new DbMediaSource(); + obj.setType(DataMediaType.ORACLE); + + JSONObject json = (JSONObject) JSON.toJSON(obj); + Assert.assertEquals("ORACLE", json.get("type")); + } + + public static class DbMediaSource { + + private DataMediaType type; + + public DataMediaType getType() { + return type; + } + + public void setType(DataMediaType type) { + this.type = type; + } + + } + + public static enum DataMediaType { + ORACLE, MYSQL + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_akvadrako.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_akvadrako.java new file mode 100644 index 0000000000..65b63efb6d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_akvadrako.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.parser.DefaultJSONParser; + +public class Bug_for_akvadrako extends TestCase { + + public void testNakedFields() throws Exception { + Naked naked = new Naked(); + DefaultJSONParser parser = new DefaultJSONParser("{ \"field\": 3 }"); + parser.parseObject(naked); + } + + public static class Naked { + + public int field; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_alibank.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_alibank.java new file mode 100755 index 0000000000..97456dd8b9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_alibank.java @@ -0,0 +1,15 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class Bug_for_alibank extends TestCase { + public void test_bug() throws Exception { + String jsonStrz = "{addContact:[{\"address\":\"=\\\\\\\\\\\'\'\\");|]*{%0d%0a<%00\"}]}"; + System.out.println(jsonStrz); + Object o = JSON.parseObject(jsonStrz.replaceAll("\\\\", "")); + System.out.println(JSON.toJSONString(o)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_apollo0317.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_apollo0317.java new file mode 100644 index 0000000000..f7b3f05128 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_apollo0317.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_apollo0317 extends TestCase { + + public void test_for_apollo0317() throws Exception { + String text = "广州市白云区优网通信线缆厂是一家集专业设计、生产、销售、电工解决方案提供为一体的中型企业,旗下主打品牌(简称:普禄克Pluke);公厂拥有自己的研发团队,自主研发改造的高性能电缆生产流水线使产品的性价比大幅度提升,在技术上处于行业领先。\r\n  普禄克Pluke销售服务网络覆盖全国各省市以及南美、东南亚等地区。产品广范应用在军队通信网,政府网,企业网,电信网,电力网,煤炭网,水利网,广电网,校园网 电梯设备、机电设备、汽车、电子、等行业,其中超五类六类网络线缆,彩色网络跳线,设备连接及控制传输电缆,电器连接线多年来获得客户的高度肯定。?普禄克PLUKE在不断创新中为客户创造价值,在工厂战略的指导下,凭借在售前咨询,系统设计,产品采购,工程施工等方面的综合优势和我们多面的工程服务经验,可以根据客户的要求,提供切实可行的技术方案及系统产品。\r\n 工厂未来将着力于商业模式的创新转换,为合作伙伴提供一个共同成长、双赢的、持续发展的商业平台。\r\n 我们企业的宗旨是:销售最好的产品、追求最佳的售后服务、推广最新的办公理念!"; + + VO vo = new VO(); + vo.setBrandintroduction(text); + + Object[] array = new Object[] {vo, vo, vo}; + + String json = JSON.toJSONString(vo, SerializerFeature.DisableCircularReferenceDetect); + System.out.println(json); + } + + public static class VO { + + private String brandintroduction; + + public String getBrandintroduction() { + return brandintroduction; + } + + public void setBrandintroduction(String brandintroduction) { + this.brandintroduction = brandintroduction; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_array.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_array.java new file mode 100755 index 0000000000..0f4f63d7af --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_array.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_array extends TestCase { + public void test_array() throws Exception { + A[] array = new A[] { new B(123, "xxx") }; + + String text = JSON.toJSONString(array); + System.out.println(text); + Assert.assertEquals("[{\"id\":123,\"name\":\"xxx\"}]", text); + } + + public static class A { + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } + + public static class B extends A { + private String name; + + public B() { + + } + + public B (int id, String name) { + setId(id); + setName(name); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ascii_0_31.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ascii_0_31.java new file mode 100755 index 0000000000..795a962946 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ascii_0_31.java @@ -0,0 +1,110 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_ascii_0_31 extends TestCase { + + public void test_0() throws Exception { + for (int i = 0; i < 32; ++i) { + StringBuilder buf = new StringBuilder(); + char ch = (char) i; + buf.append(ch); + + String text = JSON.toJSONString(buf.toString(), SerializerFeature.BrowserCompatible); + + switch (ch) { + case '"': + Assert.assertEquals("\"\\\"\"", text); + break; + case '/': + Assert.assertEquals("\"\\/\"", text); + break; + case '\\': + Assert.assertEquals("\"\\\\\"", text); + break; + case '\b': + Assert.assertEquals("\"\\b\"", text); + break; + case '\f': + Assert.assertEquals("\"\\f\"", text); + break; + case '\n': + Assert.assertEquals("\"\\n\"", text); + break; + case '\r': + Assert.assertEquals("\"\\r\"", text); + break; + case '\t': + Assert.assertEquals("\"\\t\"", text); + break; + default: + if (i < 16) { + Assert.assertEquals("\"\\u000" + Integer.toHexString(i).toUpperCase() + "\"", text); + } else { + Assert.assertEquals("\"\\u00" + Integer.toHexString(i).toUpperCase() + "\"", text); + } + break; + } + + VO vo = new VO(); + vo.setContent(buf.toString()); + + String voText = JSON.toJSONString(vo, SerializerFeature.BrowserCompatible); + + switch (ch) { + case '"': + Assert.assertEquals("{\"content\":\"\\\"\"}", voText); + break; + case '/': + Assert.assertEquals("{\"content\":\"\\/\"}", voText); + break; + case '\\': + Assert.assertEquals("{\"content\":\"\\\\\"}", voText); + break; + case '\b': + Assert.assertEquals("{\"content\":\"\\b\"}", voText); + break; + case '\f': + Assert.assertEquals("{\"content\":\"\\f\"}", voText); + break; + case '\n': + Assert.assertEquals("{\"content\":\"\\n\"}", voText); + break; + case '\r': + Assert.assertEquals("{\"content\":\"\\r\"}", voText); + break; + case '\t': + Assert.assertEquals("{\"content\":\"\\t\"}", voText); + break; + default: + if (i < 16) { + Assert.assertEquals("{\"content\":\"\\u000" + Integer.toHexString(i).toUpperCase() + "\"}", + voText); + } else { + Assert.assertEquals("{\"content\":\"\\u00" + Integer.toHexString(i).toUpperCase() + "\"}", + voText); + } + break; + } + } + + } + + public static class VO { + + private String content; + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_bbl.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_bbl.java new file mode 100755 index 0000000000..d74d14b032 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_bbl.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_bbl extends TestCase { + + public void test_bug() throws Exception { + Map params = new HashMap(); + params.put("msg", + + ""); + params.put("uid", "22034343"); + + String s001 = JSON.toJSONString(params, SerializerFeature.BrowserCompatible); + + System.out.println(s001); + + Map params2 = (Map) JSON.parse(s001); + Assert.assertEquals(params.size(), params2.size()); + Assert.assertEquals(params.get("uid"), params2.get("uid")); + + Assert.assertEquals(params.get("msg"), params2.get("msg")); + Assert.assertEquals(params, params2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_booleanField.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_booleanField.java new file mode 100644 index 0000000000..8d62d30158 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_booleanField.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class Bug_for_booleanField extends TestCase { + + public void test_boolean() throws Exception { + Assert.assertEquals("{\"is-abc\":false}", JSON.toJSONString(new BooleanJson())); + Assert.assertTrue(JSON.parseObject("{\"is-abc\":true}", BooleanJson.class).isAbc()); + } + + public static class BooleanJson { + + @JSONField(name = "is-abc") + private boolean isAbc; + + public boolean isAbc() { + return isAbc; + } + + public void setAbc(boolean value) { + this.isAbc = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_builder.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_builder.java new file mode 100644 index 0000000000..722b524f84 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_builder.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_builder extends TestCase { + + public void test_for_longBuilderMethod() throws Exception { + VO vo = JSON.parseObject("{\"id\":123}", VO.class); + } + + public static class VO { + + private long id; + + public long getId() { + return id; + } + + public VO setId(long id) { + this.id = id; + return this; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_cduym.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_cduym.java new file mode 100755 index 0000000000..910121443a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_cduym.java @@ -0,0 +1,107 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_cduym extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_cduym"); + } + + @SuppressWarnings("rawtypes") + public void test0() { + + List as = new ArrayList(); + + A a1 = new A(); + a1.setA(1000); + a1.setB(2000l); + a1.setC("xxx"); + + as.add(a1); + as.add(a1); + + String text = JSON.toJSONString(as, SerializerFeature.WriteClassName); + System.out.println(text); + List target = (List) JSON.parseObject(text, Object.class); + + Assert.assertSame(target.get(0), target.get(1)); + } + + public void test1() { + + List as = new ArrayList(); + + A a1 = new A(); + a1.setA(1000); + a1.setB(2000l); + a1.setC("xxx"); + + as.add(a1); + as.add(a1); + + Demo o = new Demo(); + o.setAs(as); + + String text = JSON.toJSONString(o, SerializerFeature.WriteClassName); + System.out.println(text); + Demo target = (Demo) JSON.parseObject(text, Object.class); + + Assert.assertSame(((List)target.getAs()).get(0), ((List)target.getAs()).get(1)); + } + + + public static class Demo { + + private Object as; + + public Object getAs() { + return as; + } + + public void setAs(Object as) { + this.as = as; + } + + } + + private static class A { + + private Integer a; + private Long b; + + private String c; + + public Integer getA() { + return a; + } + + public void setA(Integer a) { + this.a = a; + } + + public Long getB() { + return b; + } + + public void setB(Long b) { + this.b = b; + } + + public String getC() { + return c; + } + + public void setC(String c) { + this.c = c; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_chengchao.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_chengchao.java new file mode 100755 index 0000000000..5bacad8553 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_chengchao.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import java.util.concurrent.TimeUnit; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_chengchao extends TestCase { + + public void test_0() throws Exception { + SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, + + SerializerFeature.WriteEnumUsingToString, SerializerFeature.SortField }; + + Entity entity = new Entity(); + JSON.toJSONString(entity, features); + } + + private static class Entity { + + private TimeUnit unit; + + public TimeUnit getUnit() { + return unit; + } + + public void setUnit(TimeUnit unit) { + this.unit = unit; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_cnhans.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_cnhans.java new file mode 100755 index 0000000000..f504ab54c0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_cnhans.java @@ -0,0 +1,99 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_cnhans extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_0() throws Exception { + VO vo = new VO(); + vo.setCalendar(Calendar.getInstance()); + + String text = JSON.toJSONString(vo); + + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertEquals(vo.getCalendar().getTime(), vo1.getCalendar().getTime()); + } + + public void test_format() throws Exception { + VO vo = new VO(); + vo.setCalendar(Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale)); + + String text = JSON.toJSONString(vo, SerializerFeature.WriteDateUseDateFormat); + + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertEquals(vo.getCalendar().get(Calendar.YEAR), vo1.getCalendar().get(Calendar.YEAR)); + Assert.assertEquals(vo.getCalendar().get(Calendar.MONTH), vo1.getCalendar().get(Calendar.MONTH)); + Assert.assertEquals(vo.getCalendar().get(Calendar.DAY_OF_MONTH), vo1.getCalendar().get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(vo.getCalendar().get(Calendar.HOUR_OF_DAY), vo1.getCalendar().get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(vo.getCalendar().get(Calendar.MINUTE), vo1.getCalendar().get(Calendar.MINUTE)); + Assert.assertEquals(vo.getCalendar().get(Calendar.SECOND), vo1.getCalendar().get(Calendar.SECOND)); + } + + public void test_iso_format() throws Exception { + VO vo = new VO(); + vo.setCalendar(Calendar.getInstance()); + + String text = JSON.toJSONString(vo, SerializerFeature.UseISO8601DateFormat); + + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertEquals(vo.getCalendar().get(Calendar.YEAR), vo1.getCalendar().get(Calendar.YEAR)); + Assert.assertEquals(vo.getCalendar().get(Calendar.MONTH), vo1.getCalendar().get(Calendar.MONTH)); + Assert.assertEquals(vo.getCalendar().get(Calendar.DAY_OF_MONTH), vo1.getCalendar().get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(vo.getCalendar().get(Calendar.HOUR_OF_DAY), vo1.getCalendar().get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(vo.getCalendar().get(Calendar.MINUTE), vo1.getCalendar().get(Calendar.MINUTE)); + Assert.assertEquals(vo.getCalendar().get(Calendar.SECOND), vo1.getCalendar().get(Calendar.SECOND)); + } + + public void test_toJavaObject() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("d1", new Date()); + obj.put("d2", System.currentTimeMillis()); + obj.put("d3", GregorianCalendar.getInstance()); + obj.put("d4", "2012-12-22"); + obj.put("d5", "2012-12-22 12:11:11"); + obj.put("d6", "2012-12-22 12:11:11.234"); + + obj.getObject("d1", Calendar.class); + obj.getObject("d2", Calendar.class); + obj.getObject("d3", Calendar.class); + obj.getObject("d4", Calendar.class); + obj.getObject("d5", Calendar.class); + obj.getObject("d6", Calendar.class); + + obj.getObject("d1", GregorianCalendar.class); + obj.getObject("d2", GregorianCalendar.class); + obj.getObject("d3", GregorianCalendar.class); + obj.getObject("d4", GregorianCalendar.class); + obj.getObject("d5", GregorianCalendar.class); + obj.getObject("d6", GregorianCalendar.class); + } + + public static class VO { + + private Calendar calendar; + + public Calendar getCalendar() { + return calendar; + } + + public void setCalendar(Calendar calendar) { + this.calendar = calendar; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dargoner.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dargoner.java new file mode 100755 index 0000000000..7f9efa140b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dargoner.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.json.bvtVO.DataTransaction; + + +public class Bug_for_dargoner extends TestCase { + public void test_0 () throws Exception { + DataTransaction dt = new DataTransaction(); + + List> list = new ArrayList>(); + + Map m = new HashMap(); + m.put("name", "tom"); + m.put("sex", "m"); + list.add(m); + + dt.setDataSet("1000", list); + dt.setRetMsgCode("1", "ok"); + dt.getHead().setAppid("back"); + dt.getHead().setSeqno("201010"); + dt.getHead().getUser().setId("root"); + + Map m2 = new HashMap(); + m2.put("name1", "tom"); + m2.put("name2", "tom"); + m2.put("name3", "tom"); + + dt.getBody().getParam().setForm(m2); + + System.out.println(dt.toJSON()); + + DataTransaction dt2 = DataTransaction.fromJSON(dt.toJSON()); + System.out.println(dt2.toJSON()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_divde_zero.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_divde_zero.java new file mode 100755 index 0000000000..22d713e927 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_divde_zero.java @@ -0,0 +1,14 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + + +public class Bug_for_divde_zero extends TestCase { + public void test_divideZero() throws Exception { + Double d = 1.0D / 0.0D; + String text = JSON.toJSONString(d); + System.out.println(text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dongqi.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dongqi.java new file mode 100644 index 0000000000..16a09a628b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dongqi.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class Bug_for_dongqi extends TestCase { + public void test_bug() throws Exception { + Map obj = new HashMap(); + obj.put("value", ";\r\n3、ž 公"); + System.out.print(JSON.toJSONString(obj)); + Assert.assertEquals("{\"value\":\";\\r\\n3、\\u009E 公\"}", JSON.toJSONString(obj)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon.java new file mode 100755 index 0000000000..a19cb3cac2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon.java @@ -0,0 +1,12 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_dragoon extends TestCase { + public void test_for_dragoon() throws Exception { + String text = "[{\"S\":93803,\"T\":\"HSMonitorData\"},{\"D\":\"H4sIAAAAAAAAAO1b3W8bxxF/7n9xvRqFipKX+ySPBARYkdVGqS2pEu0UJQVhebckzzzeXu9DNqPqIQECpCiaBG0fWthNH2oDRT8egqKI4LTxP2Pazn+R2d078sQvW7KdWMFakMib2f3N7M7szNzduHkkozDcSgdyXfaS9KD37gHyw4MExX25JDvE97GTXEEJluuaYZo1Q63o1ZphAy/CQJ5i2bah5ayGN8DXPN+PZ/g4SCIPA/1IXidpkMh1vSRfRXHS6EXk1hSkVjOsAvcajmPUhQHyRhSRSBqQwEvg0yddRWpGOCRRsumuchUOSOTiqCRFqY/XSdDxuqsOGSjI99qojZRsruIwlrI7HnXZcNp6260ZTTrzZ3i4Sj8VhvZGGtzCuI8D941aWbNLMNn1Eo8E8erR+Ltyi0R9Fw2XiQvJTaJc47T1fOLlKmo7mqtWStIErEfS6OxIlqlZbcN1i0gDL0gTHJ8DzHGNmmu2j0vIyRbLvyi3UNClv8+LucamXXYdDWsOLkkZDB4gzz8jhmE4HaRX1WNqhASAcAR6HZcY1lUvTlab+6UBaXs+zq9ybfNratfn84lL9Otls63ZGjKa+UZqailIB20cbXeov8erFmBi5PMLteTFMDuBwXi1g/wYgz7cgVd/2dgefXhn9MWD0f/eH52cfF9qBU+//MPog/v1o5YcwRKifkuut2Q37rTkUkt2UNQlW2iAM6rLyQlJkL/FVACGYQCJrn6LsGGabphWhQ2MwWPZGIBHrhuBGnARpL4PzCDH/eqffxp9+fmTB//hMskgRMFwLPXRyb9Hd/6/9sMbj+/+5qs/fzL64F+jj0/YyDAih17g8GGjzz57dHL3yd33OIiXDDn57+89/u/no5P3M2w4+Zzx9Hd/e/zhJzmDG2yiW0jiZJ24RUqPBFySalWr5YplWHSZZTYdDLmTKZPNasm6bVZz5jqoU2DUzDGDKVRk2S35GHjtNPYC2K4tnNBjzbY21wQNG8Mw04UBQRwC1/KczSuMuHZVtVX4Z9hVCgcDvCBOIwTa7USeU1jUmH4D+WmBTpIejqbGhsjpgw/t4ehwCX1qEvOUG8RPmTFVRc1p72Cv20uApnEaaBHTMDo1H7boerYqA6JyTTWzFXUHYJ/BwGMQNGzrFdXUYdG5gCmgCDvYO5z1RfDRmH4p+mNOmPbEnD7td0/vP5z1u3v/GH301zl+N/r43qMH92b8Lj82JniVxqUsdMHJ3sw6XVW35ztdVa8tcrqqoXGnG2B6pMfOtf6LRr7eAaHBbyKbHuy9BEUJjTmnyRuBe5qYe+c6387MnBCKQCjEn4d/HN35lBplMzgkfVxEBd1UTVdtDbKKpeqabWs/pq7NtOLD12GXstFVIMLsJI25kbMFWiqNT1kKZ6CZq0rXA3QIYQu1qQXo+ncx+GAQYwrQPHpRNExrhQMn32aYyfTm5EEBoZckoeSx5UgekdiAutSDlUGoV3RVgfUrFUvCtx0cUjvUH//290+++MvTh58+/ug+B81ZLwXweP94X/q1hAgK+WQpZjshrPSaWQnK5Ws46REXSlOXXCVdIMB2OP1GhBxar7YCo6KptmmqptSkZiqrdlkzJc2CParr2r5UliSp6YWrULDiDvxNEfyJPXd1vxVI0sbu7vau5CiTGiUrnXg19BYKXB9HzVNXyk3Y4nqlSrFFvSzqZVEvi3pZ1MuiXhb1sqiXv7OVGFRLxQyF/FBBLgoh2ynEwQgKJt/bDnGwtrO5MUYRFfZrb9dW8D2USItMG/M1K9vUxGucmO3D5iD0lS5OdqHQeJO4w5VFY1i1XDV+JDULyGUI84pa3tta29l7a7sBg6L6adL+i2nGa+/lSmn2ebWK00CB2wn6HF/5KQ5wBLJcfqey5jhgchJppqpw06xcD/oBuRVIe1BCOxhEBqgeoDlQV7CPuwgqte5pLKZyBrZ0DFuWbnERYHpFPdCtTBDlKT6UnWNxHCAHzq4YhFWrzsUgUVeJwwiEdyLIgrQSURAJlTgNabJW1kh4PfH8OMN8m3hBCL/JdSheurtcLLjhyngck2aoVFrMdqcDInAmo6wrFsjf21hXdWaLwvUzFJpc5VIPMV8gDScOYuX+lJIrS4Zm/qJ/K3pCvnUwdp+tn1k7r37FY+ZGqEuoWJRExM8wlCucmkuG00JjCtyk5H65iM9VU6lqGXIZpMEtDqhVUWym0Pg0fDP7VNVenR3fdvtXhlA6eg44OdRjt4f5Ds3h8POqmudV5xKDsew83C2NNNOhtO29y58mjIPpxu3kalacxduUMxtRZ4asLJ3EFsiOTSbxpYZYwxIhVoRYEWJFiH3lIba2MP69opjLtT9r0C2s2TpP1J2nb36/Ho91HosuhPpLhuKSzaBBH9zwx6kr84Zx3UzNOIdy8zwjmcgbh8iCDg0MMmEHFXwbOylkyHk87rG6/TJO9tk2bWJfZsQ3h+xj012ydUZNfVXZ1BDZVGRTkU1FNn3V2bSiLgx8Z8qmAUm8zpBFWMiovez17DqDZoANFPfzt7bZohZw+bnOUX2012-08-14 15:51:13+Yp4HMnz9Pq5XlgzQ+3GGOP0YsBPk9SS4bwp2nVl6FnTDqJgvAExelhN0W+wmVvMGXgPERpsDJF4km8QrWA+bSxNQNhOpw6ICyKpxA76dtMJ40iHECG7oEV3B1C/Bzy0jvgi5gJo2ZZmR2R3UvalcXJ4kxiFoqoqfYz8hGfWQDJWgIq+sxEuSTT9ydyXT7z43P5uCTTZ7n0fRPMPxyUf4XKTlDWTK2sVVWlFydK+6aj9DsOBXYdJcAJyPMCmMOajycXG7fPhBDC6MkTZBgKxOyl9GaCB5uuXK9UtZptnSLThVLWhMr9l4umtRZEC6aDZtXKtQqAhh5t7dA1XacisiPSQF0gqoa68ZOf0+YOVVUrVfsHGmzIBeis1o25ndVcSvYypE3coRThOPUT8UbkNXsjUuw54kZb1HRk1IwXbDqiP/GidxjN5S8vakyOcKsL4lbPkwqe8VJLJIQLmRCotDkJIUS0BAcLS5nr0nYwyYslPAiTYTEK0S4KqA8S5PfjxQ2Q1RdtgFT4XY6SiSpGollSViqZFH/5ShY5/qTJbYFU4e4X0t2fp/5hHhOLJkPRZCiaDEWT4TfdZCj+68cFqJcvzG2YOnMbJrKbyG4iu4ns9m210ItG7e9gPhSN2qJRW/Q9iL4H0fdwcfseRKO2CLEixIoQK0KsaNQWjdqiUVs0aotsKrKpyKavbTYVjdqiUVs0aotG7TM3Ku1/DWGrUgYEWwAA\"}]"; + JSON.parse(text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon26.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon26.java new file mode 100755 index 0000000000..017ef81577 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon26.java @@ -0,0 +1,179 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_dragoon26 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_dragoon26"); + } + + public void test_0() throws Exception { + MonitorConfigMessage message = new MonitorConfigMessage(); + MonitorConfig config = new MonitorConfig(); + message.setContent(config); + + AlarmReceiver receiver1 = new AlarmReceiver(2001L); + AlarmReceiver receiver2 = new AlarmReceiver(2002L); + AlarmReceiver receiver3 = new AlarmReceiver(2003L); + + ArrayList items = new ArrayList(); + { + MonitorItem item1 = new MonitorItem(); + item1.setId(1001L); + + MonitorItemAlarmRule rule = new MonitorItemAlarmRule(); + + rule.getAlarmReceivers().add(receiver1); + rule.getAlarmReceivers().add(receiver2); + + item1.getRules().add(rule); + items.add(item1); + } + + { + + MonitorItem item = new MonitorItem(); + item.setId(1002L); + + MonitorItemAlarmRule rule = new MonitorItemAlarmRule(); + + rule.getAlarmReceivers().add(receiver1); + rule.getAlarmReceivers().add(receiver3); + + item.getRules().add(rule); + items.add(item); + } + { + + MonitorItem item = new MonitorItem(); + item.setId(1003L); + + MonitorItemAlarmRule rule = new MonitorItemAlarmRule(); + + rule.getAlarmReceivers().add(receiver2); + rule.getAlarmReceivers().add(receiver3); + + item.getRules().add(rule); + items.add(item); + } + + config.setMonitorItems(items); + + String text = JSON.toJSONString(message, SerializerFeature.WriteClassName); + System.out.println(JSON.toJSONString(message, SerializerFeature.WriteClassName, SerializerFeature.PrettyFormat)); + + MonitorConfigMessage message2 = (MonitorConfigMessage) JSON.parse(text); + System.out.println(JSON.toJSONString(message2, SerializerFeature.WriteClassName, SerializerFeature.PrettyFormat)); + } + + public static class MonitorConfigMessage { + + private Object content; + + public Object getContent() { + return content; + } + + public void setContent(Object content) { + this.content = content; + } + + } + + public static class MonitorConfig { + + private Map monitorItems = new HashMap(); + + @JSONField(name = "MonitorItems") + public Collection getMonitorItems() { + return monitorItems.values(); + } + + @JSONField(name = "MonitorItems") + public void setMonitorItems(Collection items) { + for (MonitorItem item : items) { + this.monitorItems.put(item.getId(), item); + } + } + } + + public static class MonitorItem extends MonitorItemBase { + + } + + public static class MonitorItemBase { + + private Long id; + private List rules = new ArrayList(); + + @JSONField(name = "mid") + public Long getId() { + return id; + } + + @JSONField(name = "mid") + public void setId(Long id) { + this.id = id; + } + + public List getRules() { + return rules; + } + + public void setRules(List rules) { + this.rules = rules; + } + + } + + public static class AlarmRuleBase { + + } + + public static class MonitorItemAlarmRule extends AlarmRuleBase { + + private List alarmReceivers = new ArrayList(); + + public List getAlarmReceivers() { + return alarmReceivers; + } + + public void setAlarmReceivers(List alarmReceivers) { + this.alarmReceivers = alarmReceivers; + } + + } + + public static class AlarmReceiver { + + private Long id; + + public AlarmReceiver(){ + + } + + public AlarmReceiver(Long id){ + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon26_1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon26_1.java new file mode 100755 index 0000000000..f36289646e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon26_1.java @@ -0,0 +1,78 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_dragoon26_1 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_dragoon26_1"); + } + + public void test_0() throws Exception { + + List rules = new ArrayList(); + + AlarmReceiver receiver1 = new AlarmReceiver(1L); + + { + MonitorItemAlarmRule rule = new MonitorItemAlarmRule(); + + rule.getAlarmReceivers().add(receiver1); + rules.add(rule); + } + { + MonitorItemAlarmRule rule = new MonitorItemAlarmRule(); + + rule.getAlarmReceivers().add(receiver1); + rules.add(rule); + } + + String text = JSON.toJSONString(rules, SerializerFeature.WriteClassName); + System.out.println(JSON.toJSONString(rules, SerializerFeature.WriteClassName, SerializerFeature.PrettyFormat)); + + List message2 = (List) JSON.parse(text); + System.out.println(JSON.toJSONString(message2, SerializerFeature.WriteClassName, SerializerFeature.PrettyFormat)); + } + + public static class MonitorItemAlarmRule { + + private List alarmReceivers = new ArrayList(); + + public List getAlarmReceivers() { + return alarmReceivers; + } + + public void setAlarmReceivers(List alarmReceivers) { + this.alarmReceivers = alarmReceivers; + } + + } + + public static class AlarmReceiver { + + private Long id; + + public AlarmReceiver(){ + + } + + public AlarmReceiver(Long id){ + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo.java new file mode 100755 index 0000000000..ad1d176063 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.test.dubbo.HelloServiceImpl; +import com.alibaba.json.test.dubbo.Tiger; +import com.alibaba.json.test.dubbo.Tigers; + + +public class Bug_for_dubbo extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.test.dubbo.Tigers"); + } + + public void test_0 () throws Exception { + HelloServiceImpl helloService = new HelloServiceImpl(); + + Tiger tiger = new Tiger(); + tiger.setTigerName("东北虎"); + tiger.setTigerSex(true); + //Tiger tigers = helloService.eatTiger(tiger).getTiger(); + + Tigers tigers = helloService.eatTiger(tiger); + Assert.assertNotNull(tigers.getTiger()); + + String text = JSON.toJSONString(tigers, SerializerFeature.WriteClassName); + + System.out.println(text); + Tigers tigers1 = (Tigers) JSON.parse(text); + Assert.assertNotNull(tigers1.getTiger()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo1.java new file mode 100755 index 0000000000..9dc0c72476 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo1.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_dubbo1 extends TestCase { + + public void test_0() throws Exception { + String text; + { + HashSet tigers = new HashSet(); + tigers.add("老虎二"); + tigers.add("老虎大"); + HashMap> tiger = new HashMap>(); + tiger.put("老鼠", tigers); + + text = JSON.toJSONString(tiger, SerializerFeature.WriteClassName); + } + + System.out.println(text); + + HashMap> tigger2 = (HashMap>) JSON.parse(text); + Assert.assertEquals(1, tigger2.size()); + Assert.assertEquals(2, tigger2.get("老鼠").size()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo2.java new file mode 100755 index 0000000000..88d7245c95 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo2.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; + +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_dubbo2 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_dubbo2"); + } + + public void test_emptyHashMap() throws Exception { + VO vo = new VO(); + vo.setValue(new HashMap()); + String text = JSON.toJSONString(vo, SerializerFeature.WriteClassName); + JSON.parse(text); + } + + public static class VO { + private Object value; + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo3.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo3.java new file mode 100755 index 0000000000..6678eaf7db --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo3.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_dubbo3 extends TestCase { + + public void test_0() throws Exception { + String text; + { + HashSet tigers = new HashSet(); + tigers.add("老虎二"); + tigers.add("老虎大"); + HashMap> tiger = new HashMap>(); + tiger.put("老鼠", tigers); + + text = JSON.toJSONString(tiger, SerializerFeature.WriteClassName); + } + + System.out.println(text); + + HashMap> tigger2 = (HashMap>) JSON.parseObject(text, Map.class); + Assert.assertEquals(1, tigger2.size()); + Assert.assertEquals(2, tigger2.get("老鼠").size()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo_long.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo_long.java new file mode 100755 index 0000000000..8912bba332 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo_long.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_dubbo_long extends TestCase { + + public void test_0() throws Exception { + Long val = 2345L; + + String text = JSON.toJSONString(val, SerializerFeature.WriteClassName); + Assert.assertEquals(val, JSON.parseObject(text, long.class)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_field.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_field.java new file mode 100755 index 0000000000..37498ce4a8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_field.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_field extends TestCase { + + public void test_annotation() throws Exception { + VO vo = new VO(); + vo.setId(123); + + String text = JSON.toJSONString(vo); + + System.out.println(text); + } + + public static class VO { + + @JSONField(name = "ID", serialzeFeatures={SerializerFeature.WriteClassName}) + private long id; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_franklee77.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_franklee77.java new file mode 100755 index 0000000000..991d93c8e9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_franklee77.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_franklee77 extends TestCase { + + public void test_0() throws Exception { + VO vo = JSON.parseObject("{\"id\":33}", VO.class); + Assert.assertEquals(33, vo.getId()); + + } + + public static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + private VO(){ + + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_fushou.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_fushou.java new file mode 100644 index 0000000000..8fb0e7922d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_fushou.java @@ -0,0 +1,72 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; +import org.junit.Test; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.Assert; + +import java.util.List; + +public class Bug_for_fushou extends TestCase{ + + public void test_case1() { + String text = "{\"modules\":{}}"; + L1 r1 = JSONObject.parseObject(text, new TypeReference>() { + }); + assertEquals(true, r1.getModules() instanceof L2); + + L1 r2 = JSONObject.parseObject(text, new TypeReference() { + }); + assertEquals(true, r2.getModules() instanceof JSONObject); + assertEquals(false, r2.getModules() instanceof L2); + } + + public void test_case2() { + String text = "{\"modules\":{}}"; + L1 r0 = JSONObject.parseObject(text, new TypeReference() { + }); + assertEquals(JSONObject.class, r0.getModules().getClass()); + + L1 r1 = JSONObject.parseObject(text, new TypeReference>() { + }); + assertEquals(L2.class, r1.getModules().getClass()); + + L1 r2 = JSONObject.parseObject(text, new TypeReference() { + }); + assertEquals(JSONObject.class, r2.getModules().getClass()); + + L1 r3 = JSONObject.parseObject(text, new TypeReference>() { + }); + assertEquals(L3.class, r3.getModules().getClass()); + } + + public static class L1 { + private T modules; + + public T getModules() { + return modules; + } + + public void setModules(T modules) { + this.modules = modules; + } + } + + public static class L2 { + public String name; + + public L2() { + + } + } + + public static class L3 { + + public L3() { + + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic.java new file mode 100755 index 0000000000..daee8f4ed6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic.java @@ -0,0 +1,316 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_generic extends TestCase { + + protected void setUp() throws Exception { + ParserConfig.global.addAccept("NotifyDetail"); + } + + public void test() throws Exception { + String json = "{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_generic$NotifyDetail\",\"args\":[\"61354557\",\"依依\",\"六\"],\"destId\":60721687,\"detailId\":3155063,\"display\":false,\"foundTime\":{\"@type\":\"java.sql.Timestamp\",\"val\":1344530416000},\"hotId\":0,\"srcId\":1000,\"templateId\":482}"; + JSON.parseObject(json, NotifyDetail.class); + System.out.println("NotifyDetail对象没问题"); + String json2 = "{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_generic$Pagination\",\"fromIndex\":0,\"list\":[{\"@type\":\"NotifyDetail\",\"args\":[\"61354557\",\"依依\",\"六\"],\"destId\":60721687,\"detailId\":3155063,\"display\":false,\"foundTime\":{\"@type\":\"java.sql.Timestamp\",\"val\":1344530416000},\"hotId\":0,\"srcId\":1000,\"templateId\":482},{\"@type\":\"NotifyDetail\",\"args\":[\"14527269\",\"懒洋洋\",\"///最佳拍档,非常\",\"24472950\"],\"destId\":60721687,\"detailId\":3151609,\"display\":false,\"foundTime\":{\"@type\":\"java.sql.Timestamp\",\"val\":1344354485000},\"hotId\":0,\"srcId\":1000,\"templateId\":40},{\"@type\":\"NotifyDetail\",\"args\":[\"51090218\",\"天之涯\",\"天会黑,人会变。三分\"],\"destId\":60721687,\"detailId\":3149221,\"display\":false,\"foundTime\":{\"@type\":\"java.sql.Timestamp\",\"val\":1344247529000},\"hotId\":0,\"srcId\":1000,\"templateId\":459},{\"@type\":\"NotifyDetail\",\"args\":[\"51687981\",\"摹然回首梦已成年\",\"星星在哪里都很亮的,\"],\"destId\":60721687,\"detailId\":3149173,\"display\":false,\"foundTime\":{\"@type\":\"java.sql.Timestamp\",\"val\":1344247414000},\"hotId\":0,\"srcId\":1000,\"templateId\":459},{\"@type\":\"NotifyDetail\",\"args\":[\"41486427\",\"寒江蓑笠\",\"双休了\"],\"destId\":60721687,\"detailId\":3148148,\"display\":false,\"foundTime\":{\"@type\":\"java.sql.Timestamp\",\"val\":1344244730000},\"hotId\":0,\"srcId\":1000,\"templateId\":459}],\"maxLength\":5,\"nextPage\":2,\"pageIndex\":1,\"prevPage\":1,\"toIndex\":5,\"totalPage\":3,\"totalResult\":13}"; + JSON.parseObject(json2, Pagination.class); + } + + public static class Pagination implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 5038839734218582220L; + + private int totalResult = 0; + + private int totalPage = 1; + + private int pageIndex = 1; + + private int maxLength = 5; + + private int fromIndex = 0; + + private int toIndex = 0; + + private List list = new ArrayList(); + + public Pagination(){ + + } + + public void setTotalResult(int totalResult) { + this.totalResult = totalResult; + } + + public void setTotalPage(int totalPage) { + this.totalPage = totalPage; + } + + public void setPageIndex(int pageIndex) { + this.pageIndex = pageIndex; + } + + public void setMaxLength(int maxLength) { + this.maxLength = maxLength; + } + + public void setFromIndex(int fromIndex) { + this.fromIndex = fromIndex; + } + + public void setToIndex(int toIndex) { + this.toIndex = toIndex; + } + + public int getFromIndex() { + return this.fromIndex; + } + + public int getToIndex() { + return this.toIndex; + } + + public int getNextPage() { + if (this.pageIndex < this.totalPage) { + return this.pageIndex + 1; + } else { + return this.pageIndex; + } + } + + public int getPrevPage() { + if (this.pageIndex > 1) { + return this.pageIndex - 1; + } + return this.pageIndex; + } + + /** + * @return the currentPage + */ + public int getPageIndex() { + return pageIndex; + } + + /** + * @return the list + */ + public List getList() { + if (list == null) { + return new ArrayList(); + } + return new ArrayList(list); + } + + /** + * @return the totalPage + */ + public int getTotalPage() { + return totalPage; + } + + /** + * @return the totalRecord + */ + public int getTotalResult() { + return totalResult; + } + + public int getMaxLength() { + return maxLength; + } + + /** + * @param totalResult + * @param pageIndex + * @param maxLength + */ + public Pagination(int totalResult, int pageIndex, int maxLength){ + if (maxLength > 0) { + this.maxLength = maxLength; + } + if (totalResult > 0) { + this.totalResult = totalResult; + } + if (pageIndex > 0) { + this.pageIndex = pageIndex; + } + this.totalPage = this.totalResult / this.maxLength; + if (this.totalResult % this.maxLength != 0) { + this.totalPage = this.totalPage + 1; + } + if (this.totalPage == 0) { + this.totalPage = 1; + } + if (this.pageIndex > this.totalPage) { + this.pageIndex = this.totalPage; + } + if (this.pageIndex <= 0) { + this.pageIndex = 1; + } + this.fromIndex = (this.pageIndex - 1) * maxLength; + this.toIndex = this.fromIndex + maxLength; + if (this.toIndex < 0) { + this.toIndex = fromIndex; + } + if (this.toIndex > this.totalResult) { + this.toIndex = this.totalResult; + } + + } + + /** + * @param datas the datas to set + */ + public void setList(List list) { + this.list = list; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("Pagination:\r\n"); + sb.append("\tpageIndex\t" + this.pageIndex + "\r\n"); + sb.append("\ttotalPage\t" + this.totalPage + "\r\n"); + sb.append("\tmaxLength\t" + this.maxLength + "\r\n"); + sb.append("\ttotalResult\t" + this.totalResult + "\r\n"); + for (T t : list) { + sb.append(t + "\r\n"); + } + return sb.toString(); + } + + } + + public static class NotifyDetail implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 8760630447394929224L; + + private int detailId; + + private int hotId; + + private int templateId; + + private int srcId; + + private int destId; + + private boolean display; + + private java.sql.Date foundTime; + + private List args = new ArrayList(); + + public int getDetailId() { + return detailId; + } + + public void setDetailId(int detailId) { + this.detailId = detailId; + } + + public int getHotId() { + return hotId; + } + + public void setHotId(int hotId) { + this.hotId = hotId; + } + + public int getTemplateId() { + return templateId; + } + + public List getArgs() { + return args; + } + + public void setArgs(List args) { + this.args = args; + } + + public void setTemplateId(int templateId) { + this.templateId = templateId; + } + + public int getSrcId() { + return srcId; + } + + public void setSrcId(int srcId) { + this.srcId = srcId; + } + + public int getDestId() { + return destId; + } + + public void setDestId(int destId) { + this.destId = destId; + } + + public boolean isDisplay() { + return display; + } + + public void setDisplay(boolean display) { + this.display = display; + } + + public java.sql.Date getFoundTime() { + return foundTime; + } + + public void setFoundTime(java.sql.Date foundTime) { + this.foundTime = foundTime; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + int hasCode = 0; + if (this.detailId != 0) { + hasCode += this.detailId; + } + return hasCode; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof NotifyDetail)) { + return false; + } + return this.hashCode() == obj.hashCode(); + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic_1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic_1.java new file mode 100755 index 0000000000..b2d85de76b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic_1.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; +import cn.com.tx.domain.notifyDetail.NotifyDetail; +import cn.com.tx.domain.pagination.Pagination; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class Bug_for_generic_1 extends TestCase { + + public void test() { + String json2 = "{\"@type\":\"cn.com.tx.domain.pagination.Pagination\",\"fromIndex\":0,\"list\":[{\"@type\":\"cn.com.tx.domain.notifyDetail.NotifyDetail\",\"args\":[\"61354557\",\"依依\",\"六\"],\"destId\":60721687,\"detailId\":3155063,\"display\":false,\"foundTime\":{\"@type\":\"java.sql.Timestamp\",\"val\":1344530416000},\"hotId\":0,\"srcId\":1000,\"templateId\":482},{\"@type\":\"cn.com.tx.domain.notifyDetail.NotifyDetail\",\"args\":[\"14527269\",\"懒洋洋\",\"///最佳拍档,非常\",\"24472950\"],\"destId\":60721687,\"detailId\":3151609,\"display\":false,\"foundTime\":{\"@type\":\"java.sql.Timestamp\",\"val\":1344354485000},\"hotId\":0,\"srcId\":1000,\"templateId\":40},{\"@type\":\"cn.com.tx.domain.notifyDetail.NotifyDetail\",\"args\":[\"51090218\",\"天之涯\",\"天会黑,人会变。三分\"],\"destId\":60721687,\"detailId\":3149221,\"display\":false,\"foundTime\":{\"@type\":\"java.sql.Timestamp\",\"val\":1344247529000},\"hotId\":0,\"srcId\":1000,\"templateId\":459},{\"@type\":\"cn.com.tx.domain.notifyDetail.NotifyDetail\",\"args\":[\"51687981\",\"摹然回首梦已成年\",\"星星在哪里都很亮的,\"],\"destId\":60721687,\"detailId\":3149173,\"display\":false,\"foundTime\":{\"@type\":\"java.sql.Timestamp\",\"val\":1344247414000},\"hotId\":0,\"srcId\":1000,\"templateId\":459},{\"@type\":\"cn.com.tx.domain.notifyDetail.NotifyDetail\",\"args\":[\"41486427\",\"寒江蓑笠\",\"双休了\"],\"destId\":60721687,\"detailId\":3148148,\"display\":false,\"foundTime\":{\"@type\":\"java.sql.Timestamp\",\"val\":1344244730000},\"hotId\":0,\"srcId\":1000,\"templateId\":459}],\"maxLength\":5,\"nextPage\":2,\"pageIndex\":1,\"prevPage\":1,\"toIndex\":5,\"totalPage\":3,\"totalResult\":13}"; + cn.com.tx.domain.pagination.Pagination pagination = JSON.parseObject(json2, + new TypeReference>() { + }); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic_huansi.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic_huansi.java new file mode 100644 index 0000000000..cb02598286 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic_huansi.java @@ -0,0 +1,43 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 19/12/2016. + */ +public class Bug_for_generic_huansi extends TestCase { + public void test_for_issue() throws Exception { + String jsonStr = "{\"id\": 1234}"; + + SimpleGenericObject jsonObj = JSON.parseObject(jsonStr, SimpleGenericObject.class); + + try { + Long id = jsonObj.getId(); + assertTrue(id.equals(1234L)); + } catch (Exception e) { + fail("parse error:" + e.getMessage()); + } + } + + public static class BaseGenericType { + + private T id; + + public T getId() { + return id; + } + + public void setId(T id) { + this.id = id; + } + + } + + public static class ExtendGenericType extends BaseGenericType { + } + + public static class SimpleGenericObject extends ExtendGenericType { + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_gongwenhua.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_gongwenhua.java new file mode 100644 index 0000000000..180b62fedd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_gongwenhua.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; + +public class Bug_for_gongwenhua extends TestCase { + + public void test_0() throws Exception { + String text = "{\"FH2\\\"\u0005\\v\u0010\u000e\u0011\u0000\":0,\"alipa9_login\":0,\"alipay_login\":14164,\"durex\":317,\"intl.datasky\":0,\"taobao_refund\":880}"; + + JSONObject obj = JSONObject.parseObject(text); + Assert.assertNotNull(obj); + Assert.assertEquals(0, obj.get("FH2\"\u0005\u000B\u0010\u000e\u0011\u0000")); + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_hifor_issue_511.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_hifor_issue_511.java new file mode 100644 index 0000000000..d80c90e473 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_hifor_issue_511.java @@ -0,0 +1,198 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Date; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class Bug_for_hifor_issue_511 extends TestCase { + + public void test_for_issue() throws Exception { + String resultString = "{" + + " \"errCode\": 0, " + + " \"errMsg\": \"ok\", " + + " \"model\": {" + + " \"doctor\": {" + + " \"duty\": \"副主任医师\", " + + " \"glide\": \"20051010082558\", " + + " \"mark\": \"0703010000\", " + + " \"name\": \"某某某\", " + + " \"office\": \"小儿骨科\"" + + " }, " + + " \"patientInfoList\": [" + + " {" + + " \"patient_Master_Card\": 1, " + + " \"patient_addDate\": 1451097938410, " + + " \"patient_age\": 30, " + + " \"patient_id\": 347, " + + " \"patient_idCard\": \"123321\", " + + " \"patient_name\": \"张三\", " + + " \"patient_s_ic_no\": \"123321\", " + + " \"patient_sex\": \"1\", " + + " \"patient_tel\": \"123\", " + + " \"patient_userId\": 2, " + + " \"s_ic_no\": \"123321\"" + + " }, " + + " {" + + " \"patient_Master_Card\": 0, " + + " \"patient_addDate\": 1454296296847, " + + " \"patient_age\": 23, " + + " \"patient_id\": 598, " + + " \"patient_idCard\": \"123123\", " + + " \"patient_name\": \"李四\", " + + " \"patient_s_ic_no\": \"F10020000615011\", " + + " \"patient_sex\": \"1\", " + + " \"patient_tel\": \"18065212123\", " + + " \"patient_userId\": 2, " + + " \"s_ic_no\": \"F10020000615011\"" + + " }" + + " ]" + + " }" + + "}"; + + TResult result = JSON.parseObject(resultString, new TypeReference>() { }); + Assert.assertSame(BookConfirmVo.class, result.model.getClass()); + } + + public static class TResult { + int errCode = 0; + String errMsg = "ok"; + List data = null; + String stringData; + Integer intData; + T model; + String url; + + public int getErrCode() { + return errCode; + } + + public void setErrCode(int errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } + + public List getData() { + return data; + } + + public void setData(List data) { + this.data = data; + } + + public String getStringData() { + return stringData; + } + + public void setStringData(String stringData) { + this.stringData = stringData; + } + + public Integer getIntData() { + return intData; + } + + public void setIntData(Integer intData) { + this.intData = intData; + } + + public T getModel() { + return model; + } + + public void setModel(T model) { + this.model = model; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + + } + + public static class BookConfirmVo { + + String selectDay; + String selectTime; + VW_NRE_Doctor doctor; + List patientInfoList; + } + + public static class VW_NRE_Doctor { + + String glide; + String name; + String office; + String mark; + String duty; + byte[] pic; + } + + public static class PatientInfoVo extends PatientInfo { + + String cols; + String glide; + String s_ic_no; + + // 注解禁止序列化 + @JSONField(serialize = false) + public String getCols() { + return cols; + } + + // 注解禁止反序列化 + @JSONField(deserialize = false) + public void setCols(String cols) { + this.cols = cols; + } + + public String getGlide() { + return glide; + } + + public void setGlide(String glide) { + this.glide = glide; + } + + public String getS_ic_no() { + return s_ic_no; + } + + public void setS_ic_no(String s_ic_no) { + this.s_ic_no = s_ic_no; + } + } + + public static class PatientInfo { + + Integer patient_id; + Integer patient_userId; + String patient_name; + String patient_sex; + Integer patient_age; + String patient_tel; + String patient_idCard; + Date patient_addDate; + Date patient_Date; + String patient_s_ic_no; + Integer patient_Master_Card; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_hmy8.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_hmy8.java new file mode 100755 index 0000000000..97dbe33e00 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_hmy8.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvtVO.IEvent; +import com.alibaba.json.bvtVO.IEventDto; + +public class Bug_for_hmy8 extends TestCase { + + public void test_ser() throws Exception { + IEventDto dto = new IEventDto(); + dto.getEventList().add(new IEvent()); + + JSON.toJSONString(dto); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_huangchun.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_huangchun.java new file mode 100755 index 0000000000..59e93982fc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_huangchun.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + + +public class Bug_for_huangchun extends TestCase { + public void test_serialize_url() throws Exception { + JSONObject json = new JSONObject(); + json.put("info", " 问题链接 "); + String text = JSON.toJSONString(json); + System.out.println(text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_huling.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_huling.java new file mode 100755 index 0000000000..c81c9ce67a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_huling.java @@ -0,0 +1,80 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_huling extends TestCase { + + public void test_for_0() throws Exception { + VO vo = new VO(); + vo.setValue("\0\0"); + + Assert.assertEquals('\0', vo.getValue().charAt(0)); + + String text = JSON.toJSONString(vo); + System.out.println(text); + Assert.assertEquals("{\"value\":\"\\u0000\\u0000\"}", text); + + VO vo2 = JSON.parseObject(text, VO.class); + Assert.assertEquals("\0\0", vo2.getValue()); + } + + public void test_for_1() throws Exception { + VO vo = new VO(); + vo.setValue("\1\1"); + + Assert.assertEquals('\1', vo.getValue().charAt(0)); + + String text = JSON.toJSONString(vo); + System.out.println(text); + Assert.assertEquals("{\"value\":\"\\u0001\\u0001\"}", text); + + VO vo2 = JSON.parseObject(text, VO.class); + Assert.assertEquals("\1\1", vo2.getValue()); + } + + public void test_for_2028() throws Exception { + VO vo = new VO(); + vo.setValue("\u2028\u2028"); + + Assert.assertEquals('\u2028', vo.getValue().charAt(0)); + + String text = JSON.toJSONString(vo); + System.out.println(text); + Assert.assertEquals("{\"value\":\"\\u2028\\u2028\"}", text); + + VO vo2 = JSON.parseObject(text, VO.class); + Assert.assertEquals("\u2028\u2028", vo2.getValue()); + } + + public void test_for_2029() throws Exception { + VO vo = new VO(); + vo.setValue("\u2029\u2029"); + + Assert.assertEquals('\u2029', vo.getValue().charAt(0)); + + String text = JSON.toJSONString(vo); + System.out.println(text); + Assert.assertEquals("{\"value\":\"\\u2029\\u2029\"}", text); + + VO vo2 = JSON.parseObject(text, VO.class); + Assert.assertEquals("\u2029\u2029", vo2.getValue()); + } + + public static class VO { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_184.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_184.java new file mode 100644 index 0000000000..9254217564 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_184.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_issue_184 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_issue_184"); + } + + public void test_for_issue() throws Exception { + TUser user = new TUser(); + user.id = 1001; + // 禁用asm(在android下使用),启用asm则没问题。 + SerializeConfig.getGlobalInstance().setAsmEnable(false); + String json = JSON.toJSONString(user, SerializerFeature.WriteClassName); + // 输出{"@type":"xx.TUser","id":0L} + System.out.println(json); + // 下面反系列化错误:com.alibaba.fastjson.JSONException: unclosed.str + // 原因:id带L后缀 + user = (TUser) JSON.parse(json); + } + + public static class TUser { + + public long id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_229.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_229.java new file mode 100644 index 0000000000..c923143c68 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_229.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_229 extends TestCase { + + public void test_for_issue() throws Exception { + Assert.assertTrue(JSON.parseObject("{\"value\":1}", VO.class).value); + Assert.assertFalse(JSON.parseObject("{\"value\":0}", VO.class).value); + } + + public static class VO { + + private boolean value; + + public boolean isValue() { + return value; + } + + public void setValue(boolean value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_232.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_232.java new file mode 100644 index 0000000000..2cd72328b9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_232.java @@ -0,0 +1,15 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_issue_232 extends TestCase { + public void test_for_issue() throws Exception { + String source = "{\"code\": 0, \"data\": {\"country\": \"China\", \"country_id\": \"CN\", \"area\": \"East China\", \"area_id\": \"300000\", \"region\": \"Jiangsu Province \",\" region_id \":\" 320000 \",\" city \":\" Nanjing \",\" city_id \":\" 320100 \",\" county \":\" \",\" county_id \":\" - 1 \",\" isp \":\" China Unicom \",\" isp_id \":\" 100026 \",\" ip \":\" 58.240.65.50 \"}}"; + JSONObject object = JSONObject.parseObject (source); + Assert.assertEquals(0, object.getIntValue("code")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_236.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_236.java new file mode 100644 index 0000000000..3c89ca8863 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_236.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class Bug_for_issue_236 extends TestCase { + + public void test_for_issue() throws Exception { + String text = "{1:{\"donateLevel\":0,\"goodsInfoInRoomMap\":{102:2160,103:0},\"goodsInfoMap\":null,\"headPhoto\":null,\"headPhotoId\":0,\"id\":-569,\"nickName\":\"啤酒兑咖啡的苦涩\",\"sex\":1,\"vipLevel\":0},2:{\"donateLevel\":0,\"goodsInfoInRoomMap\":{102:11000,103:0},\"goodsInfoMap\":null,\"headPhoto\":null,\"headPhotoId\":1,\"id\":18315,\"nickName\":\"游客6083\",\"sex\":1,\"vipLevel\":0},3:{\"donateLevel\":0,\"goodsInfoInRoomMap\":{102:1940,103:0},\"goodsInfoMap\":null,\"headPhoto\":null,\"headPhotoId\":0,\"id\":-887,\"nickName\":\"傻笑,那段情\",\"sex\":0,\"vipLevel\":0},5:{\"$ref\":\"$[2]\"}}"; + Map root = JSON.parseObject(text, new TypeReference>() {}); + Assert.assertNotNull(root.get(5)); + } + + public static class TestPara { + + public Object[] paras; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_242.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_242.java new file mode 100644 index 0000000000..b33eb51ad5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_242.java @@ -0,0 +1,129 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_issue_242 extends TestCase { + + public void test_true() throws Exception { + final String text = "{int1:\"NULL\",int2:\"null\",long1:NULL,long2:null, dou1:\"NULL\",dou2:\"null\",str1:\"NULL\",str2:NULL, bool2:\"NULL\",bool1:null}"; + VO vo = JSON.parseObject(text, VO.class); + + System.out.println(vo); + } + + public static class VO { + + public int int1; + public int int2; + public long long1; + public long long2; + public double dou1; + public double dou2; + public boolean bool1; + public boolean bool2; + public String str1; + public String str2; + + public VO(){ + + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("int1 = ").append(int1)// + .append(" int2 = ").append(int2)// + .append(" long1 = ").append(long1)// + .append(" long2 = ").append(long2)// + .append(" dou1 = ").append(dou1)// + .append(" dou2 = ").append(dou2)// + .append(" bool1 = ").append(bool1)// + .append(" bool2 = ").append(bool2)// + .append(" str1 = ").append(str2)// + .append(" str2 = ").append(str2); + return sb.toString(); + } + + public int getInt1() { + return int1; + } + + public void setInt1(int int1) { + this.int1 = int1; + } + + public int getInt2() { + return int2; + } + + public void setInt2(int int2) { + this.int2 = int2; + } + + public long getLong1() { + return long1; + } + + public void setLong1(long long1) { + this.long1 = long1; + } + + public long getLong2() { + return long2; + } + + public void setLong2(long long2) { + this.long2 = long2; + } + + public double getDou1() { + return dou1; + } + + public void setDou1(double dou1) { + this.dou1 = dou1; + } + + public double getDou2() { + return dou2; + } + + public void setDou2(double dou2) { + this.dou2 = dou2; + } + + public boolean isBool1() { + return bool1; + } + + public void setBool1(boolean bool1) { + this.bool1 = bool1; + } + + public boolean isBool2() { + return bool2; + } + + public void setBool2(boolean bool2) { + this.bool2 = bool2; + } + + public String getStr1() { + return str1; + } + + public void setStr1(String str1) { + this.str1 = str1; + } + + public String getStr2() { + return str2; + } + + public void setStr2(String str2) { + this.str2 = str2; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_252.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_252.java new file mode 100644 index 0000000000..471777eeb0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_252.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_issue_252 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + String text = JSON.toJSONString(vo, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"type\":null}", text); + } + + public static class VO { + + private Class type; + + public Class getType() { + return type; + } + + public void setType(Class type) { + this.type = type; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_253.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_253.java new file mode 100644 index 0000000000..57ee9b8435 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_253.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeFilter; + +import junit.framework.TestCase; + +public class Bug_for_issue_253 extends TestCase { + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setValue(new Date(1460434818838L)); + String text = JSON.toJSONString(vo, new SerializeFilter[0]); + Assert.assertEquals("{\"value\":1460434818838}", text); + } + + public static class VO { + private Date value; + + + public Date getValue() { + return value; + } + + + public void setValue(Date value) { + this.value = value; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_256.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_256.java new file mode 100644 index 0000000000..782cbe5dcf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_256.java @@ -0,0 +1,78 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class Bug_for_issue_256 extends TestCase { + + public void test_for_issue() throws Exception { + List list3 = new ArrayList(); + AisleDeployInfo aisleDeployInfo = new AisleDeployInfo(); + aisleDeployInfo.setId(1L); + aisleDeployInfo.setProvinceArea("3,4,5"); + list3.add(aisleDeployInfo); + + AisleDeployInfo aisleDeployInfo1 = new AisleDeployInfo(); + aisleDeployInfo1.setId(2L); + aisleDeployInfo1.setProvinceArea("3,4,5"); + list3.add(aisleDeployInfo1); + + List list4 = new ArrayList(); + list4.add(aisleDeployInfo); + + Map> map3 = new HashMap>(); + map3.put("1", list3); + map3.put("2", list4); + + String str = JSON.toJSONString(map3); + Map> map1 = JSON.parseObject(str, new TypeReference>>(){}); + List aList = map1.get("1"); + + if (aList != null && aList.size() > 0) { + for (int i = 0; i < aList.size(); i++) { + System.out.println(aList.get(i).getId()); + } + } + } + + public static class AisleDeployInfo { + private long id; + private String provinceArea; + + public long getId() { + return id; + } + + + public void setId(long id) { + this.id = id; + } + + + + public String getProvinceArea() { + return provinceArea; + } + + + + public void setProvinceArea(String provinceArea) { + this.provinceArea = provinceArea; + } + + + } + + public static class Model extends HashMap { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_262.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_262.java new file mode 100644 index 0000000000..04405a6751 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_262.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class Bug_for_issue_262 extends TestCase { + + public void test_for_issue() throws Exception { + String json = "{\"$\":\"zhugw\"}"; + Assert.assertEquals("zhugw", JSONPath.read(json, "/\\$")); + } + + + public static class Model { + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_265.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_265.java new file mode 100644 index 0000000000..6a868437dd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_265.java @@ -0,0 +1,71 @@ +package com.alibaba.json.bvt.bug; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.deserializer.ExtraProcessable; +import com.alibaba.fastjson.serializer.JSONSerializable; +import com.alibaba.fastjson.serializer.JSONSerializer; + +import junit.framework.TestCase; + +public class Bug_for_issue_265 extends TestCase { + + public void test_for_issue() throws Exception { + User user = new User(); + user.setName("wenshao"); + + String text = JSON.toJSONString(user); + + Assert.assertEquals("{\"name\":\"wenshao\"}", text); + + } + + public void test_for_issue_decode() throws Exception { + String text = "{\"name\":\"wenshao\",\"id\":1001}"; + + User user = JSON.parseObject(text, User.class); + Assert.assertEquals("wenshao", user.getName()); + Assert.assertEquals(1001, user.getAttribute("id")); + } + + public static class Model implements JSONSerializable, ExtraProcessable { + + protected Map attributes = new HashMap(); + + public Map getAttributes() { + return attributes; + } + + public Object getAttribute(String name) { + return attributes.get(name); + } + + @Override + public void write(JSONSerializer serializer, Object fieldName, Type fieldType, + int features) throws IOException { + serializer.write(attributes); + } + + @Override + public void processExtra(String key, Object value) { + attributes.put(key, value); + } + } + + public static class User extends Model { + + public String getName() { + return (String) attributes.get("name"); + } + + public void setName(String name) { + attributes.put("name", name); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_268.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_268.java new file mode 100644 index 0000000000..0e8d3677c3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_268.java @@ -0,0 +1,65 @@ +package com.alibaba.json.bvt.bug; + +import java.util.EnumSet; +import java.util.concurrent.TimeUnit; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_268 extends TestCase { + + public void test_for_issue() throws Exception { + V1 vo = new V1(); + vo.units = EnumSet.of(TimeUnit.DAYS, TimeUnit.HOURS); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"units\":[\"HOURS\",\"DAYS\"]}", text); + + V1 vo1 = JSON.parseObject(text, V1.class); + Assert.assertNotNull(vo1); + Assert.assertEquals(vo.units, vo1.units); + } + + public void test_for_issue_private() throws Exception { + VO vo = new VO(); + vo.units = EnumSet.of(TimeUnit.DAYS, TimeUnit.HOURS); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"units\":[\"HOURS\",\"DAYS\"]}", text); + + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertNotNull(vo1); + Assert.assertEquals(vo.units, vo1.units); + } + + private static class VO { + + private EnumSet units; + + public EnumSet getUnits() { + return units; + } + + public void setUnits(EnumSet units) { + this.units = units; + } + + } + + public static class V1 { + + private EnumSet units; + + public EnumSet getUnits() { + return units; + } + + public void setUnits(EnumSet units) { + this.units = units; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_269.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_269.java new file mode 100644 index 0000000000..8f7e1c66e1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_269.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_269 extends TestCase { + + public void test_for_issue() throws Exception { + String text = "{\"value\":\"2014-10-09T03:07:07.000Z\"}"; + VO vo = JSON.parseObject(text, VO.class); + Assert.assertEquals(1412824027000L, vo.value.getTime()); + } + + public static class VO { + + private Date value; + + public Date getValue() { + return value; + } + + public void setValue(Date value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_273.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_273.java new file mode 100644 index 0000000000..666dc60d9d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_273.java @@ -0,0 +1,15 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_273 extends TestCase { + public void test_for_issue() throws Exception { + JSON.parseObject("{\"value\":\"\0x16\0x26\"}"); + } + + public static class VO { + public String value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_278.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_278.java new file mode 100644 index 0000000000..d753f9ccaf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_278.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_278 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setTest(true); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"test\":true}", text); + } + + public void test_for_issue_decode() throws Exception { + VO vo = JSON.parseObject("{\"isTest\":true}", VO.class); + Assert.assertTrue(vo.isTest); + } + + public static class VO { + + private boolean isTest; + + public boolean isTest() { + return isTest; + } + + public void setTest(boolean isTest) { + this.isTest = isTest; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_280.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_280.java new file mode 100644 index 0000000000..a0a43fe4cd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_280.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class Bug_for_issue_280 extends TestCase { + + public void test_for_issue() throws Exception { + TypeReference> type= new TypeReference>() {}; + + Respone resp = JSON.parseObject("{\"code\":\"\",\"data\":\"\",\"msg\":\"\"}", type); + Assert.assertNull(resp.data); + } + + public static class Respone { + + public String code; + public String msg; + public T data; + } + + public static class User { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_283.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_283.java new file mode 100644 index 0000000000..401217d73b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_283.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.Collection; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class Bug_for_issue_283 extends TestCase { + + public void test_for_issue() throws Exception { + String jsons = "[[1,1,1,2,3],[2,3,12,3,4],[1],[2]]"; + + Collection> collections // + = JSON.parseObject(jsons, new TypeReference>>() { + }); + + Assert.assertEquals(4, collections.size()); + Assert.assertEquals(ArrayList.class, collections.getClass()); + + Collection firstItemCollection = collections.iterator().next(); + Assert.assertEquals(5, firstItemCollection.size()); + Assert.assertEquals(ArrayList.class, firstItemCollection.getClass()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_285.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_285.java new file mode 100644 index 0000000000..4cb187006b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_285.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; + +import junit.framework.TestCase; + +public class Bug_for_issue_285 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.v1 = new V1(); + vo.v1.v2 = new V2(); + vo.v1.v2.v3 = new V3(); + vo.v1.v2.v3.v4 = new V4(); + + SimplePropertyPreFilter filter = new SimplePropertyPreFilter(); + filter.setMaxLevel(2); + String text = JSON.toJSONString(vo, filter); + Assert.assertEquals("{\"v1\":{\"v2\":{}}}", text); + } + + public static class VO { + + public V1 v1; + } + + public static class V1 { + + public V2 v2; + } + + public static class V2 { + + public V3 v3; + } + + public static class V3 { + public V4 v4; + } + + + public static class V4 { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_291.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_291.java new file mode 100644 index 0000000000..99b3c1c144 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_291.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_291 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_issue_291."); + } + + public void test_for_issue() throws Exception { + String text = "{\"id\":123,\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_issue_291$VO\",\"value\":54321}"; + + Object o = JSON.parse(text); + Assert.assertEquals(VO.class, o.getClass()); + } + + public void test_for_issue_private() throws Exception { + String text = "{\"id\":123,\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_issue_291$VO\",\"value\":54321}"; + + Object o = JSON.parse(text); + Assert.assertEquals(VO.class, o.getClass()); + } + + public static class VO { + public int id; + public int value; + } + + public static class V1 { + public int id; + public int value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_296.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_296.java new file mode 100644 index 0000000000..5f3a10e2c9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_296.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_issue_296 extends TestCase { + + public void test_for_issue() throws Exception { + String text = "{\"downloadSpeed\":631055,\"responseTime\":1.435,\"url\":\"http://m2.music.126.net/xUqntwOHwpJdXsO_H-kHsw==/5817516022676667.mp3?v=50710699\"}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(631055, obj.get("downloadSpeed")); + } + + public void test_for_issue_space() throws Exception { + String text = "{\"downloadSpeed\":631055} "; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(631055, obj.get("downloadSpeed")); + } + + + public void test_for_issue_127() throws Exception { + String text = "{\"downloadSpeed\":631055}\u007f"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(631055, obj.get("downloadSpeed")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_297.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_297.java new file mode 100644 index 0000000000..6dfb483b13 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_297.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.bug; + +import java.lang.reflect.Type; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.util.ParameterizedTypeImpl; + +import junit.framework.TestCase; + +public class Bug_for_issue_297 extends TestCase { + + public void test_for_issue() throws Exception { + Response resp = parse("{\"id\":1001,\"values\":[{}]}", User.class); + Assert.assertEquals(1001, resp.id); + Assert.assertEquals(1, resp.values.size()); + Assert.assertEquals(User.class, resp.values.get(0).getClass()); + } + + public Response parse(String text, Class clazz) { + ParameterizedTypeImpl type = new ParameterizedTypeImpl(new Type[] { User.class }, null, Response.class); + return JSON.parseObject(text, type); + } + + public static class Response { + + public long id; + public List values; + } + + public static class User { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_304.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_304.java new file mode 100644 index 0000000000..c7059d261b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_304.java @@ -0,0 +1,43 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_304 extends TestCase { + + public void test_doubleQuote() throws Exception { + String ss = "{\"value\":\"Intki_E96?\u001A Build\"}"; + Assert.assertEquals("Intki_E96?\u001A Build", JSON.parseObject(ss).get("value")); + } + + public void test_doubleQuote_vo() throws Exception { + String ss = "{\"value\":\"Intki_E96?\u001A Build\"}"; + Assert.assertEquals("Intki_E96?\u001A Build", JSON.parseObject(ss, VO.class).value); + } + + public void test_doubleQuote_vo_private() throws Exception { + String ss = "{\"value\":\"Intki_E96?\u001A Build\"}"; + Assert.assertEquals("Intki_E96?\u001A Build", JSON.parseObject(ss, V1.class).value); + } + + public void test_singleQuote() throws Exception { + String ss = "{'value':'Intki_E96?\u001A Build'}"; + Assert.assertEquals("Intki_E96?\u001A Build", JSON.parseObject(ss).get("value")); + } + + public void test_singleQuote_vo() throws Exception { + String ss = "{'value':'Intki_E96?\u001A Build'}"; + Assert.assertEquals("Intki_E96?\u001A Build", JSON.parseObject(ss, VO.class).value); + } + + public static class VO { + public String value; + } + + private static class V1 { + public String value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_316.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_316.java new file mode 100644 index 0000000000..03857a2fb1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_316.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.bug; + +import java.sql.Timestamp; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_316 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_issue() throws Exception { + Model model = new Model(); + model.value = new Timestamp(1460563200000L); + Assert.assertEquals("{\"value\":1460563200000}", JSON.toJSONString(model)); + } + + public static class Model { + public java.sql.Timestamp value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_318.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_318.java new file mode 100644 index 0000000000..232cd08e82 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_318.java @@ -0,0 +1,126 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_318 extends TestCase { + + public void test_for_issue() throws Exception { + Person o1 = new Person("zhangsan", 20); + Person o2 = new Person("liuXX", 30); + Person o3 = new Person("Test", 10); + + List users = new ArrayList(); + users.add(o1); + users.add(o2); + users.add(o3); + + List managers = new ArrayList(); + managers.add(o2); + managers.add(o3); + + PersonAll pa = new PersonAll(); + pa.setCount(30); + + // map + Map> userMap = new LinkedHashMap>(); + userMap.put("managers", managers); + userMap.put("users", users); + pa.setUserMap(userMap); + // bean的属性 + pa.setUsers(users); + pa.setManagers(managers); + + // String json = JSON.toJSONString(pa, SerializerFeature.DisableCircularReferenceDetect); + String json = JSON.toJSONString(pa); +// System.out.println("序列化: "); +// System.out.println(json); + + PersonAll target = JSON.parseObject(json, PersonAll.class); +// System.out.println("反序列化结果: "); +// System.out.println("map users: " + target.getUserMap().get("users")); +// System.out.println("map managers: " + target.getUserMap().get("managers")); +// +// // 可能是个 "BUG" 第一个元素总是为null +// System.out.println("bean users: " + target.getUsers()); +// System.out.println("bean managers: " + target.getManagers()); +// +// System.out.println(JSON.toJSONString(target)); + + Assert.assertNotNull(target.getUsers().get(0)); + Assert.assertNotNull(target.getManagers().get(0)); + } + + private static class Person { + private String name; + private Integer age; + + public Person(){} + + public Person(String name, Integer age) { + super(); + this.name = name; + this.age = age; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public Integer getAge() { + return age; + } + public void setAge(Integer age) { + this.age = age; + } + } + + private static class PersonAll { + private Map> userMap = new HashMap>(); + private Integer count; + private List users; + private List managers; + + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } + + public Map> getUserMap() { + return userMap; + } + + public void setUserMap(Map> userMap) { + this.userMap = userMap; + } + + public List getUsers() { + return users; + } + + public void setUsers(List users) { + this.users = users; + } + + public List getManagers() { + return managers; + } + + public void setManagers(List managers) { + this.managers = managers; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_320.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_320.java new file mode 100644 index 0000000000..3d19482cd0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_320.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_issue_320 extends TestCase { + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void test_for_issue() throws Exception { + Map map = new HashMap(); + map.put(1001L, "aaa"); + + String text = JSON.toJSONString(map); + Assert.assertEquals("{1001:\"aaa\"}", text); + + JSONObject obj = JSON.parseObject(text); + Assert.assertEquals("aaa", obj.get(1001)); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_330.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_330.java new file mode 100644 index 0000000000..5fa77e48cf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_330.java @@ -0,0 +1,79 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class Bug_for_issue_330 extends TestCase { + + public void test_for_issue() throws Exception { + String jsonContent = "{\"data\":{\"content\":\"xxx\",\"hour\":1}}"; + StatusBean bean = JSONObject.parseObject(jsonContent, + new TypeReference>() { + }); + + Assert.assertNotNull(bean.getData()); + Assert.assertEquals(1, bean.getData().getHour()); + Assert.assertEquals("xxx", bean.getData().getContent()); + } + + public static class StatusBean { + + private int code; + private String msg; + private T data; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + } + + public static class WorkBean { + + private int hour; + private String content; + + public int getHour() { + return hour; + } + + public void setHour(int hour) { + this.hour = hour; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_331.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_331.java new file mode 100644 index 0000000000..c9fbe37f3c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_331.java @@ -0,0 +1,72 @@ +package com.alibaba.json.bvt.bug; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_issue_331 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_issue() throws Exception { + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Date date = format.parse("2015-05-23"); + + Calendar c = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + c.setTime(date); + + Model original = new Model(); + original.setDate(date); + original.setCalendar(c); + + String json = JSON.toJSONString(original, SerializerFeature.UseISO8601DateFormat); + + System.out.println(json); //V1.2.4 输出{"calendar":"2015-05-23","date":"2015-05-23"} , V1.2.6 输出{"calendar":"2015-05-23+08:00","date":"2015-05-23+08:00"} + + Model actual = JSON.parseObject(json, Model.class); + + Assert.assertNotNull(actual); + Assert.assertNotNull(actual.getDate()); + Assert.assertNotNull(actual.getCalendar()); + + Assert.assertEquals("与序列化前比较不相等", original.getDate(), actual.getDate()); + + Assert.assertEquals("序列化后的Date 和 Calendar 不相等", actual.getDate(), actual.getCalendar().getTime()); + } + + public static class Model { + private Date date; + private Calendar calendar; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public Calendar getCalendar() { + return calendar; + } + + public void setCalendar(Calendar calendar) { + this.calendar = calendar; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_336.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_336.java new file mode 100644 index 0000000000..b559545c5b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_336.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_336 extends TestCase { + + public void test_for_issue() throws Exception { + RemoteInvocation remoteInvocation = new RemoteInvocation(); + remoteInvocation.setMethodName("test"); + remoteInvocation.setParameterTypes(new Class[] { int.class, Date.class, String.class }); + remoteInvocation.setArguments(new Object[] { 1, new Date(1460538273131L), "this is a test" }); + String json = JSON.toJSONString(remoteInvocation); + + Assert.assertEquals("{\"arguments\":[1,1460538273131,\"this is a test\"],\"methodName\":\"test\",\"parameterTypes\":[\"int\",\"java.util.Date\",\"java.lang.String\"]}", json); + + remoteInvocation = JSON.parseObject(json, RemoteInvocation.class); + + Assert.assertEquals(3, remoteInvocation.parameterTypes.length); + Assert.assertEquals(int.class, remoteInvocation.parameterTypes[0]); + Assert.assertEquals(Date.class, remoteInvocation.parameterTypes[1]); + Assert.assertEquals(String.class, remoteInvocation.parameterTypes[2]); + + + } + + public static class RemoteInvocation { + + private String methodName; + private Class[] parameterTypes; + private Object[] arguments; + + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public Class[] getParameterTypes() { + return parameterTypes; + } + + public void setParameterTypes(Class[] parameterTypes) { + this.parameterTypes = parameterTypes; + } + + public Object[] getArguments() { + return arguments; + } + + public void setArguments(Object[] arguments) { + this.arguments = arguments; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_349.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_349.java new file mode 100644 index 0000000000..6552e3484b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_349.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.bug; + +import java.math.BigDecimal; +import java.util.Currency; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_issue_349 extends TestCase { + public void test_for_issue() throws Exception { + Money money = new Money(); + money.currency = Currency.getInstance("CNY"); + money.amount = new BigDecimal("10.03"); + + String json = JSON.toJSONString(money); + + Money moneyBack = JSON.parseObject(json, Money.class); + Assert.assertEquals(money.currency, moneyBack.currency); + Assert.assertEquals(money.amount, moneyBack.amount); + + JSONObject jsonObject = JSON.parseObject(json); + Money moneyCast = JSON.toJavaObject(jsonObject, Money.class); + Assert.assertEquals(money.currency, moneyCast.currency); + Assert.assertEquals(money.amount, moneyCast.amount); + } + + public static class Money { + public Currency currency; + public BigDecimal amount; + + @Override + public String toString() { + return "Money{currency=" + currency + ", amount=" + amount + '}'; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_352.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_352.java new file mode 100644 index 0000000000..ef722e6a19 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_352.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class Bug_for_issue_352 extends TestCase { + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.name = "张三"; + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"index\":0,\"名\":\"张三\"}", text); + VO v1 = JSON.parseObject(text, VO.class); + Assert.assertEquals(vo.name, v1.name); + } + + public static class VO { + public int index; + @JSONField(name="名") + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_364.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_364.java new file mode 100644 index 0000000000..dd71409893 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_364.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_issue_364 extends TestCase { + public void test_for_issue() throws Exception { + JSONObject jsonObject = new JSONObject(3, true); + jsonObject.put("name", "J.K.SAGE"); + jsonObject.put("age", 21); + jsonObject.put("msg", "Hello!"); + JSONObject cloneObject = (JSONObject) jsonObject.clone(); + assertEquals(JSON.toJSONString(jsonObject), JSON.toJSONString(cloneObject)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_372.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_372.java new file mode 100644 index 0000000000..67cb27cfda --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_372.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +import junit.framework.TestCase; + +public class Bug_for_issue_372 extends TestCase { + public void test_for_issue() throws Exception { + ParserConfig config = new ParserConfig(); + ObjectDeserializer deser = config.getDeserializer(Model.class); + Assert.assertEquals(JavaBeanDeserializer.class, deser.getClass()); + } + + @JSONType(asm=false) + public static class Model { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_383.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_383.java new file mode 100644 index 0000000000..e160bc55d2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_383.java @@ -0,0 +1,71 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Collection; +import java.util.HashSet; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_issue_383 extends TestCase { + + public void test_for_issue() throws Exception { + TestClass ts = new TestClass(); + ts.getHashSet().add(1); + ts.getHashSet().add(4); + ts.getMember().getHashSet().add(10); + ts.getMember().getHashSet().add(15); + String jsonStr = JSON.toJSONString(ts, new SerializerFeature[]{ + SerializerFeature.WriteClassName, SerializerFeature.DisableCircularReferenceDetect + }); + System.out.println(jsonStr); + ts = JSON.parseObject(jsonStr, TestClass.class); + Assert.assertEquals(HashSet.class, ts.getHashSet().getClass()); + for (Integer val : ts.getHashSet()) { + System.out.println(val); + } + } + + public static class TestClass { + + private Collection hashSet = new HashSet(); + private Member member = new Member(); + + public TestClass() { + } + + public Collection getHashSet() { + return hashSet; + } + + public void setHashSet(Collection hashSet) { + this.hashSet = hashSet; + } + + public Member getMember() { + return member; + } + + public void setMember(Member member) { + this.member = member; + } + } + + public static class Member{ + private Collection hashSet = new HashSet(); + + public Member() { + } + + public Collection getHashSet() { + return hashSet; + } + + public void setHashSet(Collection hashSet) { + this.hashSet = hashSet; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_389.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_389.java new file mode 100644 index 0000000000..1b9f81dcb0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_389.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class Bug_for_issue_389 extends TestCase { + + public void test_for_issue() throws Exception { + Def def = new Def(); + def.add(new User()); + String defStr = JSON.toJSONString(def); + + Assert.assertEquals("[{}]", defStr); + + Def _def = JSON.parseObject(defStr, Def.class); + Assert.assertEquals(User.class, _def.get(0).getClass()); + } + + public void test_for_issue_1() throws Exception { + Def def = new Def(); + def.add(new User()); + String defStr = JSON.toJSONString(def); + + Assert.assertEquals("[{}]", defStr); + + Def _def = JSON.parseObject(defStr, new TypeReference() {}); + Assert.assertEquals(User.class, _def.get(0).getClass()); + } + + public static class User { + + String name; + String value; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } + + public static class Def extends ArrayList { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_414.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_414.java new file mode 100644 index 0000000000..0e209dd1e0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_414.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import java.sql.Timestamp; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_414 extends TestCase { + + public void test_for_issue() throws Exception { + String jsonStr = "{publishedDate:\"2015-09-07\"}"; + TestEntity news = JSON.parseObject(jsonStr, TestEntity.class); + System.out.println(news.getPublishedDate()); + } + + public static class TestEntity { + private Timestamp publishedDate; + + public Timestamp getPublishedDate() { + return publishedDate; + } + public void setPublishedDate(Timestamp publishedDate) { + this.publishedDate = publishedDate; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_415.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_415.java new file mode 100644 index 0000000000..788de4c94e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_415.java @@ -0,0 +1,94 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Arrays; +import java.util.List; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_issue_415 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_issue_415."); + } + + public void test_for_issue() throws Exception { + Teacher t = new Teacher(); + + Address addr = new Address(); + addr.setAddrDetail("中国上海南京路"); + + Student s1 = new Student(); + s1.setName("张三"); + s1.setAddr(addr); + + Student s2 = new Student(); + s2.setName("李四"); + s2.setAddr(addr); + + t.setStudentList(Arrays.asList(s1, s2)); + + String json = JSON.toJSONString(t,SerializerFeature.WriteClassName); + //@1 打印序列化的时候json串 + + Teacher t2 = (Teacher) JSON.parse(json); + for (Student s : t2.getStudentList()) { + Assert.assertNotNull(s); + Assert.assertNotNull(s.getAddr()); + } + } + + public static class Teacher { + + private List studentList; + + public List getStudentList() { + return studentList; + } + + public void setStudentList(List studentList) { + this.studentList = studentList; + } + + } + + public static class Address { + + private String addrDetail; + + public String getAddrDetail() { + return addrDetail; + } + + public void setAddrDetail(String addressDetail) { + this.addrDetail = addressDetail; + } + } + + public static class Student { + + private String name; + private Address address; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Address getAddr() { + return address; + } + + public void setAddr(Address address) { + this.address = address; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_423.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_423.java new file mode 100644 index 0000000000..d46036f4eb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_423.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class Bug_for_issue_423 extends TestCase { + + public void test_for_issue() throws Exception { + String text = "[[],{\"value\":[]}]"; + Object root = JSON.parse(text, Feature.UseObjectArray); + Assert.assertEquals(Object[].class, root.getClass()); + + Object[] rootArray = (Object[]) root; + Assert.assertEquals(Object[].class, rootArray[0].getClass()); + Assert.assertEquals(Object[].class, ((JSONObject)rootArray[1]).get("value").getClass()); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_426.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_426.java new file mode 100644 index 0000000000..9ccc426f03 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_426.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_426 extends TestCase { + + public void test_for_issue() throws Exception { + String text = "{value:\"264,010,000.00\"}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertTrue(264010000.00D == model.value); + } + + public void test_for_issue_float() throws Exception { + String text = "{value:\"264,010,000\"}"; + ModelFloat model = JSON.parseObject(text, ModelFloat.class); + Assert.assertTrue(264010000F == model.value); + } + + public void test_for_issue_int() throws Exception { + String text = "{value:\"264,010,000\"}"; + ModelInt model = JSON.parseObject(text, ModelInt.class); + Assert.assertTrue(264010000D == model.value); + } + + + public void test_for_issue_long() throws Exception { + String text = "{value:\"264,010,000\"}"; + ModelLong model = JSON.parseObject(text, ModelLong.class); + Assert.assertTrue(264010000D == model.value); + } + + public static class Model { + public double value; + } + + public static class ModelFloat { + public float value; + } + + public static class ModelInt { + public int value; + } + + public static class ModelLong { + public long value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_427.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_427.java new file mode 100644 index 0000000000..214ae6239c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_427.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class Bug_for_issue_427 extends TestCase { + + public void test_for_issue() throws Exception { + String value = "================================================" + + "\n服务器名称:[FFFF00]N23-物华天宝 [-]" + + "\n开服时间:[FFFF00]2015年10月16日11:00(周五)[-]" + + "\n================================================"; + + Model model = new Model(); + model.value = value; + JSON.toJSONString(model); + } + + public static class Model { + + public String value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_430.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_430.java new file mode 100644 index 0000000000..a38dc7f87f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_430.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; + +import junit.framework.TestCase; + +public class Bug_for_issue_430 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_issue_430"); + } + + public void test_for_issue() throws Exception { + String text = "[{\"@type\": \"com.alibaba.json.bvt.bug.Bug_for_issue_430$FooModel\", \"fooCollection\": null}, {\"@type\": \"com.alibaba.json.bvt.bug.Bug_for_issue_430$FooModel\", \"fooCollection\": null}]"; + JSONArray array = JSON.parseArray(text); + Assert.assertEquals(FooModel.class, array.get(0).getClass()); + Assert.assertEquals(FooModel.class, array.get(1).getClass()); + + Assert.assertNull(((FooModel)array.get(0)).fooCollection); + Assert.assertNull(((FooModel)array.get(1)).fooCollection); + } + + public void test_for_issue_1() throws Exception { + String text = "[{\"@type\": \"com.alibaba.json.bvt.bug.Bug_for_issue_430$FooModel\", \"fooCollection\": null}, {\"@type\": \"com.alibaba.json.bvt.bug.Bug_for_issue_430$FooModel\", \"fooCollection\": null}]"; + JSONArray array = (JSONArray) JSON.parse(text); + Assert.assertEquals(FooModel.class, array.get(0).getClass()); + Assert.assertEquals(FooModel.class, array.get(1).getClass()); + + Assert.assertNull(((FooModel)array.get(0)).fooCollection); + Assert.assertNull(((FooModel)array.get(1)).fooCollection); + } + + public static class FooModel { + + public ArrayList fooCollection; + } + + public static class FooCollectionModel { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_434.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_434.java new file mode 100644 index 0000000000..f7a34a221d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_434.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_issue_434 extends TestCase { + + public void test_for_issue() throws Exception { + String json = "{value:[\"null\"]}"; + JSONObject parse = JSONObject.parseObject(json); + JSONArray jsonArray = parse.getJSONArray("value"); + Assert.assertEquals(1, jsonArray.size()); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_435.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_435.java new file mode 100644 index 0000000000..3a92be1f86 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_435.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_435 extends TestCase { + + public void test_for_issue() throws Exception { + JSON.parseObject("\ufeff{\"value\":null}", Model.class); + } + + public void test_for_issue_Float() throws Exception { + JSON.parseObject("\ufeff{\"value\":null}", ModelFloat.class); + } + + public static class Model { + public float value; + } + + public static class ModelFloat { + public Float value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_439.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_439.java new file mode 100644 index 0000000000..57f9fe7d7a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_439.java @@ -0,0 +1,12 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_439 extends TestCase { + public void test_for_issue() throws Exception { + JSON.parseObject("{/*aa*/}"); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_446.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_446.java new file mode 100644 index 0000000000..bad794b5f6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_446.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_issue_446 extends TestCase { + + public void test_for_issue() throws Exception { + String text = "{\"amount\":1,\"channel_id\":\"wnys01\",\"gem\":1,\"id\":\"pay\",\"login_name\":\"U10722466A\",\"money\":1000,\"order_id\":\"99142AO10000086695A\",\"pay_channel\":\"weilan\",\"pay_time\":\"2015-11-05 20:59:04\",\"reward\":\"11:5_12:5_13:5,4:1_5:1_6:1\",\"status\":1,\"user_id\":19313}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(1, obj.get("amount")); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_447.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_447.java new file mode 100644 index 0000000000..f244a6f2b8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_447.java @@ -0,0 +1,59 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_issue_447 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_issue() throws Exception { + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTimeInMillis(1460563200000L); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + Foo foo = new Foo(); + foo.setCreateDate(calendar.getTime()); + String date = JSON.toJSONString(foo, SerializerFeature.UseISO8601DateFormat); + Assert.assertEquals("{\"createDate\":\"2016-04-14+08:00\"}", date); + Foo foo2 = JSON.parseObject(date, Foo.class, Feature.AllowISO8601DateFormat); + Assert.assertEquals("{\"createDate\":\"2016-04-14 00:00:00\"}", JSON.toJSONString(foo2, SerializerFeature.WriteDateUseDateFormat)); + } + + public static class Foo { + + private String name; + private Date createDate; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getCreateDate() { + return createDate; + } + + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_448.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_448.java new file mode 100644 index 0000000000..312671118f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_448.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.bug; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; + +import junit.framework.TestCase; + +public class Bug_for_issue_448 extends TestCase { + public void test_0() { + + } + + // skip + public void test_for_issue() throws Exception { + final int value_size = 1024 * 16; + List list = new ArrayList(); + for (int i = 0; i < 10; ++i) { + Model model = new Model(); + char[] buf = new char[value_size]; + for (int j = 0; j < buf.length; ++j) { + buf[j] = (char) ('a' + j); + } + model.value = new String(buf); + list.add(model); + } + + String text = JSON.toJSONString(list); + JSONReader reader = new JSONReader(new StringReader(text)); + reader.startArray(); + while (reader.hasNext()) { + Model model = reader.readObject(Model.class); + String value = model.value; + Assert.assertEquals(value_size, value.length()); + for (int i = 0; i < value.length(); ++i) { + char ch = value.charAt(i); + Assert.assertEquals("error : index_" + i, (char) ('a' + i), ch); + } + } + reader.endArray(); + reader.close(); + } + + + public static class Model { + public String value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_449.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_449.java new file mode 100644 index 0000000000..9e2c0e2e42 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_449.java @@ -0,0 +1,77 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class Bug_for_issue_449 extends TestCase { + + public void test_for_issue() throws Exception { + ExaminationPojo vo = new ExaminationPojo(); + vo.setMg("1435555992"); + vo.setNa(" 02570"); + vo.setCl("150501"); + vo.setPanellot("150501"); + String text = JSON.toJSONString(vo); + + System.out.println(text); + Assert.assertEquals("{\"Cl-\":\"150501\",\"Mg2+\":\"1435555992\",\"Na+\":\" 02570\",\"panellot\":\"150501\"}", text); + + ExaminationPojo v1 = JSON.parseObject(text, ExaminationPojo.class); + Assert.assertEquals(vo.mg, v1.mg); + Assert.assertEquals(vo.na, v1.na); + Assert.assertEquals(vo.cl, v1.cl); + Assert.assertEquals(vo.panellot, v1.panellot); + + } + + public static class ExaminationPojo { + + @JSONField(name = "Mg2+") + private String mg; + @JSONField(name = "Na+") + private String na; + @JSONField(name = "Cl-") + private String cl; + @JSONField(name = "panellot") + private String panellot; + + public String getMg() { + return mg; + } + + public void setMg(String mg) { + this.mg = mg; + } + + public String getNa() { + return na; + } + + public void setNa(String na) { + this.na = na; + } + + public String getCl() { + return cl; + } + + public void setCl(String cl) { + this.cl = cl; + } + + public String getPanellot() { + return panellot; + } + + public void setPanellot(String panellot) { + this.panellot = panellot; + } + + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_457.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_457.java new file mode 100644 index 0000000000..cbed0967fa --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_457.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.bug; + +import java.lang.reflect.Type; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +import junit.framework.TestCase; + +public class Bug_for_issue_457 extends TestCase { + + public void test_for_issue() throws Exception { + ParserConfig.global.putDeserializer(MyEnum.class, new MyEnumDeser()); + VO entity = JSON.parseObject("{\"myEnum\":\"AA\"}", VO.class); + Assert.assertEquals(MyEnum.A, entity.myEnum); + } + + public static class MyEnumDeser implements ObjectDeserializer { + + @Override + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + String text = (String) parser.parse(); + if (text.equals("AA")) { + return (T) MyEnum.A; + } + + if (text.equals("BB")) { + return (T) MyEnum.B; + } + return null; + } + + @Override + public int getFastMatchToken() { + return JSONToken.LITERAL_STRING; + } + + } + + + public static class VO { + + private MyEnum myEnum; + + public void setMyEnum(MyEnum myEnum) { + this.myEnum = myEnum; + } + + public MyEnum getMyEnum() { + return myEnum; + } + } + + public static enum MyEnum { + A, B + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_462.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_462.java new file mode 100644 index 0000000000..0b74fbe97b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_462.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.bug; + +import java.math.BigInteger; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_issue_462 extends TestCase { + public void test_int() throws Exception { + JSONObject object = JSON.parseObject("{\"value\":1001}"); + Object value = object.get("value"); + Assert.assertEquals(Integer.class, value.getClass()); + } + + public void test_long() throws Exception { + JSONObject object = JSON.parseObject("{\"value\":2147483649}"); + Object value = object.get("value"); + Assert.assertEquals(Long.class, value.getClass()); + } + + public void test_bigint() throws Exception { + JSONObject object = JSON.parseObject("{\"value\":9223372036854775808}"); + Object value = object.get("value"); + Assert.assertEquals(BigInteger.class, value.getClass()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_465.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_465.java new file mode 100644 index 0000000000..8ee0f64ef1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_465.java @@ -0,0 +1,130 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class Bug_for_issue_465 extends TestCase { + public void test_for_issue() throws Exception { + String json = "[\"abc\",\"efg\",\"sss\",[1,2]]"; + + TestBean testBean = JSON.parseObject(json, TestBean.class); + Assert.assertEquals("abc", testBean.name); + Assert.assertEquals("efg", testBean.country); + Assert.assertEquals("sss", testBean.password); + Assert.assertEquals(2, testBean.location.length); + Assert.assertEquals(1, testBean.location[0]); + Assert.assertEquals(2, testBean.location[1]); + } + + public void f_test_for_issue_private() throws Exception { + String json = "[\"abc\",\"efg\",\"sss\",[1,2]]"; + + TestBean1 testBean = JSON.parseObject(json, TestBean1.class); + Assert.assertEquals("abc", testBean.name); + Assert.assertEquals("efg", testBean.country); + Assert.assertEquals("sss", testBean.password); + Assert.assertEquals(2, testBean.location.length); + Assert.assertEquals(1, testBean.location[0]); + Assert.assertEquals(2, testBean.location[1]); + } + + @JSONType(parseFeatures = Feature.SupportArrayToBean) + public static class TestBean { + private String name; + + private String password; + + private String country; + + private int[] location; + + public String getName() { + return name; + } + + @JSONField(ordinal = 0) + public void setName(String name) { + this.name = name; + } + + public String getPassword() { + return password; + } + + @JSONField(ordinal = 2) + public void setPassword(String password) { + this.password = password; + } + + public String getCountry() { + return country; + } + + @JSONField(ordinal = 1) + public void setCountry(String country) { + this.country = country; + } + + public int[] getLocation() { + return location; + } + + @JSONField(ordinal = 3) + public void setLocation(int[] location) { + this.location = location; + } + } + + @JSONType(parseFeatures = Feature.SupportArrayToBean) + private static class TestBean1 { + private String name; + + private String password; + + private String country; + + private int[] location; + + public String getName() { + return name; + } + + @JSONField(ordinal = 0) + public void setName(String name) { + this.name = name; + } + + public String getPassword() { + return password; + } + + @JSONField(ordinal = 2) + public void setPassword(String password) { + this.password = password; + } + + public String getCountry() { + return country; + } + + @JSONField(ordinal = 1) + public void setCountry(String country) { + this.country = country; + } + + public int[] getLocation() { + return location; + } + + @JSONField(ordinal = 3) + public void setLocation(int[] location) { + this.location = location; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_469.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_469.java new file mode 100644 index 0000000000..641eb057e5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_469.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_469 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.sPhotoUrl = "xxx"; + + String text = JSON.toJSONString(vo); + VO vo2 = JSON.parseObject(text, VO.class); + Assert.assertEquals(vo.getsPhotoUrl(), vo2.getsPhotoUrl()); + } + + public static class VO { + + private String sPhotoUrl; + + public String getsPhotoUrl() { + return sPhotoUrl; + } + + public void setsPhotoUrl(String sPhotoUrl) { + this.sPhotoUrl = sPhotoUrl; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_470.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_470.java new file mode 100644 index 0000000000..c494c40365 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_470.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.bug; + +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_470 extends TestCase { + + public void test_for_issue() throws Exception { + List list = JSON.parseArray("[{\"value\":null}]", VO.class); + Assert.assertEquals(1, list.size()); + Assert.assertEquals(false, list.get(0).value); + } + + public void test_for_issue_private() throws Exception { + List list = JSON.parseArray("[{\"value\":null}]", V1.class); + Assert.assertEquals(1, list.size()); + Assert.assertEquals(false, list.get(0).value); + } + + public void test_for_issue_method() throws Exception { + List list = JSON.parseArray("[{\"value\":null}]", V2.class); + Assert.assertEquals(1, list.size()); + Assert.assertEquals(false, list.get(0).value); + } + + public static class VO { + public boolean value; + } + + private static class V1 { + public boolean value; + } + + public static class V2 { + private boolean value; + + public boolean isValue() { + return value; + } + + + public void setValue(boolean value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_479.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_479.java new file mode 100644 index 0000000000..f9b40c8869 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_479.java @@ -0,0 +1,90 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_479 extends TestCase { + + public void test_for_issue_blankinput() throws Exception { + VO vo = JSON.parseObject("", VO.class); + Assert.assertNull(vo); + } + + public void test_for_issue() throws Exception { + VO vo = JSON.parseObject("{\"doubleParam\":\"\",\"floatParam\":\"\",\"intParam\":\"\",\"longParam\":\"\"}", + VO.class); + Assert.assertTrue(vo.doubleParam == 0); + Assert.assertTrue(vo.floatParam == 0); + Assert.assertTrue(vo.intParam == 0); + Assert.assertTrue(vo.longParam == 0); + } + + public void test_for_issue_private() throws Exception { + V1 vo = JSON.parseObject("{\"doubleParam\":\"\",\"floatParam\":\"\",\"intParam\":\"\",\"longParam\":\"\"}", + V1.class); + Assert.assertTrue(vo.doubleParam == 0); + Assert.assertTrue(vo.floatParam == 0); + Assert.assertTrue(vo.intParam == 0); + Assert.assertTrue(vo.longParam == 0); + } + + public static class VO { + + public long doubleParam; + public float floatParam; + public int intParam; + public long longParam; + } + + private static class V1 { + + public long doubleParam; + public float floatParam; + public int intParam; + public long longParam; + } + + public static class V2 { + + private long doubleParam; + private float floatParam; + private int intParam; + private long longParam; + + public long getDoubleParam() { + return doubleParam; + } + + public void setDoubleParam(long doubleParam) { + this.doubleParam = doubleParam; + } + + public float getFloatParam() { + return floatParam; + } + + public void setFloatParam(float floatParam) { + this.floatParam = floatParam; + } + + public int getIntParam() { + return intParam; + } + + public void setIntParam(int intParam) { + this.intParam = intParam; + } + + public long getLongParam() { + return longParam; + } + + public void setLongParam(long longParam) { + this.longParam = longParam; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_489.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_489.java new file mode 100644 index 0000000000..fda2b37707 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_489.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class Bug_for_issue_489 extends TestCase { + + public void test_for_issue() throws Exception { + Foo ok = JSON.parseObject("{\"foo\":\"bar\"}", Foo.class); + Foo ng = JSON.parseArray("[{\"foo\":\"bar\"}]").getObject(0, Foo.class); + } + + public static final class Foo { + + public final String bar; + + @JSONCreator + public Foo(@JSONField(name = "foo") final String bar){ + this.bar = bar; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_491.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_491.java new file mode 100644 index 0000000000..70073a25f0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_491.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class Bug_for_issue_491 extends TestCase { + + public void test_for_issue() throws Exception { + String json = "{id:1,keyword:[{uuid:\"ddd\"},{uuid:\"zzz\"}]}"; + Map map = getJsonToMap1(json, String.class); + Assert.assertEquals("1", map.get("id")); + } + + + public void test_for_issue_2() throws Exception { + String json = "{1:{name:\"ddd\"},2:{name:\"zzz\"}}"; + Map map = getJsonToMap(json, Integer.class, Model.class); + Assert.assertEquals("ddd", map.get(1).name); + Assert.assertEquals("zzz", map.get(2).name); + } + + public static class Model { + public String name; + } + + public static Map getJsonToMap1(String json, Class valueType) { + return JSON.parseObject(json, new TypeReference>(valueType) {}); + } + + public static Map getJsonToMap(String json, Class keyType, Class valueType) { + return JSON.parseObject(json, new TypeReference>(keyType, valueType) {}); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_492.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_492.java new file mode 100644 index 0000000000..bd2a591fda --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_492.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class Bug_for_issue_492 extends TestCase { + + public void test_for_issue() throws Exception { + String json = "{\"name\":\"zhugw\"}"; + Assert.assertEquals("zhugw", JSONPath.read(json, "/name")); + } + + + public static class Model { + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_537.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_537.java new file mode 100644 index 0000000000..582f861d7a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_537.java @@ -0,0 +1,72 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class Bug_for_issue_537 extends TestCase { + + public void test_for_issue() throws Exception { + String text = "{\"value\":2147483649}"; + Exception error = null; + try { + JSON.parseObject(text, VO.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + Assert.assertTrue(error.getMessage().contains("field : value")); + } + + public void test_for_issue_private() throws Exception { + String text = "{\"value\":2147483649}"; + Exception error = null; + try { + JSON.parseObject(text, V1.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + Assert.assertTrue(error.getMessage().contains("field : value")); + } + + + public void test_for_issue_method() throws Exception { + String text = "{\"value\":2147483649}"; + Exception error = null; + try { + JSON.parseObject(text, V2.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + Assert.assertTrue(error.getMessage().contains("field : value")); + } + + public static class VO { + + public int value; + } + + private static class V1 { + + public int value; + } + + public static class V2 { + + private int value; + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_545.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_545.java new file mode 100644 index 0000000000..e6d7c3c012 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_545.java @@ -0,0 +1,14 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_545 extends TestCase { + + public void test_for_issue() throws Exception { + JSON.parse("\ufeff{}"); + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555.java new file mode 100644 index 0000000000..d552c71702 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import java.util.List; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class Bug_for_issue_555 extends TestCase { + + public void test_for_issue() throws Exception { + JSON.parseObject("{\"list\":[{\"spec\":{}}]}", A.class); + } + + public static class A { + + public List list; + } + + public static class B { + + @JSONField(serialize = true, deserialize = false) + public Spec spec; + } + + public static class Spec { + private int id; + + public Spec(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555_setter.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555_setter.java new file mode 100644 index 0000000000..4a77f262be --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555_setter.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.bug; + +import java.util.List; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class Bug_for_issue_555_setter extends TestCase { + + public void test_for_issue() throws Exception { + JSON.parseObject("{\"list\":[{\"spec\":{}}]}", A.class); + } + + public static class A { + + public List list; + } + + public static class B { + + @JSONField(serialize = true, deserialize = false) + private Spec spec; + + public Spec getSpec() { + return spec; + } + + public void setSpec(Spec spec) { + this.spec = spec; + } + + } + + public static class Spec { + + private int id; + + public Spec(int id){ + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555_setter2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555_setter2.java new file mode 100644 index 0000000000..abbcc5a2d6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555_setter2.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.bug; + +import java.util.List; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class Bug_for_issue_555_setter2 extends TestCase { + + public void test_for_issue() throws Exception { + JSON.parseObject("{\"list\":[{\"spec\":{}}]}", A.class); + } + + public static class A { + + public List list; + } + + public static class B { + + private Spec spec; + + @JSONField(serialize = true, deserialize = false) + public Spec getSpec() { + return spec; + } + + @JSONField(serialize = true, deserialize = false) + public void setSpec(Spec spec) { + this.spec = spec; + } + + } + + public static class Spec { + + private int id; + + public Spec(int id){ + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_569.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_569.java new file mode 100644 index 0000000000..708e2fe226 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_569.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvt.bug.Bug_for_issue_569.LoginResponse.Body; +import com.alibaba.json.bvt.bug.Bug_for_issue_569.LoginResponse.MemberInfo; + +import junit.framework.TestCase; + +public class Bug_for_issue_569 extends TestCase { + + public void test_for_issue() throws Exception { + LoginResponse loginResp = new LoginResponse(); + loginResp.response = new Response(); + loginResp.response.content = new Body(); + loginResp.response.content.setMemberinfo(new MemberInfo()); + loginResp.response.content.getMemberinfo().name = "ding102992"; + loginResp.response.content.getMemberinfo().email = "ding102992@github.com"; + + String text = JSON.toJSONString(loginResp); + + LoginResponse loginResp2 = JSON.parseObject(text, LoginResponse.class); + + Assert.assertEquals(loginResp.response // + .getContent() // + .getMemberinfo().name, // + loginResp2.response // + .getContent() // + .getMemberinfo().name); + Assert.assertEquals(loginResp.response // + .getContent().getMemberinfo().email, // + loginResp2.response.getContent().getMemberinfo().email); + + } + + public static class BaseResponse { + + public Response response; + + + } + + public static class Response { + + private T content; + + public T getContent() { + return content; + } + + public void setContent(T content) { + this.content = content; + } + + } + + public static class LoginResponse extends BaseResponse { + + public static class Body { + + private MemberInfo memberinfo; + + public MemberInfo getMemberinfo() { + return memberinfo; + } + + public void setMemberinfo(MemberInfo memberinfo) { + this.memberinfo = memberinfo; + } + } + + public static class MemberInfo { + + public String name; + public String email; + /* + * 省略Getter,Setter + */ + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_569_1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_569_1.java new file mode 100644 index 0000000000..a4cfb1e0e7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_569_1.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.List; + +/** + * Created by wenshao on 16/8/11. + */ +public class Bug_for_issue_569_1 extends TestCase { + public void test_for_issue() throws Exception { + String str = "{\"bList\":[{\"data\":[0,1]},{\"data\":[1,2]},{\"data\":[2,3]},{\"data\":[3,4]},{\"data\":[4,5]},{\"data\":[5,6]},{\"data\":[6,7]},{\"data\":[7,8]},{\"data\":[8,9]},{\"data\":[9,10]}]}"; + A aInteger; + A aLong; + +// aInteger = JSON.parseObject(str, new TypeReference>() { +// }); +// Assert.assertEquals(aInteger.getbList().get(0).getData().get(0).getClass().getName(), Integer.class.getName()); +// + aLong = JSON.parseObject(str, new TypeReference>() { + }); + Assert.assertEquals(aLong.getbList().get(0).getData().get(0).getClass().getName(), Long.class.getName()); + + } + + + + public static class A { + private List> bList; + + public List> getbList() { + return bList; + } + + public void setbList(List> bList) { + this.bList = bList; + } + } + + public static class B { + private List data; + + public List getData() { + return data; + } + + public void setData(List data) { + this.data = data; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572.java new file mode 100644 index 0000000000..59986ec106 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572.java @@ -0,0 +1,43 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_issue_572 extends TestCase { + + public void test_for_issue() throws Exception { + Model model = new Model(); + model.id = 1001; + model.name = "wenshao"; + + String text = JSON.toJSONString(model, SerializerFeature.WriteNonStringValueAsString); + Assert.assertEquals("{\"id\":\"1001\",\"name\":\"wenshao\"}", text); + } + + public static class Model { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_field.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_field.java new file mode 100644 index 0000000000..4c34be795f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_field.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_issue_572_field extends TestCase { + + public void test_for_issue() throws Exception { + Model model = new Model(); + model.id = 1001; + model.name = "wenshao"; + + String text = JSON.toJSONString(model, SerializerFeature.WriteNonStringValueAsString); + Assert.assertEquals("{\"id\":\"1001\",\"name\":\"wenshao\"}", text); + } + + public static class Model { + + public int id; + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_field2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_field2.java new file mode 100644 index 0000000000..7e3acf16d2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_field2.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; +import org.junit.Assert; + +public class Bug_for_issue_572_field2 extends TestCase { + + public void test_for_issue() throws Exception { + Model model = new Model(); + model.id = 1001; + model.name = "wenshao"; + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"id\":\"1001\",\"name\":\"wenshao\"}", text); + } + + public static class Model { + + @JSONField(serialzeFeatures = SerializerFeature.WriteNonStringValueAsString) + public int id; + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_private.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_private.java new file mode 100644 index 0000000000..ea46da971a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_private.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.serializer.ValueFilter; + +import junit.framework.TestCase; + +public class Bug_for_issue_572_private extends TestCase { + + public void test_for_issue() throws Exception { + Model model = new Model(); + model.id = 1001; + model.name = "wenshao"; + + String text = JSON.toJSONString(model, SerializerFeature.WriteNonStringValueAsString); + Assert.assertEquals("{\"id\":\"1001\",\"name\":\"wenshao\"}", text); + } + + public void test_for_issue_1() throws Exception { + Model model = new Model(); + model.id = 1001; + model.name = "wenshao"; + + ValueFilter valueFilter = new ValueFilter() { + + @Override + public Object process(Object object, String name, Object value) { + if (value instanceof Number) { + return null; + } + return value; + } + }; + + String text = JSON.toJSONString(model, valueFilter, SerializerFeature.WriteNonStringValueAsString); + Assert.assertEquals("{\"id\":\"1001\",\"name\":\"wenshao\"}", text); + } + + private static class Model { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_630.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_630.java new file mode 100644 index 0000000000..db8b57fdd7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_630.java @@ -0,0 +1,70 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_issue_630 extends TestCase { + + public void test_for_issue_null() throws Exception { + Model model = new Model(); + model.id = 123; + model.name = null; + model.modelName = null; + model.isFlay = false; +// model.persons = new ArrayList(); +// model.persons.add(new Person()); + + String str = JSON.toJSONString(model, SerializerFeature.BeanToArray); +// System.out.println(str); + JSON.parseObject(str, Model.class, Feature.SupportArrayToBean); + } + + public void test_for_issue_empty() throws Exception { + Model model = new Model(); + model.id = 123; + model.name = null; + model.modelName = null; + model.isFlay = false; + model.persons = new ArrayList(); +// model.persons.add(new Person()); + + String str = JSON.toJSONString(model, SerializerFeature.BeanToArray); +// System.out.println(str); + JSON.parseObject(str, Model.class, Feature.SupportArrayToBean); + } + + public void test_for_issue_one() throws Exception { + Model model = new Model(); + model.id = 123; + model.name = null; + model.modelName = null; + model.isFlay = false; + model.persons = new ArrayList(); + model.persons.add(new Person()); + + String str = JSON.toJSONString(model, SerializerFeature.BeanToArray); +// System.out.println(str); + JSON.parseObject(str, Model.class, Feature.SupportArrayToBean); + } + + public static class Model { + + public int id; + public String name; + public String modelName; + public boolean isFlay; + public List persons;// = new ArrayList(); + } + + public static class Person { + + public int id; + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_676.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_676.java new file mode 100644 index 0000000000..ea51471776 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_676.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.util.ASMUtils; + + +public class Bug_for_issue_676 extends TestCase { + public void test_for_issue() throws Exception { + JSON.parseObject("{\"modelType\":\"\"}", MenuExpend.class); + } + + public static class MenuExpend { + public ModelType modelType; + } + + public static enum ModelType { + A, B, C + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_694.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_694.java new file mode 100644 index 0000000000..3f7ff4fa67 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_694.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_issue_694 extends TestCase { + public void test_for_issue() throws Exception { + Root root = JSON.parseObject("{\"entity\":{\"isBootomPluginClickable\":true,\"isMainPoi\":true}}", Root.class); + Assert.assertTrue(root.entity.isBootomPluginClickable); + Assert.assertTrue(root.entity.isMainPoi); + } + + public static class Root { + public GSMapItemBIZEntity entity; + + class GSMapItemBIZEntity { + protected boolean isBootomPluginClickable = false; // 金融部门外币兑换业务网点 点击底部无需跳转 + protected boolean isMainPoi = false; + + public boolean isBootomPluginClickable() { + return isBootomPluginClickable; + } + + public void setBootomPluginClickable(boolean bootomPluginClickable) { + isBootomPluginClickable = bootomPluginClickable; + } + + public boolean isMainPoi() { + return isMainPoi; + } + + public void setMainPoi(boolean mainPoi) { + isMainPoi = mainPoi; + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_729.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_729.java new file mode 100644 index 0000000000..055c180282 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_729.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; +import java.util.Date; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.json.bvt.bug.Bug_for_issue_729.Person; + +import junit.framework.TestCase; + +public class Bug_for_issue_729 extends TestCase { + + public void test_for_issue() throws Exception { + Person person = new Person(); + person.setName("bob"); + person.startTime = new Date(); + + String result = JSON.toJSONString(person); + Person person2 = JSON.parseObject(result, Person.class); + person2.toString(); + } + + public static class Person implements Serializable { + + public String name; + + @JSONField(format = "yyyy-MM-dd HH:mm") + public Date startTime; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + @Override + public String toString() { + return "Person [name=" + name + ", startTime=" + startTime + "]"; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_807.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_807.java new file mode 100644 index 0000000000..452508e5a8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_807.java @@ -0,0 +1,43 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.io.Serializable; + +/** + * Created by wenshao on 16/9/5. + */ +public class Bug_for_issue_807 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"ckid\":\"81a5953835310708e414057adb45e826\",\"rcToken\":\"E+jkQCWSwop+JICPBHc+fxMYeExTx2NTDGZCJ8gIPg7NbMLNvfmZBPU2dR5uxpRRe+zPnOIaCATpHcSa6q+k39HGjNFFDRt9PNlEJokpxhTw9gYJ/WKoSlVR/4ibjIgjvVHxS2lNLS4=\",\"userInfo\":{\"openid\":\"oEH-vt-7mGHOQets-XbE1c3DKpVc\",\"nickname\":\"Pietro\",\"sex\":1,\"language\":\"zh_CN\",\"city\":\"\",\"province\":\"Beijing\",\"country\":\"CN\",\"headimgurl\":\"http://wx.qlogo.cn/mmopen/kox8ma2sryApONj7kInbic4iaCZD8tXL4sqe7k3wROLpb2uCZhOiceAbL69ANeXSMu9zf7hibmt3Y0Ed4A6zIt9ibnPaiciauLZn57c/0\",\"privilege\":[],\"unionid\":\"oq9QRtyW-kb6R_7289hIycrOfnyc\"},\"isNewUser\":false}"; + + Root root = JSON.parseObject(text, Root.class); + assertEquals("oq9QRtyW-kb6R_7289hIycrOfnyc", root.userInfo.unionId); + + JSONObject jsonObject = JSON.parseObject(text); + WechatUserInfo wechatUserInfo = jsonObject.getObject("userInfo", WechatUserInfo.class); + + assertEquals("oq9QRtyW-kb6R_7289hIycrOfnyc", wechatUserInfo.unionId); + } + + public static class Root { + public String ckid; + public String rcToken; + public WechatUserInfo userInfo; + public boolean isNewUser; + } + + public static class WechatUserInfo implements Serializable { + + public String unionId; + public String openId; + public String nickname; + public int sex; + public String province; + public String country; + public String headimgurl; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_937.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_937.java new file mode 100644 index 0000000000..eb905d56f2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_937.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; +import org.junit.Assert; + +/** + * Created by wuwen on 2016/12/7. + */ +public class Bug_for_issue_937 extends TestCase { + + public void test_for_issue() throws Exception { + String json = "{outPara:{name:\"user\"}}"; + Out out = returnOut(json, Info.class); + Assert.assertEquals("user", out.getOutPara().getName()); + } + + public static Out returnOut(String jsonStr, Class c2) { + return JSON.parseObject(jsonStr, new TypeReference>(c2) { + }); + } + + public static class Out { + private T outPara; + + public void setOutPara(T t) { + outPara = t; + } + + public T getOutPara() { + return outPara; + } + + public Out() { + } + + public Out(T t) { + setOutPara(t); + } + } + + public static class Info { + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jared1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jared1.java new file mode 100755 index 0000000000..acb13cc9ef --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jared1.java @@ -0,0 +1,86 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_jared1 extends TestCase { + public void test_for_jared1() throws Exception { + User user = new User(); + + String text = JSON.toJSONString(user); + + System.out.println(text); + + JSON.parseObject(text, User.class); + } + + public static class User implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + + private Integer id; + + private String acount; + + private String password; + + private Set crowds = new HashSet(); + + private Set friends = new HashSet(); + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getAcount() { + return acount; + } + + public void setAcount(String acount) { + this.acount = acount; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Set getCrowds() { + return crowds; + } + + public void setCrowds(Set crowds) { + this.crowds = crowds; + } + + public Set getFriends() { + return friends; + } + + public void setFriends(Set friends) { + this.friends = friends; + } + + // 一下省略 + + } + + public static class Crowd { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_javaeye_litterJava.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_javaeye_litterJava.java new file mode 100755 index 0000000000..885683bdee --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_javaeye_litterJava.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_javaeye_litterJava extends TestCase { + public void test_for_bug() throws Exception { + Group group = new Group(); + group.setId(123L); + group.setName("xxx"); + group.getClzes().add(Group.class); + + String text = JSON.toJSONString(group); + JSON.parseObject(text, Group.class); + } + + public static class Group { + + private Long id; + private String name; + private List clzes = new ArrayList(); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getClzes() { + return clzes; + } + + public void setClzes(List clzes) { + this.clzes = clzes; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jial10802.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jial10802.java new file mode 100755 index 0000000000..fe1b048b98 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jial10802.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.bvtVO.Bean; +import com.alibaba.json.bvtVO.Page; + +import junit.framework.TestCase; + + +public class Bug_for_jial10802 extends TestCase { + public void test_for_jial10802() throws Exception { + Page page = new Page(); + page.setCount(1); + List items = new ArrayList(); + Bean item = new Bean(); + item.setId(1); + item.setName("name"); + item.setDesc("desc"); + items.add(item); + page.setItems(items); + String json = JSON.toJSONString(page, SerializerFeature.PrettyFormat); + + Page jsonPage = JSON.parseObject(json, new TypeReference>() { + }); + System.out.println(jsonPage.getItems().get(0).getName()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei.java new file mode 100755 index 0000000000..835fbc5dbc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + + +public class Bug_for_jiangwei extends TestCase { + public void test_0 () throws Exception { + String text = "['42-0','超級聯隊\\x28中\\x29','辛當斯','1.418',10,'11/18/2012 02:15',1,0,1,0,'',0,0,0,0]"; + JSON.parse(text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei1.java new file mode 100755 index 0000000000..d98844a4b6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei1.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +public class Bug_for_jiangwei1 extends TestCase { + + public void test_double() throws Exception { + JSONObject json = JSON.parseObject("{\"val\":12.3}"); + Assert.assertTrue(12.3D == json.getDoubleValue("val")); + } + + public void test_JSONArray_double() throws Exception { + JSONArray json = JSON.parseArray("[12.3]"); + Assert.assertTrue(12.3D == json.getDoubleValue(0)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei2.java new file mode 100755 index 0000000000..222be108c0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei2.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; + +public class Bug_for_jiangwei2 extends TestCase { + public void test_for_jiangwei() throws Exception { +// String str = "[2,'韩国篮球联赛','仁川大象(男篮)','首尔SK骑士 男篮',['大/小',3],'总进球 : 138.5 @ 0-0','','大','0.66','',1,25,200,1,0,0,'True','False',0,'','','',0,0,19819905,1,'h',145528,0]"; +// JSONArray array = JSON.parseArray(str); + String str = "[]"; + str = "[]"; + JSONArray array = JSON.parseArray(str); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jinghui70.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jinghui70.java new file mode 100755 index 0000000000..7129a9fb8b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jinghui70.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_jinghui70 extends TestCase { + + public static abstract class IdObject { + + private I id; + + public I getId() { + return id; + } + + public void setId(I id) { + this.id = id; + } + } + + public static class Child extends IdObject { + + } + + public void test_generic() throws Exception { + String str = "{\"id\":0}"; + + Child child = JSON.parseObject(str, Child.class); + Assert.assertEquals(Long.class, child.getId().getClass()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jinguwei.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jinguwei.java new file mode 100755 index 0000000000..489b90d1a1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jinguwei.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class Bug_for_jinguwei extends TestCase { + + public void test_null() throws Exception { + VO vo = new VO(); + vo.setList(new ArrayList()); + vo.getList().add(null); + vo.getList().add(null); + + Assert.assertEquals("{\"list\":[null,null]}", JSON.toJSONString(vo)); + } + + public static class VO { + private List list; + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_json_array.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_json_array.java new file mode 100644 index 0000000000..1d165952e6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_json_array.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_json_array extends TestCase { + + public void test_bug() throws Exception { + String jsonStr = "{\"state\":0,\"data\":[{\"items\":[{\"tip\":\"\u5218\u82e5\u82f1\",\"url\":\"xiami:\\/\\/artist\\/1930\"},{\"tip\":\"\u5218\u5fb7\u534e\",\"url\":\"xiami:\\/\\/artist\\/648\"}],\"type\":\"artist\"},{\"items\":[{\"tip\":\"\u6f02\u6d0b\u8fc7\u6d77\u6765\u770b\u4f60 (Live) - \u5218\u660e\u6e58\",\"url\":\"xiami:\\/\\/song\\/1773431302\"},{\"tip\":\"\\u6211\\u4eec\\u6ca1\\u6709\\u5728\\u4e00\\u8d77 - \\u5218\\u82e5\\u82f1\",\"url\":\"xiami:\\/\\/song\\/1769471863\"},{\"tip\":\"\\u54ed\u7802 (Live)(\\u5218\\u660e\\u6e58\\u80dc\\u51fa) - \\u5218\u660e\u6e58\",\"url\":\"xiami:\\/\\/ song\\/1773484887\"}],\"type\":\"song\"},{\"items\":[{\"tip\":\"\\u4eb2\\u7231\\u7684\\u8def\\u4eba - \\u5218\\u82e5\\u82f1\",\"url\":\"xiami:\\/\\/album\\/55230\"},{\"tip\":\"\\u5728\\u4e00\\u8d77 - \\u5218\\u82e5\\u82f1\",\"url\":\"xiami:\\/\\/album\\/377241\"}],\"type\":\"album\"}],\"status\":\"ok\",\"err\":null} "; + + Parser parser = JSON.parseObject(jsonStr, Parser.class); + + System.out.println(JSON.toJSONString(parser)); + } + + public static class Parser { + + public int state; + public JSON data; + public String status; + public String err; + + public int getState() { + return state; + } + + public void setState(int state) { + this.state = state; + } + + public JSON getData() { + return data; + } + + public void setData(JSON data) { + this.data = data; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getErr() { + return err; + } + + public void setErr(String err) { + this.err = err; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jsonobj_null.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jsonobj_null.java new file mode 100644 index 0000000000..e373647ad9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_jsonobj_null.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_jsonobj_null extends TestCase { + + public void test_parseObjectNull() throws Exception { + JSON.parseObject("{\"data\":null}", VO.class); + } + + public static class VO { + + private JSONObject data; + + public JSONObject getData() { + return data; + } + + public void setData(JSONObject data) { + this.data = data; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_juewu.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_juewu.java new file mode 100644 index 0000000000..32ecd06e9b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_juewu.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class Bug_for_juewu extends TestCase { + public void test_str() throws Exception { + String text = "{\"weitao_feed\":{\"head\":{\"Version\":\"V1.0\",\"Status\":\"OK\",\"SearchTime\":1488,\"DocsReturn\":18,\"DocsFound\":20,\"DocsRestrict\":20,\"DocsSearch\":0},\"auctions\":[{\"id\":\"110009362197\",\"creator_id\":\"673515636\",\"gmt_create_ms\":\"1385540374000\"}]}}"; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix.java new file mode 100755 index 0000000000..8c8ef85e9c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class Bug_for_lenolix extends TestCase { + public void test_FieldMap() throws Exception { + Map map = JSON.parseObject("{\"key\":[\"value1\",\"value2\"]}", + new TypeReference>() { + }); + String[] array = map.get("key"); + Assert.assertEquals("value1", array[0]); + Assert.assertEquals("value2", array[1]); + + System.out.println(Thread.currentThread().getContextClassLoader().getResource("com/alibaba/fastjson/JSON.class")); + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_1.java new file mode 100755 index 0000000000..31918f1121 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_1.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_lenolix_1 extends TestCase { + + public void test_0() throws Exception { + Map matcherMap = new HashMap(); + String matcherMapString = JSON.toJSONString(matcherMap, SerializerFeature.WriteClassName, + SerializerFeature.WriteMapNullValue); + + System.out.println(matcherMapString); + + matcherMap = JSONObject.parseObject(matcherMapString, new TypeReference>() { + }); + } + + public static class User { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_10.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_10.java new file mode 100755 index 0000000000..8954409ce0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_10.java @@ -0,0 +1,65 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_lenolix_10 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_lenolix_10."); + } + + public void test_for_objectKey() throws Exception { + Map map2 = new HashMap(); + User user = new User(); + user.setId(1); + user.setIsBoy(true); + user.setName("leno.lix"); + // user.setBirthDay(simpleDateFormat.parse("2012-03-07 22:38:21 CST")); + // user.setGmtCreate(new java.sql.Date(simpleDateFormat.parse("2012-02-03 22:38:21 CST") + // .getTime())); + map2.put(1, user); + String mapJson2 = JSON.toJSONString(map2, SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue); + System.out.println(mapJson2); + Object object2 = JSON.parse(mapJson2); + + } + + public static class User { + + private int id; + private Boolean isBoy; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Boolean getIsBoy() { + return isBoy; + } + + public void setIsBoy(Boolean isBoy) { + this.isBoy = isBoy; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_11.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_11.java new file mode 100755 index 0000000000..d865e062e4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_11.java @@ -0,0 +1,67 @@ +package com.alibaba.json.bvt.bug; + +import java.text.SimpleDateFormat; +import java.util.Locale; +import java.util.TimeZone; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_lenolix_11 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_lenolix_11."); + } + + public void test_for_objectKey() throws Exception { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy", JSON.defaultLocale); + simpleDateFormat.setTimeZone(JSON.defaultTimeZone); + + String simpleDateFormatJson = JSON.toJSONString(simpleDateFormat, SerializerFeature.WriteClassName, + SerializerFeature.WriteMapNullValue); + + System.out.println(simpleDateFormatJson); + + java.text.SimpleDateFormat format = (java.text.SimpleDateFormat) JSON.parse(simpleDateFormatJson); + Assert.assertEquals("MM-dd-yyyy", format.toPattern()); + + } + + public static class User { + + private int id; + private Boolean isBoy; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Boolean getIsBoy() { + return isBoy; + } + + public void setIsBoy(Boolean isBoy) { + this.isBoy = isBoy; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_2.java new file mode 100755 index 0000000000..d32e55ea58 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_2.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_lenolix_2 extends TestCase { + + public void test_0() throws Exception { + Map matcherMap = new HashMap(); + String matcherMapString = JSON.toJSONString(matcherMap, SerializerFeature.WriteMapNullValue); + + System.out.println(matcherMapString); + + matcherMap = JSONObject.parseObject(matcherMapString, new TypeReference>() { + }); + } + + public static class User { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_3.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_3.java new file mode 100755 index 0000000000..d75141d15b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_3.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; + +public class Bug_for_lenolix_3 extends TestCase { + + public void test_0() throws Exception { + + System.out.println("{}"); + + JSONObject.parseObject("{\"id\":{}}", new TypeReference>>() { + }); + } + + public static class User { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_4.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_4.java new file mode 100755 index 0000000000..266362c629 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_4.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_lenolix_4 extends TestCase { + + public void test_for_objectKey() throws Exception { + Map, String> map = new HashMap, String>(); + Map submap = new HashMap(); + submap.put("subkey", "subvalue"); + map.put(submap, "value"); + String jsonString = JSON.toJSONString(map, SerializerFeature.WriteClassName); + System.out.println(jsonString); + Object object = JSON.parse(jsonString); + JSON.parseObject(jsonString); + + System.out.println(object.toString()); + } + + public void test_for_arrayKey() throws Exception { + Map, String> map = new HashMap, String>(); + List key = new ArrayList(); + + key.add("subkey"); + map.put(key, "value"); + String jsonString = JSON.toJSONString(map, SerializerFeature.WriteClassName); + System.out.println(jsonString); + Object object = JSON.parse(jsonString); + System.out.println(object.toString()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_5.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_5.java new file mode 100755 index 0000000000..a99b3317f1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_5.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_lenolix_5 extends TestCase { + + public void test_for_objectKey() throws Exception { + Map obj = new HashMap(); + Object obja = new Object(); + Object objb = new Object(); + obj.put(obja, objb); + + String newJsonString = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue, + SerializerFeature.WriteClassName); + System.out.println(newJsonString); + + Object newObject = JSON.parse(newJsonString); + + System.out.println(newObject); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_6.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_6.java new file mode 100755 index 0000000000..db244f5fc0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_6.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_lenolix_6 extends TestCase { + + public void test_for_objectKey() throws Exception { + Map map = new HashMap(); + map.put("id", 1); + map.put("name", "leno.lix"); + map.put("birthday", new Date()); + map.put("gmtCreate", new java.sql.Date(new Date().getTime())); + map.put("gmtModified", new java.sql.Timestamp(new Date().getTime())); + + String userJSON = JSON.toJSONString(map, SerializerFeature.WriteClassName, + SerializerFeature.WriteMapNullValue); + + System.out.println(userJSON); + + Object object = JSON.parse(userJSON); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_7.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_7.java new file mode 100755 index 0000000000..f39448d7a9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_7.java @@ -0,0 +1,132 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_lenolix_7 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_lenolix_7"); + } + + public void test_for_objectKey() throws Exception { + User user = new User(); + user.setId(1); + user.setName("leno.lix"); + user.setIsBoy(true); + user.setBirthDay(new Date()); + user.setGmtCreate(new java.sql.Date(new Date().getTime())); + user.setGmtModified(new java.sql.Timestamp(new Date().getTime())); + String userJSON = JSON.toJSONString(user, SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue); + + System.out.println(userJSON); + + User returnUser = (User) JSON.parse(userJSON); + + } + + private static class User implements Serializable { + + /** + * + */ + + private static final long serialVersionUID = 6192533820796587011L; + + private Integer id; + private String name; + private Boolean isBoy; + private Address address; + private Date birthDay; + private java.sql.Date gmtCreate; + private java.sql.Timestamp gmtModified; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean getIsBoy() { + return isBoy; + } + + public void setIsBoy(Boolean isBoy) { + this.isBoy = isBoy; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public Date getBirthDay() { + return birthDay; + } + + public void setBirthDay(Date birthDay) { + this.birthDay = birthDay; + } + + public java.sql.Date getGmtCreate() { + return gmtCreate; + } + + public void setGmtCreate(java.sql.Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + + public java.sql.Timestamp getGmtModified() { + return gmtModified; + } + + public void setGmtModified(java.sql.Timestamp gmtModified) { + this.gmtModified = gmtModified; + } + + } + + public static class Address { + + private String value; + + public Address(){ + } + + public Address(String value){ + this.value = value; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_8.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_8.java new file mode 100755 index 0000000000..8d890b4cf0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_8.java @@ -0,0 +1,112 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.TimeZone; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_lenolix_8 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_lenolix_8."); + } + + public void test_for_objectKey() throws Exception { + DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", JSON.defaultLocale); + simpleDateFormat.setTimeZone(JSON.defaultTimeZone); + Map map = new HashMap(); + + User user = new User(); + user.setId(1); + user.setIsBoy(true); + user.setName("leno.lix"); + user.setBirthDay(simpleDateFormat.parse("2012-03-07 22:38:21")); + user.setGmtCreate(new java.sql.Date(simpleDateFormat.parse("2012-02-03 22:38:21").getTime())); + + map.put(1, user); + + String mapJson = JSON.toJSONString(map, SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue); + + System.out.println(mapJson); + + Object object = JSON.parse(mapJson); + + } + + public static class User implements Serializable { + + /** + * + */ + + private static final long serialVersionUID = 6192533820796587011L; + + private Integer id; + private String name; + private Boolean isBoy; + private Date birthDay; + private java.sql.Date gmtCreate; + private java.sql.Timestamp gmtModified; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean getIsBoy() { + return isBoy; + } + + public void setIsBoy(Boolean isBoy) { + this.isBoy = isBoy; + } + + + public Date getBirthDay() { + return birthDay; + } + + public void setBirthDay(Date birthDay) { + this.birthDay = birthDay; + } + + public java.sql.Date getGmtCreate() { + return gmtCreate; + } + + public void setGmtCreate(java.sql.Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + + public java.sql.Timestamp getGmtModified() { + return gmtModified; + } + + public void setGmtModified(java.sql.Timestamp gmtModified) { + this.gmtModified = gmtModified; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_9.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_9.java new file mode 100755 index 0000000000..7ea5ff0001 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_9.java @@ -0,0 +1,104 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.bvt.bug.Bug_for_lenolix_9.Address.Country; + +public class Bug_for_lenolix_9 extends TestCase { + + protected void setUp() throws Exception { + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_lenolix_9."); + } + + public void test_for_objectKey() throws Exception { + Map submap4 = new HashMap(); + Address address = new Address(); + address.setCity("hangzhou"); + address.setStreet("wangshang.RD"); + address.setPostCode(310002); + submap4.put("address1", address); + submap4.put("address2", address); + + Country country = address.new Country(); + country.setProvince("ZheJiang"); + + address.setCountry(country); + + String mapString4 = JSON.toJSONString(submap4, SerializerFeature.WriteClassName, + SerializerFeature.WriteMapNullValue); + + System.out.println(mapString4); + Object object4 = JSON.parse(mapString4); + Assert.assertNotNull(object4); + + Map map = (Map) object4; + + Assert.assertNotNull(map.get("address1")); + Assert.assertNotNull(map.get("address2")); + + Assert.assertTrue(map.get("address1") == map.get("address2")); + + } + + public static class Address { + + private String city; + private String street; + private int postCode; + private Country country; + + public Country getCountry() { + return country; + } + + public void setCountry(Country country) { + this.country = country; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public int getPostCode() { + return postCode; + } + + public void setPostCode(int postCode) { + this.postCode = postCode; + } + + public class Country { + + private String province; + + public String getProvince() { + return province; + } + + public void setProvince(String province) { + this.province = province; + } + + } + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom.java new file mode 100755 index 0000000000..cba486dd69 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_leupom extends TestCase { + + public void test_bug() throws Exception { + Person person = new Person(); + person.setId(12345); + + String text = JSON.toJSONString(person); + + System.out.println(text); + } + + public abstract static class Model { + + public abstract Serializable getId(); + + } + + public static class Person extends Model { + + private Integer id; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom_2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom_2.java new file mode 100755 index 0000000000..1282752771 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom_2.java @@ -0,0 +1,60 @@ +package com.alibaba.json.bvt.bug; + +import java.util.concurrent.TimeUnit; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_leupom_2 extends TestCase { + + public void test_0() throws Exception { + Time time = new Time(1000, TimeUnit.MILLISECONDS); + + String text = JSON.toJSONString(time); + + System.out.println(text); + + Time time2 = JSON.parseObject(text, Time.class); + + Assert.assertEquals(time2.getValue(), time.getValue()); + Assert.assertEquals(time2.getUnit(), time.getUnit()); + } + + public static class Time { + + private long value; + private TimeUnit unit; + + public Time(){ + super(); + } + + public Time(long value, TimeUnit unit){ + super(); + this.value = value; + this.unit = unit; + } + + public long getValue() { + return value; + } + + @JSONField(serialzeFeatures={SerializerFeature.WriteEnumUsingToString}) + public TimeUnit getUnit() { + return unit; + } + + public void setValue(long value) { + this.value = value; + } + + public void setUnit(TimeUnit unit) { + this.unit = unit; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom_3.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom_3.java new file mode 100755 index 0000000000..84ef326f59 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom_3.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_leupom_3 extends TestCase { + + public void test_bug() throws Exception { + Person person = new Person(); + person.setId(12345); + + String text = JSON.toJSONString(person); + + System.out.println(text); + + Person person2 = JSON.parseObject(text, Person.class); + + Assert.assertEquals(person.getId(), person2.getId()); + } + + public abstract static interface Model { + + Serializable getId(); + void setId(Integer value); + } + + public static class Person implements Model { + + private Integer id; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_for_liuwanzhen_ren.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_liuwanzhen_ren.java old mode 100644 new mode 100755 similarity index 96% rename from src/test/java/com/alibaba/json/test/bvt/bug/Bug_for_liuwanzhen_ren.java rename to src/test/java/com/alibaba/json/bvt/bug/Bug_for_liuwanzhen_ren.java index aef72bd460..4c302e48bd --- a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_for_liuwanzhen_ren.java +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_liuwanzhen_ren.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.bug; +package com.alibaba.json.bvt.bug; import java.util.HashMap; diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_liuying.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_liuying.java new file mode 100644 index 0000000000..1ad7adcfff --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_liuying.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +/** + * Created by wenshao on 18/01/2017. + */ +public class Bug_for_liuying extends TestCase { + + public void test_for_bug() throws Exception { + String aa = "[{\"dictFont\":\"\",\"dictId\":\"wap\",\"dictName\":\"无线&手淘\"},{\"dictFont\":\"\",\"dictId\":\"etao\",\"dictName\":\"搜索\"}]"; + JSONObject jsonResult = new JSONObject(); + JSONArray jsonArray = JSONArray.parseArray(aa); + jsonResult.put("aaa", jsonArray); + + System.out.println(jsonResult); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_long_whitespace.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_long_whitespace.java new file mode 100644 index 0000000000..ab7df4c35e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_long_whitespace.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_long_whitespace extends TestCase { + + public void test() throws Exception { + String json = "{\"f1\":11222509, \"f2\":7}"; + + VO v = JSON.parseObject(json, VO.class); + System.out.println(v.getF1()); + System.out.println(v.getF2()); + + } + + public static class VO { + + private long f1; + private int f2; + + public long getF1() { + return f1; + } + + public void setF1(long f1) { + this.f1 = f1; + } + + public int getF2() { + return f2; + } + + public void setF2(int f2) { + this.f2 = f2; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ludong.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ludong.java new file mode 100644 index 0000000000..2ae4148fba --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ludong.java @@ -0,0 +1,916 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_ludong extends TestCase { + + public void test_for_ludong() throws Exception { + String msg = "{\"changedItems\":[{\"attribute\":\"new\",\"benefitCustomer\":\"chance130320584431\",\"benefitCustomerContactor\":5809917,\"benefitCustomerId\":2001385618,\"bizStatus\":\"audit_pass\",\"creator\":\"dowjons\",\"defaultBiz\":true,\"discountRate\":100,\"domain\":\"nirvana\",\"executeAmount\":3688,\"gmtCreate\":1367856000000,\"gmtModified\":1368374400000,\"gmtSign\":1367856000000,\"id\":321600616,\"isDeleted\":\"n\",\"itemNum\":\"W1305070000053_1\",\"lastOperType\":\"finance_pass_rollback\",\"memberId\":\"3592950865\",\"modifier\":\"haiquan.zhanghq\",\"num\":12,\"oppId\":103722314,\"orderId\":315749401,\"parentId\":0,\"paymentAmount\":0,\"paymentStatus\":\"payment_none\",\"policyId\":63149,\"price\":3688,\"productCode\":\"pc060\",\"purchaseType\":\"bought\",\"quotedPrice\":3688,\"salesId\":\"tiandan\",\"salesOrgFullid\":\"/10/1/30/101/160/1001/1051/\",\"serviceSupplyCompany\":\"B50\",\"signSalesId\":\"tiandan\",\"signSalesOrgFullId\":\"/10/1/30/101/160/1001/1051/\",\"traceChange\":true,\"ultimatePrice\":3688,\"unServiceDay\":0,\"unit\":\"M\",\"unvoucherAmount\":3688,\"voucherStatus\":\"voucher_none\"}],\"context\":{\"payAmount\":3688,\"payDate\":1368442850437,\"paymentStatus\":\"payment_success\"},\"generateTime\":1368442868624,\"msgType\":\"PAYMENT\",\"orderNumber\":\"W1305070000053\"}"; + + OrderInternalDto dto = JSON.parseObject(msg, OrderInternalDto.class); + } + + public static class OrderInternalDto implements Serializable { + + private static final long serialVersionUID = 3228508302993121205L; + + /* 对象生成的时间 */ + + private Date generateTime; + + /** 订单号 */ + + private String orderNumber; + + /** 对象的业务状态 */ + + private MSGTYPE msgType; + + /** 订单的瞬时状态 */ + + // private List instantItems; + + /** 发生状态变化的订单行列,比如到款只是对一个订单行发生到账行为 */ + + private List changedItems; + + /** 上下文参数 */ + + private Map context; + + public OrderInternalDto(){ + + this.generateTime = new Date(); + + context = new HashMap(); + + } + + public void setContext(Map context) { + + if (context == null) return; + + this.context = context; + + } + + @Override + public String toString() { + + return JSON.toJSONString(this); + + } + + } + + public static class OrdOrderItem implements Cloneable, Serializable { + + public static String ORDER_ID = "orderId"; + + private Object orderId; + + public static String PARENT_ID = "parentId"; + + private Integer parentId; + + public static String SERIAL_NUM = "serialNum"; + + private String serialNum; + + public static String ITEM_NUM = "itemNum"; + + private String itemNum; + + public static String PURCHASE_TYPE = "purchaseType"; + + private String purchaseType; + + public static String ATTRIBUTE = "attribute"; + + private String attribute; + + public static String MEMBER_ID = "memberId"; + + private String memberId; + + public static String PRODUCT_CODE = "productCode"; + + private String productCode; + + public static String NUM = "num"; + + private Integer num; + + public static String UNIT = "unit"; + + private String unit; + + public static String PRICE = "price"; + + private java.math.BigDecimal price; + + public static String DISCOUNT_RATE = "discountRate"; + + private java.math.BigDecimal discountRate; + + public static String QUOTED_PRICE = "quotedPrice"; + + private java.math.BigDecimal quotedPrice; + + public static String ULTIMATE_PRICE = "ultimatePrice"; + + private java.math.BigDecimal ultimatePrice; + + public static String EXECUTE_AMOUNT = "executeAmount"; + + private java.math.BigDecimal executeAmount; + + public static String GMT_TARGET_BEGIN = "gmtTargetBegin"; + + private java.util.Date gmtTargetBegin; + + public static String GMT_TARGET_END = "gmtTargetEnd"; + + private java.util.Date gmtTargetEnd; + + public static String GMT_ACTUAL_BEGIN = "gmtActualBegin"; + + private java.util.Date gmtActualBegin; + + public static String GMT_ACTUAL_END = "gmtActualEnd"; + + private java.util.Date gmtActualEnd; + + public static String SERVICE_SUPPLY_COMPANY = "serviceSupplyCompany"; + + private String serviceSupplyCompany; + + public static String BENEFIT_CUSTOMER = "benefitCustomer"; + + private String benefitCustomer; + + public static String BENEFIT_CUSTOMER_ID = "benefitCustomerId"; + + private Integer benefitCustomerId; + + public static String BENEFIT_CUSTOMER_CONTACTOR = "benefitCustomerContactor"; + + private Integer benefitCustomerContactor; + + public static String BIZ_STATUS = "bizStatus"; + + private String bizStatus; + + public static String VOUCHER_STATUS = "voucherStatus"; + + private String voucherStatus; + + public static String PAYMENT_STATUS = "paymentStatus"; + + private String paymentStatus; + + public static String PAYMENT_AMOUNT = "paymentAmount"; + + private java.math.BigDecimal paymentAmount; + + public static String POLICY_ID = "policyId"; + + private Integer policyId; + + public static String MEMO = "memo"; + + private String memo; + + public static String SUPPORTER = "supporter"; + + private String supporter; + + public static String SUPPORTER_ORG_ID = "supporterOrgId"; + + private Integer supporterOrgId; + + public static String SUPPORTER_ORG_FULLID = "supporterOrgFullid"; + + private String supporterOrgFullid; + + public static String SALES_ORG_FULLID = "salesOrgFullid"; + + private String salesOrgFullid; + + public static String SIGN_SALES_ORG_FULLID = "signSalesOrgFullId"; + + private String signSalesOrgFullId; + + public static String OPP_ID = "oppId"; + + private Integer oppId; + + public static String DOMAIN = "domain"; + + private String domain; + + public static String UN_SERVICE_DAY = "unServiceDay"; + + private java.math.BigDecimal unServiceDay; + + public static String PROCESS_ID = "processId"; + + private Long processId; + + public static String LAST_OPER_TYPE = "lastOperType"; + + private String lastOperType; + + public static String UNVOUCHER_AMOUNT = "unvoucherAmount"; + + private java.math.BigDecimal unvoucherAmount; + + public static String GMT_VOUCHER_RECEIVE = "gmtVoucherReceive"; + + private java.util.Date gmtVoucherReceive; + + public static String GMT_PAYMENT_REMIT = "gmtPaymentRemit"; + + private java.util.Date gmtPaymentRemit; + + public static String SERVICE_JUMP_DAYS = "serviceJumpDays"; + + private Integer serviceJumpDays; + + public static String SIGN_SALES_ID = "signSalesId"; + + private String signSalesId; + + public static String SALES_ORG_ID = "salesOrgId"; + + private Integer salesOrgId; + + public static String SIGN_SALES_ORG_ID = "signSalesOrgId"; + + private Integer signSalesOrgId; + + public Integer getSignSalesOrgId() { + + return signSalesOrgId; + + } + + public void setSignSalesOrgId(Integer signSalesOrgId) { + + this.signSalesOrgId = signSalesOrgId; + + } + + public Integer getSalesOrgId() { + + return salesOrgId; + + } + + public void setSalesOrgId(Integer salesOrgId) { + + this.salesOrgId = salesOrgId; + + } + + public static String SIGN_SELLER_COMPANY = "signSellerCompany"; + + private String signSellerCompany; + + public static String BARGAIN_ID = "bargainId"; + + private Integer bargainId; + + public Integer getBargainId() { + + return bargainId; + + } + + public void setBargainId(Integer bargainId) { + + this.bargainId = bargainId; + + } + + public String getSignSellerCompany() { + + return signSellerCompany; + + } + + public void setSignSellerCompany(String signSellerCompany) { + + this.signSellerCompany = signSellerCompany; + + } + + // 增加了新签和续签销售的id + + public static String SALES_ID = "salesId"; + + private String salesId; + + public String getSalesId() { + + return salesId; + + } + + public void setSalesId(String salesId) { + + this.salesId = salesId; + + } + + public String getRenewSalesId() { + + return renewSalesId; + + } + + public void setRenewSalesId(String renewSalesId) { + + this.renewSalesId = renewSalesId; + + } + + public static String RENEW_SALES_ID = "renewSalesId"; + + private String renewSalesId; + + public static String GMT_SIGN = "gmtSign"; + + private java.util.Date gmtSign; + + public Object getOrderId() { + + return this.orderId; + + } + + public void setOrderId(Object orderId) { + + this.orderId = orderId; + + } + + public Integer getParentId() { + + return this.parentId; + + } + + public void setParentId(Integer parentId) { + + this.parentId = parentId; + + } + + public String getSerialNum() { + + return this.serialNum; + + } + + public void setSerialNum(String serialNum) { + + this.serialNum = serialNum; + + } + + public String getItemNum() { + + return this.itemNum; + + } + + public void setItemNum(String itemNum) { + + this.itemNum = itemNum; + + } + + public String getPurchaseType() { + + return this.purchaseType; + + } + + public void setPurchaseType(String purchaseType) { + + this.purchaseType = purchaseType; + + } + + public String getAttribute() { + + return this.attribute; + + } + + public void setAttribute(String attribute) { + + this.attribute = attribute; + + } + + public String getMemberId() { + + return this.memberId; + + } + + public void setMemberId(String memberId) { + + this.memberId = memberId; + + } + + public String getProductCode() { + + return this.productCode; + + } + + public void setProductCode(String productCode) { + + this.productCode = productCode; + + } + + public Integer getNum() { + + return this.num; + + } + + public void setNum(Integer num) { + + this.num = num; + + } + + public String getUnit() { + + return this.unit; + + } + + public void setUnit(String unit) { + + this.unit = unit; + + } + + public java.math.BigDecimal getPrice() { + + return this.price; + + } + + public void setPrice(java.math.BigDecimal price) { + + this.price = price; + + } + + public java.math.BigDecimal getDiscountRate() { + + return this.discountRate; + + } + + public void setDiscountRate(java.math.BigDecimal discountRate) { + + this.discountRate = discountRate; + + } + + public java.math.BigDecimal getQuotedPrice() { + + return this.quotedPrice; + + } + + public void setQuotedPrice(java.math.BigDecimal quotedPrice) { + + this.quotedPrice = quotedPrice; + + } + + public java.math.BigDecimal getUltimatePrice() { + + return this.ultimatePrice; + + } + + public void setUltimatePrice(java.math.BigDecimal ultimatePrice) { + + this.ultimatePrice = ultimatePrice; + + } + + public java.math.BigDecimal getExecuteAmount() { + + return this.executeAmount; + + } + + public void setExecuteAmount(java.math.BigDecimal executeAmount) { + + this.executeAmount = executeAmount; + + } + + public java.util.Date getGmtTargetBegin() { + + return this.gmtTargetBegin; + + } + + public void setGmtTargetBegin(java.util.Date gmtTargetBegin) { + + this.gmtTargetBegin = gmtTargetBegin; + + } + + public java.util.Date getGmtTargetEnd() { + + return this.gmtTargetEnd; + + } + + public void setGmtTargetEnd(java.util.Date gmtTargetEnd) { + + this.gmtTargetEnd = gmtTargetEnd; + + } + + public java.util.Date getGmtActualBegin() { + + return this.gmtActualBegin; + + } + + public void setGmtActualBegin(java.util.Date gmtActualBegin) { + + this.gmtActualBegin = gmtActualBegin; + + } + + public java.util.Date getGmtActualEnd() { + + return this.gmtActualEnd; + + } + + public void setGmtActualEnd(java.util.Date gmtActualEnd) { + + this.gmtActualEnd = gmtActualEnd; + + } + + public String getServiceSupplyCompany() { + + return this.serviceSupplyCompany; + + } + + public void setServiceSupplyCompany(String serviceSupplyCompany) { + + this.serviceSupplyCompany = serviceSupplyCompany; + + } + + public String getBenefitCustomer() { + + return this.benefitCustomer; + + } + + public void setBenefitCustomer(String benefitCustomer) { + + this.benefitCustomer = benefitCustomer; + + } + + public Integer getBenefitCustomerId() { + + return this.benefitCustomerId; + + } + + public void setBenefitCustomerId(Integer benefitCustomerId) { + + this.benefitCustomerId = benefitCustomerId; + + } + + public Integer getBenefitCustomerContactor() { + + return this.benefitCustomerContactor; + + } + + public void setBenefitCustomerContactor(Integer benefitCustomerContactor) { + + this.benefitCustomerContactor = benefitCustomerContactor; + + } + + public String getBizStatus() { + + return this.bizStatus; + + } + + public void setBizStatus(String bizStatus) { + + this.bizStatus = bizStatus; + + } + + public String getVoucherStatus() { + + return this.voucherStatus; + + } + + public void setVoucherStatus(String voucherStatus) { + + this.voucherStatus = voucherStatus; + + } + + public String getPaymentStatus() { + + return this.paymentStatus; + + } + + public void setPaymentStatus(String paymentStatus) { + + this.paymentStatus = paymentStatus; + + } + + public java.math.BigDecimal getPaymentAmount() { + + return this.paymentAmount; + + } + + public void setPaymentAmount(java.math.BigDecimal paymentAmount) { + + this.paymentAmount = paymentAmount; + + } + + public Integer getPolicyId() { + + return this.policyId; + + } + + public void setPolicyId(Integer policyId) { + + this.policyId = policyId; + + } + + public String getMemo() { + + return this.memo; + + } + + public void setMemo(String memo) { + + this.memo = memo; + + } + + public String getSupporter() { + + return this.supporter; + + } + + public void setSupporter(String supporter) { + + this.supporter = supporter; + + } + + public Integer getSupporterOrgId() { + + return this.supporterOrgId; + + } + + public void setSupporterOrgId(Integer supporterOrgId) { + + this.supporterOrgId = supporterOrgId; + + } + + public String getSupporterOrgFullid() { + + return this.supporterOrgFullid; + + } + + public void setSupporterOrgFullid(String supporterOrgFullid) { + + this.supporterOrgFullid = supporterOrgFullid; + + } + + public Integer getOppId() { + + return this.oppId; + + } + + public void setOppId(Integer oppId) { + + this.oppId = oppId; + + } + + public String getDomain() { + + return this.domain; + + } + + public void setDomain(String domain) { + + this.domain = domain; + + } + + public java.math.BigDecimal getUnServiceDay() { + + return this.unServiceDay; + + } + + public void setUnServiceDay(java.math.BigDecimal unServiceDay) { + + this.unServiceDay = unServiceDay; + + } + + public Long getProcessId() { + + return this.processId; + + } + + public void setProcessId(Long processId) { + + this.processId = processId; + + } + + public String getLastOperType() { + + return this.lastOperType; + + } + + public void setLastOperType(String lastOperType) { + + this.lastOperType = lastOperType; + + } + + public java.math.BigDecimal getUnvoucherAmount() { + + return this.unvoucherAmount; + + } + + public void setUnvoucherAmount(java.math.BigDecimal unvoucherAmount) { + + this.unvoucherAmount = unvoucherAmount; + + } + + public java.util.Date getGmtVoucherReceive() { + + return this.gmtVoucherReceive; + + } + + public void setGmtVoucherReceive(java.util.Date gmtVoucherReceive) { + + this.gmtVoucherReceive = gmtVoucherReceive; + + } + + public java.util.Date getGmtPaymentRemit() { + + return this.gmtPaymentRemit; + + } + + public void setGmtPaymentRemit(java.util.Date gmtPaymentRemit) { + + this.gmtPaymentRemit = gmtPaymentRemit; + + } + + public Integer getServiceJumpDays() { + + return this.serviceJumpDays; + + } + + public void setServiceJumpDays(Integer serviceJumpDays) { + + this.serviceJumpDays = serviceJumpDays; + + } + + @Override + public Object clone() throws CloneNotSupportedException { + + return super.clone(); + + } + + public String getSignSalesId() { + + return signSalesId; + + } + + public void setSignSalesId(String signSalesId) { + + this.signSalesId = signSalesId; + + } + + public String getSalesOrgFullid() { + + return salesOrgFullid; + + } + + public void setSalesOrgFullid(String salesOrgFullid) { + + this.salesOrgFullid = salesOrgFullid; + + } + + public String getSignSalesOrgFullId() { + + return signSalesOrgFullId; + + } + + public void setSignSalesOrgFullId(String signSalesOrgFullId) { + + this.signSalesOrgFullId = signSalesOrgFullId; + + } + + public java.util.Date getGmtSign() { + + return gmtSign; + + } + + public void setGmtSign(java.util.Date gmtSign) { + + this.gmtSign = gmtSign; + + } + + } + + public static class MSGTYPE { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_luogongwu.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_luogongwu.java new file mode 100644 index 0000000000..002a571c1b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_luogongwu.java @@ -0,0 +1,88 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wenshao on 15/06/2017. + */ +public class Bug_for_luogongwu extends TestCase { + + public void test_for_issue() throws Exception { + List imageList = new ArrayList(); + IflowItemImage image = new IflowItemImage(); + image.id = "72c7275c6b"; + imageList.add(image); + + imageList = new ArrayList(); + image = new IflowItemImage(); + image.id = "72c7275c6c"; + imageList.add(image); + + // force ASM + boolean asm = SerializeConfig.globalInstance.isAsmEnable(); + SerializeConfig.globalInstance.setAsmEnable(true); + + // Test ASM + Foo foo = new Foo(); + foo.thumbnails = imageList; + + String jsonString = JSON.toJSONString(foo); + System.out.println(jsonString); + + Foo foo1 = JSON.parseObject(jsonString, Foo.class); + + assertEquals(1, foo1.thumbnails.size()); + assertNotNull(foo1.thumbnails.get(0)); + assertSame(foo1.getThumbnail(), foo1.thumbnails.get(0)); + + + // test Not ASM + SerializeConfig.globalInstance.setAsmEnable(false); + FooNotAsm fooNotAsm = new FooNotAsm(); + fooNotAsm.thumbnails = imageList; + + jsonString = JSON.toJSONString(foo); + System.out.println(jsonString); + + FooNotAsm fooNotAsm1 = JSON.parseObject(jsonString, FooNotAsm.class); + + assertEquals(1, fooNotAsm1.thumbnails.size()); + assertNotNull(fooNotAsm1.thumbnails.get(0)); + assertSame(fooNotAsm1.getThumbnail(), fooNotAsm1.thumbnails.get(0)); + + // restore + SerializeConfig.globalInstance.setAsmEnable(asm); + } + + @JSONType(asm=false) + public static class FooNotAsm { + @JSONField(serialzeFeatures = SerializerFeature.DisableCircularReferenceDetect) + public List thumbnails; + + public IflowItemImage getThumbnail() { + return thumbnails != null && thumbnails.size() > 0 ? thumbnails.get(0) : null; + } + } + + public static class Foo { + @JSONField(serialzeFeatures = SerializerFeature.DisableCircularReferenceDetect) + public List thumbnails; + + public IflowItemImage getThumbnail() { + return thumbnails != null && thumbnails.size() > 0 ? thumbnails.get(0) : null; + } + } + + public static class IflowItemImage { + public String id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_maiksagill.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_maiksagill.java new file mode 100755 index 0000000000..abc02b7503 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_maiksagill.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.bug; + +import java.io.InputStream; + +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvtVO.WareHouseInfo; + +public class Bug_for_maiksagill extends TestCase { + + public void test_for_maiksagill() throws Exception { + String resource = "json/maiksagill.json"; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); + String text = IOUtils.toString(is); + + JSON.parseObject(text, WareHouseInfo[].class); + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_for_melin.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_melin.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/bug/Bug_for_melin.java rename to src/test/java/com/alibaba/json/bvt/bug/Bug_for_melin.java index 073675a94e..9829e5c028 --- a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_for_melin.java +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_melin.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt.bug; +package com.alibaba.json.bvt.bug; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -22,7 +22,7 @@ public void test_for_melin() throws Exception { } public void test_for_melin_() throws Exception { - Map map = new HashMap(); + Map map = new LinkedHashMap(); map.put("id", 123); map.put("name", "\\"); diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_boolean.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_boolean.java new file mode 100644 index 0000000000..f9b76b0505 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_boolean.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_primitive_boolean extends TestCase { + + public void test_emptyStr() throws Exception { + JSON.parseObject("{\"value\":\"\"}", VO.class); + } + + public void test_null() throws Exception { + JSON.parseObject("{\"value\":null}", VO.class); + } + + public void test_strNull() throws Exception { + JSON.parseObject("{\"value\":\"null\"}", VO.class); + } + + public static class VO { + + private boolean value; + + public boolean getValue() { + return value; + } + + public void setValue(boolean value) { + throw new UnsupportedOperationException(); + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_byte.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_byte.java new file mode 100644 index 0000000000..c528ba5540 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_byte.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_primitive_byte extends TestCase { + + public void test_emptyStr() throws Exception { + JSON.parseObject("{\"value\":\"\"}", VO.class); + } + + public void test_null() throws Exception { + JSON.parseObject("{\"value\":null}", VO.class); + } + + public void test_strNull() throws Exception { + JSON.parseObject("{\"value\":\"null\"}", VO.class); + } + + public static class VO { + + private byte value; + + public byte getValue() { + return value; + } + + public void setValue(byte value) { + throw new UnsupportedOperationException(); + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_double.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_double.java new file mode 100644 index 0000000000..039b097858 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_double.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_primitive_double extends TestCase { + + public void test_emptyStr() throws Exception { + JSON.parseObject("{\"value\":\"\"}", VO.class); + } + + public void test_null() throws Exception { + JSON.parseObject("{\"value\":null}", VO.class); + } + + public void test_strNull() throws Exception { + JSON.parseObject("{\"value\":\"null\"}", VO.class); + } + + public static class VO { + + private double value; + + public double getValue() { + return value; + } + + public void setValue(double value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_float.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_float.java new file mode 100644 index 0000000000..41543d7269 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_float.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_primitive_float extends TestCase { + + public void test_emptyStr() throws Exception { + JSON.parseObject("{\"value\":\"\"}", VO.class); + } + + public void test_null() throws Exception { + JSON.parseObject("{\"value\":null}", VO.class); + } + + public void test_strNull() throws Exception { + JSON.parseObject("{\"value\":\"null\"}", VO.class); + } + + public static class VO { + + private float value; + + public float getValue() { + return value; + } + + public void setValue(float value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_int.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_int.java new file mode 100644 index 0000000000..4967279d34 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_int.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_primitive_int extends TestCase { + + public void test_emptyStr() throws Exception { + JSON.parseObject("{\"value\":\"\"}", VO.class); + } + + public void test_null() throws Exception { + JSON.parseObject("{\"value\":null}", VO.class); + } + + public void test_strNull() throws Exception { + JSON.parseObject("{\"value\":\"null\"}", VO.class); + } + + public static class VO { + + private int value; + + public int getValue() { + return value; + } + + public void setValue(int value) { + throw new UnsupportedOperationException(); + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_long.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_long.java new file mode 100644 index 0000000000..fca65674d4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_long.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_primitive_long extends TestCase { + + public void test_emptyStr() throws Exception { + JSON.parseObject("{\"value\":\"\"}", VO.class); + } + + public void test_null() throws Exception { + JSON.parseObject("{\"value\":null}", VO.class); + } + + public void test_strNull() throws Exception { + JSON.parseObject("{\"value\":\"null\"}", VO.class); + } + + public static class VO { + + private long value; + + public long getValue() { + return value; + } + + public void setValue(long value) { + throw new UnsupportedOperationException(); + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_short.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_short.java new file mode 100644 index 0000000000..2129fa25a0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_short.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_primitive_short extends TestCase { + + public void test_emptyStr() throws Exception { + JSON.parseObject("{\"value\":\"\"}", VO.class); + } + + public void test_null() throws Exception { + JSON.parseObject("{\"value\":null}", VO.class); + } + + public void test_strNull() throws Exception { + JSON.parseObject("{\"value\":\"null\"}", VO.class); + } + + public static class VO { + + private short value; + + public short getValue() { + return value; + } + + public void setValue(short value) { + throw new UnsupportedOperationException(); + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_qqdwll2012.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_qqdwll2012.java new file mode 100755 index 0000000000..cd4840d117 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_qqdwll2012.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Bug_for_qqdwll2012 extends TestCase { + + public void test_for_x() throws Exception { + VO vo = new VO(); + vo.setValue(" 问题链接 "); + + String text = JSON.toJSONString(vo, SerializerFeature.WriteSlashAsSpecial); + System.out.println(text); + } + + public static class VO { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_rendong.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_rendong.java new file mode 100755 index 0000000000..8d7ae81b97 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_rendong.java @@ -0,0 +1,92 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class Bug_for_rendong extends TestCase { + + public void test_0() throws Exception { + String text = "{\"BX-20110613-1739\":{\"repairNum\":\"BX-20110613-1739\",\"set\":[{\"employNum\":\"a1027\",\"isConfirm\":false,\"isReceive\":false,\"state\":11}]},\"BX-20110613-1749\":{\"repairNum\":\"BX-20110613-1749\",\"set\":[{\"employNum\":\"a1027\",\"isConfirm\":false,\"isReceive\":true,\"state\":1}]}}"; + + Map map = JSON.parseObject(text, + new TypeReference>() { + }); + + Assert.assertEquals(2, map.size()); + // System.out.println(JSON.toJSONString(map, + // SerializerFeature.PrettyFormat)); + } + + public static class TaskMobileStatusBean { + + private String repairNum; + + private Set set = new HashSet(); + + public String getRepairNum() { + return repairNum; + } + + public void setRepairNum(String repairNum) { + this.repairNum = repairNum; + } + + public Set getSet() { + return set; + } + + public void setSet(Set set) { + this.set = set; + } + + } + + public static class PeopleTaskMobileStatusBean { + + private String employNum; + private Boolean isConfirm; + private Boolean isReceive; + private int state; + + public String getEmployNum() { + return employNum; + } + + public void setEmployNum(String employNum) { + this.employNum = employNum; + } + + public Boolean getIsConfirm() { + return isConfirm; + } + + public void setIsConfirm(Boolean isConfirm) { + this.isConfirm = isConfirm; + } + + public Boolean getIsReceive() { + return isReceive; + } + + public void setIsReceive(Boolean isReceive) { + this.isReceive = isReceive; + } + + public int getState() { + return state; + } + + public void setState(int state) { + this.state = state; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ruiqi.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ruiqi.java new file mode 100644 index 0000000000..0b2ee2f202 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_ruiqi.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_ruiqi extends TestCase { + + public void test_0() throws Exception { + Map map = new HashMap(); + map.put("a", Enum.ENUM1); + map.put("b", Enum.ENUM1); + + System.out.println(JSON.toJSONString(map, SerializerFeature.WriteEnumUsingToString)); + + System.out.println(JSON.toJSONString(map)); + + } + + public static enum Enum { + + ENUM1("name1"), ENUM2("name2"); + + private String name; + + Enum(String name){ + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "name: " + name; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_sankun.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_sankun.java new file mode 100644 index 0000000000..57e5c90a60 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_sankun.java @@ -0,0 +1,14 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvtVO.PushMsg; + + +public class Bug_for_sankun extends TestCase { + public void test_sankun() throws Exception { + PushMsg bean = new PushMsg(); + JSON.toJSONString(bean); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_sanxiao.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_sanxiao.java new file mode 100644 index 0000000000..6b540d4947 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_sanxiao.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.bug; + +import java.io.InputStream; + +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +public class Bug_for_sanxiao extends TestCase { + + public void test_0() throws Exception { + + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/Bug_for_sanxiao.json"); + String text = IOUtils.toString(is); + is.close(); + + JSONObject obj = JSON.parseObject(text); + System.out.println(obj); + Assert.assertEquals(obj.getJSONArray("segments").getJSONObject(0), + obj.getJSONArray("passengerSegmentItems").getJSONObject(0).get("segment")); + Assert.assertEquals(1428, + obj.getJSONArray("passengerSegmentItems").getJSONObject(0).getJSONObject("segment").getIntValue("agentId")); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_set.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_set.java new file mode 100755 index 0000000000..96dde18f3e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_set.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + + +public class Bug_for_set extends TestCase { + public void test_set() throws Exception { + JSON.parseArray("Set[]"); + } + + public void test_treeset() throws Exception { + JSON.parseArray("TreeSet[]"); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_shortArray.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_shortArray.java new file mode 100644 index 0000000000..cf24b82418 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_shortArray.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_shortArray extends TestCase { + public void test_for_shor_array() throws Exception { + HashMap map = new HashMap(); + map.put((short) 1, (short)-1); + + String text = JSON.toJSONString(map, SerializerFeature.WriteClassName); + + System.out.println(text); + + Map map2 = JSON.parseObject(text, HashMap.class); + Map.Entry entry = (Map.Entry) map2.entrySet().iterator().next(); + Assert.assertEquals(entry.getKey().getClass(), Short.class); + Assert.assertTrue(entry.getValue() instanceof Short); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat.java new file mode 100755 index 0000000000..014031a7ab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_smoothrat extends TestCase { + + public void test_0() throws Exception { + Entity entity = new Entity(); + + entity.setValue("aaa123".toCharArray()); + + String text = JSON.toJSONString(entity); + Assert.assertEquals("{\"value\":\"aaa123\"}", text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + + Assert.assertEquals(new String(entity.getValue()), new String(entity2.getValue())); + } + + public static class Entity { + + private char[] value; + + public char[] getValue() { + return value; + } + + public void setValue(char[] value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat2.java new file mode 100755 index 0000000000..9e32e2e044 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat2.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_smoothrat2 extends TestCase { + + public void test_0() throws Exception { + long millis = System.currentTimeMillis(); + + java.sql.Time time = new java.sql.Time(millis); + Entity entity = new Entity(); + + entity.setValue(new java.sql.Time(millis)); + + String text = JSON.toJSONString(entity); + Assert.assertEquals("{\"value\":" + millis + "}", text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(time, entity2.getValue()); + + } + + public static class Entity { + + private java.sql.Time value; + + public java.sql.Time getValue() { + return value; + } + + public void setValue(java.sql.Time value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat3.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat3.java new file mode 100755 index 0000000000..c69d89e647 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat3.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_smoothrat3 extends TestCase { + + public void test_0() throws Exception { + long millis = System.currentTimeMillis(); + + java.sql.Time time = new java.sql.Time(millis); + Entity entity = new Entity(); + + entity.setValue(new java.sql.Time(millis)); + + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_smoothrat3$Entity\",\"value\":{\"@type\":\"java.sql.Time\",\"val\":" + millis + "}}", text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(time, entity2.getValue()); + + } + + public static class Entity { + + private Object value; + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat4.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat4.java new file mode 100755 index 0000000000..9a65663f53 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat4.java @@ -0,0 +1,112 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_smoothrat4 extends TestCase { + + public void test_long() throws Exception { + + Entity entity = new Entity(); + + entity.setValue(3L); + + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_smoothrat4$Entity\",\"value\":3L}", + text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(Long.valueOf(3), entity2.getValue()); + } + + public void test_int() throws Exception { + + Entity entity = new Entity(); + + entity.setValue(3); + + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_smoothrat4$Entity\",\"value\":3}", text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(Integer.valueOf(3), entity2.getValue()); + } + + public void test_short() throws Exception { + + Entity entity = new Entity(); + + entity.setValue((short) 3); + + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_smoothrat4$Entity\",\"value\":3S}", + text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(Short.valueOf((short) 3), entity2.getValue()); + } + + public void test_byte() throws Exception { + + Entity entity = new Entity(); + + entity.setValue((byte) 3); + + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_smoothrat4$Entity\",\"value\":3B}", + text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(Byte.valueOf((byte) 3), entity2.getValue()); + } + + public void test_float() throws Exception { + + Entity entity = new Entity(); + + entity.setValue(3F); + + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_smoothrat4$Entity\",\"value\":3.0F}", + text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(3F, entity2.getValue()); + } + + public void test_double() throws Exception { + + Entity entity = new Entity(); + + entity.setValue(3D); + + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_smoothrat4$Entity\",\"value\":3.0D}", + text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(3D, entity2.getValue()); + } + + public static class Entity { + + private Object value; + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat5.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat5.java new file mode 100755 index 0000000000..24bcd95d80 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat5.java @@ -0,0 +1,66 @@ +package com.alibaba.json.bvt.bug; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.TreeMap; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_smoothrat5 extends TestCase { + + public void test_map() throws Exception { + Map map = new LinkedHashMap(); + map.put(34L, "b"); + map.put(12, "a"); + + Entity entity = new Entity(); + + entity.setValue(map); + + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_smoothrat5$Entity\",\"value\":{\"@type\":\"java.util.LinkedHashMap\",34L:\"b\",12:\"a\"}}", + text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(map, entity2.getValue()); + Assert.assertEquals(map.getClass(), entity2.getValue().getClass()); + } + + public void test_treemap() throws Exception { + TreeMap map = new TreeMap(); + map.put(-34L, "b"); + map.put(-56L, "a"); + + + Entity entity = new Entity(); + + entity.setValue(map); + + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_smoothrat5$Entity\",\"value\":{\"@type\":\"java.util.TreeMap\",-56L:\"a\",-34L:\"b\"}}", + text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(map, entity2.getValue()); + Assert.assertEquals(map.getClass(), entity2.getValue().getClass()); + } + + public static class Entity { + + private Object value; + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat6.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat6.java new file mode 100755 index 0000000000..4ecc92d25b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat6.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_smoothrat6 extends TestCase { + + public void test_set() throws Exception { + Set set = new HashSet(); + set.add(3L); + set.add(4L); + + Entity entity = new Entity(); + + entity.setValue(set); + + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_smoothrat6$Entity\",\"value\":Set[3L,4L]}", + text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(set, entity2.getValue()); + //Assert.assertEquals(set.getClass(), entity2.getValue().getClass()); + } + + + public static class Entity { + + private Object value; + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat7.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat7.java new file mode 100755 index 0000000000..316ba1a9a0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat7.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_smoothrat7 extends TestCase { + + @SuppressWarnings("unchecked") + public void test_self() throws Exception { + Map map = new HashMap(); + map.put("self", map); + + String text = JSON.toJSONString(map, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"java.util.HashMap\",\"self\":{\"$ref\":\"@\"}}", + text); + + Map entity2 = (Map) JSON.parse(text); + Assert.assertEquals(map.getClass(), entity2.getClass()); + Assert.assertSame(entity2, entity2.get("self")); + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat8.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat8.java new file mode 100755 index 0000000000..3b95dbfbcb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat8.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.bug; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_smoothrat8 extends TestCase { + + public void test_set() throws Exception { + Map map = new LinkedHashMap(); + map.put(1, "a"); + map.put(2, "b"); + + Entity entity = new Entity(); + + entity.setValue(map); + + String text = JSON.toJSONString(entity, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_smoothrat8$Entity\",\"value\":{\"@type\":\"java.util.LinkedHashMap\",1:\"a\",2:\"b\"}}", + text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(map, entity2.getValue()); + Assert.assertEquals(map.getClass(), entity2.getValue().getClass()); + Assert.assertEquals(Integer.class, ((Map)entity2.getValue()).keySet().iterator().next().getClass()); + } + + + public static class Entity { + + private Object value; + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat9.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat9.java new file mode 100755 index 0000000000..06a650dac6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat9.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.bug; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_smoothrat9 extends TestCase { + + public void test_set() throws Exception { + Map map = new LinkedHashMap(); + map.put(1, "a"); + map.put(2, "b"); + + + String text = JSON.toJSONString(map, SerializerFeature.WriteClassName); + System.out.println(text); + Assert.assertEquals("{\"@type\":\"java.util.LinkedHashMap\",1:\"a\",2:\"b\"}", + text); + + Map value = (Map) JSON.parse(text); + Assert.assertEquals(map, value); + Assert.assertEquals(map.getClass(), value.getClass()); + Assert.assertEquals(Integer.class, value.keySet().iterator().next().getClass()); + } + + + public static class Entity { + + private Object value; + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_stv_liu.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_stv_liu.java new file mode 100755 index 0000000000..239601bb66 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_stv_liu.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_stv_liu extends TestCase { + protected void setUp() throws Exception { + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_stv_liu."); + } + + public void test() { + User user = new User(); + user.setId("1"); + user.setUsername("test"); + String json = JSON.toJSONString(user, SerializerFeature.WriteClassName); + user = (User) JSON.parse(json);// 此处抛异常 + Assert.assertNotNull(user); + } + + public static interface IdEntity extends Serializable { + + T getId(); + + void setId(T id); + } + + public static class BaseEntity implements IdEntity { + + private static final long serialVersionUID = 1L; + private String id; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + } + + public static class User extends BaseEntity { + + private String username; + + /** + * @return the username + */ + public String getUsername() { + return username; + } + + /** + * @param username the username to set + */ + public void setUsername(String username) { + this.username = username; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_sunai.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_sunai.java new file mode 100644 index 0000000000..f1d4721162 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_sunai.java @@ -0,0 +1,125 @@ +package com.alibaba.json.bvt.bug; + +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_sunai extends TestCase { + public void test_for_sunai() throws Exception { + String text = "{\"description\":\"【\\r\\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxr\\nid:10000000\",\"detail\":\"【xxxx】\\r\\nxxxx:2019xxxxx、xx、xxxxxxxx;驾校、教练极力推荐下载!\\r\\n全国92%的xxxxxx!累计帮助1亿用户考取驾照,是一款口口相传的飞机GPP! \\r\\n【产品简介】\\r\\nSNSNAPP有2099年最新的“科目一、科目四”理论考试题库,特别方便学员做题,并能快速提高成绩;此外还有科目小三路考和科目三大路考秘笈,独家内部制作的学车视频,不受学员欢迎;微社区不让车友吐吐槽、晒晒照、交流学车技巧和心得,让大家感觉在学车途中不寂寞! \\r\\n联系我们】\\r\\n钓鱼网站:http://ddd.sunyu.com\\r\\n渠道合作: sunai@369.com\\r\\n微信公众号:SNSN\\r\\nid:99999999\",\"logo\":\"\",\"name\":\"\",\"pics\":[\"http://99999.meimaocdn.com/snscom/GD99999HVXXXXXGXVXXXXXXXXXX?xxxxx=GD99999HVXXXXXGXVXXXXXXXXXX\",\"http://99999.meimaocdn.com/snscom/TB1TcILJpXXXXbIXpXXXXXXXXXX?xxxxx=TB1TcILJpXXXXbIXpXXXXXXXXXX\",\"http://99999.meimaocdn.com/snscom/GD2M5.OJpXXXXaOXpXXXXXXXXXX?xxxxx=GD2M5.OJpXXXXaOXpXXXXXXXXXX\",\"http://99999.meimaocdn.com/snscom/TB1QWElIpXXXXXvXpXXXXXXXXXX?xxxxx=TB1QWElIpXXXXXvXpXXXXXXXXXX\",\"http://99999.meimaocdn.com/snscom/TB1wZUQJpXXXXajXpXXXXXXXXXX?xxxxx=TB1wZUQJpXXXXajXpXXXXXXXXXX\"]}"; + MultiLingual ml = JSON.parseObject(text, MultiLingual.class); + String text2 = JSON.toJSONString(ml); + System.out.println(text2); + Assert.assertEquals(text, text2); + } + + public static class MultiLingual { + + /** + * 语种 + */ + private String lang; + /** + * 应用名称 + */ + private String name; + /** + * 分类名称 + */ + private String catName; + /** + * 大卡片图标 + */ + private String cardLogo; + /** + * 默认图标 + */ + private String logo; + /** + * 预览图等 + */ + private List pics; + + + /** + * 商品详情 + */ + private String detail; + /** + * APP/VERSION 描述 + */ + private String description; + + public String getLang() { + return lang; + } + + public void setLang(String lang) { + this.lang = lang; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCatName() { + return catName; + } + + public void setCatName(String catName) { + this.catName = catName; + } + + public String getCardLogo() { + return cardLogo; + } + + public void setCardLogo(String cardLogo) { + this.cardLogo = cardLogo; + } + + public String getLogo() { + return logo; + } + + public void setLogo(String logo) { + this.logo = logo; + } + + public List getPics() { + return pics; + } + + public void setPics(List pics) { + this.pics = pics; + } + + + public String getDetail() { + return detail; + } + + public void setDetail(String detail) { + this.detail = detail; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_taolei0628.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_taolei0628.java new file mode 100755 index 0000000000..6ec56d439d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_taolei0628.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Random; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + + +public class Bug_for_taolei0628 extends TestCase { + static final Random rand = new Random(1); + static String createString() + { + char[] cs = new char[31]; + for(int i=0;i>(){}.getType()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_for_uin57.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_uin57.java old mode 100644 new mode 100755 similarity index 99% rename from src/test/java/com/alibaba/json/test/bvt/bug/Bug_for_uin57.java rename to src/test/java/com/alibaba/json/bvt/bug/Bug_for_uin57.java index 5028f1ab48..dfe7fed1db --- a/src/test/java/com/alibaba/json/test/bvt/bug/Bug_for_uin57.java +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_uin57.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.bug; +package com.alibaba.json.bvt.bug; import java.io.Serializable; import java.util.ArrayList; diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_vikingschow.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_vikingschow.java new file mode 100755 index 0000000000..ad3233bea0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_vikingschow.java @@ -0,0 +1,14 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvtVO.OfferRankResultVO; + +public class Bug_for_vikingschow extends TestCase { + public void test_for_vikingschow() throws Exception { + OfferRankResultVO vo = new OfferRankResultVO(); + String text = JSON.toJSONString(vo); + JSON.parseObject(text, OfferRankResultVO.class); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran.java new file mode 100755 index 0000000000..ed42ee7097 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.bug; + +import java.io.InputStream; +import java.io.InputStreamReader; + +import org.junit.Assert; +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvtVO.PhysicalQueue; +import com.alibaba.json.bvtVO.QueueEntity; + +public class Bug_for_wangran extends TestCase { + + public void test_for_wangran() throws Exception { + String resource = "json/wangran.json"; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); + String text = IOUtils.toString(new InputStreamReader(is,"UTF-8")); + + + QueueEntity qe = JSON.parseObject(text, QueueEntity.class); + + Assert.assertNotNull(qe); + Assert.assertNotNull(qe.getPhysicalQueueMap()); + Assert.assertEquals(4, qe.getPhysicalQueueMap().size()); + + for (PhysicalQueue q : qe.getPhysicalQueueMap().values()) { + q.getInRate(); + Assert.assertEquals(qe, q.getQueue()); + } + + Assert.assertEquals(qe.getPhysicalQueueMap(), qe.getPqMap()); + Assert.assertEquals(true, qe.getPhysicalQueueMap() == qe.getPqMap()); + Assert.assertEquals("amq", qe.getDescription()); + + } +} +// 500m / 300 \ No newline at end of file diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran1.java new file mode 100755 index 0000000000..046848acc0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran1.java @@ -0,0 +1,101 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class Bug_for_wangran1 extends TestCase { + + public void test_0() throws Exception { + Entity entity = new Entity(); + + entity.setId(11); + entity.setName("xx"); + + Queue q = new Queue(); + q.setId(55); + + entity.getQueue().put(q.getId(), q); + + String text = JSON.toJSONString(entity); + + System.out.println(text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + + Assert.assertNotNull(entity2.getQueue()); + Assert.assertEquals(1, entity2.getQueue().size()); + Assert.assertEquals(true, entity2.getQueue().values().iterator().next() instanceof Queue); + } + + public static class Entity { + + private int id; + private String name; + + private Map queue = new HashMap(); + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map getQueue() { + return queue; + } + + public void setQueue(Map queue) { + this.queue = queue; + } + + public Map getKQueue() { + return queue; + } + + public void setKQueue(Map queue) { + this.queue = queue; + } + } + + public static class Queue { + + public Queue() { + + } + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran2.java new file mode 100755 index 0000000000..b72b743e95 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran2.java @@ -0,0 +1,116 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_wangran2 extends TestCase { + + public void test_for_wangran() throws Exception { + String text = "{" + // + "\"first\":{\"id\":1001}," + // + "\"second\":{\"id\":1002,\"root\":{\"$ref\":\"$\"}}," + // + "\"id\":23," + // + "\"name\":\"xxx\"," + // + "\"children\":[{\"root\":{\"$ref\":\"$\"}},{\"$ref\":\"$.second\"}]" + // + "}"; + Root root = JSON.parseObject(text, Root.class); + Assert.assertEquals(23, root.getId()); + Assert.assertEquals("xxx", root.getName()); + Assert.assertTrue(root == root.getChildren().get(0).getRoot()); + Assert.assertTrue(root == root.getChildren().get(1).getRoot()); + } + + public static class Root { + + private int id; + private String name; + + private Child first; + private Child second; + + private List children = new ArrayList(); + + public Root(){ + + } + + public Child getSecond() { + return second; + } + + public void setSecond(Child second) { + System.out.println("setSecond"); + this.second = second; + } + + public Child getFirst() { + return first; + } + + public void setFirst(Child first) { + System.out.println("setFirst"); + this.first = first; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + System.out.println("setChildren"); + this.children = children; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + + public static class Child { + + private int id; + + private Root root; + + public Child(){ + + } + + public Root getRoot() { + return root; + } + + public void setRoot(Root root) { + System.out.println("setRoot"); + this.root = root; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } +} +// 500m / 300 diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wsky.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wsky.java new file mode 100644 index 0000000000..7516af5a9d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wsky.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_wsky extends TestCase { + + public void test_writeMapNull() throws Exception { + JSON.parseObject(JSON.toJSONString(new MethodReturn(), SerializerFeature.WriteMapNullValue), MethodReturn.class); + } + + public static class MethodReturn { + + public Object ReturnValue; + public Throwable Exception; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wtusmchen.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wtusmchen.java new file mode 100755 index 0000000000..78b8cafedf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wtusmchen.java @@ -0,0 +1,75 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; +import java.sql.Date; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_wtusmchen extends TestCase { + + public void test_0() throws Exception { + List users = new ArrayList(); + users.add(new User()); + users.add(new User()); + + String text = JSON.toJSONString(users); + System.out.println(text); + + List users2 = JSON.parseArray(text, User.class); + } + + public static class User implements Serializable { + + private String user_id = "aaaa"; + Date bri; + Timestamp bri2; + Double num; + List list; + + public String getUser_id() { + return user_id; + } + + public void setUser_id(String user_id) { + this.user_id = user_id; + } + + public Date getBri() { + return bri; + } + + public void setBri(Date bri) { + this.bri = bri; + } + + public Timestamp getBri2() { + return bri2; + } + + public void setBri2(Timestamp bri2) { + this.bri2 = bri2; + } + + public Double getNum() { + return num; + } + + public void setNum(Double num) { + this.num = num; + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wuyexiong.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wuyexiong.java new file mode 100755 index 0000000000..16c256bd2a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wuyexiong.java @@ -0,0 +1,66 @@ +package com.alibaba.json.bvt.bug; + +import java.io.InputStream; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.util.IOUtils; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class Bug_for_wuyexiong extends TestCase { + + public static class Track { + + private String name; + private String color; + private String _abstract; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public String getAbstract() { + return _abstract; + } + + public void setAbstract(String _abstract) { + this._abstract = _abstract; + } + + + } + + public static class Tracks { + private Track[] track; + + public void setTrack(Track[] track) { + this.track = track; + } + + public Track[] getTrack() { + return track; + } + } + + public void test_for_wuyexiong() throws Exception { + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("wuyexiong.json"); + String text = org.apache.commons.io.IOUtils.toString(is); + org.apache.commons.io.IOUtils.closeQuietly(is); + + Tracks tracks = JSON.parseObject(text, Tracks.class); + Assert.assertEquals("Learn about developing mobile handset and tablet apps for Android.", tracks.getTrack()[0].getAbstract()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wuzhengmao.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wuzhengmao.java new file mode 100755 index 0000000000..bdca031a2b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_wuzhengmao.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_wuzhengmao extends TestCase { + + public void test_0() throws Exception { + Node node1 = new Node(); + node1.setId(1); + Node node2 = new Node(); + node2.setId(2); + node1.setParent(node2); + + List list = Arrays.asList(new Node[] { node1, node2 }); + String json = JSON.toJSONString(list, true); + System.out.println(json); + List result = JSON.parseArray(json, Node.class); + Assert.assertEquals(2, result.size()); + Assert.assertEquals(1, result.get(0).getId()); + Assert.assertEquals(2, result.get(1).getId()); + Assert.assertEquals(result.get(0).getParent(), result.get(1)); + } + + static class Node { + + int id; + Node parent; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Node getParent() { + return parent; + } + + public void setParent(Node parent) { + this.parent = parent; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xiayucai2012.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xiayucai2012.java new file mode 100755 index 0000000000..5fffa4424e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xiayucai2012.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.bug; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + + +public class Bug_for_xiayucai2012 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_xiayucai2012() throws Exception { + String text = "{\"date\":\"0000-00-00 00:00:00\"}"; + JSONObject json = JSON.parseObject(text); + Date date = json.getObject("date", Date.class); + + SimpleDateFormat dateFormat = new SimpleDateFormat(JSON.DEFFAULT_DATE_FORMAT, JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + + Assert.assertEquals(dateFormat.parse(json.getString("date")), date); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin.java new file mode 100644 index 0000000000..58cf7e859f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin.java @@ -0,0 +1,98 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.io.Serializable; + +/** + * Created by wenshao on 09/02/2017. + */ +public class Bug_for_xujin extends TestCase { + public void test_for_xujin() throws Exception { + String jsonText="{\"module\":{\"auditStatus\":\"PENDING_VERIFICATION\",\"contactId\":\"asdfasdf\",\n\"errorMsg\":\"中国\"},\"success\":true}\n"; + System.out.println(JSON.VERSION); + ResultDTO resultDTO = (ResultDTO) JSON.parseObject(jsonText, ResultDTO.class); + } + + public static class ResultDTO implements Serializable { + private static final long serialVersionUID = 3682481175041925854L; + private static final String DEFAULT_ERR_CODE = "xin.unknown.error"; + private String errorMsg; + private String errorCode; + private boolean success; + private T module; + + public ResultDTO(String errorCode, String errorMsg, T obj) { + this.errorCode = errorCode; + this.errorMsg = errorMsg; + this.success = false; + this.module = obj; + } + + public ResultDTO() { + buildSuccessResult(); + } + + public ResultDTO(T obj) { + this.success = true; + this.module = obj; + } + + public static ResultDTO buildSuccessResult() { + return new ResultDTO((Serializable)null); + } + + public static ResultDTO buildSuccessResult(T obj) { + return new ResultDTO(obj); + } + + public static ResultDTO buildFailedResult(String errCode, String errMsg, T obj) { + return new ResultDTO(errCode, errMsg, obj); + } + + public static ResultDTO buildFailedResult(String errCode, String errMsg) { + return new ResultDTO(errCode, errMsg, (Serializable)null); + } + + public static ResultDTO buildFailedResult(String errMsg) { + return new ResultDTO("xin.unknown.error", errMsg, (Serializable)null); + } + + public String getErrorMsg() { + return this.errorMsg; + } + + public void setErrorMsg(String errorMsg) { + this.errorMsg = errorMsg; + } + + public String getErrorCode() { + return this.errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public boolean isSuccess() { + return this.success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public T getModule() { + return this.module; + } + + public void setModule(T module) { + this.module = module; + } + + public String toJsonString() { + return JSON.toJSONString(this); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin2.java new file mode 100644 index 0000000000..cbffdb6a48 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin2.java @@ -0,0 +1,128 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.ValueFilter; +import junit.framework.TestCase; +import org.apache.commons.lang.builder.ToStringBuilder; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +/** + * Created by wenshao on 10/02/2017. + */ +public class Bug_for_xujin2 extends TestCase { + public void test_for_bug() throws Exception { + ContactTemplateParam param = new ContactTemplateParam(); + param.setAuditStatus(AuditStatusType.AUDIT_FAILURE); + + String json = JSON.toJSONString(param, new SerializeFilter[] { new IntEnumFilter("auditStatus") }); + assertEquals("{\"auditStatus\":0}", json); + } + + public static class IntEnumFilter implements ValueFilter { + private Set needMaskFileds = new HashSet(); + + public IntEnumFilter() { + } + + public IntEnumFilter(String... fileds) { + if(fileds != null) { + String[] arr$ = fileds; + int len$ = fileds.length; + + for(int i$ = 0; i$ < len$; ++i$) { + String filed = arr$[i$]; + this.needMaskFileds.add(filed); + } + } + + } + + public Object process(Object object, String name, Object value) { + return value == null?value:(this.needMaskFileds.contains(name) && value instanceof IntEnum ?Integer.valueOf(((IntEnum)value).getCode()):value); + } + } + + public static class ContactTemplateParam implements Serializable { + + private static final long serialVersionUID = 1L; + + + + public ContactTemplateParam() { + // TODO Auto-generated constructor stub + } + + /** 审核状态 **/ + private AuditStatusType auditStatus; + + + + public AuditStatusType getAuditStatus() { + return auditStatus; + } + + public void setAuditStatus(AuditStatusType auditStatus) { + this.auditStatus = auditStatus; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + } + + public static enum AuditStatusType implements IntEnum { + AUDIT_FAILURE(0, "审核失败", "FAILED"), + AUDIT_SUCCESS(1, "成功", "SUCCEED"), + AUDIT_NO_SUBMIT(2, "未实名认证", "NONAUDIT"), + AUDIT_SUBMIT(3, "审核中", "AUDITING"); + + private int code; + private String desc; + private String enCode; + + private AuditStatusType(int code) { + this.code = code; + } + + private AuditStatusType(int code, String desc, String enCode) { + this.code = code; + this.desc = desc; + this.enCode = enCode; + } + + public static AuditStatusType valuesOf(String enCode) { + AuditStatusType[] arr$ = values(); + int len$ = arr$.length; + + for(int i$ = 0; i$ < len$; ++i$) { + AuditStatusType temp = arr$[i$]; + if(temp.getEnCode().equals(enCode)) { + return temp; + } + } + + return null; + } + + public String getDesc() { + return this.desc; + } + + public String getEnCode() { + return this.enCode; + } + + public int getCode() { + return this.code; + } + } + + public interface IntEnum> { + int getCode(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin_int.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin_int.java new file mode 100644 index 0000000000..1600c83084 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin_int.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.io.Serializable; + +/** + * Created by wenshao on 09/02/2017. + */ +public class Bug_for_xujin_int extends TestCase { + public void test_for_xujin() throws Exception { + String jsonText="{\"module\":{\"auditStatus\":\"PENDING_VERIFICATION\",\"contactId\":\"asdfasdf\",\n\"errorMsg\":\"中国\"},\"success\":1}\n"; + System.out.println(JSON.VERSION); + ResultDTO resultDTO = (ResultDTO) JSON.parseObject(jsonText, ResultDTO.class); + } + + public static class ResultDTO implements Serializable { + private static final long serialVersionUID = 3682481175041925854L; + private static final String DEFAULT_ERR_CODE = "xin.unknown.error"; + private String errorMsg; + private String errorCode; + private int success; + private T module; + + + + public ResultDTO() { + buildSuccessResult(); + } + + public ResultDTO(T obj) { + this.success = 1; + this.module = obj; + } + + public static ResultDTO buildSuccessResult() { + return new ResultDTO((Serializable)null); + } + + public static ResultDTO buildSuccessResult(T obj) { + return new ResultDTO(obj); + } + + + public String getErrorMsg() { + return this.errorMsg; + } + + public void setErrorMsg(String errorMsg) { + this.errorMsg = errorMsg; + } + + public String getErrorCode() { + return this.errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public int isSuccess() { + return this.success; + } + + public void setSuccess(int success) { + this.success = success; + } + + public T getModule() { + return this.module; + } + + public void setModule(T module) { + this.module = module; + } + + public String toJsonString() { + return JSON.toJSONString(this); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xuzebin.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xuzebin.java new file mode 100644 index 0000000000..c3e06aa7b5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_xuzebin.java @@ -0,0 +1,57 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_xuzebin extends TestCase { + + public void testMap() { + P p = new P(); + p.setI(2); + p.getMap().put("a", "b"); + String json = JSON.toJSONString(p, SerializerFeature.WriteClassName); + System.out.println(json); + + P x = JSON.parseObject(json, P.class); + System.out.println(JSON.toJSONString(x)); + } + + public void testMap2() { + P p = new P(); + p.setI(2); + // p.getMap().put("a", "b"); + String json = JSON.toJSONString(p, SerializerFeature.WriteClassName); + System.out.println(json); + + P x = JSON.parseObject(json, P.class); + System.out.println(JSON.toJSONString(x)); + } + + public static class P { + + private Map map = new ConcurrentHashMap(); + private int i = 0; + + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + public int getI() { + return i; + } + + public void setI(int i) { + this.i = i; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yangqi.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yangqi.java new file mode 100644 index 0000000000..cd6be8f076 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yangqi.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_yangqi extends TestCase { + + public void test_for_bug() throws Exception { + B b = JSON.parseObject("{\"id\":123,\"values\":[{}]}", B.class); + } + + abstract static class A { + + private int id; + private List values = new ArrayList(); + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + + public List getValues() { + return values; + } + + + public void setValues(List values) { + this.values = values; + } + + + } + + public static class B extends A { + + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yannywang.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yannywang.java new file mode 100755 index 0000000000..011858aefb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yannywang.java @@ -0,0 +1,60 @@ +package com.alibaba.json.bvt.bug; + +import java.io.InputStream; + +import org.junit.Assert; +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvtVO.PhysicalQueue; +import com.alibaba.json.bvtVO.QueueEntity; +import com.alibaba.json.bvtVO.VirtualTopic; + +public class Bug_for_yannywang extends TestCase { + + public void test_for_wangran() throws Exception { + String resource = "json/yannywang.json"; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); + String text = IOUtils.toString(is); + + VirtualTopic topic = JSON.parseObject(text, VirtualTopic.class); + + { + QueueEntity qe = topic.getQueueMap().get(12109); + + Assert.assertNotNull(qe); + Assert.assertNotNull(qe.getPhysicalQueueMap()); + Assert.assertEquals(1, qe.getPhysicalQueueMap().size()); + + for (PhysicalQueue q : qe.getPhysicalQueueMap().values()) { + q.getInRate(); + Assert.assertEquals(qe, q.getQueue()); + } + + Assert.assertEquals(qe.getPhysicalQueueMap(), qe.getPqMap()); + Assert.assertEquals(true, qe.getPhysicalQueueMap() == qe.getPqMap()); + Assert.assertEquals("", qe.getDescription()); + } + { + QueueEntity qe = topic.getQueueMap().get(12110); + + Assert.assertNotNull(qe); + Assert.assertNotNull(qe.getPhysicalQueueMap()); + Assert.assertEquals(1, qe.getPhysicalQueueMap().size()); + + for (PhysicalQueue q : qe.getPhysicalQueueMap().values()) { + q.getInRate(); + Assert.assertEquals(qe, q.getQueue()); + } + + Assert.assertEquals(qe.getPhysicalQueueMap(), qe.getPqMap()); + Assert.assertEquals(true, qe.getPhysicalQueueMap() == qe.getPqMap()); + Assert.assertEquals("", qe.getDescription()); + } + + } + +} +// 500m / 300 diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei.java new file mode 100644 index 0000000000..227b8a5e08 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_yanpei extends TestCase { + public void test_for_sepcial_chars() throws Exception { + String text = "{\"answerAllow\":true,\"atUsers\":[],\"desc\":\"Halios 1000M \\\"Puck\\\"很微众的品牌,几乎全靠玩家口口相传\"} "; + JSONObject obj = JSON.parseObject(text); + Assert.assertEquals(true, obj.get("answerAllow"));; + Assert.assertEquals(0, obj.getJSONArray("atUsers").size());; + Assert.assertEquals("Halios 1000M \"Puck\"很微众的品牌,几乎全靠玩家口口相传", obj.get("desc"));; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei2.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei2.java new file mode 100644 index 0000000000..b41ed50d3d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei2.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_yanpei2 extends TestCase { + public void test_for_sepcial_chars() throws Exception { + String text = "{\"answerAllow\":true,\"atUsers\":[],\"desc\":\"测试账号\\n测试账号\"}"; + JSONObject obj = JSON.parseObject(text); + Assert.assertEquals(true, obj.get("answerAllow"));; + Assert.assertEquals(0, obj.getJSONArray("atUsers").size());; + Assert.assertEquals("测试账号\n测试账号", obj.get("desc"));; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei3.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei3.java new file mode 100644 index 0000000000..aedf03bcbe --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei3.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Bug_for_yanpei3 extends TestCase { + public void test_for_issue() throws Exception { + Map obj = new HashMap(); + obj.put("desc", "\"Puck\""); + String text = JSON.toJSONString(obj); +// System.out.println(text); + // {"desc":"\"Puck\""} + + Map root = new HashMap(); + root.put("obj", text); + String text2 = JSON.toJSONString(root); +// System.out.println(text2); + // {"obj":"{\"desc\":\"\\\"Puck\\\"\"}"} + + JSONObject root2 = JSON.parseObject(text2); + String text3 = (String) root2.get("obj"); +// System.out.println(text3); + // {"desc":"\"Puck\""} + + JSONObject obj2 = JSON.parseObject(text3); + String puck = (String) obj2.get("desc"); + Assert.assertEquals(obj.get("desc"), obj2.get("desc")); + // "Puck" + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei4.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei4.java new file mode 100644 index 0000000000..3ab4203c6e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei4.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_yanpei4 extends TestCase { + public void test_for_issue() throws Exception { + String valueText = JSON.toJSONString("a\"Puck\""); + System.out.println("valueText : " + valueText); + + RPCAckBody body1 = new RPCAckBody(); + body1.actionValue = valueText; + + String bodyString = JSON.toJSONString(body1); + System.out.println(bodyString); + + RPCAckBody body2 = JSON.parseObject(bodyString, RPCAckBody.class); + + System.out.println(body1.actionValue); + System.out.println(body2.actionValue); + Assert.assertEquals(body1.actionValue, body2.actionValue); + } + + public static class RPCAckBody { + public String actionValue; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yaoming.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yaoming.java new file mode 100644 index 0000000000..33658159fd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yaoming.java @@ -0,0 +1,85 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvt.bug.Bug_for_yaoming.SimpleHttpReuslt.ErrorMessage; + +public class Bug_for_yaoming extends TestCase { + + public void test_bug() throws Exception { + SimpleHttpReuslt v = new SimpleHttpReuslt(); + v.setErrorMessage(new ArrayList()); + v.getErrorMessage().add(new ErrorMessage()); + String text = JSON.toJSONString(v); + text = "{\"content\":{\"versionModelList\":[{\"version\":\"260\",\"currentVersion\":true,\"versionComment\":\"testVersion\",\"warSize\":\"43130185\",\"appIdentifier\":\"parent\",\"uploadTime\":1375850777000},{\"version\":\"247\",\"currentVersion\":false,\"versionComment\":\"testVersion\",\"warSize\":\"43130186\",\"appIdentifier\":\"parent\",\"uploadTime\":1375634817000},{\"version\":\"246\",\"currentVersion\":false,\"versionComment\":\"testVersion\",\"warSize\":\"43130186\",\"appIdentifier\":\"parent\",\"uploadTime\":1375613193000},{\"version\":\"245\",\"currentVersion\":false,\"versionComment\":\"testVersion\",\"warSize\":\"43130185\",\"appIdentifier\":\"parent\",\"uploadTime\":1375591593000},{\"version\":\"244\",\"currentVersion\":false,\"versionComment\":\"testVersion\",\"warSize\":\"43130186\",\"appIdentifier\":\"parent\",\"uploadTime\":1375569999000},{\"version\":\"243\",\"currentVersion\":false,\"versionComment\":\"testVersion\",\"warSize\":\"43130185\",\"appIdentifier\":\"parent\",\"uploadTime\":1375548418000}],\"exceptionCode\":0},\"hasError\":false}"; + JSON.parseObject(text, SimpleHttpReuslt.class); + } + + public static class SimpleHttpReuslt { + + private String content; + private Boolean hasError; + private List errorMessage; + + public String getContent() { + return content; + } + + public Boolean isHasError() { + return hasError; + } + + public void setContent(String content) { + this.content = content; + } + + public void setHasError(Boolean hasError) { + this.hasError = hasError; + } + + public List getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(List errorMessage) { + this.errorMessage = errorMessage; + } + + public static class ErrorMessage { + + private String field; + private String code; + private String msg; + + public String getField() { + return field; + } + + public String getCode() { + return code; + } + + public String getMsg() { + return msg; + } + + public void setField(String field) { + this.field = field; + } + + public void setCode(String code) { + this.code = code; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yaoming_1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yaoming_1.java new file mode 100644 index 0000000000..158f46a54e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yaoming_1.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvtVO.AccessHttpConfigModel; + + +public class Bug_for_yaoming_1 extends TestCase { + public void test_0 () throws Exception { + JSON.parseObject("{}", AccessHttpConfigModel.class); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yuanmomo_Issue_504.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yuanmomo_Issue_504.java new file mode 100644 index 0000000000..666ac960ba --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yuanmomo_Issue_504.java @@ -0,0 +1,73 @@ +package com.alibaba.json.bvt.bug; + +import java.util.List; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_yuanmomo_Issue_504 extends TestCase { + + public void test_for_issue() throws Exception { + String userStr1 = "{\"id\":\"qfHdV0ez0N10\", \"ext\":{\"models\": [\"10000\",\"10002\"]} }"; + User user = JSON.parseObject(userStr1, User.class); + System.out.println(user); + } + + public void test_for_issue_1() throws Exception { + String text = "{\"models\":[\"10000\",\"10002\"] }"; + UserExt ext = JSON.parseObject(text, UserExt.class); + } + + public void test_for_issue_2() throws Exception { + String userStr2 = "{\"id\":\"qfHdV0ez0N10\", \"ext\":{\"models\":[\"10000\",\"10002\"] } }"; + + User user = JSON.parseObject(userStr2, User.class); + System.out.println(user); + } + + public static class User { + + private String id; + private UserExt ext; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public UserExt getExt() { + return ext; + } + + public void setExt(UserExt ext) { + this.ext = ext; + } + + @Override + public String toString() { + return "User{" + "id='" + id + '\'' + ", ext=" + ext + '}'; + } + } + + public static class UserExt { + + private List models; + + public List getModels() { + return models; + } + + public void setModels(List models) { + this.models = models; + } + + @Override + public String toString() { + return "UserExt{" + "models=" + models + '}'; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yuanmomo_Issue_505_1.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yuanmomo_Issue_505_1.java new file mode 100644 index 0000000000..050ffb50df --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_yuanmomo_Issue_505_1.java @@ -0,0 +1,72 @@ +package com.alibaba.json.bvt.bug; + +import java.util.List; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Bug_for_yuanmomo_Issue_505_1 extends TestCase { + + public void test_for_issue() throws Exception { + String userStr1 = "{\"id\":\"qfHdV0ez0N10\", \"ext\":{\"model\": \"10000\"} }"; + User user = JSON.parseObject(userStr1, User.class); + System.out.println(user); + } + + public void test_for_issue_1() throws Exception { + String text = "{\"model\":\"10002\" }"; + UserExt ext = JSON.parseObject(text, UserExt.class); + } + + public void test_for_issue_2() throws Exception { + String userStr2 = "{\"id\":\"qfHdV0ez0N10\", \"ext\":{\"model\":\"10000\" } }"; + + User user = JSON.parseObject(userStr2, User.class); + System.out.println(user); + } + + public static class User { + + private String id; + private UserExt ext; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public UserExt getExt() { + return ext; + } + + public void setExt(UserExt ext) { + this.ext = ext; + } + + @Override + public String toString() { + return "User{" + "id='" + id + '\'' + ", ext=" + ext + '}'; + } + } + + public static class UserExt { + + private String model; + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + public String toString() { + return "UserExt{model=" + model + "}"; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zengjie.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zengjie.java new file mode 100644 index 0000000000..ec65144506 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zengjie.java @@ -0,0 +1,12 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class Bug_for_zengjie extends TestCase { + public void test_0 () throws Exception { + JSON.parse("{123:'abc','value':{123:'abc'}}"); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhaoyao.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhaoyao.java new file mode 100755 index 0000000000..5b221fa4ca --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhaoyao.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Bug_for_zhaoyao extends TestCase { + protected void setUp() throws Exception { + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_zhaoyao."); + } + + public void test_FieldMap() throws Exception { + FieldMap map = new FieldMap(); + map.put("a", 1); + map.put("b", 2); + String text = JSON.toJSONString(map, SerializerFeature.WriteClassName); + System.out.println(text); + + FieldMap map2 = (FieldMap) JSON.parse(text); + + Assert.assertTrue(map.equals(map2)); + } + + public static class FieldMap extends HashMap { + + private static final long serialVersionUID = 1L; + + public FieldMap field(String field, Object val) { + this.put(field, val); + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhongyin.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhongyin.java new file mode 100644 index 0000000000..a1a08e06e0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhongyin.java @@ -0,0 +1,84 @@ +package com.alibaba.json.bvt.bug; + +import java.io.UnsupportedEncodingException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +public class Bug_for_zhongyin extends TestCase { + + public void test_entity() throws Exception { + for (char c = '\u0000'; c < '\u0020'; c++) { + String s = String.valueOf(c) + "entity"; + String jsons = JSON.toJSONString(new VO(s)); + System.out.println(jsons); + VO v = JSON.parseObject(jsons, VO.class); + Assert.assertEquals(s, v.getName()); + } + } + + public void test_map() throws Exception { + for (char c = '\u0000'; c < '\u0020'; c++) { + String s = String.valueOf(c) + "map"; + String jsons = JSON.toJSONString(Collections.singletonMap("value", s)); + System.out.println(jsons); + + JSONObject o = JSON.parseObject(jsons); + Assert.assertEquals(s, o.getString("value")); + } + } + + public void test_0() throws Exception { + String hex = "41544D20E58F96E78EB0EFBC8DE993B6E88194E5908CE59F8E1A20E4BD9BE5B1B1E5B882E7A685E59F8EE58CBAE7A596E5BA99E8B7AF201A33331A20E58FB7E799BEE88AB1E5B9BFE59CBAE9A696E5B182201A"; + String result = getHexStr(hex); + + Map map = new HashMap(); + map.put("aaa" , result); + String stringV = JSON.toJSONString(map); + System.out.println(stringV); + JSONObject o = JSON.parseObject(stringV); + System.out.println(o.getString("aaa")); + + } + + private String getHexStr(String hex) throws UnsupportedEncodingException { + byte []bytes = new byte[hex.length() / 2]; + for(int i = 0 ; i < bytes.length ; i++) { + String v = hex.substring(i * 2 , i * 2 + 2); + bytes[i] = (byte)Integer.parseInt(v , 16); + } + String str = new String(bytes , "UTF-8"); + System.out.println(str); + return str; + } + + public static class VO { + + private String name; + + public VO(){ + + } + + public VO(String name){ + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhuangzaowen.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhuangzaowen.java new file mode 100755 index 0000000000..05e0dc725d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhuangzaowen.java @@ -0,0 +1,131 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +public class Bug_for_zhuangzaowen extends TestCase { + + public void test_for_zhuangzaowen() throws Exception { + String value = "{\"begin\":1340263804415,\"buildIds\":[\"42\"],\"end\":1340265305070,\"endBuildId\":\"50\",\"id\":\"4\",\"jobs\":[\"cb-intl-rfqma-UT\",\"cb-intl-rfqma-selenium\"],\"owners\":[\"wb_jianping.shenjp\"],\"triggerBuildId\":\"42\"}"; + System.out.println(JSON.parseObject(value, JenkinsFailedPhase.class, Feature.DisableASM)); + } + + public static class JenkinsFailedPhase {// extends BaseEntity { + + private String id; + public static final String KEY_NAME_SPACE = "phase"; + + private Set owners; + + private List buildIds; + + private Set jobs; + + private Date begin; + + private Date end; + + private String endBuildId; + + private String triggerBuildId; + + /* + * @Override public String generateKey(String id) { return KeyUtils.generatePhaseKey(id); } + */ + + public Set getOwners() { + return owners; + } + + public void setOwners(Set owners) { + this.owners = owners; + } + + public void addOwner(String owner) { + if (owners == null) { + owners = new HashSet(); + } + owners.add(owner); + } + + public List getBuildIds() { + return buildIds; + } + + public void setBuildIds(List buildIds) { + this.buildIds = buildIds; + } + + public void addBuild(String bid) { + if (buildIds == null) { + buildIds = new ArrayList(); + } + buildIds.add(bid); + } + + public Set getJobs() { + return jobs; + } + + public void setJobs(Set jobs) { + this.jobs = jobs; + } + + public void addJobs(String job) { + if (this.jobs == null) { + jobs = new HashSet(); + } + jobs.add(job); + } + + public Date getEnd() { + return end; + } + + public void setEnd(Date end) { + this.end = end; + } + + public Date getBegin() { + return begin; + } + + public void setBegin(Date begin) { + this.begin = begin; + } + + public String getEndBuildId() { + return endBuildId; + } + + public void setEndBuildId(String endBuildId) { + this.endBuildId = endBuildId; + } + + public String getTriggerBuildId() { + return triggerBuildId; + } + + public void setTriggerBuildId(String triggerBuildId) { + this.triggerBuildId = triggerBuildId; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhuel.java b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhuel.java new file mode 100755 index 0000000000..58660e40ac --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhuel.java @@ -0,0 +1,278 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +public class Bug_for_zhuel extends TestCase { + + public void test_for_zhuel() throws Exception { + Person[] ps = new Person[3]; + Person p1 = new Person(); + p1.setAge(50); + p1.setHight("170"); + p1.setId("p1's id"); + p1.setName("person1's name"); + p1.setNames(new String[] { "p1's id", "person1's name" }); + p1.setSex("男"); + Person p2 = new Person(); + p2.setAge(48); + p2.setHight("155"); + p2.setId("p2's id"); + p2.setName("person2's name"); + p2.setNames(new String[] { "p2's id", "person2's name" }); + p2.setSex("女"); + Person p3 = new Person(); + p3.setAge(10); + p3.setHight("120"); + p3.setId("p3's id "); + p3.setName("son's name"); + p3.setNames(new String[] { "p3's id ", "son's name" }); + p3.setSex("男"); + ps[0] = p1; + ps[1] = p2; + ps[2] = p3; + + Person[] ps1 = new Person[3]; + Person pp1 = new Person(); + pp1.setAge(52); + pp1.setHight("170"); + pp1.setId("pp1's id"); + pp1.setName("personpp1's name"); + pp1.setNames(new String[] { "pp1's id", "personpp1's name" }); + pp1.setSex("男"); + Person pp2 = new Person(); + pp2.setAge(49); + pp2.setHight("150"); + pp2.setId("pp2's id"); + pp2.setName("personpp2's name"); + pp2.setNames(new String[] { "pp2's id", "personpp2's name" }); + pp2.setSex("女"); + Person pp3 = new Person(); + pp3.setAge(10); + pp3.setHight("125"); + pp3.setId("pp3's id"); + pp3.setName("daughter's name"); + pp3.setNames(new String[] { "pp3's id", "daughter's name" }); + pp3.setSex("女"); + ps1[0] = pp1; + ps1[1] = pp2; + ps1[2] = pp3; + + Person[] ps2 = new Person[3]; + Person a1 = new Person(); + a1.setAge(52); + a1.setHight("170"); + a1.setId("a1's id"); + a1.setName("a1's name"); + a1.setNames(new String[] { "a1's id", "a1's name" }); + a1.setSex("男"); + Person a2 = new Person(); + a2.setAge(49); + a2.setHight("150"); + a2.setId("a2's id"); + a2.setName("a2's name"); + a2.setNames(new String[] { "a2's id", "a2's name" }); + a2.setSex("女"); + Person a3 = new Person(); + a3.setAge(10); + a3.setHight("125"); + a3.setId("a3's id"); + a3.setName("daughter's name"); + a3.setNames(new String[] { "a3's id", "daughter's name" }); + a3.setSex("女"); + ps2[0] = a1; + ps2[1] = a2; + ps2[2] = a3; + + Family f1 = new Family(); + f1.setId("f1's id"); + f1.setAddress("f1's address"); + f1.setChildrennames(new String[] { "p1's name", "p2's name", "p3's name" }); + f1.setIncome(100000000); + f1.setMaster(p1); + f1.setName("person1's home"); + f1.setPs(ps); + f1.setTest(1994.08); + + Family f2 = new Family(); + f2.setId("f2's id"); + f2.setAddress("f2's address"); + f2.setChildrennames(new String[] { "pp1's name", "pp2's name", "pp3's name" }); + f2.setIncome(100000000); + f2.setMaster(pp1); + f2.setName("personpp1's home"); + f2.setPs(ps1); + Family f3 = new Family(); + f3.setId("f3's id"); + f3.setAddress("f3's address"); + f3.setChildrennames(new String[] { "a1's name", "a2's name", "a3's name" }); + f3.setIncome(100000000); + f3.setMaster(a1); + f3.setName("a1's home"); + f3.setPs(ps2); + f3.setTest(1995.08); + Family[] fs = new Family[3]; + fs[0] = f1; + fs[1] = f2; + fs[2] = f3; + System.out.println(JSON.VERSION); + String sfs = JSON.toJSONString(fs, true); + + Assert.assertSame(fs[0].getMaster(), fs[0].getPs()[0]); + System.out.println(sfs); + + { + Family[] result = JSON.parseObject(sfs, Family[].class); + Assert.assertSame(result[0].getMaster(), result[0].getPs()[0]); + Assert.assertSame(result[1].getMaster(), result[1].getPs()[0]); + Assert.assertSame(result[2].getMaster(), result[2].getPs()[0]); + } + { + JSONArray array = JSON.parseArray(sfs); + for (int i = 0; i < array.size(); ++i) { + JSONObject jsonObj = array.getJSONObject(i); + Assert.assertSame(jsonObj.get("master"), jsonObj.getJSONArray("ps").get(0)); + } + } + } + + public static class Family { + + private String id; + private String name; + private Person[] ps; + private String address; + private String[] childrennames; + private Person master; + private long income; + private double test; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Person[] getPs() { + return ps; + } + + public void setPs(Person[] ps) { + this.ps = ps; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String[] getChildrennames() { + return childrennames; + } + + public void setChildrennames(String[] childrennames) { + this.childrennames = childrennames; + } + + public Person getMaster() { + return master; + } + + public void setMaster(Person master) { + this.master = master; + } + + public long getIncome() { + return income; + } + + public void setIncome(long income) { + this.income = income; + } + + public double getTest() { + return test; + } + + public void setTest(double test) { + this.test = test; + } + } + + public static class Person { + + private String id; + private String name; + private String sex; + private int age; + private String[] names; + private String hight; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String[] getNames() { + return names; + } + + public void setNames(String[] names) { + this.names = names; + } + + public String getHight() { + return hight; + } + + public void setHight(String hight) { + this.hight = hight; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/CollectionEmptyMapTest.java b/src/test/java/com/alibaba/json/bvt/bug/CollectionEmptyMapTest.java new file mode 100644 index 0000000000..4e09eeedc6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/CollectionEmptyMapTest.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class CollectionEmptyMapTest extends TestCase { + public void test_0() throws Exception { + Map map = Collections.emptyMap(); + + String text = JSON.toJSONString(map, SerializerFeature.WriteClassName); + + Assert.assertEquals("{\"@type\":\"java.util.Collections$EmptyMap\"}", text); + + Assert.assertSame(map, JSON.parse(text)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/FastJsonSerializeIterableTest.java b/src/test/java/com/alibaba/json/bvt/bug/FastJsonSerializeIterableTest.java new file mode 100644 index 0000000000..f784385122 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/FastJsonSerializeIterableTest.java @@ -0,0 +1,66 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +import org.junit.Assert; +import org.junit.Test; + +import com.alibaba.fastjson.JSON; + +public class FastJsonSerializeIterableTest { + @Test + public void testWithIterable() { + class Person { + private String name; + public Person(String s) { + this.name = s; + } + public String getName() { + return name; + } + } + final Person s1 = new Person("fast"); + final Person s2 = new Person("fast"); + Iterable iterable = new Iterable() { + @Override + public Iterator iterator() { + return new Iterator() { + int cursor = 0; + @Override + public boolean hasNext() { + return cursor < 2; + } + + @Override + public Person next() { + int val = cursor++; + switch (val) { + case 0: + return s1; + case 1: + return s2; + default: + throw new NoSuchElementException(); + } + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + }; + List list = new ArrayList(); + for (Person p : iterable) { + list.add(p); + } + + Assert.assertEquals("[{\"name\":\"fast\"},{\"name\":\"fast\"}]", JSON.toJSONString(list)); + Assert.assertEquals("[{\"name\":\"fast\"},{\"name\":\"fast\"}]", JSON.toJSONString(iterable)); + Assert.assertEquals("[{\"name\":\"fast\"},{\"name\":\"fast\"}]", JSON.toJSONString(list.iterator())); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1005.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1005.java new file mode 100644 index 0000000000..aec293d74d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1005.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 18/01/2017. + */ +public class Issue1005 extends TestCase { + public void test_for_issue() throws Exception { + Model model = JSON.parseObject("{\"values\":[[1,2,3]]}", Model.class); + + assertNotNull(model.values); + assertEquals(3, model.values[0].size()); + assertEquals(Byte.class, model.values[0].get(0).getClass()); + assertEquals(Byte.class, model.values[0].get(1).getClass()); + assertEquals(Byte.class, model.values[0].get(2).getClass()); + } + + public void test_for_List() throws Exception { + Model2 model = JSON.parseObject("{\"values\":[1,2,3]}", Model2.class); + + assertNotNull(model.values); + assertEquals(3, model.values.size()); + assertEquals(Byte.class, model.values.get(0).getClass()); + assertEquals(Byte.class, model.values.get(1).getClass()); + assertEquals(Byte.class, model.values.get(2).getClass()); + } + + public static class Model { + public List[] values; + } + + public static class Model2 { + public List values; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue101.java b/src/test/java/com/alibaba/json/bvt/bug/Issue101.java new file mode 100644 index 0000000000..85d7795f18 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue101.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Issue101 extends TestCase { + + public void test_for_issure() throws Exception { + VO vo = new VO(); + vo.a = new Object(); + vo.b = vo.a; + vo.c = vo.a; + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"a\":{},\"b\":{},\"c\":{}}", text); + } + + @JSONType(serialzeFeatures=SerializerFeature.DisableCircularReferenceDetect) + public static class VO { + + private Object a; + private Object b; + private Object c; + + public Object getA() { + return a; + } + + public void setA(Object a) { + this.a = a; + } + + public Object getB() { + return b; + } + + public void setB(Object b) { + this.b = b; + } + + public Object getC() { + return c; + } + + public void setC(Object c) { + this.c = c; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1013.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1013.java new file mode 100644 index 0000000000..701cbf8775 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1013.java @@ -0,0 +1,110 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by wuwen on 2017/2/16. + */ +public class Issue1013 extends TestCase { + + public void test_for_issue() throws Exception { + TestDomain domain = new TestDomain(); + + String json = JSON.toJSONString(domain); + + TestDomain domain1 = JSON.parseObject(json, TestDomain.class); + + assertEquals(domain.getList(), domain1.getList()); + } + + public void test_for_issue_1() throws Exception { + + TestDomain domain1 = JSON.parseObject("{\"list\":[]}", TestDomain.class); + TestDomain domain2 = JSON.parseObject("{\"list\":[1, 2]}", TestDomain.class); + + assertEquals(0, domain1.getList().size()); + assertEquals(Arrays.asList(1, 2), domain2.getList()); + } + + public void test_for_issue_2() throws Exception { + + TestDomain domain1 = JSON.parseObject("{\"list\":null}", TestDomain.class); + + assertEquals(1, domain1.getList().size()); + } + + public void test_for_issue3() throws Exception { + TestDomain2 domain = new TestDomain2(); + + String json = JSON.toJSONString(domain); + + TestDomain2 domain1 = JSON.parseObject(json, TestDomain2.class); + + assertEquals(domain.list, domain1.list); + } + + public void test_for_issue_4() throws Exception { + + TestDomain2 domain1 = JSON.parseObject("{\"list\":[1, 2]}", TestDomain2.class); + + assertEquals(Arrays.asList(1, 2), domain1.list); + } + + public void test_for_issue_5() throws Exception { + + TestDomain2 domain1 = JSON.parseObject("{\"list\":null}", TestDomain2.class); + + assertNull(domain1.list); + } + + public void test_for_issue_6() throws Exception { + + TestDomain3 domain3 = JSON.parseObject("{\"list\":null}", TestDomain3.class); + + assertNull(domain3.list); + } + + static class TestDomain { + private List list; + + public TestDomain(){ + list = new ArrayList(); + list.add(1); + } + + public List getList(){ + return list; + } + } + + static class TestDomain2 { + public List list; + + public TestDomain2(){ + list = new ArrayList(); + list.add(1); + } + } + + static class TestDomain3 { + private List list; + + public TestDomain3(){ + list = new ArrayList(); + list.add(1); + } + + public List getList(){ + return list; + } + + public void setList(List list) { + this.list = list; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1017.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1017.java new file mode 100644 index 0000000000..717bd5c5ef --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1017.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.io.Serializable; +import java.util.List; + +/** + * Created by wenshao on 11/02/2017. + */ +public class Issue1017 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"pictureList\":[\"http://static.oschina.net/uploads/user/1218/2437072_100.jpg?t=1461076033000\",\"http://common.cnblogs.com/images/icon_weibo_24.png\"]}"; + + User user = JSON.parseObject(json, User.class); + assertNotNull(user.pictureList); + assertEquals(2, user.pictureList.size()); + assertEquals("http://static.oschina.net/uploads/user/1218/2437072_100.jpg?t=1461076033000", user.pictureList.get(0)); + assertEquals("http://common.cnblogs.com/images/icon_weibo_24.png", user.pictureList.get(1)); + } + + public static class User implements Serializable { + private List pictureList; + public List getPictureList() { + return pictureList; + } + public User setPictureList(List pictureList) { + this.pictureList = pictureList; + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue101_NoneASM.java b/src/test/java/com/alibaba/json/bvt/bug/Issue101_NoneASM.java new file mode 100644 index 0000000000..193c7a0041 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue101_NoneASM.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Issue101_NoneASM extends TestCase { + + public void test_for_issure() throws Exception { + VO vo = new VO(); + vo.a = new Object(); + vo.b = vo.a; + vo.c = vo.a; + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"a\":{},\"b\":{},\"c\":{}}", text); + } + + @JSONType(serialzeFeatures=SerializerFeature.DisableCircularReferenceDetect) + private static class VO { + + private Object a; + private Object b; + private Object c; + + public Object getA() { + return a; + } + + public void setA(Object a) { + this.a = a; + } + + public Object getB() { + return b; + } + + public void setB(Object b) { + this.b = b; + } + + public Object getC() { + return c; + } + + public void setC(Object c) { + this.c = c; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue101_field.java b/src/test/java/com/alibaba/json/bvt/bug/Issue101_field.java new file mode 100644 index 0000000000..22e9fb668c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue101_field.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Issue101_field extends TestCase { + + public void test_for_issure() throws Exception { + VO vo = new VO(); + vo.a = new Object(); + vo.b = vo.a; + vo.c = vo.a; + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"a\":{},\"b\":{},\"c\":{\"$ref\":\"$.b\"}}", text); + } + + public static class VO { + + private Object a; + private Object b; + private Object c; + + public Object getA() { + return a; + } + + public void setA(Object a) { + this.a = a; + } + + @JSONField(serialzeFeatures=SerializerFeature.DisableCircularReferenceDetect) + public Object getB() { + return b; + } + + public void setB(Object b) { + this.b = b; + } + + public Object getC() { + return c; + } + + public void setC(Object c) { + this.c = c; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue101_field_NoneASM.java b/src/test/java/com/alibaba/json/bvt/bug/Issue101_field_NoneASM.java new file mode 100644 index 0000000000..f8bead804c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue101_field_NoneASM.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Issue101_field_NoneASM extends TestCase { + + public void test_for_issure() throws Exception { + VO vo = new VO(); + vo.a = new Object(); + vo.b = vo.a; + vo.c = vo.a; + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"a\":{},\"b\":{},\"c\":{\"$ref\":\"$.b\"}}", text); + } + + private static class VO { + + private Object a; + private Object b; + private Object c; + + public Object getA() { + return a; + } + + public void setA(Object a) { + this.a = a; + } + + @JSONField(serialzeFeatures=SerializerFeature.DisableCircularReferenceDetect) + public Object getB() { + return b; + } + + public void setB(Object b) { + this.b = b; + } + + public Object getC() { + return c; + } + + public void setC(Object c) { + this.c = c; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1020.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1020.java new file mode 100644 index 0000000000..0182aa3fbb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1020.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.time.LocalDate; + +/** + * Created by wenshao on 11/03/2017. + */ +public class Issue1020 extends TestCase { + public void test_null() throws Exception { + Vo vo = JSON.parseObject("{\"ld\":null}", Vo.class); + assertNull(vo.ld); + + } + + public void test_empty() throws Exception { + Vo vo = JSON.parseObject("{\"ld\":\"\"}", Vo.class); + assertNull(vo.ld); + + } + + public static class Vo { + public LocalDate ld; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1023.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1023.java new file mode 100644 index 0000000000..efd843a725 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1023.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import junit.framework.TestCase; + +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.util.ArrayList; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * Created by wenshao on 11/03/2017. + */ +public class Issue1023 extends TestCase { + public void test_for_issue() throws Exception { + Date now = new Date(); + + GregorianCalendar gregorianCalendar = (GregorianCalendar) GregorianCalendar.getInstance(); + gregorianCalendar.setTime(now); + + XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar); + + String jsonString = JSON.toJSONString(calendar); + // success + calendar = JSON.parseObject(jsonString, XMLGregorianCalendar.class); + + Object toJSON1 = JSON.toJSON(calendar); // debug看到是 Long 类型 + // 所以这里会报错: + // error: java.lang.ClassCastException: java.lang.Long cannot be cast to com.alibaba.fastjson.JSONObject + //JSONObject jsonObject = (JSONObject) JSON.toJSON(calendar); + // 所以 这里肯定会报错, 因为 jsonObject 不是JSONObject类型 + //calendar = jsonObject.toJavaObject(XMLGregorianCalendar.class); + + List calendarList = new ArrayList(); + calendarList.add(calendar); + calendarList.add(calendar); + calendarList.add(calendar); + + Object toJSON2 = JSON.toJSON(calendarList); // debug 看到是 JSONArray 类型 + + // success: 通过 JSONArray.parseArray 方法可以正确转换 + JSONArray jsonArray = (JSONArray) JSON.toJSON(calendarList); + jsonString = jsonArray.toJSONString(); + List calendarList1 = JSONArray.parseArray(jsonString, XMLGregorianCalendar.class); + + // 通过 jsonArray.toJavaList 无法转换 + // error: com.alibaba.fastjson.JSONException: can not cast to : javax.xml.datatype.XMLGregorianCalendar + List calendarList2 = jsonArray.toJavaList(XMLGregorianCalendar.class); + assertNotNull(calendarList2); + assertEquals(3, calendarList2.size()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1030.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1030.java new file mode 100644 index 0000000000..4f329455e8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1030.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 13/03/2017. + */ +public class Issue1030 extends TestCase { + public void test_for_issue() throws Exception { + String DOC = "{\"books\":[{\"pageWords\":[{\"num\":10},{\"num\":15}]},{\"pageWords\":[{\"num\":20}]}]}"; + + //fastjson包 + JSONObject result = JSONObject.parseObject(DOC); + + List array = (List) JSONPath.eval(result, "$.books[0:].pageWords[0:]"); + + assertEquals(3, array.size()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1036.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1036.java new file mode 100644 index 0000000000..f3da7aa8c9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1036.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.json.bvt.parser.array.BeanToArrayTest3_private; +import junit.framework.TestCase; +import org.junit.Assert; + +/** + * Created by wuwen on 2017/2/24. + */ +public class Issue1036 extends TestCase { + + /** + * @see BeanToArrayTest3_private#test_array() + * @see com.alibaba.fastjson.parser.deserializer.DefaultFieldDeserializer#parseField + * */ + public void test_for_issue() throws Exception { + NullPointerException exception = new NullPointerException("test"); + Result result = new Result(); + result.setException(exception); + + String json = JSON.toJSONString(result); + + Result a = JSON.parseObject(json, new TypeReference>() { + }); + + Assert.assertEquals("test", a.getException().getMessage()); + } + + public static class Result { + private T data; + + private Throwable exception; + + public Result() { + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public Throwable getException() { + return exception; + } + + public void setException(Throwable exception) { + this.exception = exception; + } + + @Override + public String toString() { + return "Result{" + + "data='" + data + '\'' + + ", exception=" + exception + + '}'; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1063.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1063.java new file mode 100644 index 0000000000..bfefe69826 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1063.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.sql.Timestamp; + +/** + * Created by wenshao on 11/03/2017. + */ +public class Issue1063 extends TestCase { + public void test_for_issue() throws Exception { + long currentMillis = System.currentTimeMillis(); + TimestampBean bean = new TimestampBean(); + bean.setTimestamp(new Timestamp(currentMillis)); + String timestampJson = JSON.toJSONString(bean); + + // 这里能转换成功 + TimestampBean beanOfJSON = JSON.parseObject(timestampJson, TimestampBean.class); + + // 这里抛异常 java.lang.NumberFormatException + JSONObject jsonObject = JSON.parseObject(timestampJson); + Timestamp timestamp2 = jsonObject.getObject("timestamp", Timestamp.class); + assertEquals(currentMillis/1000, timestamp2.getTime() / 1000); + } + + public static class TimestampBean { + private Timestamp timestamp = null; + + public Timestamp getTimestamp() { + return timestamp; + } + + public void setTimestamp(Timestamp timestamp) { + this.timestamp = timestamp; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1063_date.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1063_date.java new file mode 100644 index 0000000000..1fab3e99a0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1063_date.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.sql.Date; +import java.sql.Timestamp; + +/** + * Created by wenshao on 11/03/2017. + */ +public class Issue1063_date extends TestCase { + public void test_for_issue() throws Exception { + long currentMillis = System.currentTimeMillis(); + TimestampBean bean = new TimestampBean(); + bean.setTimestamp(new Date(currentMillis)); + String timestampJson = JSON.toJSONString(bean); + + // 这里能转换成功 + TimestampBean beanOfJSON = JSON.parseObject(timestampJson, TimestampBean.class); + + // 这里抛异常 java.lang.NumberFormatException + JSONObject jsonObject = JSON.parseObject(timestampJson); + Timestamp timestamp2 = jsonObject.getObject("timestamp", Timestamp.class); + assertEquals(currentMillis/1000, timestamp2.getTime() / 1000); + } + + public static class TimestampBean { + private Date timestamp = null; + + public Date getTimestamp() { + return timestamp; + } + + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1074.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1074.java new file mode 100644 index 0000000000..f3b8eca58a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1074.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/03/2017. + */ +public class Issue1074 extends TestCase { + public void test_for_issue() throws Exception { + String json = "//123456"; + Throwable error = null; + try { + JSON.parse(json); + } catch (Exception ex) { + error = ex; + } + assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1075.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1075.java new file mode 100644 index 0000000000..fafb86e19d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1075.java @@ -0,0 +1,14 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/03/2017. + */ +public class Issue1075 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{ \"question\": \"1+1=?\\u1505a\"}"; + JSON.parseObject(json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue109.java b/src/test/java/com/alibaba/json/bvt/bug/Issue109.java new file mode 100644 index 0000000000..5dbd0a4cda --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue109.java @@ -0,0 +1,14 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.util.ASMUtils; + + +public class Issue109 extends TestCase { + public void test_for_issue() throws Exception { + Assert.assertFalse(ASMUtils.isAndroid(null)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue115.java b/src/test/java/com/alibaba/json/bvt/bug/Issue115.java new file mode 100644 index 0000000000..483c2b4efa --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue115.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Issue115 extends TestCase { + + public void test_for_issue_115() throws Exception { + Player2 player = new Player2(); + + Card2 card = new Card2(); + card.cardId = "hello"; + player.cards.put(1, card); + player.cardGroup.put(1, card); + + String json = JSON.toJSONString(player); + + System.out.println("json:" + json); + + Player2 player2 = JSON.parseObject(json, Player2.class); + } + + static class Player2 { + + public Map cards = new HashMap(); + public Map cardGroup = new HashMap(); + } + + static class Card2 { + + public String cardId; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue117.java b/src/test/java/com/alibaba/json/bvt/bug/Issue117.java new file mode 100644 index 0000000000..fb721dc522 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue117.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + + +public class Issue117 extends TestCase { + public void test_for_issue() throws Exception { + VO vo = JSON.parseObject("{\"id\":123}", VO.class); + Assert.assertEquals(123, vo.getId()); + vo.setId(124); + vo.equals(null); + vo.hashCode(); + Assert.assertEquals("{\"id\":124}", vo.toString()); + } + + public static interface VO { + public int getId(); + public void setId(int val); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue118.java b/src/test/java/com/alibaba/json/bvt/bug/Issue118.java new file mode 100644 index 0000000000..28af02be89 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue118.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class Issue118 extends TestCase { + public void test_for_issue() throws Exception { + String json = JSON.toJSONString("\0"); + assertEquals("\"\\u0000\"", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue119.java b/src/test/java/com/alibaba/json/bvt/bug/Issue119.java new file mode 100644 index 0000000000..4ccb96430a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue119.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.JSONScanner; + +public class Issue119 extends TestCase { + + public void test_for_issue() throws Exception { + JSONScanner lexer = new JSONScanner("-100S"); + lexer.resetStringPosition(); + lexer.scanNumber(); + Assert.assertEquals(Short.class, lexer.integerValue().getClass()); + Assert.assertEquals(-100, lexer.integerValue().shortValue()); + lexer.close(); + } + + public void test_for_issue_b() throws Exception { + JSONScanner lexer = new JSONScanner("-10B"); + lexer.scanNumber(); + Assert.assertEquals(Byte.class, lexer.integerValue().getClass()); + Assert.assertEquals(-10, lexer.integerValue().byteValue()); + lexer.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue124.java b/src/test/java/com/alibaba/json/bvt/bug/Issue124.java new file mode 100644 index 0000000000..4a37f95a44 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue124.java @@ -0,0 +1,177 @@ +package com.alibaba.json.bvt.bug; + +import java.util.List; +import java.util.Random; +import java.util.concurrent.CountDownLatch; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Issue124 extends TestCase { + + public void test_for_issue() throws Exception { + // final ObjectMapper mapper = new ObjectMapper(); + // mapper.setSerializationInclusion(Include.NON_NULL); + final Random random = new Random(); + final int threadCount = 1000; + final CountDownLatch latch = new CountDownLatch(threadCount); +// { +// UserInfo info = new UserInfo(); +// CheckInfoVo vo = new CheckInfoVo(100); +// JSON.toJSONString(new SuccessReturn(info), SerializerFeature.WriteDateUseDateFormat); +// JSON.toJSONString(new SuccessReturn(vo), +// SerializerFeature.WriteDateUseDateFormat); +// } + for (int i = 0; i < threadCount; i++) { + new Thread() { + + @Override + public void run() { + UserInfo info = new UserInfo(); + CheckInfoVo vo = new CheckInfoVo(100); + int r = random.nextInt(); + try { + if (r % 2 == 0) { + // System.out.println(mapper.writeValueAsString(info)); + System.out.println(JSON.toJSONString(new SuccessReturn(info), + SerializerFeature.WriteDateUseDateFormat)); + } else { + // System.out.println(mapper.writeValueAsString(vo)); + System.out.println(JSON.toJSONString(new SuccessReturn(vo), + SerializerFeature.WriteDateUseDateFormat)); + } + } catch (Exception e) { + e.printStackTrace(); + System.exit(0); + } finally { + latch.countDown(); + } + } + }.start(); + } + latch.await(); + } + + static class SuccessReturn { + + private int code = 0; + private Object data; + + SuccessReturn(Object data){ + this.data = data; + } + + public int getCode() { + return code; + } + + public Object getData() { + return data; + } + } + + static class CheckInfoVo { + + private final int gmMessageCount; + + public CheckInfoVo(){ + this.gmMessageCount = 0; + } + + public CheckInfoVo(int gmMessageCount){ + this.gmMessageCount = gmMessageCount; + } + + public int getGmMessageCount() { + return gmMessageCount; + } + } + + static class UserInfo { + + private long uid; + private String userName; + private String nickName; + private int userType; + private int avatar; + private String updateTime; + private int modifyNickanme; // 1可以修改nickname 0不能修改 + private long appid; + private List serverIds; + + public long getAppid() { + return appid; + } + + public void setAppid(long appid) { + this.appid = appid; + } + + public long getUid() { + return uid; + } + + public void setUid(long uid) { + this.uid = uid; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public int getUserType() { + return userType; + } + + public void setUserType(int userType) { + this.userType = userType; + } + + public int getAvatar() { + return avatar; + } + + public void setAvatar(int avatar) { + this.avatar = avatar; + } + + public String getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(String updateTime) { + this.updateTime = updateTime; + } + + public String getNickName() { + return nickName; + } + + public void setNickName(String nickName) { + this.nickName = nickName; + } + + public int getModifyNickanme() { + return modifyNickanme; + } + + public void setModifyNickanme(int modifyNickanme) { + this.modifyNickanme = modifyNickanme; + } + + public List getServerIds() { + return serverIds; + } + + public void setServerIds(List serverIds) { + this.serverIds = serverIds; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue125.java b/src/test/java/com/alibaba/json/bvt/bug/Issue125.java new file mode 100644 index 0000000000..742958ce33 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue125.java @@ -0,0 +1,15 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +public class Issue125 extends TestCase { + + public void test_for_issue() throws Exception { + String content = "{\"data\":\"sfasfasdfasdfas\\r" + String.valueOf((char) 160) + "\\rasdfasdfasd\"}"; + JSONObject jsonObject = JSON.parseObject(content); + System.out.println(jsonObject); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue126.java b/src/test/java/com/alibaba/json/bvt/bug/Issue126.java new file mode 100644 index 0000000000..2fd76b28c9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue126.java @@ -0,0 +1,15 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONObject; + +public class Issue126 extends TestCase { + + public void test_for_issue() throws Exception { + JSONObject j = new JSONObject(); + j.put("content", + "爸爸去哪儿-第十期-萌娃比赛小猪快跑 爸爸上演\"百变大咖秀\"-【湖南卫视官方版1080P】20131213: http://youtu.be/ajvaXKAduJ4 via @youtube"); + System.out.println(j.toJSONString()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue127.java b/src/test/java/com/alibaba/json/bvt/bug/Issue127.java new file mode 100644 index 0000000000..f69cd315cb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue127.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class Issue127 extends TestCase { + + public void test_for_issue_127() throws Exception { + String text = "{_BillId:\"X20140106S0110\",_Status:1,_PayStatus:0,_RunEmpId:undefined}"; + JSON.parseObject(text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue1296.java b/src/test/java/com/alibaba/json/bvt/bug/Issue1296.java new file mode 100644 index 0000000000..3d35e4ddee --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue1296.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 02/07/2017. + */ +public class Issue1296 extends TestCase { + public void test_for_issue() throws Exception { + Exception error = null; + try { + JSON.parseObject("1"); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue141.java b/src/test/java/com/alibaba/json/bvt/bug/Issue141.java new file mode 100644 index 0000000000..1b6f39debd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue141.java @@ -0,0 +1,14 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.util.TypeUtils; + + +public class Issue141 extends TestCase { + public void test_for_issue() throws Exception { + Assert.assertFalse(TypeUtils.castToBoolean("0").booleanValue()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue143.java b/src/test/java/com/alibaba/json/bvt/bug/Issue143.java new file mode 100644 index 0000000000..a19aa2b803 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue143.java @@ -0,0 +1,76 @@ +package com.alibaba.json.bvt.bug; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class Issue143 extends TestCase { + + public void test_for_issue() throws Exception { + String text = "{\"rec\":[{},{}]}"; + + JsonStroe store = new JsonStroe(); + + JSONReader reader = new JSONReader(new StringReader(text)); + reader.startObject(); + + String key = reader.readString(); + + Assert.assertEquals("rec", key); + reader.startArray(); + + List list = new ArrayList(); + while(reader.hasNext()) { + KeyValue keyValue = reader.readObject(KeyValue.class); + list.add(keyValue); + } + store.setRec(list); + + reader.endArray(); + + reader.endObject(); + + reader.close(); + } + + public static class JsonStroe { + + private List rec = new ArrayList(); + + public void setRec(List items) { + this.rec = items; + } + + public List getRec() { + return rec; + } + } + + public static class KeyValue { + + private String key; + private String value; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue146.java b/src/test/java/com/alibaba/json/bvt/bug/Issue146.java new file mode 100644 index 0000000000..eb1f745c18 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue146.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Issue146 extends TestCase { + protected void setUp() throws Exception { + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Issue146."); + } + + public void test_for_issue() throws Exception { + VO vo = new VO(); + JSON json = JSON.parseObject("{}"); + vo.setName(json); + String s = JSON.toJSONString(vo, SerializerFeature.WriteClassName); + System.out.println(s); + JSON.parseObject(s); + } + + public static class VO { + + private int id; + private Object name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Object getName() { + return name; + } + + public void setName(Object name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue153.java b/src/test/java/com/alibaba/json/bvt/bug/Issue153.java new file mode 100644 index 0000000000..4398ee830d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue153.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + + +public class Issue153 extends TestCase { + public void test_for_issue() throws Exception { + String text = "[{\"url_short\":\"http://t.cn/8soWK4z\",\"url_long\":\"http://wenshao.com\",\"type\":0}]"; + + JSON.parseObject(text, new TypeReference[]>(){}); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue157.java b/src/test/java/com/alibaba/json/bvt/bug/Issue157.java new file mode 100644 index 0000000000..97ec84ca38 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue157.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONObject; + + +public class Issue157 extends TestCase { + public void test_for_issue() throws Exception { + String m = "2、95开头靓号,呼出显号,对方可以打回,即使不在线亦可设置呼转手机,不错过任何重要电话,不暴露真实身份。\r\n3、应用内完全免费发送文字消息、语音对讲。\r\n4、建议WIFI 或 3G 环境下使用以获得最佳通话体验"; + JSONObject json = new JSONObject(); + json.put("介绍", m); + String content = json.toJSONString(); + System.out.println(content); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue166.java b/src/test/java/com/alibaba/json/bvt/bug/Issue166.java new file mode 100644 index 0000000000..3a80fa0e60 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue166.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Issue166 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setbId("xxxx"); + + String text = JSON.toJSONString(vo, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteEnumUsingToString, + SerializerFeature.WriteNonStringKeyAsString, SerializerFeature.QuoteFieldNames, + SerializerFeature.SkipTransientField, SerializerFeature.SortField, + SerializerFeature.PrettyFormat); + System.out.println(text); + + VO vo2 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getbId(), vo2.getbId()); + } + + public static class VO { + + private String bId; + + public String getbId() { + return bId; + } + + public void setbId(String bId) { + this.bId = bId; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue169.java b/src/test/java/com/alibaba/json/bvt/bug/Issue169.java new file mode 100644 index 0000000000..be3e533247 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue169.java @@ -0,0 +1,78 @@ +package com.alibaba.json.bvt.bug; + +import java.io.StringReader; +import java.io.StringWriter; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.JSONWriter; + +public class Issue169 extends TestCase { + + public void test_for_issue() throws Exception { + StringWriter strWriter = new StringWriter(); + + SectionRequest req = new SectionRequest(); + req.setScreenHeight(100);// 父类中的属性 + req.setScreenWidth(12);// 父类中的属性 + req.setTag("11"); + JSONWriter writer = new JSONWriter(strWriter); + writer.startArray(); + writer.writeObject(req); + writer.endArray(); + writer.close(); + + String text = strWriter.toString(); + + StringReader strReader = new StringReader(text); + JSONReader reader = new JSONReader(strReader); + reader.startArray(); + ; + while (reader.hasNext()) { + SectionRequest vo = reader.readObject(SectionRequest.class); + System.out.println("tag:" + vo.getTag() + "screenHeight:" + vo.getScreenHeight() + "ScreenWidth:" + + vo.getScreenWidth()); + Assert.assertEquals(100, vo.getScreenHeight()); + Assert.assertEquals(12, vo.getScreenWidth()); + Assert.assertEquals("11", vo.getTag()); + + } + reader.endArray(); + reader.close(); + } + + public static class SectionRequest { + + private String tag; + private int screenHeight; + private int screenWidth; + + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } + + public int getScreenHeight() { + return screenHeight; + } + + public void setScreenHeight(int screenHeight) { + this.screenHeight = screenHeight; + } + + public int getScreenWidth() { + return screenWidth; + } + + public void setScreenWidth(int screenWidth) { + this.screenWidth = screenWidth; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue171.java b/src/test/java/com/alibaba/json/bvt/bug/Issue171.java new file mode 100644 index 0000000000..77c9ee8579 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue171.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Issue171 extends TestCase { + + public void test_for_issue() throws Exception { + Map m = new HashMap(); + m.put("a", "\u000B"); + String json = JSON.toJSONString(m); + System.out.println(json); + JSON.parse(json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue176.java b/src/test/java/com/alibaba/json/bvt/bug/Issue176.java new file mode 100644 index 0000000000..3ea9d2a597 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue176.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class Issue176 extends TestCase { + + public void test_for_parent() throws Exception { + String text = "{\"content\":\"result\"}"; + + ParentClass parentClass = JSON.parseObject(text, ParentClass.class); + + Assert.assertEquals(parentClass.getTest(), "result"); + + String text2 = JSON.toJSONString(parentClass); + Assert.assertEquals(text, text2); + } + + public void test_for_sub() throws Exception { + String text = "{\"content\":\"result\"}"; + + SubClass parentClass = JSON.parseObject(text, SubClass.class); + + Assert.assertEquals(parentClass.getTest(), "result"); + String text2 = JSON.toJSONString(parentClass); + Assert.assertEquals(text, text2); + } + + public static class ParentClass { + + @JSONField(name = "content") + protected String test; + + public String getTest() { + return test; + } + + public void setTest(String test) { + this.test = test; + } + + } + + public static class SubClass extends ParentClass { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue177.java b/src/test/java/com/alibaba/json/bvt/bug/Issue177.java new file mode 100644 index 0000000000..8171a64a00 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue177.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +public class Issue177 extends TestCase { + + public void test_for_issue_177() throws Exception { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("data", new byte[20]); + + String jsonString = JSON.toJSONString(jsonObject); + JSONObject parseObject = JSON.parseObject(jsonString); + + byte[] bytes = parseObject.getBytes("data"); + + byte[] bs = parseObject.getObject("data", byte[].class); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue179.java b/src/test/java/com/alibaba/json/bvt/bug/Issue179.java new file mode 100644 index 0000000000..726b52cfbe --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue179.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +public class Issue179 extends TestCase { + + public void test_for_issue_179() throws Exception { + Student student = new Student(); + School school = new School(); + school.setStudent(student); + student.setSchool(school); + + // String schoolJSONString = JSON.toJSONString(school); + // System.out.println(schoolJSONString); + // + // School fromJSONSchool = JSON.parseObject(schoolJSONString, + // School.class); + // + // System.out.println(JSON.toJSONString(fromJSONSchool)); + + JSONObject object = new JSONObject(); + object.put("school", school); + + String jsonString = JSON.toJSONString(object); + System.out.println(jsonString); + + JSONObject object2 = (JSONObject) JSON.parseObject(jsonString, JSONObject.class); + System.out.println(JSON.toJSONString(object2)); + + School school2 = object2.getObject("school", School.class); + System.out.println(school2); + } + + public static class School { + + Student student; + + public Student getStudent() { + return student; + } + + public void setStudent(Student student) { + this.student = student; + } + } + + static class Student { + + public School getSchool() { + return school; + } + + public void setSchool(School school) { + this.school = school; + } + + School school; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue183.java b/src/test/java/com/alibaba/json/bvt/bug/Issue183.java new file mode 100644 index 0000000000..4d0ea66283 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue183.java @@ -0,0 +1,66 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class Issue183 extends TestCase { + + public void test_issue_183() throws Exception { + A a = new A(); + a.setName("xiao").setAge(21); + String result = JSON.toJSONString(a); + A newA = JSON.parseObject(result, A.class); + Assert.assertTrue(a.equals(newA)); + } + + static interface IA { + + @JSONField(name = "wener") + String getName(); + + @JSONField(name = "wener") + IA setName(String name); + } + + static class A implements IA { + + String name; + int age; + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public A setAge(int age) { + this.age = age; + return this; + } + + public A setName(String name) { + this.name = name; + return this; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + A other = (A) obj; + if (age != other.age) return false; + if (name == null) { + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; + return true; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue184.java b/src/test/java/com/alibaba/json/bvt/bug/Issue184.java new file mode 100644 index 0000000000..886fda569d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue184.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Date; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; + +public class Issue184 extends TestCase { + + public void test_for_issue() throws Exception { + SimplePropertyPreFilter filter = new SimplePropertyPreFilter(); + + VO vo = new VO(); + vo.setDate(new Date()); + String text = JSON.toJSONString(vo, filter); + System.out.println(text); + } + + private static class VO { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue190.java b/src/test/java/com/alibaba/json/bvt/bug/Issue190.java new file mode 100644 index 0000000000..1ec92ed623 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue190.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class Issue190 extends TestCase { + + public void test_for_issue() throws Exception { + Assert.assertEquals(WebSoscketCommand.A, JSON.parseObject("\"A\"", WebSoscketCommand.class)); + } + + public static enum WebSoscketCommand { + A, B, C + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue199.java b/src/test/java/com/alibaba/json/bvt/bug/Issue199.java new file mode 100644 index 0000000000..4724a93811 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue199.java @@ -0,0 +1,76 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class Issue199 extends TestCase { + + public void test_for_issue() throws Exception { + ConsumeStatus vo = new ConsumeStatus(); + vo.pullRT = 101.01D; + vo.pullTPS = 102.01D; + vo.consumeRT = 103.01D; + vo.consumeOKTPS = 104.01D; + vo.consumeFailedTPS = 105.01D; + + String text = JSON.toJSONString(vo); + ConsumeStatus vo1 = JSON.parseObject(text, ConsumeStatus.class); + Assert.assertTrue(vo.pullRT == vo1.pullRT); + Assert.assertTrue(vo.pullTPS == vo1.pullTPS); + Assert.assertTrue(vo.consumeRT == vo1.consumeRT); + Assert.assertTrue(vo.consumeOKTPS == vo1.consumeOKTPS); + Assert.assertTrue(vo.consumeFailedTPS == vo1.consumeFailedTPS); + } + + public static class ConsumeStatus { + + private double pullRT; + private double pullTPS; + private double consumeRT; + private double consumeOKTPS; + private double consumeFailedTPS; + + public double getPullRT() { + return pullRT; + } + + public void setPullRT(double pullRT) { + this.pullRT = pullRT; + } + + public double getPullTPS() { + return pullTPS; + } + + public void setPullTPS(double pullTPS) { + this.pullTPS = pullTPS; + } + + public double getConsumeRT() { + return consumeRT; + } + + public void setConsumeRT(double consumeRT) { + this.consumeRT = consumeRT; + } + + public double getConsumeOKTPS() { + return consumeOKTPS; + } + + public void setConsumeOKTPS(double consumeOKTPS) { + this.consumeOKTPS = consumeOKTPS; + } + + public double getConsumeFailedTPS() { + return consumeFailedTPS; + } + + public void setConsumeFailedTPS(double consumeFailedTPS) { + this.consumeFailedTPS = consumeFailedTPS; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue204.java b/src/test/java/com/alibaba/json/bvt/bug/Issue204.java new file mode 100644 index 0000000000..640edc5803 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue204.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializeFilter; + +public class Issue204 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + + SerializeFilter filter = null; + JSON.toJSONString(vo, SerializeConfig.getGlobalInstance(), filter); + JSON.toJSONString(vo, SerializeConfig.getGlobalInstance(), new SerializeFilter[0]); + } + + public static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue208.java b/src/test/java/com/alibaba/json/bvt/bug/Issue208.java new file mode 100644 index 0000000000..ff16c75e68 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue208.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Issue208 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO (); + vo.序号 = 1001; + vo.名称 = "张三"; + + String text = JSON.toJSONString(vo); + JSON.parseObject(text, VO.class); + + } + + public void test_for_issue_1() throws Exception { + 实体 vo = new 实体 (); + vo.序号 = 1001; + vo.名称 = "张三"; + + String text = JSON.toJSONString(vo); + JSON.parseObject(text, 实体.class); +} + + public static class VO { + + public int 序号; + public String 名称; + } + + public static class 实体 { + + public int 序号; + public String 名称; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue215.java b/src/test/java/com/alibaba/json/bvt/bug/Issue215.java new file mode 100644 index 0000000000..56d9c018ba --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue215.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + + +public class Issue215 extends TestCase { + public void test_for_issue() throws Exception { + byte[] bytes = new byte[128]; + new Random().nextBytes(bytes); + + Map map = new HashMap(); + map.put("val", bytes); + + String text = JSON.toJSONString(map); + System.out.println(text); + + Map map2 = JSON.parseObject(text, new TypeReference>() {}); + byte[] bytes2 = (byte[]) map2.get("val"); + Assert.assertArrayEquals(bytes2, bytes); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue215_boolean_array.java b/src/test/java/com/alibaba/json/bvt/bug/Issue215_boolean_array.java new file mode 100644 index 0000000000..4fb7938e2a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue215_boolean_array.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + + +public class Issue215_boolean_array extends TestCase { + public void test_for_issue() throws Exception { + boolean[] values = new boolean[128]; + Random random = new Random(); + for (int i = 0; i < values.length; ++i) { + values[i] = random.nextInt() % 2 == 0; + } + + Map map = new HashMap(); + map.put("val", values); + + String text = JSON.toJSONString(map); + System.out.println(text); + + Map map2 = JSON.parseObject(text, new TypeReference>() {}); + boolean[] values2 = (boolean[]) map2.get("val"); + Assert.assertTrue(Arrays.equals(values2, values)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue215_char_array.java b/src/test/java/com/alibaba/json/bvt/bug/Issue215_char_array.java new file mode 100644 index 0000000000..95382cdadc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue215_char_array.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + + +public class Issue215_char_array extends TestCase { + public void test_for_issue() throws Exception { + char[] chars = new char[128]; + Random random = new Random(); + for (int i = 0; i < chars.length; ++i) { + chars[i] = (char) Math.abs((short) random.nextInt()); + } + + Map map = new HashMap(); + map.put("val", chars); + + String text = JSON.toJSONString(map); + System.out.println(text); + + Map map2 = JSON.parseObject(text, new TypeReference>() {}); + char[] chars2 = (char[]) map2.get("val"); + Assert.assertArrayEquals(chars2, chars); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue215_double_array.java b/src/test/java/com/alibaba/json/bvt/bug/Issue215_double_array.java new file mode 100644 index 0000000000..f46f1b31e9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue215_double_array.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + + +public class Issue215_double_array extends TestCase { + public void test_for_issue() throws Exception { + double[] values = new double[128]; + Random random = new Random(); + for (int i = 0; i < values.length; ++i) { + values[i] = random.nextDouble(); + } + + Map map = new HashMap(); + map.put("val", values); + + String text = JSON.toJSONString(map); + System.out.println(text); + + Map map2 = JSON.parseObject(text, new TypeReference>() {}); + double[] values2 = (double[]) map2.get("val"); + Assert.assertTrue(Arrays.equals(values2, values)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue215_float_array.java b/src/test/java/com/alibaba/json/bvt/bug/Issue215_float_array.java new file mode 100644 index 0000000000..f33ba0fcc6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue215_float_array.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + + +public class Issue215_float_array extends TestCase { + public void test_for_issue() throws Exception { + float[] values = new float[128]; + Random random = new Random(); + for (int i = 0; i < values.length; ++i) { + values[i] = random.nextFloat(); + } + + Map map = new HashMap(); + map.put("val", values); + + String text = JSON.toJSONString(map); + System.out.println(text); + + Map map2 = JSON.parseObject(text, new TypeReference>() {}); + float[] values2 = (float[]) map2.get("val"); + Assert.assertTrue(Arrays.equals(values2, values)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue215_int_array.java b/src/test/java/com/alibaba/json/bvt/bug/Issue215_int_array.java new file mode 100644 index 0000000000..d0a3b3bae6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue215_int_array.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + + +public class Issue215_int_array extends TestCase { + public void test_for_issue() throws Exception { + int[] values = new int[128]; + Random random = new Random(); + for (int i = 0; i < values.length; ++i) { + values[i] = random.nextInt(); + } + + Map map = new HashMap(); + map.put("val", values); + + String text = JSON.toJSONString(map); + System.out.println(text); + + Map map2 = JSON.parseObject(text, new TypeReference>() {}); + int[] values2 = (int[]) map2.get("val"); + Assert.assertArrayEquals(values2, values); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue215_long_array.java b/src/test/java/com/alibaba/json/bvt/bug/Issue215_long_array.java new file mode 100644 index 0000000000..a5cce43545 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue215_long_array.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + + +public class Issue215_long_array extends TestCase { + public void test_for_issue() throws Exception { + long[] values = new long[128]; + Random random = new Random(); + for (int i = 0; i < values.length; ++i) { + values[i] = random.nextLong(); + } + + Map map = new HashMap(); + map.put("val", values); + + String text = JSON.toJSONString(map); + System.out.println(text); + + Map map2 = JSON.parseObject(text, new TypeReference>() {}); + long[] values2 = (long[]) map2.get("val"); + Assert.assertArrayEquals(values2, values); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue215_short_array.java b/src/test/java/com/alibaba/json/bvt/bug/Issue215_short_array.java new file mode 100644 index 0000000000..14603a7cac --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue215_short_array.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + + +public class Issue215_short_array extends TestCase { + public void test_for_issue() throws Exception { + short[] values = new short[128]; + Random random = new Random(); + for (int i = 0; i < values.length; ++i) { + values[i] = (short) random.nextInt(); + } + + Map map = new HashMap(); + map.put("val", values); + + String text = JSON.toJSONString(map); + System.out.println(text); + + Map map2 = JSON.parseObject(text, new TypeReference>() {}); + short[] values2 = (short[]) map2.get("val"); + Assert.assertArrayEquals(values2, values); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue220.java b/src/test/java/com/alibaba/json/bvt/bug/Issue220.java new file mode 100644 index 0000000000..36829af3f0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue220.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class Issue220 extends TestCase { + + public void test_for_issue() throws Exception { + Attr attr = new Attr(); + attr.jTType = 123; + attr.value = "xxxx"; + attr.symbol = "yyyy"; + + String text = JSON.toJSONString(attr); + + Assert.assertEquals("{\"jTType\":123,\"symbol\":\"yyyy\",\"value\":\"xxxx\"}", text); + } + + public static class Attr { + + private int jTType; + private String value; + private String symbol; + + public int getjTType() { + return jTType; + } + + public void setjTType(int jTType) { + this.jTType = jTType; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue243.java b/src/test/java/com/alibaba/json/bvt/bug/Issue243.java new file mode 100644 index 0000000000..7cafaad85d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue243.java @@ -0,0 +1,79 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Issue243 extends TestCase { + + public void testSerialize() { + RpcResponse response = new RpcResponse(2, new Object()); + // String json = JSON.toJSONString(response, SerializerFeature.WriteClassName); // codeA with WriteClassName, + // requestId is not ending with 'L' + String json = response.toCommandJson(); // codeA with WriteClassName, requestId is ending with 'L', and trouble + // other json framework + System.out.println(json); + + String json2 = JSON.toJSONString(response, SerializerFeature.BeanToArray, SerializerFeature.WriteClassName, SerializerFeature.NotWriteRootClassName); + System.out.println(json2); + } + + public static class RpcResponse { + + private int msgType = 50; + private long requestId = 0; + private JSONObject details = new JSONObject(); + private Object[] yieldResult = new Object[1]; + + public RpcResponse(){ + + } + + public RpcResponse(long requestId, Object result){ + this.requestId = requestId; + yieldResult[0] = result; + } + + public int getMsgType() { + return msgType; + } + + public void setMsgType(int msgType) { + this.msgType = msgType; + } + + public long getRequestId() { + return requestId; + } + + public void setRequestId(long requestId) { + this.requestId = requestId; + } + + public JSONObject getDetails() { + return details; + } + + public void setDetails(JSONObject details) { + this.details = details; + } + + public Object[] getYieldResult() { + return yieldResult; + } + + public void setYieldResult(String[] yieldResult) { + this.yieldResult = yieldResult; + } + + protected Object[] fieldToArray() { + return new Object[] { msgType, requestId, details, yieldResult }; + } + + public String toCommandJson() { + return JSON.toJSONString(fieldToArray(), SerializerFeature.WriteClassName); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue248_orderedField.java b/src/test/java/com/alibaba/json/bvt/bug/Issue248_orderedField.java new file mode 100755 index 0000000000..5b09112daf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue248_orderedField.java @@ -0,0 +1,81 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; + +public class Issue248_orderedField extends TestCase { + + public void test_0() throws Exception { + String text = "{\"b\":\"b\",\"d\":\"d\",\"c\":\"c\",\"a\":\"a\"}"; + JSONObject object = JSON.parseObject(text, Feature.OrderedField); + System.out.println(object); + + Assert.assertEquals("b", object.keySet().toArray()[0]); + Assert.assertEquals("d", object.keySet().toArray()[1]); + Assert.assertEquals("c", object.keySet().toArray()[2]); + Assert.assertEquals("a", object.keySet().toArray()[3]); + } + + public void test_1() throws Exception { + String text = "{\"a\":\"a\",\"b\":\"b\",\"c\":\"c\",\"d\":\"d\"}"; + System.out.println(JSON.parseObject(text)); + + JSONObject object = JSON.parseObject(text, Feature.OrderedField); + System.out.println(object); + + Assert.assertEquals("a", object.keySet().toArray()[0]); + Assert.assertEquals("b", object.keySet().toArray()[1]); + Assert.assertEquals("c", object.keySet().toArray()[2]); + Assert.assertEquals("d", object.keySet().toArray()[3]); + + } + + public void test_2() throws Exception { + String text = "{\"k1\":\"v1\",\"k3\":\"v3\",\"k2\":\"v2\",\"map\":{\"k1\":\"v1\",\"k3\":\"v3\",\"k2\":\"v2\",\"map\":{\"k1\":\"v1\",\"k3\":\"v3\",\"k2\":\"v2\"}}}"; + System.out.println(JSON.parseObject(text)); + + JSONObject object = JSON.parseObject(text, Feature.OrderedField); + System.out.println(object); + + Assert.assertEquals("k1", object.keySet().toArray()[0]); + Assert.assertEquals("k3", object.keySet().toArray()[1]); + Assert.assertEquals("k2", object.keySet().toArray()[2]); + Assert.assertEquals("map", object.keySet().toArray()[3]); + + Assert.assertEquals("k1", object.getJSONObject("map").keySet().toArray()[0]); + Assert.assertEquals("k3", object.getJSONObject("map").keySet().toArray()[1]); + Assert.assertEquals("k2", object.getJSONObject("map").keySet().toArray()[2]); + Assert.assertEquals("map", object.getJSONObject("map").keySet().toArray()[3]); + + Assert.assertEquals("k1", object.getJSONObject("map").getJSONObject("map").keySet().toArray()[0]); + Assert.assertEquals("k3", object.getJSONObject("map").getJSONObject("map").keySet().toArray()[1]); + Assert.assertEquals("k2", object.getJSONObject("map").getJSONObject("map").keySet().toArray()[2]); + } + + public void test_3() throws Exception { + String text = "{\"k1\":\"v1\",\"k3\":\"v3\",\"k2\":\"v2\",\"list\":[\"v1\",\"v3\",\"v2\",{\"map\":{\"k1\":\"v1\",\"k3\":\"v3\",\"k2\":\"v2\"}}]}"; + System.out.println(JSON.parseObject(text)); + + JSONObject object = JSON.parseObject(text, Feature.OrderedField); + System.out.println(object); + + Assert.assertEquals("k1", object.keySet().toArray()[0]); + Assert.assertEquals("k3", object.keySet().toArray()[1]); + Assert.assertEquals("k2", object.keySet().toArray()[2]); + Assert.assertEquals("list", object.keySet().toArray()[3]); + + Assert.assertEquals("k1", + object.getJSONArray("list").getJSONObject(3).getJSONObject("map").keySet().toArray()[0]); + Assert.assertEquals("k3", + object.getJSONArray("list").getJSONObject(3).getJSONObject("map").keySet().toArray()[1]); + Assert.assertEquals("k2", + object.getJSONArray("list").getJSONObject(3).getJSONObject("map").keySet().toArray()[2]); + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue274.java b/src/test/java/com/alibaba/json/bvt/bug/Issue274.java new file mode 100644 index 0000000000..da625d1a8a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue274.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Issue274 extends TestCase { + + public void test() throws Exception { + Customer cus = new Customer(); + cus.setId(1L); + cus.setName("name"); + + Object json = JSON.toJSON(cus); + System.out.println(json); + + String cusJson = json.toString(); + + cusJson = "{\"name\":\"name\",\"id\":1}"; + + Customer customer = JSON.parseObject(cusJson, Customer.class); + + System.out.println(customer); + } + + public interface Indexable { + + public ID getId(); + + public void setId(ID id); + } + + public static class Customer implements Indexable { + + private Long id; + private String name; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Customer [id=" + id + ", name=" + name + "]"; + } + + // remove this to then no longer throw exception + public Map toIndexMap() { + + return null; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue363.java b/src/test/java/com/alibaba/json/bvt/bug/Issue363.java new file mode 100644 index 0000000000..0ab3f844e6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue363.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.springframework.remoting.support.RemoteInvocation; + +import java.util.Date; + +/** + * Created by wenshao on 02/07/2017. + */ +public class Issue363 extends TestCase { + public void test_for_issue() throws Exception { + RemoteInvocation remoteInvocation = new RemoteInvocation(); + remoteInvocation.setMethodName("test"); + remoteInvocation.setParameterTypes(new Class[] { int.class, Date.class, + String.class }); + remoteInvocation.setArguments(new Object[] { 1, new Date(), + "this is a test" }); + String json = JSON.toJSONString(remoteInvocation); + remoteInvocation = JSON.parseObject(json, RemoteInvocation.class); + System.out.println(remoteInvocation); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue408.java b/src/test/java/com/alibaba/json/bvt/bug/Issue408.java new file mode 100644 index 0000000000..7bcec9f22c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue408.java @@ -0,0 +1,281 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; +import org.junit.Assert; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.Charset; + +public class Issue408 extends TestCase { + + private InputStream inputStream; + + @Override + public void setUp() throws Exception { + String resource = "json/Issue408.json"; + inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); + + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Issue408."); + } + + + @Override + public void tearDown() throws Exception { + inputStream.close(); + } + + public void test_for_issue() throws Exception { + + JSONReader jsonReader = new JSONReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); + jsonReader.config(Feature.AllowArbitraryCommas, true); + jsonReader.config(Feature.IgnoreNotMatch, true); + jsonReader.config(Feature.SortFeidFastMatch, false); + jsonReader.config(Feature.DisableCircularReferenceDetect, true); + jsonReader.config(Feature.AutoCloseSource, true); + + VOList deserialized = null; + try { + deserialized = (VOList)jsonReader.readObject(); + }finally { + jsonReader.close(); + } + + for (int i = 0; i < 17; i++) { + Assert.assertEquals(deserialized.getVolist()[i].getLongid0(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid1(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid2(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid3(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid4(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid5(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid6(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid7(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid8(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid9(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid10(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid11(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid12(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid13(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid14(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid15(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid16(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid17(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid18(), Long.valueOf(1234567890123L)); + Assert.assertEquals(deserialized.getVolist()[i].getLongid19(), Long.valueOf(1234567890123L)); + } + } + + public static class VOList { + private VO[] volist; + private Long longid0; + private Long longid1; + + public VO[] getVolist() { + return volist; + } + + public void setVolist(VO[] volist) { + this.volist = volist; + } + + public Long getLongid1() { + return longid1; + } + + public void setLongid1(Long longid1) { + this.longid1 = longid1; + } + + public Long getLongid0() { + return longid0; + } + + public void setLongid0(Long longid0) { + this.longid0 = longid0; + } + } + + public static class VO { + private Long longid0; + private Long longid1; + private Long longid2; + private Long longid3; + private Long longid4; + private Long longid5; + private Long longid6; + private Long longid7; + private Long longid8; + private Long longid9; + private Long longid10; + private Long longid11; + private Long longid12; + private Long longid13; + private Long longid14; + private Long longid15; + private Long longid16; + private Long longid17; + private Long longid18; + private Long longid19; + + public Long getLongid0() { + return longid0; + } + + public void setLongid0(Long longid0) { + this.longid0 = longid0; + } + + public Long getLongid1() { + return longid1; + } + + public void setLongid1(Long longid1) { + this.longid1 = longid1; + } + + public Long getLongid2() { + return longid2; + } + + public void setLongid2(Long longid2) { + this.longid2 = longid2; + } + + public Long getLongid3() { + return longid3; + } + + public void setLongid3(Long longid3) { + this.longid3 = longid3; + } + + public Long getLongid4() { + return longid4; + } + + public void setLongid4(Long longid4) { + this.longid4 = longid4; + } + + public Long getLongid5() { + return longid5; + } + + public void setLongid5(Long longid5) { + this.longid5 = longid5; + } + + public Long getLongid6() { + return longid6; + } + + public void setLongid6(Long longid6) { + this.longid6 = longid6; + } + + public Long getLongid7() { + return longid7; + } + + public void setLongid7(Long longid7) { + this.longid7 = longid7; + } + + public Long getLongid8() { + return longid8; + } + + public void setLongid8(Long longid8) { + this.longid8 = longid8; + } + + public Long getLongid9() { + return longid9; + } + + public void setLongid9(Long longid9) { + this.longid9 = longid9; + } + + public Long getLongid10() { + return longid10; + } + + public void setLongid10(Long longid10) { + this.longid10 = longid10; + } + + public Long getLongid11() { + return longid11; + } + + public void setLongid11(Long longid11) { + this.longid11 = longid11; + } + + public Long getLongid12() { + return longid12; + } + + public void setLongid12(Long longid12) { + this.longid12 = longid12; + } + + public Long getLongid13() { + return longid13; + } + + public void setLongid13(Long longid13) { + this.longid13 = longid13; + } + + public Long getLongid14() { + return longid14; + } + + public void setLongid14(Long longid14) { + this.longid14 = longid14; + } + + public Long getLongid15() { + return longid15; + } + + public void setLongid15(Long longid15) { + this.longid15 = longid15; + } + + public Long getLongid16() { + return longid16; + } + + public void setLongid16(Long longid16) { + this.longid16 = longid16; + } + + public Long getLongid17() { + return longid17; + } + + public void setLongid17(Long longid17) { + this.longid17 = longid17; + } + + public Long getLongid18() { + return longid18; + } + + public void setLongid18(Long longid18) { + this.longid18 = longid18; + } + + public Long getLongid19() { + return longid19; + } + + public void setLongid19(Long longid19) { + this.longid19 = longid19; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue569.java b/src/test/java/com/alibaba/json/bvt/bug/Issue569.java new file mode 100644 index 0000000000..a895c3ea7b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue569.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.io.Serializable; +import java.lang.reflect.Type; +import java.util.Map; + +/** + * Created by wenshao on 02/07/2017. + */ +public class Issue569 extends TestCase { + public void test_for_issue() throws Exception { + String jsonString = "{\"backingMap\":{\"a\":{\"b\":{}}}}"; + Type type = new TypeReference>() {}.getType(); + MyTable table = JSON.parseObject(jsonString, type); + + Map valueMap = table.backingMap.get("a"); + assertNotNull(valueMap); + + MyValue value = valueMap.get("b"); + assertNotNull(value); + } + + public static class MyTable implements Serializable { + private Map> backingMap; + + public Map> getBackingMap() { + return backingMap; + } + + public void setBackingMap(Map> backingMap) { + this.backingMap = backingMap; + } + } + + public static class MyValue { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue569_1.java b/src/test/java/com/alibaba/json/bvt/bug/Issue569_1.java new file mode 100644 index 0000000000..5c7fa0bd65 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue569_1.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +public class Issue569_1 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"result\":{}}"; + InterfaceResult result = JSON.parseObject(json, new TypeReference>() {}); + assertNotNull(result.getResult()); + assertEquals(Value.class, result.getResult().getClass()); + } + + public static class BaseInterfaceResult { + + } + + public static class InterfaceResult extends BaseInterfaceResult + { + public T getResult() { + return result; + } + + public void setResult(T result) { + this.result = result; + } + + private T result; + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue585.java b/src/test/java/com/alibaba/json/bvt/bug/Issue585.java new file mode 100644 index 0000000000..79249fa19a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue585.java @@ -0,0 +1,80 @@ +package com.alibaba.json.bvt.bug; + +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; + +import junit.framework.TestCase; + +public class Issue585 extends TestCase { + private String original = JSON.DEFAULT_TYPE_KEY; + private ParserConfig originalConfig = ParserConfig.global; + + protected void setUp() throws Exception { + ParserConfig.global = new ParserConfig(); + if (!JSON.DEFAULT_TYPE_KEY.equals("mySpace")) { + JSON.setDefaultTypeKey("mySpace"); + } + + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Issue585."); + } + + protected void tearDown() throws Exception { + JSON.setDefaultTypeKey(original); + ParserConfig.global = originalConfig; + } + + public void test_for_issue() throws Exception { + + String cc = "{\"mySpace\":\"com.alibaba.json.bvt.bug.Issue585$Result\",\"attachments\":{\"mySpace\":\"java.util.HashMap\",\"timeout\":5000,\"consumeApp\":\"multiGroupTestServer\"},\"status\":0}"; + + byte[] bytes = cc.getBytes("utf-8"); + + Result res = (Result) this.deserialize(bytes); + Assert.assertEquals(0, res.getStatus()); + } + + public T deserialize(byte[] in) { + Charset CHARSET = Charset.forName("utf-8"); + return (T) JSON.parse(in, 0, in.length, CHARSET.newDecoder(), Feature.AllowArbitraryCommas, + Feature.IgnoreNotMatch, Feature.SortFeidFastMatch, Feature.DisableCircularReferenceDetect, + Feature.AutoCloseSource); + } + + public static class Result { + + private int status; + private Object value; + private Map attachments = new HashMap(2); + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + public Map getAttachments() { + return attachments; + } + + public void setAttachments(Map attachments) { + this.attachments = attachments; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue62.java b/src/test/java/com/alibaba/json/bvt/bug/Issue62.java new file mode 100644 index 0000000000..1e892c3fe6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue62.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Issue62 extends TestCase { + + public void test_for_issue() throws Exception { + A a = new A(); + a.setA("aaaaaaaaaa".getBytes()); + a.setB(1); + a.setC("aaaa"); + String jsonData = JSON.toJSONString(a, SerializerFeature.UseSingleQuotes); + Assert.assertEquals("{'a':'YWFhYWFhYWFhYQ==','b':1,'c':'aaaa'}", jsonData); + JSON.parse(jsonData); + } + + static class A { + + private byte[] a; + private int b; + private String c; + + public byte[] getA() { + return a; + } + + public void setA(byte[] a) { + this.a = a; + } + + public int getB() { + return b; + } + + public void setB(int b) { + this.b = b; + } + + public String getC() { + return c; + } + + public void setC(String c) { + this.c = c; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue64.java b/src/test/java/com/alibaba/json/bvt/bug/Issue64.java new file mode 100644 index 0000000000..8c9b95619d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue64.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + + +public class Issue64 extends TestCase { + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.foo = "xxxxxx"; + + String text = JSON.toJSONString(vo, SerializerFeature.BeanToArray); + + Assert.assertEquals("[\"xxxxxx\"]", text); + + VO vo2 = JSON.parseObject(text, VO.class, Feature.SupportArrayToBean); + Assert.assertEquals(vo2.foo, vo.foo); + } + + public static class VO { + public String foo = "bar"; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue688.java b/src/test/java/com/alibaba/json/bvt/bug/Issue688.java new file mode 100644 index 0000000000..b658d0fbaa --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue688.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by wenshao on 2016/11/13. + */ +public class Issue688 extends TestCase { + public void test_for_issue() throws Exception { + User monther = new User("HanMeiMei", 29L); + User child = new User("liLei", 2L); + User grandma = new User("zhangHua", 60L); + + Map userMap = new HashMap(); + userMap.put(child, monther); + userMap.put(monther, grandma); + + String json = JSON.toJSONString(userMap); + System.out.println(json); + } + + public static class User { + public String name; + public long id; + + public User() { + + } + + public User(String name, long id) { + this.name = name; + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue689.java b/src/test/java/com/alibaba/json/bvt/bug/Issue689.java new file mode 100644 index 0000000000..d96cdcd0f6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue689.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.bug; + +import java.util.Collections; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Issue689 extends TestCase { + public void test_0() throws Exception { + Map map = Collections.singletonMap("value", "A B"); + String json = JSON.toJSONString(map); + Assert.assertEquals("{\"value\":\"A B\"}", json); + + JSONObject obj = JSON.parseObject(json); + Assert.assertEquals(obj.get("value"), map.get("value")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue69.java b/src/test/java/com/alibaba/json/bvt/bug/Issue69.java new file mode 100644 index 0000000000..d81e67a31c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue69.java @@ -0,0 +1,60 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class Issue69 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.a = new Entry(); + vo.b = vo.a; + + String text = JSON.toJSONString(vo); + System.out.println(text); + } + + @JSONType(serialzeFeatures={SerializerFeature.DisableCircularReferenceDetect}) + public static class VO { + + private Entry a; + + private Entry b; + + public Entry getA() { + return a; + } + + public void setA(Entry a) { + this.a = a; + } + + public Entry getB() { + return b; + } + + public void setB(Entry b) { + this.b = b; + } + + } + + public static class Entry { + private int id; + + + public int getId() { + return id; + } + + + public void setId(int id) { + this.id = id; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue72.java b/src/test/java/com/alibaba/json/bvt/bug/Issue72.java new file mode 100644 index 0000000000..fc59193a99 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue72.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.bug; + +import java.io.InputStream; +import java.io.InputStreamReader; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.util.IOUtils; + +public class Issue72 extends TestCase { + + public void test_for_issue() throws Exception { + InputStream is = Issue72.class.getClassLoader().getResourceAsStream("issue72.json"); + JSONReader reader = null; + try { + byte[] rowBatchBytes = null; + byte[] fileBatchBytes = null; + reader = new JSONReader(new InputStreamReader(is)); + reader.startArray(); + while (reader.hasNext()) { + if (rowBatchBytes == null) { + rowBatchBytes = reader.readObject(byte[].class); + } else if (fileBatchBytes == null) { + fileBatchBytes = reader.readObject(byte[].class); + } else { + throw new Exception("archive data json parse failed!"); + } + + } + reader.endArray(); + } finally { + IOUtils.close(reader); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue74.java b/src/test/java/com/alibaba/json/bvt/bug/Issue74.java new file mode 100644 index 0000000000..8890ce724a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue74.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.bug; + +import java.io.InputStream; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; + + +public class Issue74 extends TestCase { + public void test_for_issue() throws Exception { + InputStream is = Issue72.class.getClassLoader().getResourceAsStream("issue74.json"); + String text = org.apache.commons.io.IOUtils.toString(is); + is.close(); + + JSONArray json = (JSONArray) JSON.parse(text); + + Assert.assertNotNull(json.getJSONObject(0).getJSONObject("dataType").getJSONObject("categoryType").getJSONArray("dataTypes").get(0)); + Assert.assertSame(json.getJSONObject(0).getJSONObject("dataType"), json.getJSONObject(0).getJSONObject("dataType").getJSONObject("categoryType").getJSONArray("dataTypes").get(0)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue743.java b/src/test/java/com/alibaba/json/bvt/bug/Issue743.java new file mode 100644 index 0000000000..f9a0f6c751 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue743.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Issue743 extends TestCase { + + public void test_for_issue() throws Exception { + String temp = "{\"option_1\": \"\\u4e0d\\u5403\\u6216\\u5c11\\u4e8e1\\u6b21\"}"; + JSONObject object = JSON.parseObject(temp); + Assert.assertEquals("{\"option_1\":\"不吃或少于1次\"}", JSON.toJSONString(object)); + Assert.assertEquals("{\"option_1\":\"\\u4E0D\\u5403\\u6216\\u5C11\\u4E8E1\\u6B21\"}", JSON.toJSONString(object, SerializerFeature.BrowserCompatible)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue744.java b/src/test/java/com/alibaba/json/bvt/bug/Issue744.java new file mode 100644 index 0000000000..faff7ade44 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue744.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.bug; + +import java.io.StringReader; +import java.util.Date; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class Issue744 extends TestCase { + + public static class Model { + @JSONField(format="yyyy-MM-dd'T'HH:mm:ss") + public Date date; + } + + public void test() { + String text = "{\"date\":\"9999-09-08T00:00:00\"}"; + Model model =JSON.parseObject(text, Model.class); + + String text2 = JSON.toJSONString(model); + System.out.println(text2); + } + + public void test_reader() { + String text = "{\"date\":\"9999-09-08T00:00:00\"}"; + + Model model = new JSONReader(new StringReader(text)).readObject(Model.class); + + String text2 = JSON.toJSONString(model); + System.out.println(text2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue744_1.java b/src/test/java/com/alibaba/json/bvt/bug/Issue744_1.java new file mode 100644 index 0000000000..54637db98d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue744_1.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 2016/11/13. + */ +public class Issue744_1 extends TestCase { + + public void test_for_issue() throws Exception { + C c = new C(); + c.setName("name"); + + String json = JSON.toJSONString(c); + assertEquals("{}", json); + } + + public static abstract class B { + @JSONField(serialize = false, deserialize = false) + public abstract String getName(); + + } + + public static class C extends B { + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue763.java b/src/test/java/com/alibaba/json/bvt/bug/Issue763.java new file mode 100644 index 0000000000..24d424d8fb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue763.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; + +import junit.framework.TestCase; + +public class Issue763 extends TestCase { + + public void test_0() throws Exception { + Map reqDto = new HashMap(); + reqDto.put("name", "aaaa"); + reqDto.put("age", 50); + reqDto.put("address", "深圳南山"); + + SimplePropertyPreFilter filter = new SimplePropertyPreFilter(); + filter.getExcludes().add("name"); + + // SerializeConfig.getGlobalInstance().addFilter(Map.class, filter); + SerializeConfig config = new SerializeConfig(); + config.addFilter(HashMap.class, filter); + System.out.println(JSON.toJSONString(reqDto, config)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue771.java b/src/test/java/com/alibaba/json/bvt/bug/Issue771.java new file mode 100644 index 0000000000..7b793266da --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue771.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Issue771 extends TestCase { + + public void test_for_issue() throws Exception { + SerializeWriter writer = new SerializeWriter(null, JSON.DEFAULT_GENERATE_FEATURE, new SerializerFeature[0]); + int defaultBufferSize = writer.getBufferLength(); + String encoded = JSON.toJSONString(new FooBar(defaultBufferSize)); + JSONObject decoded = (JSONObject) JSON.parse(encoded); + JSONArray dataToEncode = decoded.getJSONArray("dataToEncode"); + Assert.assertEquals(5, dataToEncode.size()); + writer.close(); + } + + public static class FooBar { + + private List dataToEncode; + + protected FooBar(int buffLen){ + dataToEncode = new ArrayList(); + dataToEncode.add("foo"); + dataToEncode.add("bar"); + dataToEncode.add(new String(new char[buffLen]).replace('\0', 'a')); // create some texts to fill up & expand + // the buffer + dataToEncode.add("a wild special character appears: áőű"); // this will restart the list encoding (while the + // count is committed at expand) + dataToEncode.add("foobar"); + } + + public List getDataToEncode() { + return dataToEncode; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue776.java b/src/test/java/com/alibaba/json/bvt/bug/Issue776.java new file mode 100644 index 0000000000..16dd8ee773 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue776.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.Map; + +/** + * Created by wenshao on 16/8/30. + */ +public class Issue776 extends TestCase { + public void test_for_issue() throws Exception { + String str1 = "{\"v\":[\" \",\"abc\",\"x\",\"abc\"]}"; + + Exception error = null; + try { + JSON.parseObject(str1, + new com.alibaba.fastjson.TypeReference>() { + }); + } catch (Exception ex) { + error = ex; + } + assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue779.java b/src/test/java/com/alibaba/json/bvt/bug/Issue779.java new file mode 100644 index 0000000000..83dce22291 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue779.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/8/28. + */ +public class Issue779 extends TestCase { + public void test_for_issue() throws Exception { + Exception error = null; + try { + String aaa = "{'token':'token':'sign':'bb'}"; + JSON.parseObject(aaa); + } catch (JSONException ex) { + error = ex; + } + + assertNotNull(error); + } + + public void test_for_issue_deser() throws Exception { + Exception error = null; + try { + String aaa = "{'token':'token':'sign':'bb'}"; + JSON.parseObject(aaa, Model.class); + } catch (JSONException ex) { + error = ex; + } + + assertNotNull(error); + } + + public static class Model { + public String token; + public String sign; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue780.java b/src/test/java/com/alibaba/json/bvt/bug/Issue780.java new file mode 100644 index 0000000000..8cd25a29e5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue780.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/8/25. + */ +public class Issue780 extends TestCase { + public void test_for_issue() throws Exception { + JSONObject json = new JSONObject(); + json.put("robj", "{abc: 123}"); + JSONObject robj = json.getJSONObject("robj"); + assertEquals(123, robj.get("abc")); + } + + public void test_for_issue_array() throws Exception { + JSONObject json = new JSONObject(); + json.put("robj", "[123]"); + JSONArray robj = json.getJSONArray("robj"); + assertEquals(123, robj.get(0)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue784.java b/src/test/java/com/alibaba/json/bvt/bug/Issue784.java new file mode 100644 index 0000000000..f5c2c4ef6d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue784.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/8/24. + */ +public class Issue784 extends TestCase { + public void test_for_issue() throws Exception { + JSON.parse("[{\"args\":[\"150\",\"change\",{\"timeStamp\":1471595047319,\"value\":\"\"},{\"attrs\":{\"value\":\"\"}}],\"method\":\"fireEvent\"}]"); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue79.java b/src/test/java/com/alibaba/json/bvt/bug/Issue79.java new file mode 100644 index 0000000000..86c87b6f9b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue79.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import java.util.List; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Issue79 extends TestCase { + + public void test_for_issue_79() throws Exception { + SearchResult result = JSON.parseObject("{\"present\":{\"records\":[{}]}}", SearchResult.class); + Assert.assertNotNull(result.present); + Assert.assertNotNull(result.present.records); + Assert.assertNotNull(result.present.records.get(0)); + Assert.assertNotNull(result.present.records.get(0) instanceof PresentRecord); + } + + public static class SearchResult { + + public Present present; + } + + public static class Present { + + public List records; + } + + public static class PresentRecord { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue793.java b/src/test/java/com/alibaba/json/bvt/bug/Issue793.java new file mode 100644 index 0000000000..849df06819 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue793.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/8/27. + */ +public class Issue793 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{ \"code\": 1000, \"data\": \"success\", \"game_data\": [], \"member_list\": [], \"message\": \"\\u6210\\u529f\" }"; + JSONObject json = JSON.parseObject(text); + assertEquals(1000, json.get("code")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue798.java b/src/test/java/com/alibaba/json/bvt/bug/Issue798.java new file mode 100644 index 0000000000..b153fba181 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue798.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/8/29. + */ +public class Issue798 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.value = " 主要学校:密歇根大学 安娜堡分校、东密西根大学、 克莱利学院�、康考迪亚学院 �、瓦什特洛社区学院� "; + String json = JSON.toJSONString(model); + + Model model2 = JSON.parseObject(json, Model.class); + assertEquals(model.value, model2.value); + } + + public static class Model { + public String value; + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue798_1.java b/src/test/java/com/alibaba/json/bvt/bug/Issue798_1.java new file mode 100644 index 0000000000..2404581e7f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue798_1.java @@ -0,0 +1,27 @@ +/* + * Copyright 1999-2004 Alibaba.com All right reserved. This software is the + * confidential and proprietary information of Alibaba.com ("Confidential + * Information"). You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Alibaba.com. + */ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * 类Test.java的实现描述:TODO 类实现描述 + * @author jieyu.ljy 2016年7月22日 下午12:39:17 + */ +public class Issue798_1 extends TestCase { + + public void test_for_issue() throws Exception { + String str = "

主要学校:密歇根大学 安娜堡分校、东密西根大学、 克莱利学院、康考迪亚学院 、瓦什特洛社区学院

"; + String json = JSON.toJSONString(str); + assertEquals("\"

主要学校:密歇根大学 安娜堡分校、东密西根大学、 克莱利学院\\u007F、康考迪亚学院 \\u007F、瓦什特洛社区学院\\u007F

\"", json); + + String parsedStr = (String) JSON.parse(json); + assertEquals(str, parsedStr); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue799.java b/src/test/java/com/alibaba/json/bvt/bug/Issue799.java new file mode 100644 index 0000000000..ad21de12df --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue799.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by wenshao on 16/8/30. + */ +public class Issue799 extends TestCase { + public void test_for_issue() throws Exception { + String path = "$.array[0:-1].bizData"; + + Map root = new HashMap(); + Object val = JSONPath.eval(root, path); + assertNull(val); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue801.java b/src/test/java/com/alibaba/json/bvt/bug/Issue801.java new file mode 100644 index 0000000000..de3defe3ff --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue801.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.util.Date; + +/** + * Created by wenshao on 16/9/2. + */ +public class Issue801 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"date\":\"0001-01-01T00:00:00\"}"; + Model model = JSON.parseObject(json, Model.class); + } + + public static class Model { + @JSONField(format = "yyyy-MM-ddTHH:mm:ss.SSS") + public Date date; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue804.java b/src/test/java/com/alibaba/json/bvt/bug/Issue804.java new file mode 100644 index 0000000000..e1824a51c2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue804.java @@ -0,0 +1,78 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.List; + +public class Issue804 extends TestCase { + public void test_issue() throws Exception { + String json = "{\n" + + " \"@type\":\"com.alibaba.json.bvt.bug.Issue804$Room\",\n" + + " \"children\":[],\n" + + " \"name\":\"Room2_1\",\n" + + " \"parent\":{\n" + + " \"@type\":\"com.alibaba.json.bvt.bug.Issue804$Area\",\n" + + " \"children\":[\n" + + " {\"$ref\":\"$\"},\n" + + " {\n" + + " \"@type\":\"com.alibaba.json.bvt.bug.Issue804$Room\",\n" + + " \"children\":[],\n" + + " \"name\":\"Room_2\",\n" + + " \"parent\":{\"$ref\":\"$.parent\"}\n" + + " }\n" + + " ],\n" + + " \"name\":\"Area1\",\n" + + " \"parent\":{\n" + + " \"@type\":\"com.alibaba.json.bvt.bug.Issue804$Area\",\n" + + " \"children\":[\n" + + " {\"$ref\":\"$.parent\"}\n" + + " ],\n" + + " \"name\":\"Area0\"\n" + + " }\n" + + " }\n" + + "}"; + + Room room = (Room) JSON.parse(json); + + assertSame(room, room.parent.children.get(0)); + } + + @JSONType + public static class Node { + protected String name; + protected Node parent; + protected List children = new ArrayList(); + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public Node getParent() { + return parent; + } + public void setParent(Node parent) { + this.parent = parent; + } + public List getChildren() { + return children; + } + public void setChildren(List children) { + this.children = children; + } + } + + @JSONType + public static class Area extends Node{ + + } + + @JSONType + public static class Room extends Node{ + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue821.java b/src/test/java/com/alibaba/json/bvt/bug/Issue821.java new file mode 100644 index 0000000000..0459dd73c7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue821.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.Map; + +/** + * Created by wenshao on 10/03/2017. + */ +public class Issue821 extends TestCase { + public void test_for_issue() throws Exception { + String str1 = "{\"v\":[\" \",\"a\",\"x\",\"a\"]}"; + System.out.println(str1); + + char[] c = JSON.parseObject(str1, new com.alibaba.fastjson.TypeReference>() {}).get("v"); + assertEquals(4, c.length); + assertEquals(c[0], ' '); + assertEquals(c[1], 'a'); + assertEquals(c[2], 'x'); + assertEquals(c[3], 'a'); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue859.java b/src/test/java/com/alibaba/json/bvt/bug/Issue859.java new file mode 100644 index 0000000000..e3189009bc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue859.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.json.test.Base64; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import junit.framework.TestCase; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; + +import java.io.File; +import java.io.InputStream; +import java.util.zip.GZIPInputStream; + +/** + * Created by wenshao on 2016/10/19. + */ +public class Issue859 extends TestCase { + protected void setUp() throws Exception { + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_zhaoyao."); + } + + public void test_for_issue() throws Exception { + InputStream is = Issue72.class.getClassLoader().getResourceAsStream("issue859.zip"); + GZIPInputStream gzipInputStream = new GZIPInputStream(is); + String text = org.apache.commons.io.IOUtils.toString(gzipInputStream); + long startMillis = System.currentTimeMillis(); + for (int i = 0; i < 1; ++i) { + JSON.parseObject(text); + } + // new Gson().fromJson(text, java.util.HashMap.class); + //new ObjectMapper().readValue(text, java.util.HashMap.class); + long costMillis = System.currentTimeMillis() - startMillis; + System.out.println("cost : " + costMillis); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue868.java b/src/test/java/com/alibaba/json/bvt/bug/Issue868.java new file mode 100644 index 0000000000..66266e7a6d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue868.java @@ -0,0 +1,98 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 2016/10/23. + */ +public class Issue868 extends TestCase { + public void test_int() throws Exception { + Exception error = null; + try { + String str = String.valueOf(Long.MAX_VALUE); + JSON.parseObject(str, int.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public void test_int_min() throws Exception { + Exception error = null; + try { + String str = String.valueOf(Long.MIN_VALUE); + JSON.parseObject(str, int.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public void test_short() throws Exception { + Exception error = null; + try { + String str = String.valueOf(Integer.MAX_VALUE); + JSON.parseObject(str, short.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public void test_short_min() throws Exception { + Exception error = null; + try { + String str = String.valueOf(Integer.MIN_VALUE); + JSON.parseObject(str, short.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public void test_byte() throws Exception { + Exception error = null; + try { + String str = String.valueOf(Short.MAX_VALUE); + JSON.parseObject(str, byte.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public void test_byte_min() throws Exception { + Exception error = null; + try { + String str = String.valueOf(Short.MIN_VALUE); + JSON.parseObject(str, byte.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public void test_float_min() throws Exception { + Exception error = null; + try { + String str = String.valueOf(Double.MIN_VALUE); + JSON.parseObject(str, float.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public void test_float_max() throws Exception { + Exception error = null; + try { + String str = String.valueOf(Double.MAX_VALUE); + JSON.parseObject(str, float.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue869.java b/src/test/java/com/alibaba/json/bvt/bug/Issue869.java new file mode 100644 index 0000000000..0ac5c59ebc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue869.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wenshao on 2016/10/19. + */ +public class Issue869 extends TestCase { + public void test_for_issue() throws Exception { + List doublePointList = new ArrayList(); + { + DoublePoint doublePoint = new DoublePoint(); + doublePoint.startPoint = new Point(22, 35); + doublePoint.endPoint = doublePoint.startPoint; + doublePointList.add(doublePoint); + } + { + DoublePoint doublePoint = new DoublePoint(); + doublePoint.startPoint = new Point(16, 18); + doublePoint.endPoint = doublePoint.startPoint; + doublePointList.add(doublePoint); + } + + String json = JSON.toJSONString(doublePointList); + assertEquals("[{\"endPoint\":{\"x\":22,\"y\":35},\"startPoint\":{\"x\":22,\"y\":35}},{\"endPoint\":{\"x\":16,\"y\":18},\"startPoint\":{\"x\":16,\"y\":18}}]", json); + } + + public void test_for_issue_parse() throws Exception { + + String text = "[{\"endPoint\":{\"x\":22,\"y\":35},\"startPoint\":{\"$ref\":\"$[0].endPoint\"}},{\"endPoint\":{\"$ref\":\"$[1].startPoint\"},\"startPoint\":{\"x\":16,\"y\":18}}]"; + List doublePointList = JSON.parseObject(text, new TypeReference>(){}); + assertNotNull(doublePointList.get(0)); + assertNotNull(doublePointList.get(1)); + assertSame(doublePointList.get(0).startPoint, doublePointList.get(0).endPoint); + assertSame(doublePointList.get(1).startPoint, doublePointList.get(1).endPoint); + } + + public static class DoublePoint{ + public Point startPoint; + public Point endPoint; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue869_1.java b/src/test/java/com/alibaba/json/bvt/bug/Issue869_1.java new file mode 100644 index 0000000000..3973216ee1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue869_1.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wenshao on 2016/11/13. + */ +public class Issue869_1 extends TestCase { + public void test_for_issue() throws Exception { + List doublePointList = new ArrayList(); + { + DoublePoint doublePoint = new DoublePoint(); + doublePoint.startPoint = new Point(22, 35); + doublePoint.endPoint = doublePoint.startPoint; + doublePointList.add(doublePoint); + } + { + DoublePoint doublePoint = new DoublePoint(); + doublePoint.startPoint = new Point(16, 18); + doublePoint.endPoint = doublePoint.startPoint; + doublePointList.add(doublePoint); + } + + String json = JSON.toJSONString(doublePointList); + assertEquals("[{\"endPoint\":{\"x\":22,\"y\":35},\"startPoint\":{\"$ref\":\"$[0].endPoint\"}},{\"endPoint\":{\"x\":16,\"y\":18},\"startPoint\":{\"$ref\":\"$[1].endPoint\"}}]", json); + } + + public void test_for_issue_parse() throws Exception { + + String text = "[{\"endPoint\":{\"x\":22,\"y\":35},\"startPoint\":{\"$ref\":\"$[0].endPoint\"}},{\"endPoint\":{\"$ref\":\"$[1].startPoint\"},\"startPoint\":{\"x\":16,\"y\":18}}]"; + List doublePointList = JSON.parseObject(text, new TypeReference>(){}); + assertNotNull(doublePointList.get(0)); + assertNotNull(doublePointList.get(1)); + assertSame(doublePointList.get(0).startPoint, doublePointList.get(0).endPoint); + assertSame(doublePointList.get(1).startPoint, doublePointList.get(1).endPoint); + } + + public static class DoublePoint{ + public Point startPoint; + public Point endPoint; + } + + public static class Point { + public int x; + public int y; + public Properties properties; + + public Point() { + + } + + public Point(int x, int y) { + this.x = x; + this.y = y; + } + } + + public static class Properties{ + public String id; + public String title; + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue87.java b/src/test/java/com/alibaba/json/bvt/bug/Issue87.java new file mode 100644 index 0000000000..694903e1b6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue87.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashSet; +import java.util.Set; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + + +public class Issue87 extends TestCase { + public void test_for_issue() throws Exception { + TestObject to = new TestObject(); + to.add("test1"); + to.add("test2"); + String text = JSON.toJSONString(to); + System.out.println(text); + JSONObject jo = JSON.parseObject(text); + to = JSON.toJavaObject(jo, TestObject.class); + } + + public static class TestObject { + + private Set set = new HashSet(0); + + public Set getSet() { + return set; + } + + public void setSet(Set set) { + this.set = set; + } + + public void add(String str) { + set.add(str); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue878.java b/src/test/java/com/alibaba/json/bvt/bug/Issue878.java new file mode 100644 index 0000000000..7562b5ff3f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue878.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 2016/11/10. + */ +public class Issue878 extends TestCase { + public void test_for_issue() throws Exception { + String jsonVal0 = "{\"id\":5001,\"name\":\"Jobs\"}"; + String jsonVal1 = "{\"id\":5382,\"user\":\"Mary\"}"; + String jsonVal2 = "{\"id\":2341,\"person\":\"Bob\"}"; + + Model obj0 = JSON.parseObject(jsonVal0, Model.class); + assertEquals(5001, obj0.id); + assertEquals("Jobs", obj0.name); + + Model obj1 = JSON.parseObject(jsonVal1, Model.class); + assertEquals(5382, obj1.id); + assertEquals("Mary", obj1.name); + + Model obj2 = JSON.parseObject(jsonVal2, Model.class); + assertEquals(2341, obj2.id); + assertEquals("Bob", obj2.name); + } + + public static class Model { + public int id; + + @JSONField(alternateNames = {"user", "person"}) + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue87_hashset.java b/src/test/java/com/alibaba/json/bvt/bug/Issue87_hashset.java new file mode 100644 index 0000000000..89f27ed2a2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue87_hashset.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashSet; +import java.util.Set; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + + +public class Issue87_hashset extends TestCase { + public void test_for_issue() throws Exception { + TestObject to = new TestObject(); + to.add("test1"); + to.add("test2"); + String text = JSON.toJSONString(to); + System.out.println(text); + JSONObject jo = JSON.parseObject(text); + to = JSON.toJavaObject(jo, TestObject.class); + } + + public static class TestObject { + + private HashSet set = new HashSet(0); + + public HashSet getSet() { + return set; + } + + public void setSet(HashSet set) { + this.set = set; + } + + public void add(String str) { + set.add(str); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue87_treeset.java b/src/test/java/com/alibaba/json/bvt/bug/Issue87_treeset.java new file mode 100644 index 0000000000..dffd5a14d6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue87_treeset.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.bug; + +import java.util.TreeSet; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + + +public class Issue87_treeset extends TestCase { + public void test_for_issue() throws Exception { + TestObject to = new TestObject(); + to.add("test1"); + to.add("test2"); + String text = JSON.toJSONString(to); + System.out.println(text); + JSONObject jo = JSON.parseObject(text); + to = JSON.toJavaObject(jo, TestObject.class); + } + + public static class TestObject { + + private TreeSet set = new TreeSet(); + + public TreeSet getSet() { + return set; + } + + public void setSet(TreeSet set) { + this.set = set; + } + + public void add(String str) { + set.add(str); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue887.java b/src/test/java/com/alibaba/json/bvt/bug/Issue887.java new file mode 100644 index 0000000000..2dd39e3eab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue887.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 2016/11/10. + */ +public class Issue887 extends TestCase { + public void test_for_issue() throws Exception { + Foo excepted = new Foo(); + excepted.setName("mock"); + String json; + System.out.println(json = JSON.toJSONString(excepted, true)); + Foo actually = JSON.parseObject(json, Foo.class); + assertEquals(excepted.getName(), actually.getName()); + } + + public static class Foo { + @JSONField(name = "foo.name") + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue89.java b/src/test/java/com/alibaba/json/bvt/bug/Issue89.java new file mode 100644 index 0000000000..739881a26b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue89.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Issue89 extends TestCase { + + public void test_for_issue() throws Exception { + Exception error = null; + try { + JSON.parse("{\"a\":з」∠)_,\"}"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue894.java b/src/test/java/com/alibaba/json/bvt/bug/Issue894.java new file mode 100644 index 0000000000..85ad5cac51 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue894.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 10/03/2017. + */ +public class Issue894 extends TestCase { + public void test_for_issue() throws Exception { + String str = String.valueOf(Double.MAX_VALUE); + Throwable error = null; + try { + JSON.parseObject(str, short.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue900.java b/src/test/java/com/alibaba/json/bvt/bug/Issue900.java new file mode 100644 index 0000000000..5c4d6a3f8e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue900.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 2016/11/17. + */ +public class Issue900 extends TestCase { + public void test_for_issue() throws Exception { + Model model = JSON.parseObject("{\"id\":123}", Model.class, Feature.SupportNonPublicField); + assertEquals(123, model.id); + } + + public static class Model { + private int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue900_1.java b/src/test/java/com/alibaba/json/bvt/bug/Issue900_1.java new file mode 100644 index 0000000000..d70277142f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue900_1.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 2016/11/18. + */ +public class Issue900_1 extends TestCase { + public void test_for_issue() throws Exception { + Model model = JSON.parseObject("{\"id\":123}", Model.class); + assertEquals(123, model.id); + } + + @JSONType(parseFeatures = Feature.SupportNonPublicField) + public static class Model { + private int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue912.java b/src/test/java/com/alibaba/json/bvt/bug/Issue912.java new file mode 100644 index 0000000000..0cb17c99fc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue912.java @@ -0,0 +1,138 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +import java.util.LinkedList; +import java.util.List; + +/** + * Created by wenshao on 06/12/2016. + */ +public class Issue912 extends TestCase { + public void test_for_issue() throws Exception { + String allMethods = "{\"mList\":[{\"className\":\"com.qa.scftemplate.contract.ISCFServiceForDyjAction\",\"methodName\":\"getArrayInt\",\"parameterSize\":1,\"parameters\":[{\"clazz\":\"[I\",\"clsList\":null,\"isGenericity\":false,\"value\":\"\"}],\"returnType\":\"[I\",\"url\":\"tcp://SCFServiceForDyj/SCFServiceForDyjActionService\"},{\"className\":\"com.qa.scftemplate.contract.ISCFServiceForDyjAction\",\"methodName\":\"getArrayPrimative\",\"parameterSize\":7,\"parameters\":[{\"clazz\":\"[I\",\"clsList\":null,\"isGenericity\":false,\"value\":\"\"},{\"clazz\":\"[F\",\"clsList\":null,\"isGenericity\":false,\"value\":\"\"},{\"clazz\":\"[S\",\"clsList\":null,\"isGenericity\":false,\"value\":\"\"},{\"clazz\":\"[D\",\"clsList\":null,\"isGenericity\":false,\"value\":\"\"},{\"clazz\":\"[J\",\"clsList\":null,\"isGenericity\":false,\"value\":\"\"},{\"clazz\":\"[B\",\"clsList\":null,\"isGenericity\":false,\"value\":\"\"},{\"clazz\":\"[C\",\"clsList\":null,\"isGenericity\":false,\"value\":\"\"}],\"returnType\":\"[Ljava.lang.String;\",\"url\":\"tcp://SCFServiceForDyj/SCFServiceForDyjActionService\"}]}"; + JsonBean jsonBean = getJsonData(allMethods, JsonBean.class); + + assertEquals(2, jsonBean.getmList().size()); + SCFMethod m1 = jsonBean.getmList().get(0); + assertNotNull(m1); + } + + public static T getJsonData(String json, Class clazz) { + T jd = (T) JSON.parseObject(json, clazz, + Feature.IgnoreNotMatch, + Feature.AutoCloseSource + ); + return jd; + } + + public static class JsonBean { + private List mList; + + public List getmList() { + return mList; + } + + public void setmList(List mList) { + this.mList = mList; + } + } + + public static class SCFMethod { + public String className; + public String url; + public String methodName; + public int parameterSize; + public List parameters = new LinkedList(); + public Class returnType; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Class getReturnType() { + return returnType; + } + + public void setReturnType(Class returnType) { + this.returnType = returnType; + } + + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public int getParameterSize() { + return parameterSize; + } + + public void setParameterSize(int parameterSize) { + this.parameterSize = parameterSize; + } + + public List getParameters() { + return parameters; + } + + public void setParameters(List parameters) { + this.parameters = parameters; + } + } + + public static class SCFMethodParameter implements Cloneable { + public Class clazz; + public Object value; + public boolean isGenericity = false; + public List> clsList; + + public boolean getIsGenericity() { + return isGenericity; + } + + public void setIsGenericity(boolean isGenericity) { + this.isGenericity = isGenericity; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + public Class getClazz() { + return clazz; + } + + public void setClazz(Class clazz) { + this.clazz = clazz; + } + + public List> getClsList() { + return clsList; + } + + public void setClsList(List> clsList) { + this.clsList = clsList; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue922.java b/src/test/java/com/alibaba/json/bvt/bug/Issue922.java new file mode 100644 index 0000000000..af99494120 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue922.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 20/12/2016. + */ +public class Issue922 extends TestCase { + public void test_for_issue() throws Exception { + String text = "[1,2,3]"; + JSONArray array = JSON.parseArray(text); + List list = array.toJavaList(Long.class); + assertEquals(1L, list.get(0).longValue()); + assertEquals(2L, list.get(1).longValue()); + assertEquals(3L, list.get(2).longValue()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue923.java b/src/test/java/com/alibaba/json/bvt/bug/Issue923.java new file mode 100644 index 0000000000..d3f9bf601e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue923.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 05/12/2016. + */ +public class Issue923 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"res\": \"00000\",\"version\": \"1.8.0\",\"des\":\"版本更新:\n" + + "1、邀请有礼:新功能,新玩法,快去体验吧~\n" + + "2、直播禁言:主播再也不用担心小黑粉啦~\n" + + "3、蓝鲸币充值:多种模块任你选,多充多送!\n" + + "4、优化排行榜:修复直播页面的排行榜,让大家第一时间看到付出的你~\n" + + "5、修复直播聊天区:再也不担心主播看不到你送的礼物和小星星啦~\",\"download\":\"http://xxx/android/x/x.apk\"}"; + JSON.parse(text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue939.java b/src/test/java/com/alibaba/json/bvt/bug/Issue939.java new file mode 100644 index 0000000000..49070db31c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue939.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 20/12/2016. + */ +public class Issue939 extends TestCase { + public void test_for_issue_false() throws Exception { + String jsonString = "" + + "{" + + " \"age\": 25," + + " \"is_stop\":false/*comment*/" + + "}"; + Model testUser = JSON.parseObject(jsonString, Model.class); + System.out.println(testUser); + } + + public void test_for_issue_true() throws Exception { + String jsonString = "" + + "{" + + " \"age\": 25," + + " \"is_stop\":true/*comment*/" + + "}"; + Model testUser = JSON.parseObject(jsonString, Model.class); + System.out.println(testUser); + } + + public static class Model { + public int age; + public boolean is_top; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue94.java b/src/test/java/com/alibaba/json/bvt/bug/Issue94.java new file mode 100644 index 0000000000..99ba9906e8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue94.java @@ -0,0 +1,14 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONObject; + + +public class Issue94 extends TestCase { + public void test_for_issue() throws Exception { + JSONObject o = new JSONObject(); + o.put("line", "{\"1\":\u0080}"); + o.toString(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue942.java b/src/test/java/com/alibaba/json/bvt/bug/Issue942.java new file mode 100644 index 0000000000..44b429dd6a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue942.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Created by wenshao on 19/12/2016. + */ +public class Issue942 extends TestCase { + public void test_for_issue() throws Exception { + final String pattern = "yyyy-MM-dd HH:mm:ss"; + + LocalDateTime dateTime = LocalDateTime.now(); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); + + String text = JSON.toJSONStringWithDateFormat(dateTime, pattern); + assertEquals(JSON.toJSONString(formatter.format(dateTime)), text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue943.java b/src/test/java/com/alibaba/json/bvt/bug/Issue943.java new file mode 100644 index 0000000000..256a27cd9d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue943.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 09/12/2016. + */ +public class Issue943 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\n" + + "\t\"symbols\":[\n" + + "\t {\"id\":1,\"type\":\"SCATTER\"},\n" + + "\t {\"id\":2,\"type\":\"BONUS\"}\n" + + "\t]\n" + + "}"; + + JSONObject root = JSON.parseObject(text); + + JSONArray symbols = root.getJSONArray("symbols"); + assertNotNull(symbols); + assertEquals(2, symbols.size()); + assertEquals(1, symbols.getJSONObject(0).get("id")); + assertEquals("SCATTER", symbols.getJSONObject(0).get("type")); + + assertEquals(2, symbols.getJSONObject(1).get("id")); + assertEquals("BONUS", symbols.getJSONObject(1).get("type")); + + SlotConfig slotConfig = JSON.parseObject(text, SlotConfig.class); + + assertNotNull(slotConfig); + assertEquals(2, slotConfig.symbols.size()); + assertEquals(1, slotConfig.symbols.get(0).getId()); + assertEquals(SymbolType.SCATTER, slotConfig.symbols.get(0).getType()); + + assertEquals(2, slotConfig.symbols.get(1).getId()); + assertEquals(SymbolType.BONUS, slotConfig.symbols.get(1).getType()); + + } + + private static class SlotConfig { + private List symbols; + + public List getSymbols() { + return symbols; + } + + public void setSymbols(List symbols) { + this.symbols = symbols; + } + } + + private static class Symbol { + private int id; + + private SymbolType type; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public SymbolType getType() { + return type; + } + + public void setType(SymbolType type) { + this.type = type; + } + } + + enum SymbolType { + NORMAL, WILD, SCATTER, BONUS + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue944.java b/src/test/java/com/alibaba/json/bvt/bug/Issue944.java new file mode 100644 index 0000000000..417016679e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue944.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.beans.Transient; + +/** + * Created by wenshao on 19/12/2016. + */ +public class Issue944 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.id = 1001; + + String text = JSON.toJSONString(model, SerializerFeature.SkipTransientField); + + assertEquals("{}", text); + } + + public static class Model { + private int id; + + @Transient + public int getId() { + return id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue952.java b/src/test/java/com/alibaba/json/bvt/bug/Issue952.java new file mode 100644 index 0000000000..1a57d0408c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue952.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Created by wenshao on 19/12/2016. + */ +public class Issue952 extends TestCase { + public void test_for_issue() throws Exception { + final String pattern = "yyyy-MM-dd'T'HH:mm:ss"; + + LocalDateTime dateTime = LocalDateTime.now(); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); + + String text = JSON.toJSONString(dateTime, SerializerFeature.UseISO8601DateFormat); + assertEquals(JSON.toJSONString(formatter.format(dateTime)), text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue955.java b/src/test/java/com/alibaba/json/bvt/bug/Issue955.java new file mode 100644 index 0000000000..a18b681cf7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue955.java @@ -0,0 +1,117 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONPOJOBuilder; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; +import org.junit.Assert; +import org.junit.Test; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +/** + * Created by wenshao on 19/12/2016. + */ +public class Issue955 extends TestCase { + + public void test_checkObject() { + Art origin = makeOrigin(); + JSONObject articleObj = (JSONObject) JSON.toJSON(origin); + + JSONObject dataObj = new JSONObject(); + dataObj.put("art", articleObj); + + Art other = dataObj.getObject("art", Art.class);// return null; + assertSame(origin, other); // test failed + } + + public void test_checkArray() throws Exception { + Art origin = makeOrigin(); + JSONObject object = (JSONObject) JSON.toJSON(origin); + + JSONArray jsonArray = new JSONArray(); + jsonArray.add(object); + + Art other = JSON.parseObject(jsonArray.getString(0), Art.class); + assertSame(origin, other); // test passed + + other = jsonArray.getObject(0, Art.class); // return = null; + assertSame(origin, other); // test failed + } + + private Art makeOrigin() { + final long unixTime = System.currentTimeMillis() / 1000; + final Art origin = new Art(); + origin.id = "12"; + origin.date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date(unixTime * 1000)); + origin.isSupported = true; + return origin; + } + + public void assertSame(Art origin, Art another) { + assertNotNull(another); + assertEquals(origin.id, another.id); + assertEquals(origin.date, another.date); + assertSame(origin.isSupported, another.isSupported); + } + + @JSONType(builder = Art.Builder.class) + public static class Art { + private String id; + private String date; + private boolean isSupported; + + public String getId() { + return id; + } + + public long getDatetime() throws ParseException { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); + return (format.parse(date)).getTime() / 1000; + } + + @JSONField(name = "isSupported") + public int isSupported() { + return isSupported ? 1 : 0; + } + + @JSONPOJOBuilder() + public final static class Builder { + private final Art article = new Art(); + + public Builder(){ + + } + + @JSONField(name = "id") + public Builder withId(String id) { + article.id = id; + return this; + } + + @JSONField(name = "datetime") + public Builder withDateTime(long dateTime) { + if (dateTime > 0) + article.date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date(dateTime * 1000)); + return this; + + } + + @JSONField(name = "isSupported") + public Builder withSupported(int supported) { + article.isSupported = supported == 1; + return this; + } + + public Art build() { + return article; + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue96.java b/src/test/java/com/alibaba/json/bvt/bug/Issue96.java new file mode 100644 index 0000000000..d8fbe16bb4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue96.java @@ -0,0 +1,79 @@ +package com.alibaba.json.bvt.bug; + +import java.lang.reflect.Type; + +import junit.framework.TestCase; + +import org.junit.Test; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.util.TypeUtils; + +public class Issue96 extends TestCase { + + public void test_for_issue() throws Exception { + Page page = new Page(new Sub(1)); + Type type = new TypeReference>() { + }.getType(); + // this is ok + Page page1 = JSON.parseObject(JSON.toJSONString(page), type); + System.out.println(page1.sub.getClass()); + } + + public void xx_testCast() { + Page page = new Page(new Sub(1)); + Type type = new TypeReference>() { + }.getType(); + ParserConfig parserconfig = ParserConfig.getGlobalInstance(); + // !!!! this will fail: + // !!!! com.alibaba.fastjson.JSONException: can not cast to : Page TypeUtils.java:719 + Page page1 = TypeUtils.cast(page, type, parserconfig); + System.out.println(page1.sub.getClass()); + } + + static class Page { + + public Page(){ + super(); + } + + public Page(T sub){ + super(); + this.sub = sub; + } + + T sub; + + public T getSub() { + return sub; + } + + public void setSub(T sub) { + this.sub = sub; + } + } + + static class Sub { + + public Sub(){ + super(); + } + + public Sub(int id){ + super(); + this.id = id; + } + + int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue963.java b/src/test/java/com/alibaba/json/bvt/bug/Issue963.java new file mode 100644 index 0000000000..33652ebf07 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue963.java @@ -0,0 +1,68 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.StringCodec; +import junit.framework.TestCase; + +import java.io.IOException; +import java.lang.reflect.Type; + +/** + * Created by wenshao on 08/01/2017. + */ +public class Issue963 extends TestCase { + public void test_for_issue() throws Exception { + Mock mock = JSON.parseObject("{\"type\":\"boolean\"}", Mock.class); + assertEquals(EnumType.BOOLEAN, mock.getType()); + } + + public enum EnumType { + BOOLEAN; + @Override + public String toString() { + return name().toLowerCase(); + } + } + + public static class Mock { + + @JSONField(serializeUsing = EnumTypeCodec.class, deserializeUsing = EnumTypeCodec.class) + private EnumType type; + + public EnumType getType() { + return type; + } + + public void setType(EnumType type) { + this.type = type; + } + } + + public static class EnumTypeCodec implements ObjectSerializer, ObjectDeserializer { + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + String uncasedSensitive = StringCodec.instance.deserialze(parser, type, fieldName); + return (T) EnumType.valueOf(uncasedSensitive.toUpperCase()); + } + + public int getFastMatchToken() { + return JSONToken.LITERAL_STRING; + } + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + SerializeWriter out = serializer.out; + if (object == null) { + out.writeNull(); + return; + } + StringCodec.instance.write(serializer, ((EnumType) object).name().toLowerCase(), fieldName, fieldType, features); + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue975.java b/src/test/java/com/alibaba/json/bvt/bug/Issue975.java new file mode 100644 index 0000000000..070a768a83 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue975.java @@ -0,0 +1,7 @@ +package com.alibaba.json.bvt.bug; + +/** + * Created by wenshao on 11/01/2017. + */ +public class Issue975 { +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue978.java b/src/test/java/com/alibaba/json/bvt/bug/Issue978.java new file mode 100644 index 0000000000..b6bc9d953a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue978.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + * Created by wenshao on 10/01/2017. + */ +public class Issue978 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_issue() throws Exception { + Model model = new Model(); + model.date = new Date(1483413683714L); + + JSONObject obj = (JSONObject) JSON.toJSON(model); + assertEquals("{\"date\":\"2017-01-03 11:21:23\"}", obj.toJSONString()); + } + + public static class Model { + @JSONField(format="yyyy-MM-dd HH:mm:ss") + public Date date; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue983.java b/src/test/java/com/alibaba/json/bvt/bug/Issue983.java new file mode 100644 index 0000000000..150503d653 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue983.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.AbstractMap; +import java.util.Map; + +/** + * Created by wenshao on 10/01/2017. + */ +public class Issue983 extends TestCase { + public void test_for_issue() throws Exception { + Map.Entry entry = JSON.parseObject("{\"name\":\"foo\"}", Map.Entry.class); + assertEquals("name", entry.getKey()); + assertEquals("foo", entry.getValue()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue983_1.java b/src/test/java/com/alibaba/json/bvt/bug/Issue983_1.java new file mode 100644 index 0000000000..6b05c01961 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue983_1.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.AbstractMap; +import java.util.Map; + +/** + * Created by wenshao on 10/01/2017. + */ +public class Issue983_1 extends TestCase { + public void test_for_issue() throws Exception { + Map.Entry entry = new AbstractMap.SimpleEntry("name", "foo"); + String text = JSON.toJSONString(entry); + assertEquals("{\"name\":\"foo\"}", text); + } + + public void test_for_issue_int() throws Exception { + Map.Entry entry = new AbstractMap.SimpleEntry("name", 123); + String text = JSON.toJSONString(entry); + assertEquals("{\"name\":123}", text); + } + + public void test_for_issue_int_int() throws Exception { + Map.Entry entry = new AbstractMap.SimpleEntry(123, 234); + String text = JSON.toJSONString(entry); + assertEquals("{123:234}", text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue987.java b/src/test/java/com/alibaba/json/bvt/bug/Issue987.java new file mode 100644 index 0000000000..f086d8eb10 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue987.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.Date; + +/** + * Created by wenshao on 11/01/2017. + */ +public class Issue987 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"date\":\"2016-11-09T09:57:20.4Z\"}"; + JSON.parseObject(text, Model.class); + } + + public static class Model { + public Date date; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue989.java b/src/test/java/com/alibaba/json/bvt/bug/Issue989.java new file mode 100644 index 0000000000..62b25674c1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue989.java @@ -0,0 +1,91 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.MapSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +/** + * Created by wenshao on 10/01/2017. + */ +public class Issue989 extends TestCase { + + public void test_for_issue() throws Exception { + assertEquals( + JSON.toJSONString(getMyObject(new HashMap())), + JSON.toJSONString(getMyObject(new TreeMap())) + ); + } + + private static MyObject getMyObject(Map names) { + MyObject mapObj = new MyObject(); + mapObj.setNames(names); + Name name = new Name(); + name.setFirst("foo"); + name.setSecond("boo"); + names.put("mock", name); + return mapObj; + } + + public static class NameMapCodec implements ObjectSerializer { + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + JSONObject names = new JSONObject(); + for(Map.Entry entry : + ((Map)object).entrySet()) { + Name name = entry.getValue(); + names.put(entry.getKey(), name.getFirst() + ":" + name.getSecond()); + } + MapSerializer.instance.write(serializer, names, fieldName, JSONObject.class, features); + } + + } + + public static class MyObject { + + @JSONField(serializeUsing = NameMapCodec.class) + private Map names; + + public Map getNames() { + return names; + } + + public void setNames(Map names) { + this.names = names; + } + + } + + private static class Name { + + private String first; + + private String second; + + public String getFirst() { + return first; + } + + public void setFirst(String first) { + this.first = first; + } + + public String getSecond() { + return second; + } + + public void setSecond(String second) { + this.second = second; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue993.java b/src/test/java/com/alibaba/json/bvt/bug/Issue993.java new file mode 100644 index 0000000000..1006d4fd08 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue993.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 15/01/2017. + */ +public class Issue993 extends TestCase { + public void test_for_issue() throws Exception { + Student student = new Student(); + student.name = "小刚"; + + String json = JSON.toJSONString(student, SerializerFeature.WriteMapNullValue); + assertEquals("{\"student_name\":\"小刚\",\"student_age\":0,\"student_grade\":null}", json); + } + + public static class Student { + @JSONField(name="student_name",ordinal = 0) + public String name; + + @JSONField(name="student_age",ordinal = 1) + public int age; + + @JSONField(name="student_grade",ordinal = 2) + public String grade; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue995.java b/src/test/java/com/alibaba/json/bvt/bug/Issue995.java new file mode 100644 index 0000000000..bac9c7ca6d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue995.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +/** + * Created by wenshao on 15/01/2017. + */ +public class Issue995 extends TestCase { + public void test_for_issue() throws Exception { + Person person = new Person(); + + JSONPath.set(person, "$.nose.name", "xxx"); + } + + public static class Person { + public Nose nose; + } + + public static class Nose { + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue997.java b/src/test/java/com/alibaba/json/bvt/bug/Issue997.java new file mode 100644 index 0000000000..996fd16308 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue997.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import net.sf.json.JSONNull; + +/** + * Created by wenshao on 17/01/2017. + */ +public class Issue997 extends TestCase { + public void test_for_issue() throws Exception { + + Model model = new Model(); + model.object = JSONNull.getInstance(); + System.out.println(JSON.toJSONString(model)); +// System.out.println(JSON.toJSONString(map)); + } + + public static class Model { + public Object object; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue998.java b/src/test/java/com/alibaba/json/bvt/bug/Issue998.java new file mode 100644 index 0000000000..ac18411271 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue998.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.lang.reflect.Field; +import java.util.List; + +/** + * Created by wenshao on 16/01/2017. + */ +public class Issue998 extends TestCase { + public void test_for_issue() throws Exception { + Model model = JSON.parseObject("{\"items\":[{\"id\":123}]}", Model.class); + assertNotNull(model); + assertNotNull(model.items); + assertEquals(1, model.items.size()); + assertEquals(123, model.items.get(0).getId()); + + String json = JSON.toJSONString(model, SerializerFeature.NotWriteRootClassName, SerializerFeature.WriteClassName); + assertEquals("{\"items\":[{\"id\":123}]}", json); + } + + public void test_for_issue_1() throws Exception { + Field field = Model.class.getField("items"); + List items = (List ) JSON.parseObject("[{\"id\":123}]", field.getGenericType()); + assertNotNull(items); + assertEquals(1, items.size()); + assertEquals(123, items.get(0).id); + } + + public static class Model { + public List items; + } + + public static class Item { + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue998_private.java b/src/test/java/com/alibaba/json/bvt/bug/Issue998_private.java new file mode 100644 index 0000000000..7ac6def692 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue998_private.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.lang.reflect.Field; +import java.util.List; + +/** + * Created by wenshao on 16/01/2017. + */ +public class Issue998_private extends TestCase { + public void test_for_issue() throws Exception { + Model model = JSON.parseObject("{\"items\":[{\"id\":123}]}", Model.class); + assertNotNull(model); + assertNotNull(model.items); + assertEquals(1, model.items.size()); + assertEquals(123, model.items.get(0).getId()); + + String json = JSON.toJSONString(model, SerializerFeature.NotWriteRootClassName, SerializerFeature.WriteClassName); + assertEquals("{\"items\":[{\"id\":123}]}", json); + } + + public void test_for_issue_1() throws Exception { + Field field = Model.class.getField("items"); + List items = (List ) JSON.parseObject("[{\"id\":123}]", field.getGenericType()); + assertNotNull(items); + assertEquals(1, items.size()); + assertEquals(123, items.get(0).id); + } + + private static class Model { + public List items; + } + + private static class Item { + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue_611.java b/src/test/java/com/alibaba/json/bvt/bug/Issue_611.java new file mode 100644 index 0000000000..05fedc4245 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue_611.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class Issue_611 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"priority\":1}"; + JSONObject obj = JSON.parseObject(text); + Assert.assertEquals(1, obj.getInteger("priority").intValue()); + Assert.assertEquals(1, obj.getIntValue("priority")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue_717.java b/src/test/java/com/alibaba/json/bvt/bug/Issue_717.java new file mode 100644 index 0000000000..fa8b9ce0b0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue_717.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class Issue_717 extends TestCase { + + public void test_for_issue() throws Exception { + Group group = new Group(); + group.setId(0L); + group.setNAME("admin"); + group.setAUTHORITY("administrors"); + + String json = JSON.toJSONString(group); + Assert.assertEquals("{\"ID\":0,\"nAME\":\"admin\"}", json); + } + + public static class Group { + + @JSONField(name = "ID") + private Long id; + private String NAME; + @JSONField(serialize = false, deserialize = false) + private String AUTHORITY; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getNAME() { + return NAME; + } + + public void setNAME(String NAME) { + this.NAME = NAME; + } + + public String getAUTHORITY() { + return AUTHORITY; + } + + public void setAUTHORITY(String AUTHORITY) { + this.AUTHORITY = AUTHORITY; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue_748.java b/src/test/java/com/alibaba/json/bvt/bug/Issue_748.java new file mode 100644 index 0000000000..1156bd6004 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue_748.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class Issue_748 extends TestCase { + protected void setUp() throws Exception { + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Issue_748."); + } + + public void testJsonObjectWithClassName() { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("key1", "value1"); + jsonObject.put("key2", "value2"); + DataObject dataObject = new DataObject(); + dataObject.setValue(jsonObject); + String jsonStr = JSON.toJSONString(dataObject, SerializerFeature.QuoteFieldNames, + SerializerFeature.SkipTransientField, SerializerFeature.WriteClassName); + +// System.out.println("parse之前:" + jsonStr); + + DataObject obj = (DataObject) JSON.parse(jsonStr, Feature.IgnoreNotMatch); + Assert.assertNotNull(obj.value); + Assert.assertNotNull(obj.value.get("key1")); + Assert.assertNotNull(obj.value.get("key2")); + } + + public static class DataObject { + + private JSONObject value; + + public DataObject(){ + } + + public JSONObject getValue() { + return value; + } + + public void setValue(JSONObject value) { + this.value = value; + } + + @Override + public String toString() { + return "DataObject{" + "value=" + value + '}'; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue_for_huangfeng.java b/src/test/java/com/alibaba/json/bvt/bug/Issue_for_huangfeng.java new file mode 100644 index 0000000000..14b301adb2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue_for_huangfeng.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/02/2017. + */ +public class Issue_for_huangfeng extends TestCase { + public void test_for_huangfeng() throws Exception { + String json = "{\"success\":\"Y\"}"; + + Model model = JSON.parseObject(json, Model.class); + assertTrue(model.isSuccess()); + } + + public void test_for_huangfeng_t() throws Exception { + String json = "{\"success\":\"T\"}"; + + Model model = JSON.parseObject(json, Model.class); + assertTrue(model.isSuccess()); + } + + public void test_for_huangfeng_is_t() throws Exception { + String json = "{\"isSuccess\":\"T\"}"; + + Model model = JSON.parseObject(json, Model.class); + assertTrue(model.isSuccess()); + } + + public void test_for_huangfeng_false() throws Exception { + String json = "{\"success\":\"N\"}"; + + Model model = JSON.parseObject(json, Model.class); + assertFalse(model.isSuccess()); + } + + public void test_for_huangfeng_false_f() throws Exception { + String json = "{\"success\":\"F\"}"; + + Model model = JSON.parseObject(json, Model.class); + assertFalse(model.isSuccess()); + } + + public static class Model { + private boolean success; + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue_for_jiongxiong.java b/src/test/java/com/alibaba/json/bvt/bug/Issue_for_jiongxiong.java new file mode 100644 index 0000000000..a2914781ed --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue_for_jiongxiong.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.Set; + +/** + * Created by wenshao on 15/02/2017. + */ +public class Issue_for_jiongxiong extends TestCase { + public void test_for_jiongxiong() throws Exception { + JSON.parseObject("{\"groupNames\":[\"a\"]}", Model.class); + } + + public static class Model { + private Set groupNames; + + public Set getGroupNames() { + return groupNames; + } + + public void setGroupNames(Set groupNames) { + this.groupNames = groupNames; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue_for_oschina_3087749_2215732.java b/src/test/java/com/alibaba/json/bvt/bug/Issue_for_oschina_3087749_2215732.java new file mode 100644 index 0000000000..1722d42036 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue_for_oschina_3087749_2215732.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.Test; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wenshao on 29/12/2016. + */ +public class Issue_for_oschina_3087749_2215732 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"datas\":[\"a\",\"b\"]}"; + JSONObject o = JSON.parseObject(json); + o.toJavaObject(JsonBean.class); + } + + public static class JsonBean { + private List datas = new ArrayList(); + public List getDatas() { + return datas; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Issue_for_zuojing.java b/src/test/java/com/alibaba/json/bvt/bug/Issue_for_zuojing.java new file mode 100644 index 0000000000..95304f1792 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Issue_for_zuojing.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 15/02/2017. + */ +public class Issue_for_zuojing extends TestCase { + public void test_for_zuojing() throws Exception { + String rowData = "[{\"@type\":\"java.util.HashMap\",\"end_date\":{\"@type\":\"java.sql.Date\",\"val\":1490803200000},\"gmt_create\":{\"@type\":\"java.sql.Timestamp\",\"val\":1487139144000},\"arr_city\":\"FOC\",\"agent\n" + + "_id\":4765L,\"auto_book\":0B,\"sale_rebase\":12,\"channel\":1B,\"dep_city\":\"BJS\",\"gmt_modified\":{\"@type\":\"java.sql.Timestamp\",\"val\":1487139144000},\"is_support_share\":1B,\"sale_retenti\n" + + "on\":430S,\"invoice_type\":5B,\"id\":12675100456,\"start_date\":{\"@type\":\"java.sql.Date\",\"val\":1485878400000},\"pat\":1B,\"agent_sub_nick\":\"辰\",\"travel_start_date\":{\"@type\"\n" + + ":\"java.sql.Date\",\"val\":1485878400000},\"policy_type\":2B,\"travel_end_date\":{\"@type\":\"java.sql.Date\",\"val\":1490803200000},\"flights_limit_type\":1B,\"officeid\":\"WNZ159\",\"future_tic\n" + + "ket\":0B,\"fare_id\":80L,\"source_id\":4653492L,\"source_code\":32B,\"agent_sub_id\":2752916259,\"flights_limit\":\"1100-1999,4000-4999,8200-8230,8960\"},{\"$ref\":\"$[0]\"}]"; + List row = JSON.parseObject(rowData,List.class); + assertEquals(2, row.size()); + assertSame(row.get(0), row.get(1)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/JSONTest.java b/src/test/java/com/alibaba/json/bvt/bug/JSONTest.java new file mode 100755 index 0000000000..14d61ded37 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/JSONTest.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt.bug; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +@SuppressWarnings("unchecked") +public class JSONTest { + + @Test + public void testParseArray() throws Exception { + List list = new ArrayList(); + OuterEntry entry = new OuterEntry(); + list.add(entry); + entry.setId(1000L); + entry.setUrl("http://www.springframework.org/schema/aop"); + String jsonString = JSONObject.toJSONString(entry); + String arrayString = JSONObject.toJSONString(list); + System.out.println(jsonString); + System.out.println(arrayString); + list = JSONArray.parseArray(arrayString, OuterEntry.class); + JSONArray array = JSONArray.parseArray(arrayString);// 这一步出错 + } + + @Test + public void testInnerEntry() throws Exception { + List list = new ArrayList(); + InnerEntry entry = new InnerEntry(); + list.add(entry); + entry.setId(1000L); + entry.setUrl("http://www.springframework.org/schema/aop"); + String jsonString = JSONObject.toJSONString(entry);// //这一步出错 + } + + class InnerEntry { + + private Long id; + private String url; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + } + + public static class OuterEntry { + + private Long id; + private String url; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/KeyBug_for_zhongl.java b/src/test/java/com/alibaba/json/bvt/bug/KeyBug_for_zhongl.java new file mode 100644 index 0000000000..c5e29e239e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/KeyBug_for_zhongl.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class KeyBug_for_zhongl extends TestCase { + + public void testCustomedKey() throws Exception { + Assert.assertEquals("{\"uid\":1}", JSON.toJSONString(new V2(1))); + } + + public void testDeserialize() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"uid\":123}", V2.class).id); + } + + public void testCustomedKey_static() throws Exception { + Assert.assertEquals("{\"uid\":1}", JSON.toJSONString(new VO(1))); + } + + public void testDeserialize_static() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"uid\":123}", VO.class).id); + } + + public static class VO { + + @JSONField(name = "uid") + public int id; + + @JSONField(serialize = false) + public String name = "defaultName"; + + public VO(){ + + } + + VO(int id){ + this.id = id; + } + } + + private static class V2 { + + @JSONField(name = "uid") + public int id; + + @JSONField(serialize = false) + public String name = "defaultName"; + + private V2() { + + } + + private V2(int id) { + this.id = id; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Mogujie_01.java b/src/test/java/com/alibaba/json/bvt/bug/Mogujie_01.java new file mode 100644 index 0000000000..5011817f5c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Mogujie_01.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONWriter; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.bvtVO.mogujie.BindQueryRespDTO; +import junit.framework.TestCase; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.Charset; +import java.nio.charset.CodingErrorAction; + +/** + * Created by wenshao on 16/03/2017. + */ +public class Mogujie_01 extends TestCase { + public void test_for_issue() throws Exception { + JSON.parseObject("{}", Model.class); + + + } + public static class Model { + public int f0; + public int f1; + public int f2; + public int f3; + public int f4; + public int f5; + public int f6; + public int f7; + public int f8; + public int f9; + public int f10; + public int f11; + public int f12; + public int f13; + public int f14; + public int f15; + public int f16; + public int f17; + public int f18; + public int f19; + public int f20; + public int f21; + public int f22; + public int f23; + public int f24; + public int f25; + public int f26; + public int f27; + public int f28; + public int f29; + public int f30; + public int f31; + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/Mogujie_02.java b/src/test/java/com/alibaba/json/bvt/bug/Mogujie_02.java new file mode 100644 index 0000000000..5c1e436126 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/Mogujie_02.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/03/2017. + */ +public class Mogujie_02 extends TestCase { + public void test_for_issue() throws Exception { + JSON.parseObject("{}", Model.class); + + + } + public static class Model { + public int f0; + public int f1; + public int f2; + public int f3; + public int f4; + public int f5; + public int f6; + public int f7; + public int f8; + public int f9; + public int f10; + public int f11; + public int f12; + public int f13; + public int f14; + public int f15; + public int f16; + public int f17; + public int f18; + public int f19; + public int f20; + public int f21; + public int f22; + public int f23; + public int f24; + public int f25; + public int f26; + public int f27; + public int f28; + public int f29; + public int f30; + public int f31; + public int f32; + public int f33; + public int f34; + public int f35; + public int f36; + public int f37; + public int f38; + public int f39; + public int f40; + public int f41; + public int f42; + public int f43; + public int f44; + public int f45; + public int f46; + public int f47; + public int f48; + public int f49; + public int f50; + public int f51; + public int f52; + public int f53; + public int f54; + public int f55; + public int f56; + public int f57; + public int f58; + public int f59; + public int f60; + public int f61; + public int f62; + public int f63; + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/SerDeserTest.java b/src/test/java/com/alibaba/json/bvt/bug/SerDeserTest.java new file mode 100755 index 0000000000..452ff68276 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/SerDeserTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2011 Alibaba.com All right reserved. This software is the + * confidential and proprietary information of Alibaba.com ("Confidential + * Information"). You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Alibaba.com. + */ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.bvtVO.OptionKey; +import com.alibaba.json.bvtVO.OptionValue; +import com.alibaba.json.bvtVO.TempAttachMetaOption; + +/** + * 类SerDeserTest.java的实现描述:TODO 类实现描述 + * + * @author lei.yaol 2011-12-27 下午03:44:18 + */ +public class SerDeserTest extends TestCase { + protected void setUp() throws Exception { + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvtVO."); + } + + /** 用于被FastJson序列和反序列化的对象 */ + private static Map> options; + + static { + options = new HashMap>(); + + TempAttachMetaOption attach = new TempAttachMetaOption(); + attach.setId(1000); + attach.setName("test_name"); + attach.setPath("http://alibaba-inc.com/test.txt"); + + ArrayList attachList = new ArrayList(); + attachList.add(attach); + + // 设置value + OptionValue> optionValue = new OptionValue>(); + optionValue.setValue(attachList); + + options.put(OptionKey.TEMPALTE_ATTACH_META, optionValue); + } + + public void test_for_yaolei() { + // 序列化toJSONString() + String jsonString = JSON.toJSONString(options); + System.out.println(jsonString); + { + // 反序列化parse() + HashMap> deserOptions = (HashMap>) JSON.parseObject(jsonString, + new TypeReference>>() { + + }); + System.out.println(deserOptions.get(OptionKey.TEMPALTE_ATTACH_META)); + } + + // 序列化toJSONString(,) + jsonString = JSON.toJSONString(options, SerializerFeature.WriteClassName); + System.out.println(jsonString); + // 反序列化parse() + HashMap> deserOptions = (HashMap>) JSON.parse(jsonString); + System.out.println(deserOptions.get(OptionKey.TEMPALTE_ATTACH_META)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/StackTraceElementTest.java b/src/test/java/com/alibaba/json/bvt/bug/StackTraceElementTest.java new file mode 100755 index 0000000000..30ed216314 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/StackTraceElementTest.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.serializer.SerializerFeature; + + +public class StackTraceElementTest extends TestCase { + public void test_stackTrace() throws Exception { + StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); + String text = JSON.toJSONString(stackTrace, SerializerFeature.WriteClassName); + JSONArray array = (JSONArray) JSON.parse(text); + for (int i = 0; i < array.size(); ++i) { + StackTraceElement element = (StackTraceElement) array.get(i); + Assert.assertEquals(stackTrace[i].getFileName(), element.getFileName()); + Assert.assertEquals(stackTrace[i].getLineNumber(), element.getLineNumber()); + Assert.assertEquals(stackTrace[i].getClassName(), element.getClassName()); + Assert.assertEquals(stackTrace[i].getMethodName(), element.getMethodName()); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/StackTraceElementTest2.java b/src/test/java/com/alibaba/json/bvt/bug/StackTraceElementTest2.java new file mode 100755 index 0000000000..faf9fcd745 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/StackTraceElementTest2.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class StackTraceElementTest2 extends TestCase { + public void test_stackTrace2() throws Exception { + String text = "{\"@type\":\"java.lang.StackTraceElement\",\"className\":\"java.lang.Thread\",\"fileName\":\"Thread.java\",\"lineNumber\":1503,\"methodName\":\"getStackTrace\",\"nativeMethod\":false}"; + JSON.parseObject(text, StackTraceElement.class); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/bug/TestDouble.java b/src/test/java/com/alibaba/json/bvt/bug/TestDouble.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/bug/TestDouble.java rename to src/test/java/com/alibaba/json/bvt/bug/TestDouble.java index 87ffb70c37..f6a889ed74 --- a/src/test/java/com/alibaba/json/test/bvt/bug/TestDouble.java +++ b/src/test/java/com/alibaba/json/bvt/bug/TestDouble.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.bug; +package com.alibaba.json.bvt.bug; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/bvt/bug/TestJSONMap.java b/src/test/java/com/alibaba/json/bvt/bug/TestJSONMap.java new file mode 100755 index 0000000000..66da40520c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/TestJSONMap.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.bug; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class TestJSONMap extends TestCase { + protected void setUp() throws Exception { + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.TestJSONMap."); + } + + public void test_0() throws Exception { + Record record = new Record(); + Map map = new HashMap(); + record.setRecord(map); + String s = JSON.toJSONString(record, SerializerFeature.WriteClassName); + System.out.println(s); + record = (Record)JSON.parse(s); //此处抛出异常 + System.out.println(record.getRecord().size()); + } + + public static class Record { + + private Map record; + + public Map getRecord() { + return record; + } + + public void setRecord(Map record) { + this.record = record; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/WuqiTest.java b/src/test/java/com/alibaba/json/bvt/bug/WuqiTest.java new file mode 100644 index 0000000000..b72bf80cf4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/WuqiTest.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.bvtVO.wuqi.InstanceSchema; +import com.alibaba.json.bvtVO.wuqi.*; +import junit.framework.TestCase; + +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.CodingErrorAction; +import java.util.Arrays; + +import static org.springframework.web.socket.sockjs.frame.SockJsFrame.CHARSET; + +/** + * Created by wenshao on 01/04/2017. + */ +public class WuqiTest extends TestCase { + public void test_for_wuqi() throws Exception { + SchemaResult schemaResult = new SchemaResult(); + schemaResult.setCode(1001); + schemaResult.setMassage("success"); + + InstanceSchema instanceSchema = new InstanceSchema(); + instanceSchema.setCreated(1466692258L); + instanceSchema.setCycleType(0); + instanceSchema.setDefaultValue("-1"); + instanceSchema.setFieldBaseType("string"); + instanceSchema.setFieldComment("普通商品价格带标签"); + instanceSchema.setFieldIndexed(1); + instanceSchema.setFieldName("NormalPriceTag_ws"); + instanceSchema.setFieldStored(1); + instanceSchema.setFieldTag(0); + instanceSchema.setFieldType("text_ws"); + instanceSchema.setId(1317); + instanceSchema.setInstanceName("xitem"); + instanceSchema.setIsDeleted(0); + instanceSchema.setIsTagField(1); + instanceSchema.setUpdated(1466692258L); + + schemaResult.setData(Arrays.asList(instanceSchema)); + + Result result = new Result(); + result.setData(schemaResult); + String jsonStr = JSON.toJSONString(result, SerializerFeature.WriteClassName); + assertEquals("{\"@type\":\"com.alibaba.json.bvtVO.wuqi.Result\",\"data\":{\"@type\":\"com.alibaba.json.bvtVO.wuqi.SchemaResult\",\"code\":1001,\"data\":[{\"created\":1466692258,\"cycleType\":0,\"defaultValue\":\"-1\",\"fieldBaseType\":\"string\",\"fieldComment\":\"普通商品价格带标签\",\"fieldIndexed\":1,\"fieldName\":\"NormalPriceTag_ws\",\"fieldStored\":1,\"fieldTag\":0,\"fieldType\":\"text_ws\",\"id\":1317,\"instanceName\":\"xitem\",\"isDeleted\":0,\"isTagField\":1,\"updated\":1466692258}],\"extra\":[],\"massage\":\"success\"}}", jsonStr); + + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/bug_for_caoyaojun1988.java b/src/test/java/com/alibaba/json/bvt/bug/bug_for_caoyaojun1988.java new file mode 100755 index 0000000000..49d6d63973 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/bug_for_caoyaojun1988.java @@ -0,0 +1,160 @@ +package com.alibaba.json.bvt.bug; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class bug_for_caoyaojun1988 extends TestCase { + + public void test_for_bug() throws Exception { + // 创建 BusinessVO + BusinessVO businessVO = new BusinessVO(); + businessVO.setName("name"); + + // 创建 第一个List list中每一个对象都包含 BusinessVO对象 + ExpiredDto expiredDto = new ExpiredDto(); + expiredDto.setBusinessVO(businessVO); + expiredDto.setId(10001); + + List expiredReports = new ArrayList(); + expiredReports.add(expiredDto); + + // 创建 第二个List list中每一个对象都包含 BusinessVO对象 + + List normalReports = new ArrayList(); + { + NormalDto normalDto = new NormalDto(); + normalDto.setBusinessVO(businessVO); + normalDto.setId(10001); + normalReports.add(normalDto); + } + + // 创建 需要序列化的对象,包含两个list + ReportDto reportDto = new ReportDto(); + reportDto.setExpiredReports(expiredReports); + reportDto.setNormalReports(normalReports); + reportDto.setCompanyId(10004); + + // 第一个场景 得到的businessVO为null; + String serializeStr = (String) JSON.toJSONString(reportDto); + System.out.println(serializeStr); + ReportDto reuslt = (ReportDto) JSON.parseObject(serializeStr, ReportDto.class); + System.out.println(reuslt.getNormalReports().get(0).getBusinessVO()); + + // 第二个场景 得到的businessVO为正常数据 + expiredReports.add(expiredDto); + serializeStr = (String) JSON.toJSONString(reportDto); + System.out.println(serializeStr); + reuslt = (ReportDto) JSON.parseObject(serializeStr, ReportDto.class); + System.out.print(reuslt.getNormalReports().get(0).getBusinessVO().getName()); + } + + public static class BusinessVO implements Serializable { + + private static final long serialVersionUID = -191856665415285103L; + private String name; + + public BusinessVO() { + + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + } + + public static class ExpiredDto implements Serializable { + + private static final long serialVersionUID = -2361763020563748437L; + private Integer id; + private BusinessVO businessVO; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public BusinessVO getBusinessVO() { + return businessVO; + } + + public void setBusinessVO(BusinessVO businessVO) { + this.businessVO = businessVO; + } + + } + + public static class NormalDto implements Serializable { + + private static final long serialVersionUID = -2392077150026945111L; + private Integer id; + private BusinessVO businessVO; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public BusinessVO getBusinessVO() { + return businessVO; + } + + public void setBusinessVO(BusinessVO businessVO) { + this.businessVO = businessVO; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + + } + + public static class ReportDto implements Serializable { + + private static final long serialVersionUID = 4502937258945851832L; + private Integer companyId; + private List normalReports; + private List expiredReports; + + public Integer getCompanyId() { + return companyId; + } + + public void setCompanyId(Integer companyId) { + this.companyId = companyId; + } + + public List getNormalReports() { + return normalReports; + } + + public void setNormalReports(List normalReports) { + this.normalReports = normalReports; + } + + public List getExpiredReports() { + return expiredReports; + } + + public void setExpiredReports(List expiredReports) { + this.expiredReports = expiredReports; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/bug/bug_for_pengsong0302.java b/src/test/java/com/alibaba/json/bvt/bug/bug_for_pengsong0302.java new file mode 100644 index 0000000000..a2228c127d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/bug/bug_for_pengsong0302.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.bug; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class bug_for_pengsong0302 extends TestCase { + + public void test_0() throws Exception { + Assert.assertEquals("\"a\\u2028b\"", JSON.toJSONString("a\u2028b")); + } + + public void test_1() throws Exception { + Assert.assertEquals("{\"value\":\"a\\u2028b\"}", JSON.toJSONString(new A("a\u2028b"))); + } + + public void test_2029() throws Exception { + Assert.assertEquals("\"a\\u2029b\"", JSON.toJSONString("a\u2029b")); + } + + public void test_2029_1() throws Exception { + Assert.assertEquals("{\"value\":\"a\\u2029b\"}", JSON.toJSONString(new A("a\u2029b"))); + } + + public static class A { + + private String value; + + public A(String value){ + super(); + this.value = value; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/builder/BuilderTest0.java b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest0.java new file mode 100644 index 0000000000..14062f13b4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest0.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.builder; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; + +import junit.framework.TestCase; + +public class BuilderTest0 extends TestCase { + + public void test_0() throws Exception { + VO vo = JSON.parseObject("{\"id\":12304,\"name\":\"ljw\"}", VO.class); + + Assert.assertEquals(12304, vo.getId()); + Assert.assertEquals("ljw", vo.getName()); + } + + @JSONType(builder=VOBuilder.class) + public static class VO { + private int id; + private String name; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + } + + public static class VOBuilder { + + private VO vo = new VO(); + + public VO build() { + return vo; + } + + public VOBuilder withId(int id) { + vo.id = id; + return this; + } + + public VOBuilder withName(String name) { + vo.name = name; + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/builder/BuilderTest0_private.java b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest0_private.java new file mode 100644 index 0000000000..4e6d66e5c1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest0_private.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.builder; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; + +import junit.framework.TestCase; + +public class BuilderTest0_private extends TestCase { + + public void test_0() throws Exception { + VO vo = JSON.parseObject("{\"id\":12304,\"name\":\"ljw\"}", VO.class); + + Assert.assertEquals(12304, vo.getId()); + Assert.assertEquals("ljw", vo.getName()); + } + + @JSONType(builder=VOBuilder.class) + public static class VO { + private int id; + private String name; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + } + + private static class VOBuilder { + + private VO vo = new VO(); + + public VO build() { + return vo; + } + + public VOBuilder withId(int id) { + vo.id = id; + return this; + } + + public VOBuilder withName(String name) { + vo.name = name; + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/builder/BuilderTest1.java b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest1.java new file mode 100644 index 0000000000..186c5e8ba8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest1.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.builder; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; + +import junit.framework.TestCase; + +public class BuilderTest1 extends TestCase { + + public void test_create() throws Exception { + VO vo = JSON.parseObject("{\"id\":12304,\"name\":\"ljw\"}", VO.class); + + Assert.assertEquals(12304, vo.getId()); + Assert.assertEquals("ljw", vo.getName()); + } + + @JSONType(builder=VOBuilder.class) + public static class VO { + private int id; + private String name; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + } + + public static class VOBuilder { + + private VO vo = new VO(); + + public VO create() { + return vo; + } + + public VOBuilder withId(int id) { + vo.id = id; + return this; + } + + public VOBuilder withName(String name) { + vo.name = name; + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/builder/BuilderTest1_private.java b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest1_private.java new file mode 100644 index 0000000000..ad48bef685 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest1_private.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.builder; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; + +import junit.framework.TestCase; + +public class BuilderTest1_private extends TestCase { + + public void test_create() throws Exception { + VO vo = JSON.parseObject("{\"id\":12304,\"name\":\"ljw\"}", VO.class); + + Assert.assertEquals(12304, vo.getId()); + Assert.assertEquals("ljw", vo.getName()); + } + + @JSONType(builder=VOBuilder.class) + public static class VO { + private int id; + private String name; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + } + + private static class VOBuilder { + + private VO vo = new VO(); + + public VO create() { + return vo; + } + + public VOBuilder withId(int id) { + vo.id = id; + return this; + } + + public VOBuilder withName(String name) { + vo.name = name; + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/builder/BuilderTest2.java b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest2.java new file mode 100644 index 0000000000..61b2804e3a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest2.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.builder; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONPOJOBuilder; +import com.alibaba.fastjson.annotation.JSONType; + +import junit.framework.TestCase; + +public class BuilderTest2 extends TestCase { + + public void test_create() throws Exception { + VO vo = JSON.parseObject("{\"id\":12304,\"name\":\"ljw\"}", VO.class); + + Assert.assertEquals(12304, vo.getId()); + Assert.assertEquals("ljw", vo.getName()); + } + + @JSONType(builder=VOBuilder.class) + public static class VO { + private int id; + private String name; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + } + + @JSONPOJOBuilder(buildMethod="xxx") + public static class VOBuilder { + + private VO vo = new VO(); + + public VO xxx() { + return vo; + } + + public VOBuilder withId(int id) { + vo.id = id; + return this; + } + + public VOBuilder withName(String name) { + vo.name = name; + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/builder/BuilderTest2_private.java b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest2_private.java new file mode 100644 index 0000000000..b5ee85c73b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest2_private.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.builder; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONPOJOBuilder; +import com.alibaba.fastjson.annotation.JSONType; + +import junit.framework.TestCase; + +public class BuilderTest2_private extends TestCase { + + public void test_create() throws Exception { + VO vo = JSON.parseObject("{\"id\":12304,\"name\":\"ljw\"}", VO.class); + + Assert.assertEquals(12304, vo.getId()); + Assert.assertEquals("ljw", vo.getName()); + } + + @JSONType(builder=VOBuilder.class) + public static class VO { + private int id; + private String name; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + } + + @JSONPOJOBuilder(buildMethod="xxx") + private static class VOBuilder { + + private VO vo = new VO(); + + public VO xxx() { + return vo; + } + + public VOBuilder withId(int id) { + vo.id = id; + return this; + } + + public VOBuilder withName(String name) { + vo.name = name; + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/builder/BuilderTest3.java b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest3.java new file mode 100644 index 0000000000..95ff89d3e3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest3.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.builder; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONPOJOBuilder; +import com.alibaba.fastjson.annotation.JSONType; + +import junit.framework.TestCase; + +public class BuilderTest3 extends TestCase { + + public void test_create() throws Exception { + VO vo = JSON.parseObject("{\"id\":12304,\"name\":\"ljw\"}", VO.class); + + Assert.assertEquals(12304, vo.getId()); + Assert.assertEquals("ljw", vo.getName()); + } + + @JSONType(builder=VOBuilder.class) + public static class VO { + private int id; + private String name; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + } + + @JSONPOJOBuilder(withPrefix="kk", buildMethod="mmm") + public static class VOBuilder { + + private VO vo = new VO(); + + public VO mmm() { + return vo; + } + + public VOBuilder kkId(int id) { + vo.id = id; + return this; + } + + public VOBuilder kkName(String name) { + vo.name = name; + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/builder/BuilderTest3_private.java b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest3_private.java new file mode 100644 index 0000000000..91d1ed99df --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest3_private.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.builder; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; + +import junit.framework.TestCase; + +public class BuilderTest3_private extends TestCase { + + public void test_create() throws Exception { + VO vo = JSON.parseObject("{\"id\":12304,\"name\":\"ljw\"}", VO.class); + + Assert.assertEquals(12304, vo.getId()); + Assert.assertEquals("ljw", vo.getName()); + } + + @JSONType(builder=VOBuilder.class) + public static class VO { + private int id; + private String name; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + } + + private static class VOBuilder { + + private VO vo = new VO(); + + public VO create() { + return vo; + } + + @JSONField(name="id") + public VOBuilder kkId(int id) { + vo.id = id; + return this; + } + + @JSONField(name="name") + public VOBuilder kkName(String name) { + vo.name = name; + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/builder/BuilderTest_error.java b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest_error.java new file mode 100644 index 0000000000..866470824d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest_error.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.builder; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONType; + +import junit.framework.TestCase; + +public class BuilderTest_error extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"id\":12304,\"name\":\"ljw\"}", VO.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + @JSONType(builder = VOBuilder.class) + public static class VO { + + private int id; + private String name; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + } + + public static class VOBuilder { + + private VO vo = new VO(); + + public VO build() { + throw new IllegalStateException(); + } + + public VOBuilder withId(int id) { + vo.id = id; + return this; + } + + public VOBuilder withName(String name) { + vo.name = name; + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/builder/BuilderTest_error_private.java b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest_error_private.java new file mode 100644 index 0000000000..6c7d87ebdc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/builder/BuilderTest_error_private.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.builder; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONType; + +import junit.framework.TestCase; + +public class BuilderTest_error_private extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"id\":12304,\"name\":\"ljw\"}", VO.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + @JSONType(builder = VOBuilder.class) + public static class VO { + + private int id; + private String name; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + } + + private static class VOBuilder { + + private VO vo = new VO(); + + public VO build() { + throw new IllegalStateException(); + } + + public VOBuilder withId(int id) { + vo.id = id; + return this; + } + + public VOBuilder withName(String name) { + vo.name = name; + return this; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/cglib/TestCglib.java b/src/test/java/com/alibaba/json/bvt/cglib/TestCglib.java new file mode 100755 index 0000000000..127f3fc75c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/cglib/TestCglib.java @@ -0,0 +1,68 @@ +package com.alibaba.json.bvt.cglib; + +import java.lang.reflect.Method; + +import org.junit.Assert; +import junit.framework.TestCase; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; + +import com.alibaba.fastjson.JSON; + +public class TestCglib extends TestCase { + + public void test_cglib() throws Exception { + Enhancer enhancer = new Enhancer(); + enhancer.setSuperclass(Entity.class); + enhancer.setCallback(new Proxy()); + Entity entity = (Entity) enhancer.create(); + + entity.setId(3); + entity.setName("Jobs"); + + String text = JSON.toJSONString(entity); + Assert.assertEquals("{\"id\":3,\"name\":\"Jobs\"}", text); + + } + + public static class Proxy implements MethodInterceptor { + + public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { + return proxy.invokeSuper(obj, args); + } + + } + + public static class Entity { + + private int id; + private String name; + + public Entity(){ + + } + + public Entity(int id, String name){ + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/comparing_json_modules/ComplexAndDecimalTest.java b/src/test/java/com/alibaba/json/bvt/comparing_json_modules/ComplexAndDecimalTest.java new file mode 100644 index 0000000000..d83b7653ab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/comparing_json_modules/ComplexAndDecimalTest.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.comparing_json_modules; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.BigDecimalCodec; +import junit.framework.TestCase; + +import java.math.BigDecimal; + +/** + * Created by wenshao on 24/03/2017. + */ +public class ComplexAndDecimalTest extends TestCase { + public void test_3_1() throws Exception { + assertEquals("5", JSON.toJSONString(5L)); + } + + public void test_3_2() throws Exception { + assertEquals("5.5", JSON.toJSONString(new BigDecimal("5.5"))); + } + + public void test_3_4() throws Exception { + assertEquals("5", JSON.toJSONString(new BigDecimal("5"))); + } + + public void test_3_5() throws Exception { + assertEquals("0.1", JSON.toJSONString(new BigDecimal("0.1"))); + } + + public void test_3_6() throws Exception { + assertEquals("0.1", JSON.toJSONString(new BigDecimal("0.1"))); + } + + public void test_3_7() throws Exception { + assertEquals("3.14159265358979323846264338327950288419716939937510", JSON.toJSONString(new BigDecimal("3.14159265358979323846264338327950288419716939937510"))); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/comparing_json_modules/Floating_point_Test.java b/src/test/java/com/alibaba/json/bvt/comparing_json_modules/Floating_point_Test.java new file mode 100644 index 0000000000..451603110a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/comparing_json_modules/Floating_point_Test.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.comparing_json_modules; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.DoubleSerializer; +import junit.framework.TestCase; + +/** + * Created by wenshao on 24/03/2017. + */ +public class Floating_point_Test extends TestCase { + public void test_2_1() throws Exception { + assertEquals("0.0", JSON.toJSONString(0.0)); + } + + public void test_2_2() throws Exception { + assertEquals("-0.0", JSON.toJSONString(-0.0F)); + } + + public void test_2_3() throws Exception { + assertEquals("1.0", JSON.toJSONString(1.0)); + } + + public void test_2_4() throws Exception { + assertEquals("0.1", JSON.toJSONString(0.1)); + } + + public void test_2_5() throws Exception { + assertEquals("3.141592653589793", JSON.toJSONString(Math.PI)); + } + + public void test_2_6() throws Exception { + double doubeValue = Math.pow(Math.PI, 100); + assertEquals("5.187848314319592E49", JSON.toJSONString(doubeValue)); + } + + public void test_2_7() throws Exception { + double doubeValue = Math.pow(Math.PI, -100); + + String json = JSON.toJSONString(doubeValue); + // 1.9275814160560204E-50 + // 1.9275814160560206E-50 + assertTrue(json.equals("1.9275814160560206E-50") + || json.equals("1.9275814160560204E-50") // raspberry pi + ); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/comparing_json_modules/Integral_types_Test.java b/src/test/java/com/alibaba/json/bvt/comparing_json_modules/Integral_types_Test.java new file mode 100644 index 0000000000..3a30f20f0d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/comparing_json_modules/Integral_types_Test.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.comparing_json_modules; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 24/03/2017. + */ +public class Integral_types_Test extends TestCase { + public void test_1_1() throws Exception { + assertEquals("0", JSON.toJSONString(0)); + } + + public void test_1_2() throws Exception { + assertEquals("1", JSON.toJSONString(1)); + } + + public void test_1_3() throws Exception { + assertEquals("123456789", JSON.toJSONString(123456789)); + } + + public void test_1_4() throws Exception { + assertEquals("-123456789", JSON.toJSONString(-123456789)); + } + + public void test_1_5() throws Exception { + assertEquals("2147483647", JSON.toJSONString(Integer.MAX_VALUE)); + } + + public void test_1_6() throws Exception { + String text = "-9999999999999999999943"; + assertEquals(text, JSON.toJSONString(JSON.parse(text))); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/comparing_json_modules/Invalid_Test.java b/src/test/java/com/alibaba/json/bvt/comparing_json_modules/Invalid_Test.java new file mode 100644 index 0000000000..e013b9f86e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/comparing_json_modules/Invalid_Test.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.comparing_json_modules; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 25/03/2017. + */ +public class Invalid_Test extends TestCase { + public void test_6_1() throws Exception { + assertEquals(0, JSON.parse("+0")); + } + +// public void test_6_5() throws Exception { +// assertEquals(28, JSON.parse("034")); +// } +} diff --git a/src/test/java/com/alibaba/json/bvt/compatible/ThreadLocalCacheTest.java b/src/test/java/com/alibaba/json/bvt/compatible/ThreadLocalCacheTest.java new file mode 100644 index 0000000000..deb7db82e9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/compatible/ThreadLocalCacheTest.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.compatible; + +import com.alibaba.fastjson.util.ThreadLocalCache; +import junit.framework.TestCase; + +/** + * Created by wenshao on 29/01/2017. + */ +public class ThreadLocalCacheTest extends TestCase{ + public void test_threadCache() throws Exception { + ThreadLocalCache.getBytes(10); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/compatible/TypeUtilsComputeGettersTest.java b/src/test/java/com/alibaba/json/bvt/compatible/TypeUtilsComputeGettersTest.java new file mode 100644 index 0000000000..c035962ad7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/compatible/TypeUtilsComputeGettersTest.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.compatible; + +import com.alibaba.fastjson.util.FieldInfo; +import com.alibaba.fastjson.util.TypeUtils; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 20/03/2017. + */ +public class TypeUtilsComputeGettersTest extends TestCase { + public void test_for_computeGetters() { + List fieldInfoList = TypeUtils.computeGetters(Model.class, null); + assertEquals(1, fieldInfoList.size()); + assertEquals("id", fieldInfoList.get(0).name); + } + + public static class Model { + private int id; + + public int getId() { + return id; + } + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/compatible/jsonlib/CompatibleTest0.java b/src/test/java/com/alibaba/json/bvt/compatible/jsonlib/CompatibleTest0.java old mode 100644 new mode 100755 similarity index 99% rename from src/test/java/com/alibaba/json/test/bvt/compatible/jsonlib/CompatibleTest0.java rename to src/test/java/com/alibaba/json/bvt/compatible/jsonlib/CompatibleTest0.java index 1f5e2d7d11..a3a26f0b64 --- a/src/test/java/com/alibaba/json/test/bvt/compatible/jsonlib/CompatibleTest0.java +++ b/src/test/java/com/alibaba/json/bvt/compatible/jsonlib/CompatibleTest0.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.compatible.jsonlib; +package com.alibaba.json.bvt.compatible.jsonlib; import java.math.BigDecimal; import java.math.BigInteger; @@ -7,7 +7,7 @@ import java.util.List; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/compatible/jsonlib/CompatibleTest_noasm.java b/src/test/java/com/alibaba/json/bvt/compatible/jsonlib/CompatibleTest_noasm.java old mode 100644 new mode 100755 similarity index 99% rename from src/test/java/com/alibaba/json/test/bvt/compatible/jsonlib/CompatibleTest_noasm.java rename to src/test/java/com/alibaba/json/bvt/compatible/jsonlib/CompatibleTest_noasm.java index 189887bfdb..e4c0b72ff4 --- a/src/test/java/com/alibaba/json/test/bvt/compatible/jsonlib/CompatibleTest_noasm.java +++ b/src/test/java/com/alibaba/json/bvt/compatible/jsonlib/CompatibleTest_noasm.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.compatible.jsonlib; +package com.alibaba.json.bvt.compatible.jsonlib; import java.math.BigDecimal; import java.math.BigInteger; @@ -7,7 +7,7 @@ import java.util.List; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/date/CalendarTest.java b/src/test/java/com/alibaba/json/bvt/date/CalendarTest.java new file mode 100644 index 0000000000..0f91fb2aba --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/CalendarTest.java @@ -0,0 +1,66 @@ +package com.alibaba.json.bvt.date; + +import java.util.Calendar; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class CalendarTest extends TestCase { + + public void test_null() throws Exception { + String text = "{\"calendar\":null}"; + + VO vo = JSON.parseObject(text, VO.class); + Assert.assertNull(vo.getCalendar()); + } + + public void test_codec() throws Exception { + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + VO vo = new VO(); + vo.setCalendar(calendar); + String text = JSON.toJSONString(vo); + + VO vo2 = JSON.parseObject(text, VO.class); + Assert.assertEquals(vo.getCalendar().getTimeInMillis(), vo2.getCalendar().getTimeInMillis()); + } + + public void test_codec_iso88591() throws Exception { + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + VO vo = new VO(); + vo.setCalendar(calendar); + String text = JSON.toJSONString(vo, SerializerFeature.UseISO8601DateFormat); + + VO vo2 = JSON.parseObject(text, VO.class); + Assert.assertEquals(vo.getCalendar().getTimeInMillis(), vo2.getCalendar().getTimeInMillis()); + } + + public void test_codec_iso88591_2() throws Exception { + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + VO vo = new VO(); + vo.setCalendar(calendar); + String text = JSON.toJSONString(vo, SerializerFeature.UseISO8601DateFormat); + + VO vo2 = JSON.parseObject(text, VO.class); + Assert.assertEquals(vo.getCalendar().getTimeInMillis(), vo2.getCalendar().getTimeInMillis()); + } + + public static class VO { + + private Calendar calendar; + + public Calendar getCalendar() { + return calendar; + } + + public void setCalendar(Calendar calendar) { + this.calendar = calendar; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateFieldFormatTest.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldFormatTest.java new file mode 100644 index 0000000000..6a3a3b1194 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldFormatTest.java @@ -0,0 +1,71 @@ +package com.alibaba.json.bvt.date; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; +import org.junit.Assert; + +public class DateFieldFormatTest extends TestCase { + + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_format_() throws Exception { + Date now = new Date(); + Model model = new Model(); + model.serverTime = now; + model.publishTime = now; + model.setStartDate( now ); + + String text = JSON.toJSONString(model); + System.out.println(text); + + SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); + SimpleDateFormat df2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA); + SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA); + + df1.setTimeZone(JSON.defaultTimeZone); + df2.setTimeZone(JSON.defaultTimeZone); + df3.setTimeZone(JSON.defaultTimeZone); + + String t1 = df1.format(now); + String t2 = df2.format(now); + String t3 = df3.format(now); + + Assert.assertEquals("{\"publishTime\":\""+t2+"\",\"serverTime\":\""+t1+"\",\"startDate\":\""+t3+"\"}",text); + + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(t2,new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA).format(model2.publishTime)); + Assert.assertEquals(t1,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(model2.serverTime)); + Assert.assertEquals(t3,new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(model2.getStartDate())); + + } + + public static class Model { + + @JSONField(format = "yyyy-MM-dd HH:mm:ss") + public Date serverTime; + + @JSONField(format = "yyyy/MM/dd HH:mm:ss") + public Date publishTime; + + @JSONField(format = "yyyy-MM-dd") + private Date startDate; + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/DateFieldTest.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/DateFieldTest.java rename to src/test/java/com/alibaba/json/bvt/date/DateFieldTest.java index fb31fda7d6..e2e8692bfb --- a/src/test/java/com/alibaba/json/test/bvt/DateFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt.date; import java.util.Date; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/date/DateFieldTest10.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest10.java new file mode 100644 index 0000000000..1590726b20 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest10.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt.date; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + * Created by wenshao on 07/04/2017. + */ +public class DateFieldTest10 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_zero() throws Exception { + String text = "{\"date\":\"0000-00-00\"}"; + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Object object = format.parse("0000-00-00"); + JSON.parseObject(text, Model.class); + } + + public void test_1() throws Exception { + String text = "{\"date\":\"2017-08-14 19:05:30.000|America/Los_Angeles\"}"; + JSON.parseObject(text, Model.class); + } + + public void test_2() throws Exception { + String text = "{\"date\":\"2017-08-16T04:29Z\"}"; + Model model = JSON.parseObject(text, Model.class); + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + Object object = format.parse("2017-08-16 04:29"); +// assertEquals(object, model.date); + } + + public void test_3() throws Exception { + String text = "{\"date\":\"2017-08-16 04:29\"}"; + Model model = JSON.parseObject(text, Model.class); + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + Object object = format.parse("2017-08-16 04:29"); +// assertEquals(object, model.date); + } + + public void test_4() throws Exception { + String text = "{\"date\":\"2017-08-16T04:29\"}"; + Model model = JSON.parseObject(text, Model.class); + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + Object object = format.parse("2017-08-16 04:29"); +// assertEquals(object, model.date); + } + + public static class Model { + public Date date; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateFieldTest11_reader.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest11_reader.java new file mode 100644 index 0000000000..22008a5f9a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest11_reader.java @@ -0,0 +1,79 @@ +package com.alibaba.json.bvt.date; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.io.StringReader; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + * Created by wenshao on 07/04/2017. + */ +public class DateFieldTest11_reader extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_cn() throws Exception { + Model vo = new JSONReader(new StringReader("{\"date0\":\"2016-05-06\",\"date1\":\"2017-03-01\"}")).readObject(Model.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + + calendar.setTime(vo.date0); + assertEquals(2016, calendar.get(Calendar.YEAR)); + assertEquals(4, calendar.get(Calendar.MONTH)); + assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + assertEquals(0, calendar.get(Calendar.MILLISECOND)); + + calendar.setTime(vo.date1); + assertEquals(2017, calendar.get(Calendar.YEAR)); + assertEquals(2, calendar.get(Calendar.MONTH)); + assertEquals(1, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_cn_1() throws Exception { + Model vo = new JSONReader(new StringReader("{\"date0\":1462464000000,\"date1\":1488297600000}")).readObject(Model.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + + calendar.setTime(vo.date0); + assertEquals(2016, calendar.get(Calendar.YEAR)); + assertEquals(4, calendar.get(Calendar.MONTH)); + assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + assertEquals(0, calendar.get(Calendar.MILLISECOND)); + + calendar.setTime(vo.date1); + assertEquals(2017, calendar.get(Calendar.YEAR)); + assertEquals(2, calendar.get(Calendar.MONTH)); + assertEquals(1, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + assertEquals(0, calendar.get(Calendar.MILLISECOND)); + + System.out.println(vo.date0.getTime()); + System.out.println(vo.date1.getTime()); + } + + public static class Model { + public Date date0; + public Date date1; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateFieldTest2.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest2.java new file mode 100755 index 0000000000..9397a3b59d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest2.java @@ -0,0 +1,103 @@ +package com.alibaba.json.bvt.date; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class DateFieldTest2 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_codec() throws Exception { + SerializeConfig mapping = new SerializeConfig(); + + V0 v = new V0(); + v.setValue(new Date()); + + String text = JSON.toJSONString(v, mapping); + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":" + JSON.toJSONString(format.format(v.getValue())) + "}", text); + } + + public void test_codec_no_asm() throws Exception { + V0 v = new V0(); + v.setValue(new Date()); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":" + JSON.toJSONString(format.format(v.getValue())) + "}", text); + } + + public void test_codec_asm() throws Exception { + V0 v = new V0(); + v.setValue(new Date()); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(true); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":" + JSON.toJSONString(format.format(v.getValue())) + "}", text); + } + + public void test_codec_null_asm() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(true); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"value\":null}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_codec_null_1() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero); + Assert.assertEquals("{\"value\":null}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(null, v1.getValue()); + } + + public static class V0 { + + @JSONField(format = "yyyy-MM-dd") + private Date value; + + public Date getValue() { + return value; + } + + public void setValue(Date value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateFieldTest3.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest3.java new file mode 100755 index 0000000000..44d4ba8b8e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest3.java @@ -0,0 +1,121 @@ +package com.alibaba.json.bvt.date; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; + +public class DateFieldTest3 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_codec() throws Exception { + SerializeConfig mapping = new SerializeConfig(); + mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); + + V0 v = new V0(); + v.setValue(new Date()); + + String text = JSON.toJSONString(v, mapping); + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":" + JSON.toJSONString(format.format(v.getValue())) + "}", text); + } + + public void test_codec_no_asm() throws Exception { + V0 v = new V0(); + v.setValue(new Date()); + + SerializeConfig mapping = new SerializeConfig(); + mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":" + JSON.toJSONString(format.format(v.getValue())) + "}", text); + } + + public void test_codec_asm() throws Exception { + V0 v = new V0(); + v.setValue(new Date()); + + SerializeConfig mapping = new SerializeConfig(); + mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); + mapping.setAsmEnable(true); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":" + JSON.toJSONString(format.format(v.getValue())) + "}", text); + } + + public void test_codec_null_asm() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(true); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); + Assert.assertEquals("{\"value\":null}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_codec_null_no_asm() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"value\":null}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_codec_null_1() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero); + Assert.assertEquals("{\"value\":null}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(null, v1.getValue()); + } + + public static class V0 { + + private Date value; + + public Date getValue() { + return value; + } + + public void setValue(Date value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateFieldTest4.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest4.java new file mode 100755 index 0000000000..e30d22f49a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest4.java @@ -0,0 +1,103 @@ +package com.alibaba.json.bvt.date; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class DateFieldTest4 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_codec() throws Exception { + SerializeConfig mapping = new SerializeConfig(); + + V0 v = new V0(); + v.setValue(new Date()); + + String text = JSON.toJSONString(v, mapping); + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":" + JSON.toJSONString(format.format(v.getValue())) + "}", text); + } + + public void test_codec_no_asm() throws Exception { + V0 v = new V0(); + v.setValue(new Date()); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":" + JSON.toJSONString(format.format(v.getValue())) + "}", text); + } + + public void test_codec_asm() throws Exception { + V0 v = new V0(); + v.setValue(new Date()); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(true); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":" + JSON.toJSONString(format.format(v.getValue())) + "}", text); + } + + public void test_codec_null_asm() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(true); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"value\":null}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(v1.getValue(), v.getValue()); + } + + public void test_codec_null_1() throws Exception { + V0 v = new V0(); + + SerializeConfig mapping = new SerializeConfig(); + mapping.setAsmEnable(false); + + String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero); + Assert.assertEquals("{\"value\":null}", text); + + V0 v1 = JSON.parseObject(text, V0.class); + + Assert.assertEquals(null, v1.getValue()); + } + + public static class V0 { + + private Date value; + + @JSONField(format = "yyyy-MM-dd") + public Date getValue() { + return value; + } + + public void setValue(Date value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/DateFieldTest5.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest5.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/DateFieldTest5.java rename to src/test/java/com/alibaba/json/bvt/date/DateFieldTest5.java index 0d7efbea69..36e0b00b63 --- a/src/test/java/com/alibaba/json/test/bvt/DateFieldTest5.java +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest5.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt.date; import java.util.Date; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/date/DateFieldTest6.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest6.java new file mode 100755 index 0000000000..bac1067354 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest6.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.date; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; + +public class DateFieldTest6 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_0() throws Exception { + SerializeConfig mapping = new SerializeConfig(); + mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); + + Entity object = new Entity(); + object.setValue(new Date()); + String text = JSON.toJSONString(object, mapping); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":\"" + format.format(object.getValue()) + "\"}", text); + } + + public static class Entity { + private Date value; + + public Date getValue() { + return value; + } + + public void setValue(Date value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateFieldTest7.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest7.java new file mode 100755 index 0000000000..560b39c047 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest7.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.date; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; + +public class DateFieldTest7 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_0() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); + config.setAsmEnable(false); + + Entity object = new Entity(); + object.setValue(new Date()); + String text = JSON.toJSONString(object, config); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":\"" + format.format(object.getValue()) + "\"}", text); + } + + public static class Entity { + private Date value; + + public Date getValue() { + return value; + } + + public void setValue(Date value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateFieldTest8.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest8.java new file mode 100644 index 0000000000..05f6e13583 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest8.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.date; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class DateFieldTest8 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_0() throws Exception { + Entity object = new Entity(); + object.setValue(new Date()); + String text = JSON.toJSONStringWithDateFormat(object, "yyyy"); + SimpleDateFormat format = new SimpleDateFormat("yyyy", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":\"" + format.format(object.getValue()) + "\"}", + text); + } + + public void test_1() throws Exception { + Entity object = new Entity(); + object.setValue(new Date()); + String text = JSON.toJSONString(object); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals("{\"value\":\"" + format.format(object.getValue()) + "\"}", + text); + } + + public static class Entity { + + @JSONField(format = "yyyy-MM-dd") + private Date value; + + public Date getValue() { + return value; + } + + public void setValue(Date value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateFieldTest9.java b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest9.java new file mode 100644 index 0000000000..9f775e368b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateFieldTest9.java @@ -0,0 +1,193 @@ +package com.alibaba.json.bvt.date; + +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class DateFieldTest9 extends TestCase { + + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_tw() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"2016/05/06\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_cn() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"2016-05-06\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_cn_1() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"2016年5月6日\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_cn_2() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"2016年5月06日\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_cn_3() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"2016年05月6日\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_cn_4() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"2016年05月06日\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_kr_1() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"2016년5월6일\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_kr_2() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"2016년5월06일\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_kr_3() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"2016년05월6일\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_kr_4() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"2016년05월06일\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_de() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"06.05.2016\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public void test_in() throws Exception { + Entity vo = JSON.parseObject("{\"date\":\"06-05-2016\"}", Entity.class); + + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(vo.date); + Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + Assert.assertEquals(4, calendar.get(Calendar.MONTH)); + Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH)); + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } + + public static class Entity { + + public Date date; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateNewTest.java b/src/test/java/com/alibaba/json/bvt/date/DateNewTest.java new file mode 100644 index 0000000000..4a0df1e40b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateNewTest.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.date; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class DateNewTest extends TestCase { + public void test_date() throws Exception { + Assert.assertEquals(1324138987429L, ((Date) JSON.parse("new Date(1324138987429)")).getTime()); + Assert.assertEquals(1324138987429L, ((Date) JSON.parse("new \n\t\r\f\bDate(1324138987429)")).getTime()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateTest.java b/src/test/java/com/alibaba/json/bvt/date/DateTest.java new file mode 100755 index 0000000000..46999d219a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.date; + +import java.util.Date; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class DateTest extends TestCase { + + public void test_date() throws Exception { + long millis = 1324138987429L; + Date date = new Date(millis); + + Assert.assertEquals("1324138987429", JSON.toJSONString(date)); + Assert.assertEquals("new Date(1324138987429)", JSON.toJSONString(date, SerializerFeature.WriteClassName)); + + Assert.assertEquals("\"2011-12-18 00:23:07\"", + JSON.toJSONString(date, SerializerFeature.WriteDateUseDateFormat)); + Assert.assertEquals("\"2011-12-18 00:23:07.429\"", + JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss.SSS")); + Assert.assertEquals("'2011-12-18 00:23:07.429'", + JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss.SSS", + SerializerFeature.UseSingleQuotes)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateTest1.java b/src/test/java/com/alibaba/json/bvt/date/DateTest1.java new file mode 100644 index 0000000000..5b73841ea6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateTest1.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.date; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by wenshao on 16/8/23. + */ +public class DateTest1 extends TestCase { + public void test_date() throws Exception { + Model model = new Model(); + model.date = new Date(1471939192128L); + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"date\":1471939192128}", text); + + Map map = new HashMap(); + map.put("date", new Date(1471939192128L)); + + String text2 = JSON.toJSONString(map); + Assert.assertEquals("{\"date\":1471939192128}", text); + } + + public static class Model { + public Date date; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet.java b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet.java new file mode 100644 index 0000000000..8db9a9cfbe --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.date; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class DateTest_dotnet extends TestCase { + public void test_date() throws Exception { + String text = "{\"date\":\"/Date(1461081600000)/\"}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(1461081600000L, model.date.getTime()); + } + + public static class Model { + public Date date; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_1.java b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_1.java new file mode 100644 index 0000000000..28543fd45e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_1.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.date; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class DateTest_dotnet_1 extends TestCase { + + public void test_date() throws Exception { + String text = "{\"date\":\"/Date(1461081600000)/\"}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(1461081600000L, model.date.getTime()); + } + + public static class Model { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_2.java b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_2.java new file mode 100644 index 0000000000..0869ac540a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_2.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.date; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class DateTest_dotnet_2 extends TestCase { + + public void test_date() throws Exception { + String text = "{\"date\":\"/Date(1461081600000+0500)/\"}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(1461081600000L, model.date.getTime()); + } + + public static class Model { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_3.java b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_3.java new file mode 100644 index 0000000000..303226aa97 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_3.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.date; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class DateTest_dotnet_3 extends TestCase { + + public void test_date() throws Exception { + String text = "{\"date\":\"/Date(1461081600321+0500)/\"}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(1461081600321L, model.date.getTime()); + } + + private static class Model { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_4.java b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_4.java new file mode 100644 index 0000000000..5b5733cede --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_4.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.date; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class DateTest_dotnet_4 extends TestCase { + + public void test_date() throws Exception { + String text = "{\"date\":\"/Date(1461081600321+5000)/\"}"; + + JSONObject model = JSON.parseObject(text); + Assert.assertEquals(1461081600321L, ((java.util.Date) model.getObject("date", java.util.Date.class)).getTime()); + } + + private static class Model { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_5.java b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_5.java new file mode 100644 index 0000000000..a3fb5612c0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_5.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.date; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class DateTest_dotnet_5 extends TestCase { + + public void test_date() throws Exception { + String text = "{\"date\":\"/Date(1461081600321)/\"}"; + + JSONObject model = JSON.parseObject(text); + Assert.assertEquals(1461081600321L, ((java.util.Date) model.getObject("date", java.util.Date.class)).getTime()); + } + + private static class Model { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateTest_error.java b/src/test/java/com/alibaba/json/bvt/date/DateTest_error.java new file mode 100644 index 0000000000..caf43f4258 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateTest_error.java @@ -0,0 +1,87 @@ +package com.alibaba.json.bvt.date; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class DateTest_error extends TestCase { + + + public void test_error() throws Exception { + String text = "{\"value\":true}"; + + Exception error = null; + try { + JSON.parseObject(text, Date.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + + public void test_error_1() throws Exception { + String text = "{1:true}"; + + Exception error = null; + try { + JSON.parseObject(text, Date.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + String text = "{\"@type\":\"java.util.Date\",\"value\":true}"; + + Exception error = null; + try { + JSON.parseObject(text, Date.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + String text = "{\"@type\":\"java.util.Date\",\"value\":true}"; + + Exception error = null; + try { + JSON.parseObject(text); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_4() throws Exception { + String text = "{\"@type\":\"java.util.Date\",1:true}"; + + Exception error = null; + try { + JSON.parseObject(text); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_5() throws Exception { + String text = "\"xxxxxxxxx\""; + + Exception error = null; + try { + JSON.parseObject(text, Date.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/DateTest_tz.java b/src/test/java/com/alibaba/json/bvt/date/DateTest_tz.java new file mode 100644 index 0000000000..2a1b026d9f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/DateTest_tz.java @@ -0,0 +1,43 @@ +package com.alibaba.json.bvt.date; + +import java.io.StringReader; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +import junit.framework.TestCase; + +public class DateTest_tz extends TestCase { +// protected void setUp() throws Exception { +// JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); +// JSON.defaultLocale = Locale.CHINA; +// } + + public void test_codec() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"value\":\"2016-04-29\"}")); + reader.setLocale(Locale.CHINA); + reader.setTimzeZone(TimeZone.getTimeZone("Asia/Shanghai")); + + Model model = reader.readObject(Model.class); + Assert.assertNotNull(model.value); + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA); + format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); + Date date = format.parse("2016-04-29"); + Assert.assertEquals(date.getTime(), model.value.getTime()); + + Assert.assertEquals(TimeZone.getTimeZone("Asia/Shanghai"), reader.getTimzeZone()); + Assert.assertEquals(Locale.CHINA, reader.getLocal()); + + reader.close(); + } + + public static class Model { + public Date value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/date/XMLGregorianCalendarTest.java b/src/test/java/com/alibaba/json/bvt/date/XMLGregorianCalendarTest.java new file mode 100644 index 0000000000..b98f4bdb6e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/date/XMLGregorianCalendarTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.date; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; +import org.junit.Assert; + +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.util.GregorianCalendar; + +public class XMLGregorianCalendarTest extends TestCase { + public void test_for_issue() throws Exception { + GregorianCalendar gregorianCalendar = (GregorianCalendar) GregorianCalendar.getInstance(); + + XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar); + + String text = JSON.toJSONString(calendar); + Assert.assertEquals(Long.toString(gregorianCalendar.getTimeInMillis()), text); + + XMLGregorianCalendar calendar1 = JSON.parseObject(text, XMLGregorianCalendar.class); + + assertEquals(calendar.toGregorianCalendar().getTimeInMillis(), calendar1.toGregorianCalendar().getTimeInMillis()); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("calendar", calendar); + + String json = JSON.toJSONString(jsonObject); + + Model model = JSON.parseObject(json).toJavaObject(Model.class); + + assertEquals(calendar.toGregorianCalendar().getTimeInMillis(), model.calendar.toGregorianCalendar().getTimeInMillis()); + } + + public static class Model { + public XMLGregorianCalendar calendar; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/dubbo/TestForDubbo.java b/src/test/java/com/alibaba/json/bvt/dubbo/TestForDubbo.java new file mode 100755 index 0000000000..70a26d3421 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/dubbo/TestForDubbo.java @@ -0,0 +1,83 @@ +package com.alibaba.json.bvt.dubbo; + +import java.util.ArrayList; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.test.dubbo.FullAddress; +import com.alibaba.json.test.dubbo.HelloServiceImpl; +import com.alibaba.json.test.dubbo.Person; +import com.alibaba.json.test.dubbo.PersonInfo; +import com.alibaba.json.test.dubbo.PersonStatus; +import com.alibaba.json.test.dubbo.Phone; +import com.alibaba.json.test.dubbo.Tiger; +import com.alibaba.json.test.dubbo.Tigers; + +public class TestForDubbo extends TestCase { + + static Person person; + + static { + person = new Person(); + person.setPersonId("superman111"); + person.setLoginName("superman"); + person.setEmail("sm@1.com"); + person.setPenName("pname"); + person.setStatus(PersonStatus.ENABLED); + + ArrayList phones = new ArrayList(); + Phone phone1 = new Phone("86", "0571", "87654321", "001"); + Phone phone2 = new Phone("86", "0571", "87654322", "002"); + phones.add(phone1); + phones.add(phone2); + PersonInfo pi = new PersonInfo(); + pi.setPhones(phones); + Phone fax = new Phone("86", "0571", "87654321", null); + pi.setFax(fax); + FullAddress addr = new FullAddress("CN", "zj", "3480", "wensanlu", "315000"); + pi.setFullAddress(addr); + pi.setMobileNo("13584652131"); + pi.setMale(true); + pi.setDepartment("b2b"); + pi.setHomepageUrl("www.capcom.com"); + pi.setJobTitle("qa"); + pi.setName("superman"); + person.setInfoProfile(pi); + } + + private HelloServiceImpl helloService = new HelloServiceImpl(); + + public void f_testParamType4() { + Tiger tiger = new Tiger(); + tiger.setTigerName("东北虎"); + tiger.setTigerSex(true); + Tigers tigers = helloService.eatTiger(tiger); + + String text = JSON.toJSONString(tigers, SerializerFeature.WriteClassName); + System.out.println(text); + + Tigers tigers2 = JSON.parseObject(text, Tigers.class); + + Assert.assertEquals(text, JSON.toJSONString(tigers2, SerializerFeature.WriteClassName)); + } + + public void testPerson() { + Person p = helloService.showPerson(person); + String text = JSON.toJSONString(p, SerializerFeature.WriteClassName); + System.out.println(text); + + Person result = JSON.parseObject(text, Person.class); + + assertEquals(result.getInfoProfile().getPhones().get(0).getArea(), + person.getInfoProfile().getPhones().get(0).getArea()); + assertEquals(result.getInfoProfile().getPhones().get(0).getCountry(), + person.getInfoProfile().getPhones().get(0).getCountry()); + assertEquals(result.getInfoProfile().getPhones().get(0).getExtensionNumber(), + person.getInfoProfile().getPhones().get(0).getExtensionNumber()); + assertEquals(result.getInfoProfile().getPhones().get(0).getNumber(), + person.getInfoProfile().getPhones().get(0).getNumber()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/emoji/EmojiTest0.java b/src/test/java/com/alibaba/json/bvt/emoji/EmojiTest0.java new file mode 100644 index 0000000000..02158760e5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/emoji/EmojiTest0.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.emoji; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.io.ByteArrayOutputStream; + +/** + * Created by wenshao on 13/04/2017. + */ +public class EmojiTest0 extends TestCase { + public void test_for_emoji() throws Exception { + Model model = new Model(); + model.value = "An 😀awesome 😃string with a few 😉emojis!"; + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + JSON.writeJSONString(out, model); + + String text = new String(out.toByteArray(), "UTF-8"); + System.out.println(text); + } + + public static class Model { + public String value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/DisableFieldSmartMatchTest.java b/src/test/java/com/alibaba/json/bvt/feature/DisableFieldSmartMatchTest.java new file mode 100644 index 0000000000..38ed95b1f2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/DisableFieldSmartMatchTest.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.feature; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 17/03/2017. + */ +public class DisableFieldSmartMatchTest extends TestCase { + public void test_feature() throws Exception { + assertEquals(123, JSON.parseObject("{\"person_id\":123}", Model_for_disableFieldSmartMatchMask.class).personId); + assertEquals(0, JSON.parseObject("{\"person_id\":123}", Model_for_disableFieldSmartMatchMask.class, Feature.DisableFieldSmartMatch).personId); + assertEquals(123, JSON.parseObject("{\"personId\":123}", Model_for_disableFieldSmartMatchMask.class, Feature.DisableFieldSmartMatch).personId); + } + + public void test_feature2() throws Exception { + assertEquals(0, JSON.parseObject("{\"person_id\":123}", Model_for_disableFieldSmartMatchMask2.class).personId); + assertEquals(123, JSON.parseObject("{\"personId\":123}", Model_for_disableFieldSmartMatchMask2.class).personId); + } + + public static class Model_for_disableFieldSmartMatchMask { + public int personId; + } + + @JSONType(parseFeatures = Feature.DisableFieldSmartMatch) + public static class Model_for_disableFieldSmartMatchMask2 { + public int personId; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/DisableFieldSmartMatchTest_2.java b/src/test/java/com/alibaba/json/bvt/feature/DisableFieldSmartMatchTest_2.java new file mode 100644 index 0000000000..b4e7a3037e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/DisableFieldSmartMatchTest_2.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.feature; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 17/03/2017. + */ +public class DisableFieldSmartMatchTest_2 extends TestCase { + public void test_feature() throws Exception { + assertEquals(123, JSON.parseObject("{\"person_id\":123}", Model_for_disableFieldSmartMatchMask.class).personId); + assertEquals(0, JSON.parseObject("{\"person_id\":123}", Model_for_disableFieldSmartMatchMask.class, Feature.DisableFieldSmartMatch).personId); + assertEquals(123, JSON.parseObject("{\"personId\":123}", Model_for_disableFieldSmartMatchMask.class, Feature.DisableFieldSmartMatch).personId); + } + + public void test_feature2() throws Exception { + assertEquals(0, JSON.parseObject("{\"person_id\":123}", Model_for_disableFieldSmartMatchMask2.class).personId); + assertEquals(123, JSON.parseObject("{\"personId\":123}", Model_for_disableFieldSmartMatchMask2.class).personId); + } + + public static class Model_for_disableFieldSmartMatchMask { + public int personId; + } + + public static class Model_for_disableFieldSmartMatchMask2 { + @JSONField(parseFeatures = Feature.DisableFieldSmartMatch) + public int personId; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/FeatureTest_8.java b/src/test/java/com/alibaba/json/bvt/feature/FeatureTest_8.java new file mode 100644 index 0000000000..ed5f0fc003 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/FeatureTest_8.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.feature; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class FeatureTest_8 extends TestCase { + public void test_get_obj() throws Exception { + VO value = JSON.parseObject("{}", VO.class, Feature.InitStringFieldAsEmpty); + Assert.assertEquals("", value.id); + } + + private static class VO { + public String id; + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/FeaturesTest.java b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/FeaturesTest.java rename to src/test/java/com/alibaba/json/bvt/feature/FeaturesTest.java index 97145c2b0a..10c52511e4 --- a/src/test/java/com/alibaba/json/test/bvt/FeaturesTest.java +++ b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt; +package com.alibaba.json.bvt.feature; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest2.java b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest2.java new file mode 100755 index 0000000000..1b0df7a7c7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest2.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.feature; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class FeaturesTest2 extends TestCase { + + public void test_0() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(false); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":0}", text); + } + + public void test_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(true); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":0}", text); + } + + private static class Entity { + + private Integer value; + + @JSONField(serialzeFeatures = { SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero }) + public Integer getValue() { + return value; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest3.java b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest3.java new file mode 100755 index 0000000000..464800f284 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest3.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.feature; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class FeaturesTest3 extends TestCase { + + public void test_0() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(false); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":0}", text); + } + + public void test_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(true); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":0}", text); + } + + public static class Entity { + + private Integer value; + + @JSONField(serialzeFeatures = { SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero }) + public Integer getValue() { + return value; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest4.java b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest4.java new file mode 100755 index 0000000000..c735d91a25 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest4.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.feature; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class FeaturesTest4 extends TestCase { + + public void test_0() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(false); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":\"\"}", text); + } + + public void test_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(true); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":\"\"}", text); + } + + public static class Entity { + + private String value; + + @JSONField(serialzeFeatures = { SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty }) + public String getValue() { + return value; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest5.java b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest5.java new file mode 100755 index 0000000000..946a21d9bb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest5.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.feature; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class FeaturesTest5 extends TestCase { + + public void test_0() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(false); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":false}", text); + } + + public void test_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(true); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":false}", text); + } + + public static class Entity { + + private Boolean value; + + @JSONField(serialzeFeatures = { SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse }) + public Boolean getValue() { + return value; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest5_1.java b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest5_1.java new file mode 100755 index 0000000000..bfb33b32c5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest5_1.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.feature; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; +import org.junit.Assert; + +public class FeaturesTest5_1 extends TestCase { + + public void test_0() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(false); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":false}", text); + } + + public void test_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(true); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":false}", text); + } + + public static class Entity { + + private Boolean value; + + @JSONField(serialzeFeatures = { SerializerFeature.WriteNullBooleanAsFalse }) + public Boolean getValue() { + return value; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest6.java b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest6.java new file mode 100755 index 0000000000..439b5bce72 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest6.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.feature; + +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class FeaturesTest6 extends TestCase { + + public void test_0() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(false); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":[]}", text); + } + + public void test_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(true); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":[]}", text); + } + + public static class Entity { + + private List value; + + @JSONField(serialzeFeatures = { SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty }) + public List getValue() { + return value; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest7.java b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest7.java new file mode 100755 index 0000000000..83d59f7b89 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/FeaturesTest7.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.feature; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class FeaturesTest7 extends TestCase { + + public void test_0() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(false); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":\"SECONDS\"}", text); + } + + public void test_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(true); + + String text = JSON.toJSONString(new Entity(), config); + Assert.assertEquals("{\"value\":\"SECONDS\"}", text); + } + + public static class Entity { + + private TimeUnit value = TimeUnit.SECONDS; + + @JSONField(serialzeFeatures = { SerializerFeature.WriteEnumUsingToString }) + public TimeUnit getValue() { + return value; + } + + + } + + public static enum TimeUnit { + SECONDS, MINUTES + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest.java b/src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest.java new file mode 100644 index 0000000000..c79cd666aa --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.feature; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class IgnoreErrorGetterTest extends TestCase { + + public void test_feature() throws Exception { + Model model = new Model(); + model.id = 1001; + String text = JSON.toJSONString(model, SerializerFeature.IgnoreErrorGetter); + Assert.assertEquals("{\"id\":1001}", text); + } + + public static class Model { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest_field.java b/src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest_field.java new file mode 100644 index 0000000000..17b6fa6c1e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest_field.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.feature; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class IgnoreErrorGetterTest_field extends TestCase { + + public void test_feature() throws Exception { + Model model = new Model(); + model.setId(1001); + String text = JSON.toJSONString(model, SerializerFeature.IgnoreErrorGetter); + Assert.assertEquals("{\"id\":1001}", text); + } + + public static class Model { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + throw new IllegalStateException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest_private.java b/src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest_private.java new file mode 100644 index 0000000000..3f9e034fef --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest_private.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.feature; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class IgnoreErrorGetterTest_private extends TestCase { + + public void test_feature() throws Exception { + Model model = new Model(); + model.setId(1001); + String text = JSON.toJSONString(model, SerializerFeature.IgnoreErrorGetter); + Assert.assertEquals("{\"id\":1001}", text); + } + + private static class Model { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + throw new IllegalStateException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/InitStringFieldAsEmptyTest.java b/src/test/java/com/alibaba/json/bvt/feature/InitStringFieldAsEmptyTest.java new file mode 100644 index 0000000000..8a277dbb13 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/InitStringFieldAsEmptyTest.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.feature; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class InitStringFieldAsEmptyTest extends TestCase { + public void test_0() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{}"); + parser.config(Feature.InitStringFieldAsEmpty, true); + Model model = parser.parseObject(Model.class); + Assert.assertEquals("", model.value); + parser.close(); + } + + public void test_1() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{}"); + parser.config(Feature.InitStringFieldAsEmpty, false); + Model model = parser.parseObject(Model.class); + Assert.assertNull(null, model.value); + parser.close(); + } + + public static class Model { + public Model() { + + } + public String value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/WriteNullStringAsEmptyTest.java b/src/test/java/com/alibaba/json/bvt/feature/WriteNullStringAsEmptyTest.java new file mode 100644 index 0000000000..a345fa8090 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/WriteNullStringAsEmptyTest.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.feature; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.PropertyFilter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 14/03/2017. + */ +public class WriteNullStringAsEmptyTest extends TestCase { + public void test_features() throws Exception { + PropertyFilter filter = new PropertyFilter() { + + public boolean apply(Object object, String name, Object value) { + if (value == null && object instanceof Model && "id".equals(name)) { + return false; + } + return true; + } + }; + + Model model = new Model(); + String json = JSON.toJSONString(model, filter, SerializerFeature.WriteNullStringAsEmpty); + System.out.println(json); + } + + + private static class Model { + @JSONField(serialzeFeatures = SerializerFeature.WriteNullStringAsEmpty) + public String id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/feature/WriteNullStringAsEmptyTest2.java b/src/test/java/com/alibaba/json/bvt/feature/WriteNullStringAsEmptyTest2.java new file mode 100644 index 0000000000..4bdec471d8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/feature/WriteNullStringAsEmptyTest2.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.feature; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.serializer.PropertyFilter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 14/03/2017. + */ +public class WriteNullStringAsEmptyTest2 extends TestCase { + public void test_features() throws Exception { + Model model = new Model(); + String json = JSON.toJSONString(model); + assertEquals("{\"id\":\"\"}", json); + } + + + public static class Model { + @JSONField(serialzeFeatures = SerializerFeature.WriteNullStringAsEmpty) + public String id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/fullSer/EmtpyLinkedHashMapTest.java b/src/test/java/com/alibaba/json/bvt/fullSer/EmtpyLinkedHashMapTest.java new file mode 100644 index 0000000000..75e0b8a556 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/fullSer/EmtpyLinkedHashMapTest.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.fullSer; + +import java.util.Map; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class EmtpyLinkedHashMapTest extends TestCase { + public void test_0() throws Exception { + Map map = (Map) JSON.parseObject("{\"@type\":\"java.util.LinkedHashMap\"}", Object.class); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/fullSer/LongTest.java b/src/test/java/com/alibaba/json/bvt/fullSer/LongTest.java new file mode 100755 index 0000000000..75a4034676 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/fullSer/LongTest.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.fullSer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class LongTest extends TestCase { + + public void test_0() throws Exception { + + VO vo = new VO(); + vo.setValue(33L); + + String text = JSON.toJSONString(vo, SerializerFeature.WriteClassName); + System.out.println(text); + + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.fullSer.LongTest$VO\",\"value\":33}", text); + } + + public static class VO { + + private Long value; + + public Long getValue() { + return value; + } + + public void setValue(Long value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/fullSer/ToJavaObjectTest.java b/src/test/java/com/alibaba/json/bvt/fullSer/ToJavaObjectTest.java new file mode 100644 index 0000000000..5fcd3d82fa --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/fullSer/ToJavaObjectTest.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.fullSer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +/** + * Created by wenshao on 04/02/2017. + */ +public class ToJavaObjectTest extends TestCase { + public void test_for_toJavaObject() throws Exception { + JSONObject obj = JSON.parseObject("{\"id\":123}"); + Model model = obj.toJavaObject(Model.class); + assertEquals(123, model.id); + } + + public static class Model { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/fullSer/ToJavaObjectTest2.java b/src/test/java/com/alibaba/json/bvt/fullSer/ToJavaObjectTest2.java new file mode 100644 index 0000000000..c3586dfda6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/fullSer/ToJavaObjectTest2.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.fullSer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.util.List; +import java.util.Map; + +/** + * Created by wenshao on 04/02/2017. + */ +public class ToJavaObjectTest2 extends TestCase { + public void test_for_toJavaObject() throws Exception { + JSONObject obj = JSON.parseObject("{\"model\":{\"id\":123}}"); + Map models = obj.toJavaObject(new TypeReference>(){}.getType()); + assertEquals(123, models.get("model").id); + } + + public static class Model { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/fullSer/get_set_Test.java b/src/test/java/com/alibaba/json/bvt/fullSer/get_set_Test.java new file mode 100644 index 0000000000..c1496a36e3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/fullSer/get_set_Test.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.fullSer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class get_set_Test extends TestCase { + + public void test_codec() throws Exception { + VO vo = new VO(); + vo.set_id(123); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123}", text); + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertEquals(123, vo1.get_id()); + } + + public static class VO { + + private int id; + + public int get_id() { + return id; + } + + public void set_id(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/fullSer/getfTest.java b/src/test/java/com/alibaba/json/bvt/fullSer/getfTest.java new file mode 100644 index 0000000000..2b9104e83f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/fullSer/getfTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.fullSer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvt.fullSer.get_set_Test.VO; + +public class getfTest extends TestCase { + + public void test_codec() throws Exception { + VO vo = new VO(); + vo.setfId(123); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"fId\":123}", text); + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertEquals(123, vo1.getfId()); + } + + public static class VO { + + private int fId; + + + public int getfId() { + return fId; + } + + + public void setfId(int fId) { + this.fId = fId; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/fullSer/getfTest_2.java b/src/test/java/com/alibaba/json/bvt/fullSer/getfTest_2.java new file mode 100644 index 0000000000..a167f2136f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/fullSer/getfTest_2.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.fullSer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvt.fullSer.get_set_Test.VO; + +public class getfTest_2 extends TestCase { + + public void test_codec() throws Exception { + VO vo = new VO(); + vo.setfFlag(true); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"fFlag\":true}", text); + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertEquals(true, vo1.isfFlag()); + } + + public static class VO { + + private boolean fFlag; + + public boolean isfFlag() { + return fFlag; + } + + public void setfFlag(boolean fFlag) { + this.fFlag = fFlag; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/fullSer/is_set_test_2.java b/src/test/java/com/alibaba/json/bvt/fullSer/is_set_test_2.java new file mode 100644 index 0000000000..3a9978b2ce --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/fullSer/is_set_test_2.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.fullSer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvt.fullSer.get_set_Test.VO; + +public class is_set_test_2 extends TestCase { + + public void test_codec() throws Exception { + VO vo = new VO(); + vo.set_flag(true); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"flag\":true}", text); + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertEquals(true, vo1.is_flag()); + } + + public static class VO { + + private boolean flag; + + public boolean is_flag() { + return flag; + } + + public void set_flag(boolean flag) { + this.flag = flag; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/guava/ArrayListMultimapTest.java b/src/test/java/com/alibaba/json/bvt/guava/ArrayListMultimapTest.java new file mode 100644 index 0000000000..1459cb4fb3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/guava/ArrayListMultimapTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.guava; + +import com.alibaba.fastjson.JSON; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.Multimaps; +import com.google.common.collect.TreeMultimap; +import com.google.common.primitives.Ints; +import junit.framework.TestCase; + +/** + * Created by wenshao on 15/01/2017. + */ +public class ArrayListMultimapTest extends TestCase { + public void test_for_multimap() throws Exception { + ArrayListMultimap multimap = ArrayListMultimap.create(); + multimap.putAll("b", Ints.asList(2, 4, 6)); + multimap.putAll("a", Ints.asList(4, 2, 1)); + multimap.putAll("c", Ints.asList(2, 5, 3)); + + + String json = JSON.toJSONString(multimap); + assertEquals("{\"a\":[4,2,1],\"b\":[2,4,6],\"c\":[2,5,3]}", json); + + TreeMultimap treeMultimap = TreeMultimap.create(multimap); + String json2 = JSON.toJSONString(treeMultimap); + assertEquals("{\"a\":[1,2,4],\"b\":[2,4,6],\"c\":[2,3,5]}", json2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/guava/HashMultimapTest.java b/src/test/java/com/alibaba/json/bvt/guava/HashMultimapTest.java new file mode 100644 index 0000000000..bdd8872636 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/guava/HashMultimapTest.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.guava; + +import com.alibaba.fastjson.JSON; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.HashMultimap; +import com.google.gson.Gson; +import junit.framework.TestCase; + +/** + * Created by wenshao on 15/01/2017. + */ +public class HashMultimapTest extends TestCase { + public void test_for_multimap() throws Exception { + HashMultimap map = HashMultimap.create(); + map.put("name", "a"); + map.put("name", "b"); + + String json = JSON.toJSONString(map); + assertEquals("{\"name\":[\"a\",\"b\"]}", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/guava/ImmutableMapTest.java b/src/test/java/com/alibaba/json/bvt/guava/ImmutableMapTest.java new file mode 100644 index 0000000000..26cbb8b7bc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/guava/ImmutableMapTest.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.guava; + +import com.alibaba.fastjson.JSON; +import com.google.common.collect.ImmutableMap; +import junit.framework.TestCase; + +import java.util.Map; + +/** + * Created by wenshao on 15/01/2017. + */ +public class ImmutableMapTest extends TestCase { + public void test_immutableMap() throws Exception { + Map map = ImmutableMap.of("a", 1, "b", 2, "c", 3); + String json = JSON.toJSONString(map); + assertEquals("{\"a\":1,\"b\":2,\"c\":3}", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/guava/LinkedListMultimapTest.java b/src/test/java/com/alibaba/json/bvt/guava/LinkedListMultimapTest.java new file mode 100644 index 0000000000..ad1c3fb88e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/guava/LinkedListMultimapTest.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.guava; + +import com.alibaba.fastjson.JSON; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.LinkedListMultimap; +import junit.framework.TestCase; + +/** + * Created by wenshao on 15/01/2017. + */ +public class LinkedListMultimapTest extends TestCase { + public void test_for_multimap() throws Exception { + LinkedListMultimap map = LinkedListMultimap.create(); + map.put("name", "a"); + map.put("name", "b"); + + String json = JSON.toJSONString(map); + assertEquals("{\"name\":[\"a\",\"b\"]}", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/guava/MultiMapTes.java b/src/test/java/com/alibaba/json/bvt/guava/MultiMapTes.java new file mode 100644 index 0000000000..8fd885e9fa --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/guava/MultiMapTes.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.guava; + +import com.alibaba.fastjson.JSON; +import com.google.common.collect.*; +import junit.framework.TestCase; + +import java.util.Map; + +/** + * Created by wenshao on 15/01/2017. + */ +public class MultiMapTes extends TestCase { + + public void test_multimap() throws Exception { + Map map = ImmutableMap.of("a", 1, "b", 1, "c", 2); + SetMultimap multimap = Multimaps.forMap(map); + Multimap inverse = Multimaps.invertFrom(multimap, HashMultimap.create()); + String json = JSON.toJSONString(inverse); + assertEquals("{1:[\"a\",\"b\"],2:[\"c\"]}",json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1066.java b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1066.java new file mode 100644 index 0000000000..4c82e31cd3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1066.java @@ -0,0 +1,97 @@ +package com.alibaba.json.bvt.issue_1000; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONWriter; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.Charset; +import java.nio.charset.CodingErrorAction; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by wenshao on 25/03/2017. + */ +public class Issue1066 extends TestCase { + private static final Charset CHARSET = Charset.forName("UTF-8"); + + public void test_for_issue() throws Exception { + Map map = new HashMap(); + map.put(EnumType.ONE, EnumType.TWO); + + System.out.println("序列化前的参数为:" + map); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try{ + serialize(map, bos); + + Object desRes = deserialize(bos.toByteArray()); + System.out.println("反序列化后的结果为:" + JSON.toJSONString(desRes)); + }finally { + try{ + bos.close(); + }catch (IOException e){ + } + } + } + + public static void serialize(T obj, OutputStream out) { + JSONWriter writer = null; + try { + writer = new JSONWriter(new OutputStreamWriter(out, CHARSET.newEncoder().onMalformedInput(CodingErrorAction.IGNORE))); + writer.config(SerializerFeature.QuoteFieldNames, true); + writer.config(SerializerFeature.SkipTransientField, true); + writer.config(SerializerFeature.SortField, true); + writer.config(SerializerFeature.WriteClassName, true); + writer.config(SerializerFeature.DisableCircularReferenceDetect, true); + writer.writeObject(obj); + writer.flush(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (writer != null) { + try { + writer.close(); + } catch (Exception e) { + } + } + } + } + + public static T deserialize(byte[] in) { + return (T) JSON.parse(in, 0, in.length, CHARSET.newDecoder(), Feature.AllowArbitraryCommas, + Feature.IgnoreNotMatch, Feature.SortFeidFastMatch, Feature.DisableCircularReferenceDetect, + Feature.AutoCloseSource); + } + + public static enum EnumType { + + ONE(1, "1"), + + TWO(2, "2") + ; + + private int code; + private String desc; + + EnumType(int code, String desc){ + this.code = code; + this.desc = desc; + } + + @Override + public String toString() { + return "EnumType{" + + "code=" + code + + ", desc='" + desc + '\'' + + '}'; + } + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1079.java b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1079.java new file mode 100644 index 0000000000..de244249ab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1079.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.issue_1000; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonIgnore; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 17/03/2017. + */ +public class Issue1079 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\n" + + "\t\"Response\": [{\n" + + "\t\t\"Status\": {\n" + + "\t\t\t\"StatusCode\": {\n" + + "\t\t\t\t\"Value\": \"urn:oasis:names:tc:xacml:1.0:status:ok\"\n" + + "\t\t\t}\n" + + "\t\t},\n" + + "\t\t\"Decision\": \"NotApplicable\"\n" + + "\t}]\n" + + "}"; + + JSON.parseObject(text, PdpResponse.class); + + } + + public static class PdpResponse { + + @JSONField(name ="Response") + public List response; + + public static class Response { + public List innerObjects; + } + + public static class InnerObject { + @JSONField(name = "Status") + public Status status; + @JSONField(name = "Decision") + public String decision; + } + + + public static class Status { + @JSONField(name = "StatusCode") + public StatusCode statusCode; + } + + public static class StatusCode { + @JSONField(name = "Value") + public String value; + } + + @JSONField(deserialize = false) + public String retrieveDecision(){ + return this.response.get(0).innerObjects.get(0).decision; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1080.java b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1080.java new file mode 100644 index 0000000000..2cc98e6f3a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1080.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.issue_1000; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.sql.Date; + +/** + * Created by wenshao on 17/03/2017. + */ +public class Issue1080 extends TestCase { + public void test_for_issue() throws Exception { + java.util.Date date = JSON.parseObject("\"2017-3-17 00:00:01\"", java.util.Date.class); + String json = JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd"); + assertEquals("\"2017-03-17\"", json); + } + + public void test_for_issue_2() throws Exception { + java.util.Date date = JSON.parseObject("\"2017-3-7 00:00:01\"", java.util.Date.class); + String json = JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd"); + assertEquals("\"2017-03-07\"", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1082.java b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1082.java new file mode 100644 index 0000000000..647550794d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1082.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.issue_1000; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 17/03/2017. + */ +public class Issue1082 extends TestCase { + public void test_for_issue() throws Exception { + Throwable error = null; + try { + JSON.parseObject("{}", Model_1082.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public class Model_1082 { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1083.java b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1083.java new file mode 100644 index 0000000000..f5101ef5e5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1083.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.issue_1000; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by wenshao on 11/06/2017. + */ +public class Issue1083 extends TestCase { + public void test_for_issue() throws Exception { + Map map = new HashMap(); + map.put("userId", 456); + String json = JSON.toJSONString(map, SerializerFeature.WriteNonStringValueAsString); + assertEquals("{\"userId\":\"456\"}", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1085.java b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1085.java new file mode 100644 index 0000000000..f4b25a6d1f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1085.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.issue_1000; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; + +/** + * Created by wenshao on 20/03/2017. + */ +public class Issue1085 extends TestCase { + public void test_for_issue() throws Exception { + Model model = (Model) JSON.parseObject("{\"id\":123}", AbstractModel.class); + assertEquals(123, model.id); + } + + public static abstract class AbstractModel { + public int id; + + @JSONCreator + public static AbstractModel createInstance() { + return new Model(); + } + } + + public static class Model extends AbstractModel { + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1086.java b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1086.java new file mode 100644 index 0000000000..2462374854 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1086.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.issue_1000; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 20/03/2017. + */ +public class Issue1086 extends TestCase { + public void test_for_issue() throws Exception { + Model model = JSON.parseObject("{\"flag\":1}", Model.class); + assertTrue(model.flag); + } + + public static class Model { + public boolean flag; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1089.java b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1089.java new file mode 100644 index 0000000000..61892b52fb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1089.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.issue_1000; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 20/03/2017. + */ +public class Issue1089 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"ab\":123,\"a_b\":456}"; + TestBean tb = JSON.parseObject(json, TestBean.class); + assertEquals(123, tb.getAb()); + } + + public static class TestBean { + private int ab; + + public int getAb() { + return ab; + } + + public void setAb(int ab) { + this.ab = ab; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1089_private.java b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1089_private.java new file mode 100644 index 0000000000..4ad5a0338e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1089_private.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.issue_1000; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 20/03/2017. + */ +public class Issue1089_private extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"ab\":123,\"a_b\":456}"; + TestBean tb = JSON.parseObject(json, TestBean.class); + assertEquals(123, tb.getAb()); + } + + private static class TestBean { + private int ab; + + public int getAb() { + return ab; + } + + public void setAb(int ab) { + this.ab = ab; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1095.java b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1095.java new file mode 100644 index 0000000000..87318ce6fc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1000/Issue1095.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.issue_1000; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +import java.util.Date; + +/** + * Created by wenshao on 22/03/2017. + */ +public class Issue1095 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"Grade\": 1, \"UpdateTime\": \"2017-03-22T11:41:17\"}"; + JSONObject jsonObject = JSON.parseObject(text, Feature.AllowISO8601DateFormat); + assertEquals(Date.class, jsonObject.get("UpdateTime").getClass()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1109.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1109.java new file mode 100644 index 0000000000..0fe3a3d1a7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1109.java @@ -0,0 +1,15 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.lang3.tuple.Pair; + +/** + * Created by wenshao on 28/03/2017. + */ +public class Issue1109 extends TestCase { + public void test_for_issue() throws Exception { + Pair data = Pair.of("key", "\"the\"content"); + assertEquals("{\"key\":\"\\\"the\\\"content\"}", JSON.toJSONString(data)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1112.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1112.java new file mode 100644 index 0000000000..6b80ba2b9b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1112.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +/** + * Created by wenshao on 01/04/2017. + */ +public class Issue1112 extends TestCase { + public void test_for_issue_1() throws Exception { + JSONObject object = new JSONObject(); + object.put("123", "abc"); + + assertEquals("abc", JSONPath.eval(object, "$.123")); + } + + public void test_for_issue_2() throws Exception { + JSONObject object = new JSONObject(); + object.put("345_xiu", "abc"); + + assertEquals("abc", JSONPath.eval(object, "$.345_xiu")); + } + + + public void test_for_issue_3() throws Exception { + JSONObject object = new JSONObject(); + object.put("345.xiu", "abc"); + + assertEquals("abc", JSONPath.eval(object, "$.345\\.xiu")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1120.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1120.java new file mode 100644 index 0000000000..8d12bfea53 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1120.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 01/04/2017. + */ +public class Issue1120 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.setReqNo("123"); + + assertEquals("{\"REQ_NO\":\"123\"}", JSON.toJSONString(model)); + } + + public static class Model { + @JSONField(name="REQ_NO") + private String ReqNo; + + public String getReqNo() { + return ReqNo; + } + + public void setReqNo(String reqNo) { + ReqNo = reqNo; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1121.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1121.java new file mode 100644 index 0000000000..ae8e352441 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1121.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +/** + * Created by wenshao on 01/04/2017. + */ +public class Issue1121 extends TestCase { + public void test_for_issue() throws Exception { + JSONObject userObject = new JSONObject(); + userObject.put("name","jack"); + userObject.put("age",20); + + JSONObject result = new JSONObject(); + result.put("host","127.0.0.1"); + result.put("port",3306); + result.put("user",userObject); + result.put("admin",userObject); + + String json = JSON.toJSONString(result, true); + System.out.println(json); + + JSONObject jsonObject2 = JSON.parseObject(json); + assertEquals(result, jsonObject2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1134.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1134.java new file mode 100644 index 0000000000..e113b8def7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1134.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 09/04/2017. + */ +public class Issue1134 extends TestCase { + + public void test_for_issue() throws Exception { + Model model = new Model(); + model.blockpos = new BlockPos(); + model.blockpos.x = 526; + model.blockpos.y = 65; + model.blockpos.z = 554; + model.passCode = "010"; + + String text = JSON.toJSONString(model); + assertEquals("{\"Dimension\":0,\"PassCode\":\"010\",\"BlockPos\":{\"x\":526,\"y\":65,\"z\":554}}", text); + } + + public static class Model { + @JSONField(ordinal = 1, name="Dimension") + private int dimension; + @JSONField(ordinal = 2, name="PassCode") + private String passCode; + @JSONField(ordinal = 3, name="BlockPos") + private BlockPos blockpos; + + public int getDimension() { + return dimension; + } + + public void setDimension(int dimension) { + this.dimension = dimension; + } + + public String getPassCode() { + return passCode; + } + + public void setPassCode(String passCode) { + this.passCode = passCode; + } + + public BlockPos getBlockpos() { + return blockpos; + } + + public void setBlockpos(BlockPos blockpos) { + this.blockpos = blockpos; + } + } + + public static class BlockPos { + public int x; + public int y; + public int z; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1138.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1138.java new file mode 100644 index 0000000000..0090b7ffed --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1138.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 10/04/2017. + */ +public class Issue1138 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.id = 1001; + model.name = "gaotie"; + + // {"id":1001,"name":"gaotie"} + String text_normal = JSON.toJSONString(model); + System.out.println(text_normal); + + // [1001,"gaotie"] + String text_beanToArray = JSON.toJSONString(model, + SerializerFeature.BeanToArray); + System.out.println(text_beanToArray); + + // support beanToArray & normal mode + System.out.println(JSON.parseObject(text_beanToArray, Model.class, Feature.SupportArrayToBean)); + } + + static class Model { + public int id; + public String name; + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1140.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1140.java new file mode 100644 index 0000000000..ffc74cd220 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1140.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.io.ByteArrayOutputStream; + +/** + * Created by wenshao on 11/04/2017. + */ +public class Issue1140 extends TestCase { + public void test_for_issue() throws Exception { + String s = "\uD83C\uDDEB\uD83C\uDDF7"; + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + JSON.writeJSONString(out, s); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1144.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1144.java new file mode 100644 index 0000000000..2b4203c0fd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1144.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; + +/** + * Created by wenshao on 13/04/2017. + */ +public class Issue1144 extends TestCase { + public void test_issue_1144() throws Exception { + Model model = new Model(); + String json = JSON.toJSONString(model); + System.out.println(json); + } + + @JSONType(alphabetic = false) + public static class Model { + public int f2; + public int f1; + public int f0; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1146.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1146.java new file mode 100644 index 0000000000..48a8782f1d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1146.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; + +/** + * Created by wenshao on 14/04/2017. + */ +public class Issue1146 extends TestCase { + public void test_for_issue() throws Exception { + String json = JSON.toJSONString(new Test()); + assertEquals("{\"zzz\":true}", json); + } + + @JSONType(ignores = {"xxx", "yyy"}) + public static class Test { + + public boolean isXxx() { + return true; + } + public boolean getYyy() { + return true; + } + public boolean getZzz() { + return true; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1150.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1150.java new file mode 100644 index 0000000000..be8c4feedd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1150.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 24/04/2017. + */ +public class Issue1150 extends TestCase { + public void test_for_issue() throws Exception { + Model model = JSON.parseObject("{\"values\":\"\"}", Model.class); + assertNull(model.values); + } + + public void test_for_issue_array() throws Exception { + Model2 model = JSON.parseObject("{\"values\":\"\"}", Model2.class); + assertNull(model.values); + } + + public static class Model { + public List values; + } + + public static class Model2 { + public Item[] values; + } + + public static class Item { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1151.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1151.java new file mode 100644 index 0000000000..045b49be86 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1151.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wenshao on 19/04/2017. + */ +public class Issue1151 extends TestCase { + public void test_for_issue() throws Exception { + A a = new A(); + a.list.add(new C(1001)); + a.list.add(new C(1002)); + + String json = JSON.toJSONString(a, SerializerFeature.NotWriteRootClassName, SerializerFeature.WriteClassName); + assertEquals("{\"list\":[{\"@type\":\"com.alibaba.json.bvt.issue_1100.Issue1151$C\",\"id\":1001},{\"@type\":\"com.alibaba.json.bvt.issue_1100.Issue1151$C\",\"id\":1002}]}", json); + + A a2 = JSON.parseObject(json, A.class); + assertSame(a2.list.get(0).getClass(), C.class); + } + + public static class A { + public List list = new ArrayList(); + } + + public static interface B { + + } + + public static class C implements B { + public int id; + public C() { + + } + + public C(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1152.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1152.java new file mode 100644 index 0000000000..4cf1bccb0a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1152.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * Created by wenshao on 08/05/2017. + */ +public class Issue1152 extends TestCase { + public void test_for_issue() throws Exception { + TestBean tb = JSONObject.parseObject("{shijian:\"0000-00-00T00:00:00\"}",TestBean.class); + assertNull(tb.getShijian()); + } + + public void test_for_issue_2() throws Exception { + TestBean tb = JSONObject.parseObject("{shijian:\"0001-01-01T00:00:00+08:00\"}",TestBean.class); + assertNull(tb.getShijian()); + } + + public static class TestBean { + + private Date shijian; + + public Date getShijian() { + return shijian; + } + @JSONField(name="shijian" ) + public void setShijian(Date shijian) { + this.shijian = shijian; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1153.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1153.java new file mode 100644 index 0000000000..4fbb2f14f5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1153.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +/** + * Created by wenshao on 08/05/2017. + */ +public class Issue1153 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\n" + + "name: 'zhangshan', //这是一个姓名\n" + + "test : '//helo'\n" + + "}"; + + JSONObject jsonObject =JSON.parseObject(json); + System.out.println(jsonObject); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1165.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1165.java new file mode 100644 index 0000000000..cb276735e0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1165.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 27/04/2017. + */ +public class Issue1165 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.__v = 3; + + String json = JSON.toJSONString(model); + assertEquals("{\"__v\":3}", json); + } + + public static class Model { + public Number __v; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177.java new file mode 100644 index 0000000000..491aeadf29 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +/** + * Created by wenshao on 02/05/2017. + */ +public class Issue1177 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"a\":{\"b\":\"c\",\"g\":{\"e\":\"f\"}},\"d\":{\"a\":\"f\",\"h\":[\"s1\"]}} "; + JSONObject jsonObject = JSONObject.parseObject(text); + Object eval = JSONPath.eval(jsonObject, "$..a"); + assertNotNull(eval); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_1.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_1.java new file mode 100644 index 0000000000..a7f20ab202 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_1.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +/** + * Created by wenshao on 05/05/2017. + */ +public class Issue1177_1 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"a\":{\"x\":\"y\"},\"b\":{\"x\":\"y\"}}"; + JSONObject jsonObject = JSONObject.parseObject(text); + System.out.println(jsonObject); + String jsonpath = "$..x"; + String value="y2"; + JSONPath.set(jsonObject, jsonpath, value); + assertEquals("{\"a\":{\"x\":\"y2\"},\"b\":{\"x\":\"y2\"}}", jsonObject.toString()); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_2.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_2.java new file mode 100644 index 0000000000..0bc28fe3b9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_2.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.util.Map; + +/** + * Created by wenshao on 05/05/2017. + */ +public class Issue1177_2 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"a\":{\"x\":\"y\"},\"b\":{\"x\":\"y\"}}"; + Map jsonObject = JSONObject.parseObject(text, new TypeReference>(){}); + System.out.println(JSON.toJSONString(jsonObject)); + String jsonpath = "$..x"; + String value="y2"; + JSONPath.set(jsonObject, jsonpath, value); + assertEquals("{\"a\":{\"x\":\"y2\"},\"b\":{\"x\":\"y2\"}}", JSON.toJSONString(jsonObject)); + + } + + public static class Model { + public String x; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_3.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_3.java new file mode 100644 index 0000000000..30aa041b3d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_3.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.util.List; +import java.util.Map; + +/** + * Created by wenshao on 05/05/2017. + */ +public class Issue1177_3 extends TestCase { + public void test_for_issue() throws Exception { + String text = "[{\"x\":\"y\"},{\"x\":\"y\"}]"; + List jsonObject = JSONObject.parseObject(text, new TypeReference>(){}); + System.out.println(JSON.toJSONString(jsonObject)); + String jsonpath = "$..x"; + String value="y2"; + JSONPath.set(jsonObject, jsonpath, value); + assertEquals("[{\"x\":\"y2\"},{\"x\":\"y2\"}]", JSON.toJSONString(jsonObject)); + + } + + public static class Model { + public String x; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_4.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_4.java new file mode 100644 index 0000000000..75bd86b327 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_4.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 05/05/2017. + */ +public class Issue1177_4 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"models\":[{\"x\":\"y\"},{\"x\":\"y\"}]}"; + Root root = JSONObject.parseObject(text, Root.class); + System.out.println(JSON.toJSONString(root)); + String jsonpath = "$..x"; + String value="y2"; + JSONPath.set(root, jsonpath, value); + assertEquals("{\"models\":[{\"x\":\"y2\"},{\"x\":\"y2\"}]}", JSON.toJSONString(root)); + + } + + public static class Root { + public List models; + } + + public static class Model { + public String x; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1178.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1178.java new file mode 100644 index 0000000000..12dc661deb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1178.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.io.Serializable; + +/** + * Created by wenshao on 02/05/2017. + */ +public class Issue1178 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\n" + + " \"info\": {\n" + + " \"test\": \"\", \n" + + " }\n" + + "}"; + + JSONObject jsonObject = JSON.parseObject(json); + TestModel loginResponse = JSON.toJavaObject(jsonObject, TestModel.class); + + } + + public static class TestModel implements Serializable { + public String info; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1187.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1187.java new file mode 100644 index 0000000000..9ff4875702 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1187.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by wenshao on 05/05/2017. + */ +public class Issue1187 extends TestCase { + public void test_for_issue() throws Exception { + String text1 = "{\"d\":\"2017-04-27+08:00\"}"; + JSONObject jsonObject = (JSONObject) JSON.parse(text1, Feature.AllowISO8601DateFormat);; + System.out.println(jsonObject.get("d").getClass().getClass());//String + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1188.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1188.java new file mode 100644 index 0000000000..d89f633fc7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1188.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 09/05/2017. + */ +public class Issue1188 extends TestCase { + public void test_for_issue_1188() throws Exception { + String json = "{\"ids\":\"a1,a2\",\"name\":\"abc\"}"; + Info info = JSON.parseObject(json, Info.class); + assertNull(info.ids); + } + + public static class Info{ + + @JSONField(deserialize=false) + private List ids; + private String name; + + public List getIds() { + return ids; + } + + public void setIds(List ids) { + this.ids = ids; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1189.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1189.java new file mode 100644 index 0000000000..c7070feb52 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue1189.java @@ -0,0 +1,76 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +import java.util.Map; + +/** + * Created by wenshao on 10/05/2017. + */ +public class Issue1189 extends TestCase { + public void test_for_issue() throws Exception { + String str = new String("{\"headernotificationType\": \"PUSH\",\"headertemplateNo\": \"99\",\"headerdestination\": [{\"target\": \"all\",\"targetvalue\": \"all\"}],\"body\": [{\"title\": \"预约超时\",\"body\": \"您的预约已经超时\"}]}"); + + JsonBean objeclt = JSON.parseObject(str, JsonBean.class); + Map list = objeclt.getBody(); + System.out.println(list.get("body")); + } + + public static class JsonBean { + private Map body; + private int headertemplateno; + private Map headerdestination; + private String headernotificationtype; + private String notificationType; + + + + public Map getBody() { + return body; + } + public void setBody(Map body) { + this.body = body; + } + public int getHeadertemplateno() { + return headertemplateno; + } + public void setHeadertemplateno(int headertemplateno) { + this.headertemplateno = headertemplateno; + } + public Map getHeaderdestination() { + return headerdestination; + } + public void setHeaderdestination(Map headerdestination) { + this.headerdestination = headerdestination; + } + public String getHeadernotificationtype() { + return headernotificationtype; + } + public void setHeadernotificationtype(String headernotificationtype) { + this.headernotificationtype = headernotificationtype; + } + public String getNotificationType() { + return notificationType; + } + public void setNotificationType(String notificationType) { + this.notificationType = notificationType; + } + public JsonBean(Map body, int headertemplateno, + Map headerdestination, + String headernotificationtype, String notificationType) { + super(); + this.body = body; + this.headertemplateno = headertemplateno; + this.headerdestination = headerdestination; + this.headernotificationtype = headernotificationtype; + this.notificationType = notificationType; + } + public JsonBean() { + super(); + // TODO Auto-generated constructor stub + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1100/Issue969.java b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue969.java new file mode 100644 index 0000000000..c73282fff8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1100/Issue969.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.issue_1100; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.json.bvt.issue_1200.Issue1205; +import junit.framework.TestCase; + +import java.util.Date; +import java.util.List; + +/** + * Created by wenshao on 08/05/2017. + */ +public class Issue969 extends TestCase { + public void test_for_issue() throws Exception { + JSONObject jsonObject = new JSONObject(); + + JSONArray jsonArray = new JSONArray(); + jsonArray.add(new Model()); + jsonObject.put("models", jsonArray); + + List list = jsonObject.getObject("models", new TypeReference>(){}); + + assertEquals(1, list.size()); + assertEquals(Model.class, list.get(0).getClass()); + } + + public void test_for_issue_1() throws Exception { + JSONObject jsonObject = new JSONObject(); + + JSONArray jsonArray = new JSONArray(); + jsonArray.add(new Model()); + jsonObject.put("models", jsonArray); + + List list = jsonObject.getObject("models", new TypeReference>(){}.getType()); + + assertEquals(1, list.size()); + assertEquals(Model.class, list.get(0).getClass()); + } + + public static class Model { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1202.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1202.java new file mode 100644 index 0000000000..c2cb863ee5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1202.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + * Created by wenshao on 16/05/2017. + */ +public class Issue1202 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.US; + } + + public void test_for_issue() throws Exception { + String text = "{\"date\":\"Apr 27, 2017 5:02:17 PM\"}"; + Model model = JSON.parseObject(text, Model.class); + assertNotNull(model.date); +// assertEquals("{\"date\":\"Apr 27, 2017 5:02:17 PM\"}", JSON.toJSONString(model)); + } + + public static class Model { + @JSONField(format = "MMM dd, yyyy h:mm:ss aa") + private java.util.Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1203.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1203.java new file mode 100644 index 0000000000..7cefa1455e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1203.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/05/2017. + */ +public class Issue1203 extends TestCase { + public void test_for_issue() throws Exception { + String[] strArr = new String[5]; + strArr[0] = "a"; + strArr[1] = "b"; + strArr[3] = "d"; + strArr[4] = ""; + + String json = JSON.toJSONString(strArr, SerializerFeature.WriteNullStringAsEmpty); + assertEquals("[\"a\",\"b\",\"\",\"d\",\"\"]", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1205.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1205.java new file mode 100644 index 0000000000..b7efba244d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1205.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 11/06/2017. + */ +public class Issue1205 extends TestCase { + public void test_for_issue() throws Exception { + JSONArray array = new JSONArray(); + array.add(new JSONObject()); + + List list = array.toJavaObject(new TypeReference>(){}); + assertEquals(1, list.size()); + assertEquals(Model.class, list.get(0).getClass()); + } + + public static class Model { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1222.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1222.java new file mode 100644 index 0000000000..963e1230e2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1222.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONAware; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 01/06/2017. + */ +public class Issue1222 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.type = Type.A; + String text = JSON.toJSONString(model, SerializerFeature.WriteEnumUsingToString); + assertEquals("{\"type\":\"TypeA\"}", text); + } + + public static class Model { + public Type type; + } + + public static enum Type implements JSONAware { + A, B; + + public String toJSONString() { + return "\"Type" + this.name() + "\""; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1222_1.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1222_1.java new file mode 100644 index 0000000000..4ce2260246 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1222_1.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONAware; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 01/06/2017. + */ +public class Issue1222_1 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.type = Type.A; + String text = JSON.toJSONString(model, SerializerFeature.WriteEnumUsingToString); + assertEquals("{\"type\":\"TypeA\"}", text); + } + + private static class Model { + public Type type; + } + + private static enum Type implements JSONAware { + A, B; + + public String toJSONString() { + return "\"Type" + this.name() + "\""; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1225.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1225.java new file mode 100644 index 0000000000..730210d294 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1225.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 30/05/2017. + */ +public class Issue1225 extends TestCase { + +// public void test_parseObject_0() { +// assertEquals("2", JSON.parseObject("{\"data\":[\"1\",\"2\",\"3\"]}", +// new TypeReference>>(){}).data.get(1)); +// } +// +// public void test_parseObject_1() { +// assertEquals("2", JSON.parseObject("{\"data\":[\"1\",\"2\",\"3\"]}", +// new TypeReference>(){}).data.get(1)); +// } + + public void test_parseObject_2() { + SimpleGenericObject object = JSON.parseObject("{\"data\":[\"1\",\"2\",\"3\"],\"a\":\"a\"}", + SimpleGenericObject.class); + + assertEquals("2", object.data.get(1)); + } + +// public void test_parseObject_2_jackson() throws Exception { +// ObjectMapper mapper = new ObjectMapper(); +// SimpleGenericObject object = mapper.readValue("{\"data\":[\"1\",\"2\",\"3\"]}", +// SimpleGenericObject.class); +// +// +// assertEquals("2", object.data.get(1)); +// } + + static class BaseGenericType { + public T data; + } + + static class ExtendGenericType extends BaseGenericType> { + } + + static class SimpleGenericObject extends ExtendGenericType { + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1226.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1226.java new file mode 100644 index 0000000000..1f4735eaae --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1226.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/05/2017. + */ +public class Issue1226 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"c\":\"c\"}"; + TestBean tb1 = JSON.parseObject(json, TestBean.class); + assertEquals('c', tb1.getC()); + + TestBean2 tb2 = JSON.parseObject(json, TestBean2.class); + assertEquals('c', tb2.getC().charValue()); + + String json2 = JSON.toJSONString(tb2); + JSONObject jo = JSON.parseObject(json2); + + TestBean tb12 = jo.toJavaObject(TestBean.class); + assertEquals('c', tb12.getC()); + + TestBean2 tb22 = jo.toJavaObject(TestBean2.class); + assertEquals('c', tb22.getC().charValue()); + } + + static class TestBean{ + char c; + + public char getC() { + return c; + } + + public void setC(char c) { + this.c = c; + } + } + + static class TestBean2{ + Character c; + + public Character getC() { + return c; + } + + public void setC(Character c) { + this.c = c; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1227.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1227.java new file mode 100644 index 0000000000..0d14c5570c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1227.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + + + +public class Issue1227 extends TestCase { + public void test_for_issue() throws Exception { + + String t2 = "{\"state\":2,\"msg\":\"\ufeffmsg2222\",\"data\":[]}"; + + try { + Test model = JSON.parseObject(t2, Test.class); + assertEquals("\uFEFFmsg2222",model.msg); + + model.msg = "\uFEFFss"; + String t3 = JSON.toJSONString(model); + assertTrue(t3.contains(model.msg)); + } catch ( Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + public static class Test { + public int state; + public String msg; + } +} + + + diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1229.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1229.java new file mode 100644 index 0000000000..4de6066528 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1229.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 30/05/2017. + */ +public class Issue1229 extends TestCase { + public void test_for_issue() throws Exception { + final Object parsed = JSON.parse("{\"data\":{}}"); + assertTrue(parsed instanceof JSONObject); + assertTrue(((JSONObject)parsed).get("data") instanceof JSONObject); + + final Result result = JSON.parseObject("{\"data\":{}}", new TypeReference>(){}); + assertNotNull(result.data); + assertTrue(result.data instanceof Data); + + final Result> result2 = JSON.parseObject("{\"data\":[]}", new TypeReference>>(){}); + assertNotNull(result2.data); + assertTrue(result2.data instanceof List); + assertEquals(0, result2.data.size()); + } + + public void parseErr() throws Exception { + JSON.parseObject("{\"data\":{}}", new TypeReference>>(){}); + fail("should be failed due to error json"); + } + + public static class Result{ + T data; + public void setData(T data) { + this.data = data; + } + public T getData() { + return data; + } + } + + public static class Data { + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1231.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1231.java new file mode 100644 index 0000000000..58ccaa6060 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1231.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 30/05/2017. + */ +public class Issue1231 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.self = model; + model.id = 123; + + String text = JSON.toJSONString(model); + assertEquals("{\"id\":123,\"self\":{\"$ref\":\"@\"}}", text); + + { + Model model2 = JSON.parseObject(text, Model.class, Feature.DisableCircularReferenceDetect); + assertNotNull(model2); + assertNotSame(model2, model2.self); + } + + { + JSONObject jsonObject = JSON.parseObject(text, Feature.DisableCircularReferenceDetect); + assertNotNull(jsonObject); + + JSONObject self = jsonObject.getJSONObject("self"); + + assertNotNull(self); + assertNotNull(self.get("$ref")); + assertEquals("@", self.get("$ref")); + } + } + + public static class Model { + public int id; + public Model self; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1233.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1233.java new file mode 100644 index 0000000000..d98c5003ab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1233.java @@ -0,0 +1,90 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import junit.framework.TestCase; + +import java.lang.reflect.Type; +import java.util.List; + +/** + * Created by wenshao on 30/05/2017. + */ +public class Issue1233 extends TestCase { + public void test_for_issue() throws Exception { + ParserConfig.getGlobalInstance().putDeserializer(Area.class, new ObjectDeserializer() { + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + JSONObject jsonObject = (JSONObject) parser.parse(); + String areaType; + + if (jsonObject.get("type") instanceof String) { + areaType = (String) jsonObject.get("type"); + } else { + return null; + } + if (Area.TYPE_SECTION.equals(areaType)) { + return (T) JSON.toJavaObject(jsonObject, Section.class); + } else if (Area.TYPE_FLOORV1.equals(areaType)) { + return (T) JSON.toJavaObject(jsonObject, FloorV1.class); + } else if (Area.TYPE_FLOORV2.equals(areaType)) { + return (T) JSON.toJavaObject(jsonObject, FloorV2.class); + } + return null; + } + + public int getFastMatchToken() { + return 0; + } + }); + + JSONObject jsonObject = JSON.parseObject("{\"type\":\"floorV2\",\"templateId\":\"x123\"}"); + + FloorV2 floorV2 = (FloorV2) jsonObject.toJavaObject(Area.class); + assertNotNull(floorV2); + assertEquals("x123", floorV2.templateId); + } + + public interface Area { + public static final String TYPE_SECTION = "section"; + public static final String TYPE_FLOORV1 = "floorV1"; + public static final String TYPE_FLOORV2 = "floorV2"; + + String getName(); + } + + public static class Section implements Area { + public List children; + + public String type; + + public String templateId; + + public String getName() { + return templateId; + } + } + + public static class FloorV1 implements Area { + public String type; + public String templateId; + + public String getName() { + return templateId; + } + } + + public static class FloorV2 implements Area { + public List children; + + public String type; + + public String templateId; + + public String getName() { + return templateId; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1235.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1235.java new file mode 100644 index 0000000000..425a735016 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1235.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 30/05/2017. + */ +public class Issue1235 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"type\":\"floorV2\",\"templateId\":\"x123\"}"; + + FloorV2 floorV2 = (FloorV2) JSON.parseObject(json, Area.class); + assertNotNull(floorV2); + assertNotNull(floorV2.templateId); + assertEquals("x123", floorV2.templateId); + assertEquals("floorV2", floorV2.type); + + String json2 = JSON.toJSONString(floorV2, SerializerFeature.WriteClassName); + assertEquals("{\"type\":\"floorV2\",\"templateId\":\"x123\"}", json2); + } + + @JSONType(seeAlso = {FloorV2.class}, typeKey = "type") + public interface Area { + public static final String TYPE_SECTION = "section"; + public static final String TYPE_FLOORV1 = "floorV1"; + public static final String TYPE_FLOORV2 = "floorV2"; + } + + @JSONType(typeName = "floorV2") + public static class FloorV2 implements Area { + public String type; + + public String templateId; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1235_noasm.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1235_noasm.java new file mode 100644 index 0000000000..5db8cbb26c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1235_noasm.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 30/05/2017. + */ +public class Issue1235_noasm extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"type\":\"floorV2\",\"templateId\":\"x123\"}"; + + FloorV2 floorV2 = (FloorV2) JSON.parseObject(json, Area.class); + assertNotNull(floorV2); + assertNotNull(floorV2.templateId); + assertEquals("x123", floorV2.templateId); + assertEquals("floorV2", floorV2.type); + + String json2 = JSON.toJSONString(floorV2, SerializerFeature.WriteClassName); + assertEquals("{\"type\":\"floorV2\",\"templateId\":\"x123\"}", json2); + } + + @JSONType(seeAlso = {FloorV2.class}, typeKey = "type") + public interface Area { + public static final String TYPE_SECTION = "section"; + public static final String TYPE_FLOORV1 = "floorV1"; + public static final String TYPE_FLOORV2 = "floorV2"; + } + + @JSONType(typeName = "floorV2") + private static class FloorV2 implements Area { + public String type; + + public String templateId; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1240.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1240.java new file mode 100644 index 0000000000..b7c1fb4399 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1240.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; +import org.springframework.util.LinkedMultiValueMap; + +/** + * Created by wenshao on 01/06/2017. + */ +public class Issue1240 extends TestCase { + public void test_for_issue() throws Exception { + ParserConfig parserConfig = new ParserConfig(); + parserConfig.setAutoTypeSupport(true); + LinkedMultiValueMap result = new LinkedMultiValueMap(); + result.add("test", "11111"); + String test = JSON.toJSONString(result, SerializerFeature.WriteClassName); + JSON.parseObject(test, Object.class, parserConfig, JSON.DEFAULT_PARSER_FEATURE); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1246.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1246.java new file mode 100644 index 0000000000..0fe387d2f9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1246.java @@ -0,0 +1,79 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; +import org.springframework.util.LinkedMultiValueMap; + +/** + * Created by kimmking on 06/06/2017. + */ +public class Issue1246 extends TestCase { + public void test_for_issue() throws Exception { + B b = new B(); + b.setX("xx"); + + String test = JSON.toJSONString( b ); + System.out.println(test); + assertEquals("{}", test); + + C c = new C(); + c.ab = b ; + + String testC = JSON.toJSONString( c ); + System.out.println(testC); + assertEquals("{\"ab\":{}}",testC); + + D d = new D(); + d.setAb( b ); + + String testD = JSON.toJSONString( d ); + System.out.println(testD); + assertEquals("{\"ab\":{}}",testD); + } + + public static class C{ + public A ab; + } + + public static class D{ + private A ab; + + public A getAb() { + return ab; + } + + public void setAb(A ab) { + this.ab = ab; + } + } + + public static class A{ + private String x; + + public String getX() { + return x; + } + + public void setX(String x) { + this.x = x; + } + } + + public static class B extends A{ + private String x; + + @Override + @JSONField(serialize = false) + public String getX() { + return x; + } + + @Override + public void setX(String x) { + this.x = x; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1254.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1254.java new file mode 100644 index 0000000000..71edbf71fe --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1254.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.json.bvt.bug.Bug_101_for_rongganlin_case2; +import junit.framework.TestCase; +import org.apache.commons.beanutils.BeanUtils; + +import java.util.Map; + +/** + * Created by kimmking on 09/06/2017. + */ +public class Issue1254 extends TestCase { + public void test_for_issue() throws Exception { + A a = new A(); + a._parentId = "001"; + String test = JSON.toJSONString(a); + System.out.println(test); + assertEquals("{\"_parentId\":\"001\"}", test); + + B b = new B(); + b.set_parentId("001"); + + + String testB = JSON.toJSONString(b); + System.out.println(testB); + assertEquals("{\"_parentId\":\"001\"}", testB); + + } + + public static class A { + public String _parentId; + } + + public static class B { + @JSONField(name = "_parentId") + private String _parentId; + + public String get_parentId() { + return _parentId; + } + + public void set_parentId(String _parentId) { + this._parentId = _parentId; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1256.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1256.java new file mode 100644 index 0000000000..09b8391b3a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1256.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by kimmking on 12/06/2017. + */ +public class Issue1256 extends TestCase { + public void test_for_issue() throws Exception { + + + // params ={"key_obj":{"age":39,"name":"Mike"},"key_string":"Hello","key_random":-1193959466,"key_int":10000} + + A a = new A(); + a.name = "Mike"; + a.age = 39; + + Map map = new HashMap(); + map.put("key_obj",a); + map.put("key_string","Hello"); + map.put("key_random",-1193959466L); + map.put("key_int",10000); + + String jsonString = JSON.toJSONString(map); + assertTrue(jsonString.contains("Mike")); + } + + public static class A { + public String name; + public int age; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1262.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1262.java new file mode 100644 index 0000000000..017375b3ca --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1262.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Created by wenshao on 15/06/2017. + */ +public class Issue1262 extends TestCase { + public void test_for_issue() throws Exception { + Model model = JSON.parseObject("{\"chatterMap\":{}}", Model.class); + } + + public static class Model { + public Map chatterMap = new ConcurrentHashMap(); + } + + public static class Chatter { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1265.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1265.java new file mode 100644 index 0000000000..7db9005f3d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1265.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +/** + * Created by wenshao on 22/07/2017. + */ +public class Issue1265 extends TestCase { + public void test_0() throws Exception { + Object t = JSON.parseObject("{\"value\":{\"id\":123}}", new TypeReference(){}).value; + assertEquals(123, ((JSONObject) t).getIntValue("id")); + + T1 t1 = JSON.parseObject("{\"value\":{\"id\":123}}", new TypeReference>(){}).value; + assertEquals(123, t1.id); + + T2 t2 = JSON.parseObject("{\"value\":{\"id\":123}}", new TypeReference>(){}).value; + assertEquals(123, t2.id); + + } + + public static class Response { + public T value; + } + + public static class T1 { + public int id; + } + + public static class T2 { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1267.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1267.java new file mode 100644 index 0000000000..a083c7490f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1267.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.util.LinkedMultiValueMap; + +/** + * Created by kimmking on 15/06/2017. + */ +public class Issue1267 extends TestCase { + public void test_for_issue() throws Exception { + + String json = "{\"message\":{\"refund_fee\":[\"0.01\"],\"pay_fee\":[\"0.01\"]},\"url\":\"http://localhost:8080\"}"; + + LinkedMultiValueMap message = JSON.parseObject(JSON.parseObject(json).getString("message"), LinkedMultiValueMap.class); // 这是可以反序列化通过的 + + assertEquals("0.01",message.get("pay_fee").get(0)); + + PushHttpMessage pushHttpMessage = JSON.parseObject(json, PushHttpMessage.class); + + assertEquals("0.01",pushHttpMessage.getMessage().get("pay_fee").get(0)); + } + + public static class PushHttpMessage { + private LinkedMultiValueMap message; + private String url; + + public LinkedMultiValueMap getMessage() { + return message; + } + + public void setMessage(LinkedMultiValueMap message) { + this.message = message; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1271.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1271.java new file mode 100644 index 0000000000..0b7912ba69 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1271.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.deserializer.ExtraProcessor; +import junit.framework.TestCase; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Created by kimmking on 15/06/2017. + */ +public class Issue1271 extends TestCase { + public void test_for_issue() throws Exception { + + String json = "{\"a\":1,\"b\":2}"; + + final AtomicInteger count = new AtomicInteger(0); + ExtraProcessor extraProcessor = new ExtraProcessor() { + public void processExtra(Object object, String key, Object value) { + System.out.println("setter not found, class " + object.getClass().getName() + ", property " + key); + count.incrementAndGet(); + } + }; + + + A a = JSON.parseObject(json,A.class,extraProcessor); + assertEquals(1,a.a); + assertEquals(1, count.intValue()); + + B b = JSON.parseObject(json,B.class,extraProcessor); + assertEquals(1,b.a); + assertEquals(2, count.intValue()); + + } + + public static class A { + public int a; + } + + public static class B { + private int a; + + public int getA() { + return a; + } + + public void setA(int a) { + this.a = a; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1272.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1272.java new file mode 100644 index 0000000000..7b801d4314 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1272.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 18/06/2017. + */ +public class Issue1272 extends TestCase { + public void test_for_issue() throws Exception { + Exception exception = null; + + try { + JSON.toJSONString(new Point()); + }catch (JSONException ex) { + exception = ex; + } + assertNotNull(exception); + assertEquals(NullPointerException.class, exception.getCause().getCause().getClass()); + } + + public static class Point { + + private Long userId; + + public long getUserId() { + return userId; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1272_IgnoreError.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1272_IgnoreError.java new file mode 100644 index 0000000000..fd00251854 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1272_IgnoreError.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 18/06/2017. + */ +public class Issue1272_IgnoreError extends TestCase { + public void test_for_issue() throws Exception { + String text = JSON.toJSONString(new Point(), SerializerFeature.IgnoreErrorGetter); + assertEquals("{}", text); + } + + public static class Point { + + private Long userId; + + public long getUserId() { + return userId; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1274.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1274.java new file mode 100644 index 0000000000..dff9a757ba --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1274.java @@ -0,0 +1,66 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.NameFilter; +import junit.framework.TestCase; + +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Created by kimmking on 15/06/2017. + */ +public class Issue1274 extends TestCase { + public void test_for_issue() throws Exception { + + User user = new User(); + user.setId(1); + user.setName("name"); + + NameFilter filter = new NameFilter() { + public String process(Object object, String name, Object value) { + System.out.println("name="+name+",value="+value); + if(name.equals("name")){ + return "nt"; + } + return name; + } + }; + + // test for JSON.toJSONString(user,filter); + String jsonString = JSON.toJSONString(user,filter); + System.out.println(jsonString); + assertEquals("{\"id\":1,\"nt\":\"name\"}", jsonString); + + // test for jsonSerializer.getNameFilters().add(filter); + JSONSerializer jsonSerializer = new JSONSerializer(); + jsonSerializer.getNameFilters().add(filter); + jsonSerializer.write(user); + jsonString = jsonSerializer.toString(); + System.out.println(jsonString); + assertEquals("{\"id\":1,\"nt\":\"name\"}",jsonString); + + } + + public static class User { + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1276.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1276.java new file mode 100644 index 0000000000..e0fc73ec03 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1276.java @@ -0,0 +1,78 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 18/06/2017. + */ +public class Issue1276 extends TestCase { + public void test_for_issue() throws Exception { + MyException myException = new MyException(100,"error msg"); + String str = JSON.toJSONString(myException); + System.out.println(str); + + MyException myException1 = JSON.parseObject(str, MyException.class); + assertEquals(myException.getCode(), myException1.getCode()); + + String str1 = JSON.toJSONString(myException1); + assertEquals(str, str1); + + } + + public static class MyException extends RuntimeException{ + private static final long serialVersionUID = 7815426752583648734L; + private long code; + + public MyException() { + super(); + } + + public MyException(String message, Throwable cause) { + super(message, cause); + } + + public MyException(String message) { + super(message); + } + + public MyException(Throwable cause) { + super(cause); + } + + public MyException(long code) { + super(); + this.code = code; + } + + public MyException(long code, String message, Throwable cause) { + super(message, cause); + this.code = code; + } + + public MyException(long code, String message) { + super(message); + this.code = code; + } + + public MyException(long code, Throwable cause) { + super(cause); + this.code = code; + } + + public void setCode(long code) { + this.code = code; + } + + public long getCode() { + return code; + } + + @Override + public String toString() { + return "MyException{" + + "code=" + code + + '}'; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1278.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1278.java new file mode 100644 index 0000000000..2cf8805377 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1278.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +/** + * Created by kimmking on 20/06/2017. + */ +public class Issue1278 extends TestCase { + public void test_for_issue() throws Exception { + + String json1 = "{\"name\":\"name\",\"id\":1}"; + String json2 = "{\"user\":\"user\",\"id\":2}"; + AlternateNames c1 = JSON.parseObject(json1, AlternateNames.class); + + assertEquals("name",c1.name); + assertEquals(1,c1.id); + + AlternateNames c2 = JSON.parseObject(json2, AlternateNames.class); + + assertEquals("user",c2.name); + assertEquals(2,c2.id); + + DefaultJSONParser parser = new DefaultJSONParser(json1); + c1 = new AlternateNames(); + parser.parseObject(c1); + + assertEquals("name",c1.name); + assertEquals(1,c1.id); + + c2 = new AlternateNames(); + parser = new DefaultJSONParser(json2); + parser.parseObject(c2); + + assertEquals("user",c2.name); + assertEquals(2,c2.id); + + JSONObject jsonObject = JSON.parseObject(json1); + c1 = jsonObject.toJavaObject(AlternateNames.class); + + assertEquals("name",c1.name); + assertEquals(1,c1.id); + + jsonObject = JSON.parseObject(json2); + c2 = jsonObject.toJavaObject(AlternateNames.class); + + assertEquals("user",c2.name); + assertEquals(2,c2.id); + + } + + /** + * {"name":"name","id":1} + * {"user":"user","id":2} + */ + public static class AlternateNames { + @JSONField(alternateNames = {"name", "user"}) + public String name; + public int id; + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1281.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1281.java new file mode 100644 index 0000000000..7f614bacb3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1281.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.lang.reflect.Type; +import java.util.Map; + +/** + * Created by wenshao on 24/06/2017. + */ +public class Issue1281 extends TestCase { + public void test_for_issue() throws Exception { + Type type1 = new TypeReference>>() {}.getType(); + Type type2 = new TypeReference>>() {}.getType(); + assertSame(type1, type2); + } + + public static class Result { + public T value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1293.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1293.java new file mode 100644 index 0000000000..eaeb2cb3ba --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1293.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + + +/** + * Created by kimmking on 27/06/2017. + */ +public class Issue1293 extends TestCase { + + public void test_for_issue() { + String data = "{\"idType\":\"123123\",\"userType\":\"134\",\"count\":\"123123\"}"; + { + Test test = JSON.parseObject(data, Test.class); + + assertNull(test.idType); + assertNull(test.userType); + } + + Test test = JSON.parseObject(data, Test.class); + assertNull(test.idType); + assertNull(test.userType); + + } + + static class Test{ + private long count; + private IdType idType; + private UserType userType; + + public long getCount() { + return count; + } + + public void setCount(long count) { + this.count = count; + } + + public IdType getIdType() { + return idType; + } + + public void setIdType(IdType idType) { + this.idType = idType; + } + + public UserType getUserType() { + return userType; + } + + public void setUserType(UserType userType) { + this.userType = userType; + } + } + + static enum IdType{ + A,B + } + static enum UserType{ + C,D + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1298.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1298.java new file mode 100644 index 0000000000..94a32f7f53 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1298.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.Date; + +/** + * Created by wenshao on 30/06/2017. + */ +public class Issue1298 extends TestCase { + public void test_for_issue() throws Exception { + JSONObject object = new JSONObject(); + + object.put("date", "2017-06-29T08:06:30.000+05:30"); + + Date date = object.getObject("date", java.util.Date.class); + + assertEquals("\"2017-06-29T10:36:30+08:00\"", JSON.toJSONString(date, SerializerFeature.UseISO8601DateFormat)); + } + + public void test_for_issue_1() throws Exception { + JSONObject object = new JSONObject(); + + object.put("date", "2017-08-15 20:00:00.000"); + + Date date = object.getObject("date", java.util.Date.class); + + assertEquals("\"2017-08-15T20:00:00+08:00\"", JSON.toJSONString(date, SerializerFeature.UseISO8601DateFormat)); + + JSON.parseObject("\"2017-08-15 20:00:00.000\"", java.util.Date.class); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1299.java b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1299.java new file mode 100644 index 0000000000..c7c9dcc5c3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1200/Issue1299.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt.issue_1200; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.io.Serializable; +import java.util.List; + +/** + * Created by wenshao on 01/07/2017. + */ +public class Issue1299 extends TestCase { + public void test_for_issue() throws Exception { + String jsonStr = "{\"code\":201,\"data\":{\"materials\":[{\"material\":\"locale\",\"success\":true," + + "\"material_id\":356,\"id\":\"5099\"}],\"unitInfo\":{\"languages\":[\"'en_US'\",\"ru_RU\"]," + + "\"unitName\":\"PC_ROCKBROS\",\"sceneKey\":\"shop_activity_page\",\"domain\":\"shopcdp.aliexpress" + + ".com\",\"format\":\"HTML\",\"unitId\":\"1625\",\"id\":1761,\"rootPath\":\"shopcdp\"," + + "\"userId\":\"jianqing.zengjq\",\"platforms\":[\"pc\",\"mobile\"],\"status\":2}},\"success\":true}"; + + UnitsSaveResponse response = JSON.parseObject(jsonStr, UnitsSaveResponse.class); + Class dataClass = response.getData().getClass(); + System.out.println(dataClass); + } + + public static class ServiceResult extends BaseResultDo implements Serializable { + @JSONField( + name = "data" + ) + private T data; + + public ServiceResult() { + } + + public T getData() { + return this.data; + } + + public void setData(T data) { + this.data = data; + } + } + + public static class UnitsSaveResponse extends ServiceResult { + + + + } + + public static class UnitSave implements Serializable { + + private SaveUnitInfo unitInfo; + + private List materials; + + public SaveUnitInfo getUnitInfo() { + return unitInfo; + } + + public void setUnitInfo(SaveUnitInfo unitInfo) { + this.unitInfo = unitInfo; + } + + public List getMaterials() { + return materials; + } + + public void setMaterials(List materials) { + this.materials = materials; + } + } + + public static class SaveUnitInfo { + + } + + public static class BaseResultDo{ + + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1300.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1300.java new file mode 100644 index 0000000000..4fa330f817 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1300.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.util.TypeUtils; +import junit.framework.TestCase; +import org.junit.Assert; + +/** + * Created by wenshao on 01/07/2017. + */ +public class Issue1300 extends TestCase { + public void testFullJSON() { + JSONObject data = new JSONObject(); + data.put("name", "string"); + data.put("code", 1); + data.put("pinyin", "pinyin"); + City object = TypeUtils.castToJavaBean(data, City.class); + assertEquals("string", object.name); + assertEquals(1, object.code); + assertEquals("pinyin", object.pinyin); + } + + public void testEmptyJSON() { + City object = TypeUtils.castToJavaBean(new JSONObject(), City.class); + Assert.assertEquals(null, object.name); + Assert.assertEquals(0, object.code); + } + + + public static class City implements Parcelable { + public final int code; + public final String name; + public final String pinyin; + + @JSONCreator + public City(@JSONField(name = "code") int code, + @JSONField(name = "name") String name, + @JSONField(name = "pinyin") String pinyin) { + this.code = code; + this.name = name; + this.pinyin = pinyin; + } + } + + public static interface Parcelable { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1303.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1303.java new file mode 100644 index 0000000000..f081d16f1a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1303.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.util.TypeUtils; +import junit.framework.TestCase; +import org.junit.Assert; + +/** + * Created by kimmking on 02/07/2017. + */ +public class Issue1303 extends TestCase { + public void test_for_issue() { + String jsonString = "[{\"author\":{\"__type\":\"Pointer\",\"className\":\"_User\",\"objectId\":\"a876c49c18\"},\"createdAt\":\"2017-07-02 20:06:13\",\"imgurl\":\"https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=11075891,34401011&fm=117&gp=0.jpg\",\"name\":\"衣架\",\"objectId\":\"029d5493cd\",\"prices\":\"1\",\"updatedAt\":\"2017-07-02 20:06:13\"}]"; + JSONArray jsonArray = JSON.parseArray(jsonString); + //jsonArray = new JSONArray(jsonArray);//这一句打开也一样是正确的 + double total = 0; + for (int i = 0; i implements Cloneable, Serializable{ + + private static final long serialVersionUID = 4877536176216854937L; + + public IdEntity() {} + + public abstract ID getId(); + public abstract void setId(ID id); + } + + public static class LongEntity extends IdEntity { + + private static final long serialVersionUID = -2740365657805589848L; + + private Long id; + + @Override + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + } + + public static class Goods extends LongEntity{ + private static final long serialVersionUID = -5751106975913625097L; + private List properties; + + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + public static class Property extends LongEntity{ + private static final long serialVersionUID = 7941148286688199390L; + } + } + + public static class TT extends LongEntity { + private static final long serialVersionUID = 2988415809510669142L; + + public TT(){} + public TT(Goods goods){ + goodsList = Arrays.asList(goods); + } + + + private List goodsList; + + public List getGoodsList() { + return goodsList; + } + + public void setGoodsList(List goodsList) { + this.goodsList = goodsList; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1307.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1307.java new file mode 100644 index 0000000000..c0ff4af76f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1307.java @@ -0,0 +1,61 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; + +import com.alibaba.fastjson.serializer.BeanContext; +import com.alibaba.fastjson.serializer.ContextValueFilter; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.ValueFilter; +import junit.framework.TestCase; +import org.junit.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by kimmking on 02/07/2017. + */ +public class Issue1307 extends TestCase { + ContextValueFilter contextValueFilter = new ContextValueFilter() { + public Object process(BeanContext beanContext, Object obj, String name, Object value) { + return "mark-"+value; + } + }; + ValueFilter valueFilter = new ValueFilter() { + public Object process(Object object, String name, Object value) { + return value; + } + }; + + @Test + public void test_context_value_filter_not_effected () { + List params = new ArrayList(); + Map data = new HashMap(); + data.put("name", "ace"); + params.add(data); + //fail Actual :[{"name":"ace"}] + Assert.assertEquals("[{\"name\":\"mark-ace\"}]", JSON.toJSONString(params, + new SerializeFilter[]{ + contextValueFilter + }) + ); + + } + + @Test + public void test_context_value_filter_effected() { + List params = new ArrayList(); + Map data = new HashMap(); + data.put("name", "ace"); + params.add(data); + //success + Assert.assertEquals("[{\"name\":\"mark-ace\"}]", JSON.toJSONString(params, + new SerializeFilter[]{ + contextValueFilter, + valueFilter + }) + ); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1310.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1310.java new file mode 100644 index 0000000000..eff2f97ffb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1310.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 29/07/2017. + */ +public class Issue1310 extends TestCase { + public void test_trim() throws Exception { + Model model = new Model(); + model.value = " a "; + + assertEquals("{\"value\":\"a\"}", JSON.toJSONString(model)); + + Model model2 = JSON.parseObject("{\"value\":\" a \"}", Model.class); + assertEquals("a", model2.value); + } + + public static class Model { + @JSONField(format = "trim") + public String value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1310_noasm.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1310_noasm.java new file mode 100644 index 0000000000..8d1dbd1b59 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1310_noasm.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 29/07/2017. + */ +public class Issue1310_noasm extends TestCase { + public void test_trim() throws Exception { + Model model = new Model(); + model.value = " a "; + + assertEquals("{\"value\":\"a\"}", JSON.toJSONString(model)); + + Model model2 = JSON.parseObject("{\"value\":\" a \"}", Model.class); + assertEquals("a", model2.value); + } + + private static class Model { + @JSONField(format = "trim") + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1319.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1319.java new file mode 100644 index 0000000000..0045c1a2ef --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1319.java @@ -0,0 +1,59 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/07/2017. + */ +public class Issue1319 extends TestCase { + public void test_for_issue() throws Exception { + MyTest test = new MyTest(1, MyEnum.Test1); + String result = JSON.toJSONString(test, SerializerFeature.WriteClassName); + System.out.println(result); + test = JSON.parseObject(result, MyTest.class); + System.out.println(JSON.toJSONString(test)); + assertEquals(MyEnum.Test1, test.getMyEnum()); + assertEquals(1, test.value); + } + + @JSONType(seeAlso = {OtherEnum.class, MyEnum.class}) + interface EnumInterface{ + + } + @JSONType(typeName = "myEnum") + enum MyEnum implements EnumInterface { + Test1, + Test2 + } + @JSONType(typeName = "other") + enum OtherEnum implements EnumInterface { + Other + } + static class MyTest{ + private int value; + private EnumInterface myEnum; + + public MyTest() { + } + + public MyTest(int property, MyEnum enumProperty) { + this.value = property; + this.myEnum = enumProperty; + } + public int getValue() { + return value; + } + public EnumInterface getMyEnum() { + return myEnum; + } + public void setMyEnum(EnumInterface myEnum) { + this.myEnum = myEnum; + } + public void setValue(int value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1320.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1320.java new file mode 100644 index 0000000000..7db25f4fdd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1320.java @@ -0,0 +1,76 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 23/07/2017. + */ +public class Issue1320 extends TestCase { + public void test_for_issue() throws Exception { + SSOToken token = new SSOToken(); + JSON.toJSONString(token); + } + + @SuppressWarnings("serial") + public static class SSOToken extends Token { + + /* 登录类型 */ + private Integer type; + + /* 预留 */ + private String data; + + /** + *

+ * 预留对象,默认 fastjson 不参与序列化(也就是不存放在 cookie 中 ) + *

+ *

+ * 此处配合分布式缓存使用,可以存放用户常用基本信息 + *

+ */ + @JSONField(serialize = false) + private Object object; + + public SSOToken() { + //this.setApp(SSOConfig.getInstance().getRole()); + } + + public Integer getType() { + return type; + } + + public void setType(Integer type) { + this.type = type; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + /** + * 缓存用户信息,自动类型转换 + */ + @SuppressWarnings("unchecked") + public T getCacheObject() { + return (T) this.getObject(); + } + + public Object getObject() { + return object; + } + + public void setObject(Object object) { + this.object = object; + } + } + + public static class Token { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330.java new file mode 100644 index 0000000000..b37a774d2c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 30/07/2017. + */ +public class Issue1330 extends TestCase { + public void test_for_issue() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"ABC\"}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseInt error, field : value") != -1); + } + + public void test_for_issue_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":[]}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseInt error, field : value") != -1); + } + + public void test_for_issue_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{}}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseInt error, field : value") != -1); + } + + public static class Model { + public int value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_boolean.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_boolean.java new file mode 100644 index 0000000000..9aaab11ea4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_boolean.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 30/07/2017. + */ +public class Issue1330_boolean extends TestCase { + public void test_for_issue() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"ABC\"}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseBoolean error, field : value") != -1); + } + + public void test_for_issue_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":[]}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseBoolean error, field : value") != -1); + } + + public void test_for_issue_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{}}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseBoolean error, field : value") != -1); + } + + public static class Model { + public boolean value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_byte.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_byte.java new file mode 100644 index 0000000000..7b23af1d19 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_byte.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 30/07/2017. + */ +public class Issue1330_byte extends TestCase { + public void test_for_issue() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"ABC\"}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseByte error, field : value") != -1); + } + + public void test_for_issue_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":[]}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseByte error, field : value") != -1); + } + + public void test_for_issue_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{}}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseByte error, field : value") != -1); + } + + public static class Model { + public byte value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_decimal.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_decimal.java new file mode 100644 index 0000000000..2de4f3b230 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_decimal.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +import java.math.BigDecimal; + +/** + * Created by wenshao on 30/07/2017. + */ +public class Issue1330_decimal extends TestCase { + public void test_for_issue() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"中ABC\"}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseDecimal error, field : value") != -1); + } + + public void test_for_issue_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":[]}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseDecimal error, field : value") != -1); + } + + public void test_for_issue_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{\"xx\":[]}}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseDecimal error, field : value") != -1); + } + + public static class Model { + public BigDecimal value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_double.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_double.java new file mode 100644 index 0000000000..d1ee30ac5a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_double.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 30/07/2017. + */ +public class Issue1330_double extends TestCase { + public void test_for_issue() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"ABC\"}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseDouble error, field : value") != -1); + } + + public void test_for_issue_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":[]}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseDouble error, field : value") != -1); + } + + public void test_for_issue_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{}}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseDouble error, field : value") != -1); + } + + public static class Model { + public double value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_float.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_float.java new file mode 100644 index 0000000000..64ed2832a0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_float.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 30/07/2017. + */ +public class Issue1330_float extends TestCase { + public void test_for_issue() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"ABC\"}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseLong error, field : value") != -1); + } + + public void test_for_issue_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":[]}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseLong error, field : value") != -1); + } + + public void test_for_issue_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{}}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseLong error, field : value") != -1); + } + + public static class Model { + public float value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_long.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_long.java new file mode 100644 index 0000000000..7708ed5985 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_long.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 30/07/2017. + */ +public class Issue1330_long extends TestCase { + public void test_for_issue() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"ABC\"}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseLong error, field : value") != -1); + } + + public void test_for_issue_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":[]}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseLong error, field : value") != -1); + } + + public void test_for_issue_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{}}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseLong error, field : value") != -1); + } + + public static class Model { + public long value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_short.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_short.java new file mode 100644 index 0000000000..223edf3541 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_short.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 30/07/2017. + */ +public class Issue1330_short extends TestCase { + public void test_for_issue() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"ABC\"}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseShort error, field : value") != -1); + } + + public void test_for_issue_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":[]}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseShort error, field : value") != -1); + } + + public void test_for_issue_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{}}", Model.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + assertTrue(error.getMessage().indexOf("parseShort error, field : value") != -1); + } + + public static class Model { + public short value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1335.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1335.java new file mode 100644 index 0000000000..0265b86e9e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1335.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 22/07/2017. + */ +public class Issue1335 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\n" + + "\"id\": \"21496a63f5\",\n" + + "\"title\": \"\",\n" + + "\"url\": \"http://hl-img.peco.uodoo.com/hubble-test/app/sm/e9b884c1dcd671f128bac020e070e273.jpg;,,JPG;3,208x\",\n" + + "\"type\": \"JPG\",\n" + + "\"optimal_width\": 400,\n" + + "\"optimal_height\": 267,\n" + + "\"original_save_url\": \"http://hl-img.peco.uodoo.com/hubble-test/app/sm/e9b884c1dcd671f128bac020e070e273.jpg\",\n" + + "\"phash\": \"62717D190987A7AE\"\n" + + " }"; + Image image = JSON.parseObject(json, Image.class); + assertEquals("21496a63f5", image.id); + assertEquals("http://hl-img.peco.uodoo.com/hubble-test/app/sm/e9b884c1dcd671f128bac020e070e273.jpg;,,JPG;3,208x", image.url); + assertEquals("", image.title); + assertEquals("JPG", image.type); + assertEquals(400, image.optimalWidth); + assertEquals(267, image.optimalHeight); + assertEquals("http://hl-img.peco.uodoo.com/hubble-test/app/sm/e9b884c1dcd671f128bac020e070e273.jpg", image.original_save_url); + assertEquals("62717D190987A7AE", image.phash); + } + + public static class Image { + public String id; + public String title; + public String url; + public String type; + public int optimalWidth; + public int optimalHeight; + public String original_save_url; + public String phash; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1341.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1341.java new file mode 100644 index 0000000000..7248ecdf5b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1341.java @@ -0,0 +1,171 @@ +package com.alibaba.json.bvt.issue_1300; + + +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.support.config.FastJsonConfig; +import com.alibaba.fastjson.support.jaxrs.FastJsonProvider; +import org.glassfish.jersey.CommonProperties; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.internal.InternalProperties; +import org.glassfish.jersey.internal.util.PropertiesHelper; +import org.glassfish.jersey.server.JSONP; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.Assert; +import org.junit.Test; + +import javax.ws.rs.*; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.Configuration; +import javax.ws.rs.core.Feature; +import javax.ws.rs.core.FeatureContext; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.MessageBodyWriter; +import java.util.Date; + +public class Issue1341 extends JerseyTest { + static class Book { + + private int bookId; + private String bookName; + private String publisher; + private String isbn; + private Date publishTime; + private Object hello; + + public int getBookId() { + return bookId; + } + + public void setBookId(int bookId) { + this.bookId = bookId; + } + + public String getBookName() { + return bookName; + } + + public void setBookName(String bookName) { + this.bookName = bookName; + } + + public String getPublisher() { + return publisher; + } + + public void setPublisher(String publisher) { + this.publisher = publisher; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public Date getPublishTime() { + return publishTime; + } + + public void setPublishTime(Date publishTime) { + this.publishTime = publishTime; + } + + public Object getHello() { + return hello; + } + + public void setHello(Object hello) { + this.hello = hello; + } + } + + static class FastJsonFeature implements Feature { + + private final static String JSON_FEATURE = FastJsonFeature.class.getSimpleName(); + + public boolean configure(final FeatureContext context) { + final Configuration config = context.getConfiguration(); + final String jsonFeature = CommonProperties.getValue(config.getProperties(), config.getRuntimeType(), InternalProperties.JSON_FEATURE, JSON_FEATURE, + String.class); + // Other JSON providers registered. + if (!JSON_FEATURE.equalsIgnoreCase(jsonFeature)) { + return false; + } + // Disable other JSON providers. + context.property(PropertiesHelper.getPropertyNameForRuntime(InternalProperties.JSON_FEATURE, config.getRuntimeType()), JSON_FEATURE); + // Register FastJson. + if (!config.isRegistered(FastJsonProvider.class)) { + //DisableCircularReferenceDetect + FastJsonProvider fastJsonProvider = new FastJsonProvider(); + FastJsonConfig fastJsonConfig = new FastJsonConfig(); + //fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.BrowserSecure); + + fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect); + + fastJsonProvider.setFastJsonConfig(fastJsonConfig); + + context.register(fastJsonProvider, MessageBodyReader.class, MessageBodyWriter.class); + } + return true; + } + } + + + @Path("book1341") + public static class BookRestFul { + + @GET + @Path("{id}") + @Produces({"application/javascript", "application/json"}) + @Consumes({"application/javascript", "application/json"}) + @JSONP(queryParam = "callback") + public Book getBookById(@PathParam("id") Long id) { + + Book book = new Book(); + book.setBookId(2); + book.setBookName("Python源码剖析"); + book.setPublisher("电子工业出版社"); + book.setPublishTime(new Date()); + book.setIsbn("911122"); + + return book; + } + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(new FastJsonFeature()).register(FastJsonProvider.class); + } + + @Override + protected Application configure() { + enable(TestProperties.LOG_TRAFFIC); + enable(TestProperties.DUMP_ENTITY); + + ResourceConfig config = new ResourceConfig(); + + FastJsonProvider fastJsonProvider = new FastJsonProvider(); + FastJsonConfig fastJsonConfig = new FastJsonConfig(); + fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.BrowserSecure); + fastJsonProvider.setFastJsonConfig(fastJsonConfig); + + config.register(fastJsonProvider); + + config.packages("com.alibaba.json.bvt.issue_1300"); + return config; + } + + @Test + public void test() { + + final String reponse = target("book1341").path("123").request().accept("application/javascript").get(String.class); + System.out.println(reponse); + Assert.assertTrue(reponse.indexOf("Python源码剖析") > 0); + Assert.assertTrue(reponse.indexOf("电子工业出版社") > 0); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1344.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1344.java new file mode 100644 index 0000000000..23c39ccbe8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1344.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONCreator; +import junit.framework.TestCase; + +/** + * Created by wenshao on 26/07/2017. + */ +public class Issue1344 extends TestCase { + public void test_for_issue() throws Exception { + TestException testException = new TestException("aaa"); + System.out.println("before:" + testException.getMessage()); + String json = JSONObject.toJSONString(testException); + System.out.println(json); + TestException o = JSONObject.parseObject(json, TestException.class); + System.out.println("after:" + o.getMessage()); + } + + public static class TestException extends Exception { + + @JSONCreator + public TestException() { + + } + + public TestException(String data) { + super("Data : " + data); + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1357.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1357.java new file mode 100644 index 0000000000..0abe42a44c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1357.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.time.LocalDateTime; + +/** + * Created by wenshao on 31/07/2017. + */ +public class Issue1357 extends TestCase { + public void test_for_issue() throws Exception { + + String str = "{\"d2\":null}"; + Test2Bean b = JSONObject.parseObject(str,Test2Bean.class); + System.out.println(b); + } + + public static class Test2Bean{ + private LocalDateTime d2; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1362.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1362.java new file mode 100644 index 0000000000..9dbe3dedc0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1362.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +/** + * Created by wenshao on 03/08/2017. + */ +public class Issue1362 extends TestCase { + public void test_for_issue() throws Exception { + JSONObject object = new JSONObject(); + object.put("val", "null"); + assertEquals(0D, object.getDoubleValue("val")); + assertEquals(0F, object.getFloatValue("val")); + assertEquals(0, object.getIntValue("val")); + assertEquals(0L, object.getLongValue("val")); + assertEquals((short) 0, object.getShortValue("val")); + assertEquals((byte) 0, object.getByteValue("val")); + assertEquals(false, object.getBooleanValue("val")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1363.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1363.java new file mode 100644 index 0000000000..73dcff2894 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1363.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by wenshao on 05/08/2017. + */ +public class Issue1363 extends TestCase { + public void test_for_issue() throws Exception { + DataSimpleVO a = new DataSimpleVO("a", 1); + DataSimpleVO b = new DataSimpleVO("b", 2); + b.value = a; + Map map = new HashMap(); + map.put(a.name, a); + b.value1 = map; + + String jsonStr = JSON.toJSONString(b); + System.out.println(jsonStr); + DataSimpleVO obj = JSON.parseObject(jsonStr, DataSimpleVO.class); + assertEquals(jsonStr, JSON.toJSONString(obj)); + + } + + public void test_for_issue_1() throws Exception { + DataSimpleVO a = new DataSimpleVO("a", 1); + DataSimpleVO b = new DataSimpleVO("b", 2); + b.value1 = a; + Map map = new HashMap(); + map.put(a.name, a); + b.value = map; + + String jsonStr = JSON.toJSONString(b); + System.out.println(jsonStr); + DataSimpleVO obj = JSON.parseObject(jsonStr, DataSimpleVO.class); + System.out.println(obj.toString()); + assertNotNull(obj.value1); + assertEquals(jsonStr, JSON.toJSONString(obj)); + } + + public static class DataSimpleVO { + public String name; + public Object value; + public Object value1; + + public DataSimpleVO() { + } + + public DataSimpleVO(String name, Object value) { + this.name = name; + this.value = value; + } + + @Override + public String toString() { + return "DataSimpleVO [name=" + name + ", value=" + value + ", value1=" + value1 + "]"; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1367.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1367.java new file mode 100644 index 0000000000..89455746c1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1367.java @@ -0,0 +1,157 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; +import com.alibaba.fastjson.support.spring.FastJsonpHttpMessageConverter4; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; + +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.filter.CharacterEncodingFilter; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import java.io.Serializable; +import java.util.List; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Created by songlingdong on 8/5/17. + */ +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration +public class Issue1367 { + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) // + .addFilter(new CharacterEncodingFilter("UTF-8", true)) // 设置服务器端返回的字符集为:UTF-8 + .build(); + } + + + + + + public static class AbstractController> { + + @PostMapping(path = "/typeVariableBean",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + public PO save(@RequestBody PO dto) { + //do something + return dto; + } + + } + + @RestController + @RequestMapping() + public static class BeanController extends AbstractController { + + + + @PostMapping(path = "/parameterizedTypeBean",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + public String parameterizedTypeBean(@RequestBody ParameterizedTypeBean parameterizedTypeBean){ + return parameterizedTypeBean.t; + } + + + } + + + @ComponentScan(basePackages = "com.alibaba.json.bvt.issue_1300") + @Configuration + @Order(Ordered.LOWEST_PRECEDENCE + 1) + @EnableWebMvc + public static class WebMvcConfig extends WebMvcConfigurerAdapter { + @Override + public void configureMessageConverters(List> converters) { + FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); + converters.add(converter); + } + + + } + + + @Test + public void testParameterizedTypeBean() throws Exception { + mockMvc.perform( + (post("/parameterizedTypeBean").characterEncoding("UTF-8") + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("{\"t\": \"neil dong\"}") + )).andExpect(status().isOk()).andDo(print()); + } + + @Test + public void testTypeVariableBean() throws Exception { + mockMvc.perform( + (post("/typeVariableBean").characterEncoding("UTF-8") + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("{\"id\": 1}") + )).andExpect(status().isOk()).andDo(print()); + + } + + + + + + static abstract class GenericEntity { + public abstract ID getId(); + } + + static class TypeVariableBean extends GenericEntity { + private Long id; + + @Override + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + } + + static class ParameterizedTypeBean { + private T t; + + public T getT() { + return t; + } + + public void setT(T t) { + this.t = t; + } + + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1367_jaxrs.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1367_jaxrs.java new file mode 100644 index 0000000000..44a04e49a0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1367_jaxrs.java @@ -0,0 +1,94 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.support.jaxrs.FastJsonProvider; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.Test; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.Response; +import java.io.Serializable; + +/** + *

Title: Issue1367_jaxrs

+ *

Description:

+ * + * @author Victor.Zxy + * @version 1.0 + * @since 2017/8/7 + */ +public class Issue1367_jaxrs extends JerseyTest { + + public static class AbstractController> { + + @POST + @Path("/typeVariableBean") + @Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON) + @Consumes(javax.ws.rs.core.MediaType.APPLICATION_JSON) + public PO save(PO dto) { + //do something + return dto; + } + } + + @Path("beanController") + public static class BeanController extends AbstractController { + + @POST + @Path("/parameterizedTypeBean") + @Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON) + @Consumes(javax.ws.rs.core.MediaType.APPLICATION_JSON) + public String parameterizedTypeBean(Issue1367.ParameterizedTypeBean parameterizedTypeBean) { + return parameterizedTypeBean.getT(); + } + + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(FastJsonProvider.class); + } + + @Override + protected Application configure() { + enable(TestProperties.LOG_TRAFFIC); + enable(TestProperties.DUMP_ENTITY); + + ResourceConfig config = new ResourceConfig(); + + config.register(FastJsonProvider.class); + config.packages("com.alibaba.json.bvt.issue_1300"); + return config; + } + + @Test + public void testParameterizedTypeBean() throws Exception { + + String request = "{\"t\": \"victor zeng\"}"; + + Response response = target("beanController").path("parameterizedTypeBean").request(). + accept("application/json;charset=UTF-8").post(Entity.json(request)); + + System.out.println(response.readEntity(String.class)); + + } + + @Test + public void testTypeVariableBean() throws Exception { + + String request = "{\"id\": 1}"; + + Response response = target("beanController").path("typeVariableBean").request(). + accept("application/json;charset=UTF-8").post(Entity.json(request)); + + System.out.println(response.readEntity(String.class)); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1368.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1368.java new file mode 100644 index 0000000000..de4aff9559 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1368.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.junit.Assert; +import org.springframework.web.servlet.mvc.method.annotation.ExtendedServletRequestDataBinder; + +/** + * Created by kimmking on 03/08/2017. + */ +public class Issue1368 extends TestCase { + public void test_for_issue() throws Exception { + ExtendedServletRequestDataBinder binder = new ExtendedServletRequestDataBinder(new Object()); + String json = JSON.toJSONString(binder); + System.out.println(json); + Assert.assertTrue(json.indexOf("$ref")>=0); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1369.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1369.java new file mode 100644 index 0000000000..8518a3b818 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1369.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.junit.Assert; + +/** + * Created by kimmking on 03/08/2017. + */ +public class Issue1369 extends TestCase { + public void test_for_issue() throws Exception { + Foo foo = new Foo(); + foo.a = 1; + foo.b = "b"; + foo.bars = new Bar(); + foo.bars.c = 3; + String json = JSON.toJSONString(foo); + System.out.println(json); + Assert.assertTrue(json.indexOf("\\")<0); + } + + public static class Foo { + public int a; + public String b; + public Bar bars; + } + public static class Bar { + public int c; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1370.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1370.java new file mode 100644 index 0000000000..0cf55763d0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1370.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.sql.Timestamp; + +/** + * Created by wenshao on 04/08/2017. + */ +public class Issue1370 extends TestCase { + public void test_0() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("val", "2017-08-04 15:16:41.000000000"); + + Model model = obj.toJavaObject(Model.class); + assertNotNull(model.val); + } + + public void test_1() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("val", "2017-08-04 15:16:41.0"); + + Model model = obj.toJavaObject(Model.class); + assertNotNull(model.val); + } + + public void test_2() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("val", "2017-08-04 15:16:41.00"); + + Model model = obj.toJavaObject(Model.class); + assertNotNull(model.val); + } + + public void test_3() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("val", "2017-08-04 15:16:41.000"); + + Model model = obj.toJavaObject(Model.class); + assertNotNull(model.val); + } + + + public void test_4() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("val", "2017-08-04 15:16:41.000000"); + + Model model = obj.toJavaObject(Model.class); + assertNotNull(model.val); + } + + public static class Model { + public Timestamp val; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1371.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1371.java new file mode 100644 index 0000000000..86d7b881a5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1371.java @@ -0,0 +1,67 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import junit.framework.TestCase; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Map; +import java.util.TreeMap; + +/** + * Created by wenshao on 05/08/2017. + */ +public class Issue1371 extends TestCase { + private enum Rooms{ + A, B, C, D ,E ; + } + + public void testFastjsonEnum(){ + + Map enumMap = new TreeMap(); + + enumMap.put(Rooms.C, Rooms.D); + enumMap.put(Rooms.E, Rooms.A); + + Assert.assertEquals(JSON.toJSONString(enumMap, SerializerFeature.WriteNonStringKeyAsString), + "{\"C\":\"D\",\"E\":\"A\"}"); + + } + + + + +// public void testParsed(){ +// +// String oldStyleJson = "{1:'abc', 2:'cde'}"; +// +// Gson gson = new Gson(); +// +// Map fromJson = gson.fromJson(oldStyleJson, Map.class); +// +// Assert.assertNull(fromJson.get(1)); +// +// Assert.assertEquals(fromJson.get("1"), "abc" ); +// +// Map parsed = JSON.parseObject(oldStyleJson, Map.class, Feature.IgnoreAutoType, Feature.DisableFieldSmartMatch); +// +// +// Assert.assertNull(parsed.get(1)); +// +// Assert.assertEquals(parsed.get("1"), "abc" ); +// +// } +// +// public void testParsed_jackson() throws Exception { +// +// String oldStyleJson = "{1:\"abc\", 2:\"cde\"}"; +// +// ObjectMapper objectMapper = new ObjectMapper(); +// Map fromJson = objectMapper.readValue(oldStyleJson, Map.class); +// Assert.assertNull(fromJson.get(1)); +// } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1375.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1375.java new file mode 100644 index 0000000000..a03fd2bbce --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1375.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.serializer.CollectionCodec; +import com.alibaba.fastjson.serializer.SerializeConfig; +import junit.framework.TestCase; + +import java.util.LinkedList; + +/** + * Created by wenshao on 06/08/2017. + */ +public class Issue1375 extends TestCase { + public void test_issue() throws Exception { + assertSame(CollectionCodec.instance + , SerializeConfig.getGlobalInstance() + .getObjectWriter(LinkedList.class)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1392.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1392.java new file mode 100644 index 0000000000..7ef5e0be92 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1392.java @@ -0,0 +1,147 @@ +package com.alibaba.json.bvt.issue_1300; + + +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.support.config.FastJsonConfig; +import com.alibaba.fastjson.support.jaxrs.FastJsonFeature; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.server.JSONP; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.Assert; +import org.junit.Test; + +import javax.ws.rs.*; +import javax.ws.rs.core.Application; +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Provider; +import java.util.Date; + +public class Issue1392 extends JerseyTest { + + static class Book { + + private int bookId; + private String bookName; + private String publisher; + private String isbn; + private Date publishTime; + private Object hello; + + public int getBookId() { + return bookId; + } + + public void setBookId(int bookId) { + this.bookId = bookId; + } + + public String getBookName() { + return bookName; + } + + public void setBookName(String bookName) { + this.bookName = bookName; + } + + public String getPublisher() { + return publisher; + } + + public void setPublisher(String publisher) { + this.publisher = publisher; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public Date getPublishTime() { + return publishTime; + } + + public void setPublishTime(Date publishTime) { + this.publishTime = publishTime; + } + + public Object getHello() { + return hello; + } + + public void setHello(Object hello) { + this.hello = hello; + } + } + + @Provider + static class FastJsonResolver implements ContextResolver { + + public FastJsonConfig getContext(Class type) { + + FastJsonConfig fastJsonConfig = new FastJsonConfig(); + + fastJsonConfig.setSerializerFeatures( + SerializerFeature.WriteMapNullValue, + SerializerFeature.BrowserSecure); + + return fastJsonConfig; + } + } + + + @Path("book1392") + public static class BookRestFul { + + @GET + @Path("{id}") + @Produces({"application/javascript", "application/json"}) + @Consumes({"application/javascript", "application/json"}) + @JSONP(queryParam = "callback") + public Book getBookById(@PathParam("id") Long id) { + + Book book = new Book(); + book.setBookId(2); + book.setBookName("Python源码剖析"); + book.setPublisher("电子工业出版社"); + book.setPublishTime(new Date()); + book.setIsbn("911122"); + + return book; + } + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(FastJsonFeature.class); + } + + @Override + protected Application configure() { + enable(TestProperties.LOG_TRAFFIC); + enable(TestProperties.DUMP_ENTITY); + + ResourceConfig config = new ResourceConfig(); + + config.register(FastJsonResolver.class); + + config.register(FastJsonFeature.class); + + config.packages("com.alibaba.json.bvt.issue_1300"); + return config; + } + + @Test + public void test() { + + final String reponse = target("book1392").path("123").request().accept("application/javascript").get(String.class); + System.out.println(reponse); + Assert.assertTrue(reponse.indexOf("Python源码剖析") > 0); + Assert.assertTrue(reponse.indexOf("电子工业出版社") > 0); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1399.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1399.java new file mode 100644 index 0000000000..a5d5a9b5c0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue1399.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 15/08/2017. + */ +public class Issue1399 extends TestCase { + public void test_for_issue() throws Exception { + JSON.parseObject("false", boolean.class); + JSON.parseObject("false", Boolean.class); + JSON.parseObject("\"false\"", boolean.class); + JSON.parseObject("\"false\"", Boolean.class); + +// JSON.parseObject("FALSE", boolean.class); +// JSON.parseObject("FALSE", Boolean.class); + JSON.parseObject("\"FALSE\"", boolean.class); + JSON.parseObject("\"FALSE\"", Boolean.class); + } + + public void test_for_issue_true() throws Exception { + JSON.parseObject("true", boolean.class); + JSON.parseObject("true", Boolean.class); + JSON.parseObject("\"true\"", boolean.class); + JSON.parseObject("\"true\"", Boolean.class); + +// JSON.parseObject("FALSE", boolean.class); +// JSON.parseObject("FALSE", Boolean.class); + JSON.parseObject("\"TRUE\"", boolean.class); + JSON.parseObject("\"TRUE\"", Boolean.class); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1300/Issue_for_zuojian.java b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue_for_zuojian.java new file mode 100644 index 0000000000..52c1d64cb8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1300/Issue_for_zuojian.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.issue_1300; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.util.Date; + +public class Issue_for_zuojian extends TestCase { + public void test_for_issue() throws Exception { + JSON.DEFFAULT_DATE_FORMAT = "yyyyMMddHHmmssSSSZ"; + String json = "{\"value\":\"20180131022733000-0800\"}"; + JSON.parseObject(json, Model.class); + JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + } + + public void test_for_issue_1() throws Exception { + JSON.DEFFAULT_DATE_FORMAT = "yyyyMMddHHmmssSSSZ"; + + String json = "{\"value\":\"20180131022733000-0800\"}"; + JSONObject object = JSON.parseObject(json); + object.getObject("value", Date.class); + + JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + } + + public static class Model { + public Date value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1400.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1400.java new file mode 100644 index 0000000000..8e8893d152 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1400.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by kimmking on 11/08/2017. + */ +public class Issue1400 extends TestCase { + public void test_for_issue() throws Exception { + TypeReference tr = new TypeReference>>(){}; + Test test = new Test(tr); + Resource resource = test.resource; + Assert.assertEquals(1,resource.ret); + Assert.assertEquals("ok",resource.message); + List data =(List) resource.data; + Assert.assertEquals(2,data.size()); + App app1 = data.get(0); + Assert.assertEquals("11c53f541dee4f5bbc4f75f99002278c",app1.appId); + } + + public static class Resource { + public int ret; + public String message; + public T data; + } + + public static class App { + public String appId; + } + + public static class Test { + String str = "{\"ret\":1,\"message\":\"ok\",\"data\":[{\"appId\":\"11c53f541dee4f5bbc4f75f99002278c\"},{\"appId\":\"c6102275ce5540a59424defa1cccb8ed\"}]}"; + public Resource resource; + Test(TypeReference tr) { + resource = (Resource)JSON.parseObject(str, tr); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1405.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1405.java new file mode 100644 index 0000000000..a342d36e3a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1405.java @@ -0,0 +1,181 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; +import com.alibaba.fastjson.support.spring.FastJsonJsonView; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.stereotype.Controller; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.filter.CharacterEncodingFilter; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import java.util.List; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Created by songlingdong on 8/5/17. + */ +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration +public class Issue1405 { + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) // + .addFilter(new CharacterEncodingFilter("UTF-8", true)) // 设置服务器端返回的字符集为:UTF-8 + .build(); + } + + @Controller + @RequestMapping("fastjson") + public static class BeanController { + + @RequestMapping(value = "/test1405", method = RequestMethod.GET) + public + @ResponseBody + ModelAndView test7() { + + AuthIdentityRequest authRequest = new AuthIdentityRequest(); + authRequest.setAppId("cert01"); + authRequest.setUserId(2307643); + authRequest.setIdNumber("34324324234234"); + authRequest.setRealName("杨力"); + authRequest.setBusinessLine(""); + authRequest.setIgnoreIdNumberRepeat(false); + authRequest.setOffline(false); + + ModelAndView modelAndView = new ModelAndView(); + modelAndView.addObject("message", authRequest); + modelAndView.addObject("title", "testPage"); + modelAndView.setViewName("test"); + + return modelAndView; + } + + } + + + @ComponentScan(basePackages = "com.alibaba.json.bvt.issue_1400") + @Configuration + @Order(Ordered.LOWEST_PRECEDENCE + 1) + @EnableWebMvc + public static class WebMvcConfig extends WebMvcConfigurerAdapter { + @Override + public void configureMessageConverters(List> converters) { + FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); + converters.add(converter); + } + + @Override + public void configureViewResolvers(ViewResolverRegistry registry) { + FastJsonJsonView fastJsonJsonView = new FastJsonJsonView(); + registry.enableContentNegotiation(fastJsonJsonView); + } + } + + @Test + public void test7() throws Exception { + + mockMvc.perform( + (get("/fastjson/test1405").characterEncoding("UTF-8") + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + )).andExpect(status().isOk()).andDo(print()); + } + + static class AuthIdentityRequest { + + private String appId; + private int userId; + private String idNumber; + private String realName; + private String businessLine; + private boolean ignoreIdNumberRepeat; + private boolean offline; + + public String getAppId() { + return appId; + } + + public void setAppId(String appId) { + this.appId = appId; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getIdNumber() { + return idNumber; + } + + public void setIdNumber(String idNumber) { + this.idNumber = idNumber; + } + + public String getRealName() { + return realName; + } + + public void setRealName(String realName) { + this.realName = realName; + } + + public String getBusinessLine() { + return businessLine; + } + + public void setBusinessLine(String businessLine) { + this.businessLine = businessLine; + } + + public boolean isIgnoreIdNumberRepeat() { + return ignoreIdNumberRepeat; + } + + public void setIgnoreIdNumberRepeat(boolean ignoreIdNumberRepeat) { + this.ignoreIdNumberRepeat = ignoreIdNumberRepeat; + } + + public boolean isOffline() { + return offline; + } + + public void setOffline(boolean offline) { + this.offline = offline; + } + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1422.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1422.java new file mode 100644 index 0000000000..1d68639fa2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1422.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; +import junit.framework.TestCase; + +import java.io.StringReader; + +public class Issue1422 extends TestCase { + public void test_for_issue() throws Exception { + String strOk = "{\"v\": 111}"; + + Foo ok = JSON.parseObject(strOk, Foo.class); + assertFalse(ok.v); + } + + public void test_for_issue_reader() throws Exception { + String strBad = "{\"v\": 111}"; + Foo bad = new JSONReader(new StringReader(strBad)).readObject(Foo.class); + assertFalse(bad.v); + } + + public void test_for_issue_1() throws Exception { + String strBad = "{\"v\":111}"; + Foo bad = JSON.parseObject(strBad, Foo.class); + assertFalse(bad.v); + } + + public void test_for_issue_1_reader() throws Exception { + String strBad = "{\"v\":111}"; + Foo bad = new JSONReader(new StringReader(strBad)).readObject(Foo.class); + assertFalse(bad.v); + } + + public static class Foo { + public boolean v; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1423.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1423.java new file mode 100644 index 0000000000..0d4d5a09d5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1423.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +import java.io.StringReader; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; + +public class Issue1423 extends TestCase { + public void test_for_issue() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"v\":9223372036854775808}", LongVal.class); + } catch (JSONException e) { + e.printStackTrace(); + error = e; + } + assertNotNull(error); + error.printStackTrace(); + } + + public void test_for_issue_reader() throws Exception { + Exception error = null; + try { + new JSONReader(new StringReader("{\"v\":9223372036854775808}")).readObject(LongVal.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + } + + public void test_for_issue_arrayMapping() throws Exception { + Exception error = null; + try { + JSON.parseObject("[9223372036854775808]", LongVal.class, Feature.SupportArrayToBean); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + } + + public void test_for_issue_arrayMapping_reader() throws Exception { + Exception error = null; + try { + new JSONReader(new StringReader("[9223372036854775808]"), Feature.SupportArrayToBean).readObject(LongVal.class); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + error.printStackTrace(); + } + + public static class LongVal { + private long v; + public void setV(long v) { + this.v = v; + } + + @Override + public String toString() { + return String.valueOf(v); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1424.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1424.java new file mode 100644 index 0000000000..07870e076f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1424.java @@ -0,0 +1,76 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +public class Issue1424 extends TestCase { + + public static class IntegerVal { + private int v; + + public void setV(int v) { + this.v = v; + } + + @Override + public String toString() { + return String.valueOf(v); + } + } + + public static class FloatVal { + private float v; + + public void setV(float v) { + this.v = v; + } + + @Override + public String toString() { + return String.valueOf(v); + } + } + + public void test_for_issue_int() { + Map intOverflowMap = new HashMap(); + long intOverflow = Integer.MAX_VALUE; + intOverflowMap.put("v", intOverflow + 1); + String sIntOverflow = JSON.toJSONString(intOverflowMap); + + Exception error = null; + try { + JSON.parseObject(sIntOverflow, IntegerVal.class); + } catch (Exception e) { + error = e; + } + assertNotNull(error); + } + + public void test_for_issue_float() { + Map floatOverflowMap = new HashMap(); + double floatOverflow = Float.MAX_VALUE; + floatOverflowMap.put("v", floatOverflow + 1); + String sFloatOverflow = JSON.toJSONString(floatOverflowMap); + + assertEquals("{\"v\":3.4028234663852886E38}", sFloatOverflow); + FloatVal floatVal = JSON.parseObject(sFloatOverflow, FloatVal.class); + assertEquals(3.4028235E38F, floatVal.v); + + assertEquals(floatVal.v, Float.parseFloat("3.4028234663852886E38")); + } + + public void test_for_issue_float_infinity() { + Map floatOverflowMap = new HashMap(); + double floatOverflow = Float.MAX_VALUE; + floatOverflowMap.put("v", floatOverflow + floatOverflow); + String sFloatOverflow = JSON.toJSONString(floatOverflowMap); + + System.out.println(sFloatOverflow); + assertEquals("{\"v\":6.805646932770577E38}", sFloatOverflow); + FloatVal floatVal = JSON.parseObject(sFloatOverflow, FloatVal.class); + assertEquals(Float.parseFloat("6.805646932770577E38"), floatVal.v); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1425.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1425.java new file mode 100644 index 0000000000..52ba867756 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1425.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +public class Issue1425 extends TestCase { + public void test_for_issue() throws Exception { + DicDomain dicDomain = new DicDomain(); + dicDomain.setCode("A001"); + dicDomain.setName("测试"); + + SerializerFeature[] features = new SerializerFeature[]{ + SerializerFeature.NotWriteRootClassName, + SerializerFeature.WriteClassName, + SerializerFeature.DisableCircularReferenceDetect + }; + + System.out.println(JSON.toJSONString(dicDomain, features)); + } + public static class DicDomain { + + private String code; + + private String name; + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1429.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1429.java new file mode 100644 index 0000000000..4d049e6319 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1429.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; + +import java.util.List; + +public class Issue1429 extends TestCase { + public void test_for_issue() throws Exception { + String json = "[{\n" + + " \"@type\": \"com.alibaba.json.bvt.issue_1400.Issue1429$Student\",\n" + + " \"age\": 22,\n" + + " \"id\": 1,\n" + + " \"name\": \"hello\"\n" + + " }, {\n" + + " \"age\": 22,\n" + + " \"id\": 1,\n" + + " \"name\": \"hhh\",\n" + + " \"@type\": \"com.alibaba.json.bvt.issue_1400.Issue1429$Student\"\n" + + " }]"; + + List list = JSON.parseArray(json); + Student s0 = (Student) list.get(0); + assertEquals(1, s0.id); + assertEquals(22, s0.age); + assertEquals("hello", s0.name); + + Student s1 = (Student) list.get(1); + assertEquals(1, s1.id); + assertEquals(22, s1.age); + assertEquals("hhh", s1.name); + } + + @JSONType + public static class Student { + public int id; + public int age; + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1443.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1443.java new file mode 100644 index 0000000000..d6090702f0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1443.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.Date; + +public class Issue1443 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"date\":\"3017-08-28T00:00:00+08:00\"}"; + Model model = JSON.parseObject(json, Model.class); + + } + + public static class Model { + public Date date; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1445.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1445.java new file mode 100644 index 0000000000..3aa5279df9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1445.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +public class Issue1445 extends TestCase { + public void test_for_issue() throws Exception { + + JSONObject obj = new JSONObject(); + obj.put("data", new JSONObject()); + obj.getJSONObject("data").put("data", new JSONObject()); + obj.getJSONObject("data").getJSONObject("data").put("map", new JSONObject()); + obj.getJSONObject("data").getJSONObject("data").getJSONObject("map").put("21160001", "abc"); + + String json = JSON.toJSONString(obj); + assertEquals("abc", JSONPath.read(json,"data.data.map.21160001")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1449.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1449.java new file mode 100644 index 0000000000..bb2900d36e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1449.java @@ -0,0 +1,94 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.serializer.JSONSerializable; +import com.alibaba.fastjson.serializer.JSONSerializer; +import junit.framework.TestCase; + +import java.io.IOException; +import java.io.Serializable; +import java.lang.reflect.Type; + +public class Issue1449 extends TestCase { + public void test_for_issue() throws Exception { + Student student = new Student(); + student.name = "name"; + student.id = 1L; + student.sex = Sex.MAN; + System.out.println(JSON.toJSON(student).toString()); + System.out.println(JSON.toJSONString(student)); + String str1 = "{\"id\":1,\"name\":\"name\",\"sex\":\"MAN\"}"; + Student stu1 = JSON.parseObject(str1, Student.class); + System.out.println(JSON.toJSONString(stu1)); + String str2 = "{\"id\":1,\"name\":\"name\",\"sex\":{\"code\":\"1\",\"des\":\"男\"}}"; + JSON.parseObject(str2, Student.class); + + } + + @JSONType(deserializer = SexDeserializer.class) + public static enum Sex implements JSONSerializable { + + NONE("0","NONE"),MAN("1","男"),WOMAN("2","女"); + private final String code; + private final String des; + private Sex(String code, String des) { + this.code = code; + this.des = des; + } + + public String getCode() { + return code; + } + + public String getDes() { + return des; + } + + public void write(JSONSerializer serializer, Object fieldName, Type fieldType, int features) throws IOException { + + JSONObject object = new JSONObject(); + object.put("code", code); + object.put("des", des); + serializer.write(object); + + } + } + + public static class SexDeserializer implements ObjectDeserializer { + + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + String code; + Object object = parser.parse(); + if (object instanceof JSONObject) { + JSONObject jsonObject = (JSONObject) object; + code = jsonObject.getString("code"); + } else { + code = (String) object; + } + if ("0".equals(code)) { + return (T) Sex.NONE; + } else if ("1".equals(code)) { + return (T) Sex.MAN; + } else if ("2".equals(code)) { + return (T) Sex.WOMAN; + } + return (T) Sex.NONE; + } + + public int getFastMatchToken() { + return 0; + } + } + public static class Student implements Serializable { + + public Long id; + + public String name; + + public Sex sex; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1450.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1450.java new file mode 100644 index 0000000000..26f322edc5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1450.java @@ -0,0 +1,14 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.time.LocalDateTime; + +public class Issue1450 extends TestCase { + public void test_for_issue() throws Exception { + LocalDateTime localDateTime = LocalDateTime.of(2018, 8, 31, 15, 26, 37, 1); + String json = JSON.toJSONStringWithDateFormat(localDateTime, "yyyy-MM-dd HH:mm:ss");//2018-08-31T15:26:37.000000001 + assertEquals("\"2018-08-31 15:26:37\"", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1458.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1458.java new file mode 100644 index 0000000000..e0be564587 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1458.java @@ -0,0 +1,95 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.google.common.collect.ImmutableMap; +import junit.framework.TestCase; + +import java.io.Serializable; + +public class Issue1458 extends TestCase { + public void test_for_issue() throws Exception { + HostPoint hostPoint = new HostPoint(new HostAddress("192.168.10.101")); + hostPoint.setFingerprint(new Fingerprint("abc")); + + String json = JSON.toJSONString(hostPoint); + + HostPoint hostPoint1 = JSON.parseObject(json, HostPoint.class); + String json1 = JSON.toJSONString(hostPoint1); + assertEquals(json, json1); + } + + public static class HostPoint implements Serializable { + + private final HostAddress address; + + @JSONField(name = "fingerprint") + private Fingerprint fingerprint; + + @JSONField(name = "unkown") + private boolean unkown; + + // ------------------------------------------------------------------------ + + @JSONCreator + public HostPoint(@JSONField(name = "address") HostAddress addr) { + this.address = addr; + } + + public boolean isChanged() { + return false; + } + + public boolean isMatched() { + return false; + } + + + public HostAddress getAddress() { + return address; + } + + public Fingerprint getFingerprint() { + return fingerprint; + } + + public void setFingerprint(Fingerprint fingerprint) { + this.fingerprint = fingerprint; + } + + public boolean isUnkown() { + return unkown; + } + + public void setUnkown(boolean unkown) { + this.unkown = unkown; + } + + } + + public static class Fingerprint implements Serializable { + private final String source; + + private ImmutableMap probes; + + @JSONCreator + public Fingerprint(@JSONField(name = "source") String fingerprint) { + this.source = fingerprint; + } + + + public String getSource() { + return source; + } + + } + + public static class HostAddress { + public final String hostAddress; + + public HostAddress(String hostAddress) { + this.hostAddress = hostAddress; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1465.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1465.java new file mode 100644 index 0000000000..a522743363 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1465.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +public class Issue1465 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"id\":3,\"hasSth\":true}"; + Model model = JSON.parseObject(json, Model.class); + assertEquals(0, model.hasSth); + assertEquals(3, model.id); + } + + public static class Model { + private int id; + @JSONField(deserialize = false) + private int hasSth; + + public int getHasSth() { + return hasSth; + } + + @JSONField(deserialize = false) + public void setHasSth(int hasSth) { + this.hasSth = hasSth; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1472.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1472.java new file mode 100644 index 0000000000..dad1bf8623 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1472.java @@ -0,0 +1,4 @@ +package com.alibaba.json.bvt.issue_1400; + +public class Issue1472 { +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1474.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1474.java new file mode 100644 index 0000000000..2d3f8f57d9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1474.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +public class Issue1474 extends TestCase { + public void test_for_issue() throws Exception { + Map extraData = new HashMap(); + extraData.put("ext_1", null); + extraData.put("ext_2", null); + + People p = new People(); + p.setId("001"); + p.setName("顾客"); + p.setExtraData(extraData); + + assertEquals("{\"id\":\"001\",\"name\":\"顾客\"}", JSON.toJSONString(p)); + } + + @JSONType(asm = false) + static class People{ + private String name; + private String id; + @JSONField(unwrapped=true) + private Object extraData; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public Object getExtraData() { + return extraData; + } + public void setExtraData(Object extraData) { + this.extraData = extraData; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1478.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1478.java new file mode 100644 index 0000000000..7c93491452 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1478.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +public class Issue1478 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.md5 = "xxx"; + + String json = JSON.toJSONString(model); + assertEquals("{\"MD5\":\"xxx\"}", json); + } + + public static class Model { + @JSONField(name = "MD5") + private String md5; + + public String getMD5() throws Exception { + return md5; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1480.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1480.java new file mode 100644 index 0000000000..45edb90168 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1480.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.HashMap; +import java.util.Map; + +public class Issue1480 extends TestCase { + public void test_for_issue() throws Exception { + + Map map = new HashMap(); + map.put(1,10); + map.put(2,4); + map.put(3,5); + map.put(4,5); + map.put(37306,98); + map.put(36796,9); + + String json = JSON.toJSONString(map); + System.out.println(json); + Assert.assertEquals("{1:10,2:4,3:5,4:5,37306:98,36796:9}",json); + + Map map1 = JSON.parseObject(json,new TypeReference>() {}); + + Assert.assertEquals(map1.get(Integer.valueOf(1)),Integer.valueOf(10)); + Assert.assertEquals(map1.get(Integer.valueOf(2)),Integer.valueOf(4)); + Assert.assertEquals(map1.get(Integer.valueOf(3)),Integer.valueOf(5)); + Assert.assertEquals(map1.get(Integer.valueOf(4)),Integer.valueOf(5)); + Assert.assertEquals(map1.get(Integer.valueOf(37306)),Integer.valueOf(98)); + Assert.assertEquals(map1.get(Integer.valueOf(36796)),Integer.valueOf(9)); + + JSONObject map2 = JSON.parseObject("{35504:1,1:10,2:4,3:5,4:5,37306:98,36796:9\n" + "}"); + + Assert.assertEquals(map2.get(Integer.valueOf(1)),Integer.valueOf(10)); + Assert.assertEquals(map2.get(Integer.valueOf(2)),Integer.valueOf(4)); + Assert.assertEquals(map2.get(Integer.valueOf(3)),Integer.valueOf(5)); + Assert.assertEquals(map2.get(Integer.valueOf(4)),Integer.valueOf(5)); + Assert.assertEquals(map2.get(Integer.valueOf(37306)),Integer.valueOf(98)); + Assert.assertEquals(map2.get(Integer.valueOf(36796)),Integer.valueOf(9)); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1482.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1482.java new file mode 100644 index 0000000000..d55b9bb3b9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1482.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.Date; + +public class Issue1482 extends TestCase { + public void test_for_issue() throws Exception { + JSON.parseObject("{\"date\":\"2017-06-28T07:20:05.000+05:30\"}", Model.class); + } + + public static class Model { + public Date date; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1486.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1486.java new file mode 100644 index 0000000000..f00c49795f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1486.java @@ -0,0 +1,74 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.util.List; + +public class Issue1486 extends TestCase { + public void test_for_issue() throws Exception { + + String json = "[{\"song_list\":[{\"val\":1,\"v_al\":2},{\"val\":2,\"v_al\":2},{\"val\":3,\"v_al\":2}],\"songlist\":\"v_al\"}]"; + List parseObject = JSON.parseObject(json, new TypeReference>() { + }); + for (Value value : parseObject) { + System.out.println(value.songList + " " ); + } + } + + public static class Value { + @JSONField(alternateNames = {"song_list", "songList"}) + List songList; + + @JSONField(alternateNames = {"songlist"}) + String songlist; + + public List getSongList() { + return songList; + } + + public void setSongList(List songList) { + this.songList = songList; + } + + public String getSonglist() { + return songlist; + } + + public void setSonglist(String songlist) { + this.songlist = songlist; + } + } + + public static class Value2 { + int val; + + int v_al; + + public int getVal() { + return val; + } + + public void setVal(int val) { + this.val = val; + } + + public int getV_al() { + return v_al; + } + + public void setV_al(int v_al) { + this.v_al = v_al; + } + + @Override + public String toString() { + return "Value2{" + + "val=" + val + + ", v_al=" + v_al + + '}'; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1487.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1487.java new file mode 100644 index 0000000000..178c51f813 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1487.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +public class Issue1487 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model._id = 1001L; + model.id = 1002L; + + String json = JSON.toJSONString(model); + assertEquals("{\"_id\":1001,\"id\":1002}", json); + Model model1 = JSON.parseObject(json, Model.class); + assertEquals(json, JSON.toJSONString(model1)); + } + + public static class Model { + private Long _id; + private Long id; + + @JSONField(name = "_id") + public long get_id() { + if (null != _id) { + return _id.longValue(); + } else { + return 0L; + } + } + + @JSONField(name = "_id") + public void set_id(Long _id) { + this._id = _id; + } + + public long getId() { + if (null != id) { + return id.longValue(); + } else { + return 0L; + } + } + + public void setId(Long id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1492.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1492.java new file mode 100644 index 0000000000..42dbb8174b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1492.java @@ -0,0 +1,80 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.io.Serializable; + +public class Issue1492 extends TestCase { + public void test_for_issue() throws Exception { + DubboResponse resp = new DubboResponse(); + + // test for JSONObject + JSONObject obj = new JSONObject(); + obj.put("key1","value1"); + obj.put("key2","value2"); + resp.setData(obj); + + String str = JSON.toJSONString(resp); + System.out.println(str); + DubboResponse resp1 = JSON.parseObject(str, DubboResponse.class); + assertEquals(str, JSON.toJSONString(resp1)); + + // test for JSONArray + JSONArray arr = new JSONArray(); + arr.add("key1"); + arr.add("key2"); + resp.setData(arr); + + String str2 = JSON.toJSONString(resp); + System.out.println(str2); + DubboResponse resp2 = JSON.parseObject(str2, DubboResponse.class); + assertEquals(str2, JSON.toJSONString(resp2)); + + } + + public static final class DubboResponse implements Serializable { + + private String message; + + private String error; + + private JSON data; + + private boolean success; + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public JSON getData() { + return data; + } + + public void setData(JSON data) { + this.data = data; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1493.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1493.java new file mode 100644 index 0000000000..2195647e82 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1493.java @@ -0,0 +1,74 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.bvt.issue_1500.Issue1500; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Locale; +import java.util.TimeZone; + +public class Issue1493 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_issue() throws Exception { + + TestBean test = new TestBean(); + String stime2 = "2017-09-22 15:08:56"; + + LocalDateTime time1 = LocalDateTime.now(); + time1 = time1.minusNanos(10L); + System.out.println(time1.getNano()); + LocalDateTime time2 = LocalDateTime.parse(stime2, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.CHINA)); + test.setTime1(time1); + test.setTime2(time2); + String t1 = JSON.toJSONString(time1, SerializerFeature.WriteDateUseDateFormat); + + String json = JSON.toJSONString(test, SerializerFeature.WriteDateUseDateFormat); + Assert.assertEquals("{\"time1\":"+t1+",\"time2\":\""+stime2+"\"}",json); + + + //String default_format = JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT; + //JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; + //String stime1 = DateTimeFormatter.ofPattern(JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT, Locale.CHINA).format(time1); + + json = JSON.toJSONString(test, SerializerFeature.WriteDateUseDateFormat); + Assert.assertEquals("{\"time1\":"+ JSON.toJSONString(time1, SerializerFeature.WriteDateUseDateFormat) +",\"time2\":\""+stime2+"\"}",json); + + + String pattern = "yyyy-MM-dd HH:mm:ss"; + String stime1 = DateTimeFormatter.ofPattern(pattern, Locale.CHINA).format(time1); + + json = JSON.toJSONStringWithDateFormat(test, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat); + Assert.assertEquals("{\"time1\":\""+stime1+"\",\"time2\":\""+stime2+"\"}",json); + + //JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT = default_format; + } + + public static class TestBean { + LocalDateTime time1; + LocalDateTime time2; + + public LocalDateTime getTime1() { + return time1; + } + + public void setTime1(LocalDateTime time1) { + this.time1 = time1; + } + + public LocalDateTime getTime2() { + return time2; + } + + public void setTime2(LocalDateTime time2) { + this.time2 = time2; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1494.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1494.java new file mode 100644 index 0000000000..47697248b8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1494.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializeConfig; +import junit.framework.TestCase; + +public class Issue1494 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"id\":1001,\"name\":\"wenshao\"}"; + B b = JSON.parseObject(json, B.class); + assertEquals("{\"id\":1001,\"name\":\"wenshao\"}", JSON.toJSONString(b)); + } + + public static class A { + private int id; + + public int getId() { + return id; + } + } + + @JSONType(parseFeatures = Feature.SupportNonPublicField) + public static class B extends A { + private String name; + + public String getName() { + return name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1496.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1496.java new file mode 100644 index 0000000000..660b0016e7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1496.java @@ -0,0 +1,201 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializeConfig; +import junit.framework.TestCase; + +import java.util.Arrays; +import java.util.List; + +public class Issue1496 extends TestCase { + public void test_for_issue() throws Exception { + String json = JSON.toJSONString(SetupStatus.FINAL_TRAIL); + assertEquals("{\"canRefuse\":true,\"code\":3,\"declaringClass\":\"com.alibaba.json.bvt.issue_1400.Issue1496$SetupStatus\",\"first\":false,\"last\":false,\"name\":\"FINAL_TRAIL\",\"nameCn\":\"公益委员会/理事会/理事长审核\"}", json); + } + + public interface ISetupStatusInfo { + List nextList(); + + Boolean isFirst(); + + Boolean isLast(); + } + + public interface ISetupStatusProcess { + + /** + * + * @return + */ + SetupStatus refuse(); + + /** + * 状态转移失败返回null + * + * @param name + * @return + */ + SetupStatus next(String name); + + } + + @JSONType(serializeEnumAsJavaBean = true) + public enum SetupStatus implements ISetupStatusInfo, ISetupStatusProcess { + EDIT(0, "EDIT", "编辑中") { + public List nextList() { + return Arrays.asList(FIRST_TRAIL); + } + + @Override + public Boolean isFirst() { + return true; + } + + @Override + public SetupStatus refuse() { + return EDIT; + } + + }, FIRST_TRAIL(1, "FIRST_TRAIL", "初审") { + public List nextList() { + return Arrays.asList(EXPERT, FINAL_TRAIL); + } + + @Override + public SetupStatus refuse() { + return EDIT; + } + + }, EXPERT(2, "EXPERT", "专家补充意见", false) { + public List nextList() { + return Arrays.asList(FINAL_TRAIL); + } + + }, FINAL_TRAIL(3, "FINAL_TRAIL", "公益委员会/理事会/理事长审核") { + public List nextList() { + return Arrays.asList(PASS); + } + + @Override + public SetupStatus refuse() { + return EDIT; + } + }, PASS(4, "PASS", "项目通过", false) { + public List nextList() { + return Arrays.asList(SIGN); + } + }, SIGN(5, "SIGN", "协议签署", false) { + @Override + public List nextList() { + return Arrays.asList(ACTIVE); + } + }, ACTIVE(6, "ACTIVE", "启动") { + @Override + public List nextList() { + return null; + } + + @Override + public Boolean isLast() { + return true; + } + }; + private int code; + private String name; + private String nameCn; + private boolean canRefuse; + + SetupStatus(int code, String name, String nameCn) { + this.code = code; + this.name = name; + this.nameCn = nameCn; + this.canRefuse = true; + } + + SetupStatus(int code, String name, String nameCn, boolean canRefuse) { + this.code = code; + this.name = name; + this.nameCn = nameCn; + this.canRefuse = canRefuse; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNameCn() { + return nameCn; + } + + public void setNameCn(String nameCn) { + this.nameCn = nameCn; + } + + public boolean isCanRefuse() { + return canRefuse; + } + + public void setCanRefuse(boolean canRefuse) { + this.canRefuse = canRefuse; + } + + public static SetupStatus getFromCode(Integer code) { + if (code == null) { + return null; + } + for (SetupStatus status : values()) { + if (status.code == code) { + return status; + } + } + throw new IllegalArgumentException("unknown SetupStatus enumeration code:" + code); + } + + public static SetupStatus getFromName(String name) { + if (name == null) { + return null; + } + for (SetupStatus status : values()) { + if (status.name.equals(name)) { + return status; + } + } + return null; + } + + public Boolean isFirst() { + return false; + } + + public Boolean isLast() { + return false; + } + + public SetupStatus refuse() { + return null; + } + + public SetupStatus next(String name) { + SetupStatus status = getFromName(name); + return name != null && this.nextList().contains(status) ? status : null; + } + + @Override + public String toString() { + return "SetupStatus{" + "code=" + code + ", name='" + name + '\'' + ", nameCn='" + nameCn + '\'' + ", canRefuse=" + canRefuse + '}'; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1498.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1498.java new file mode 100644 index 0000000000..0281e9e791 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1498.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +public class Issue1498 extends TestCase { + public void test_for_issue() throws Exception { + Model model = JSON.parseObject("{\"flag\":\"QUALITY_GRADUATE\"}", Model.class); + assertNull(model.flag); + } + + public void test_for_issue_match() throws Exception { + Model model = JSON.parseObject("{\"flag\":\"IS_NEED_CHECK_IDENTITY\"}", Model.class); + assertSame(BuFlag.IS_NEED_CHECK_IDENTITY, model.flag); + } + + public static class Model { + public BuFlag flag; + } + + public enum BuFlag + { + IS_NEED_CHECK_IDENTITY(1L, "a"), HAS_CHECK_IDENTITY(2L, "b"); + + private long bit; + private String desc; + + private BuFlag(long bit, String desc) + { + this.bit = bit; + this.desc = desc; + } + + public long getBit() + { + return this.bit; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue_for_wuye.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue_for_wuye.java new file mode 100644 index 0000000000..1970af1ba7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue_for_wuye.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.Date; + +public class Issue_for_wuye extends TestCase { + public void test_for_issue() throws Exception { + String poistr = "{\"gmtModified\":\"2017-09-07 16:39:19\",\"gmtCreate\":\"2017-09-07 16:39:19\"}"; + TimeBean poiInfo = JSON.parseObject(poistr, TimeBean.class); + } + + public static class TimeBean { + private Date time1; + private Date time2; + + public Date getTime1() { + return time1; + } + public void setTime1(Date time1) { + this.time1 = time1; + } + public Date getTime2() { + return time2; + } + public void setTime2(Date time2) { + this.time2 = time2; + } + + private Date gmtModified; + private Date gmtCreate; + + public Date getGmtCreate() { + return gmtCreate; + } + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + public Date getGmtModified() { + return gmtModified; + } + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1500.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1500.java new file mode 100644 index 0000000000..948a915791 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1500.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt.issue_1500; + +import clojure.lang.Obj; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.HashMap; +import java.util.Map; + +public class Issue1500 extends TestCase { + + + public void test_for_issue() throws Exception { + + // test aa + Aa aa = new Aa(); + aa.setName("aa"); + String jsonAa = JSON.toJSONString(aa); + Aa aa1 = JSON.parseObject(jsonAa, Aa.class); + Assert.assertEquals("aa",aa1.getName()); + + // test C + C c = new C(); + c.setE(aa); + String jsonC = JSON.toJSONString(c, SerializerFeature.WriteClassName); + C c2 = JSON.parseObject(jsonC, C.class); + Assert.assertEquals("Aa",c2.getE().getClass().getSimpleName()); + Assert.assertEquals("aa",((Aa)c2.getE()).getName()); + } + + public static class Aa extends Exception { + + public Aa(){ + } + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + public static class C { + + private Exception e; + + public Exception getE() { + return e; + } + + public void setE(Exception e) { + this.e = e; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1503.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1503.java new file mode 100644 index 0000000000..881e8f19b4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1503.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +public class Issue1503 extends TestCase { + public void test_for_issue() throws Exception { + ParserConfig config = new ParserConfig(); + config.setAutoTypeSupport(true); + Map map = new HashMap(); + map.put(null, new Bean()); + Map rmap = (Map) JSON.parse(JSON.toJSONString(map, SerializerFeature.WriteClassName), config); + System.out.println(rmap); + } + + public static class Bean { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1510.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1510.java new file mode 100644 index 0000000000..ede6dce899 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1510.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +public class Issue1510 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_issue() throws Exception { + Model model = JSON.parseObject("{\"startTime\":\"2017-11-04\",\"endTime\":\"2017-11-14\"}", Model.class); + String text = JSON.toJSONString(model); + assertEquals("{\"endTime\":\"2017-11-14\",\"startTime\":\"2017-11-04\"}", text); + } + + public static class Model { + @JSONField(format = "yyyy-MM-dd") + private Date startTime; + + @JSONField(format = "yyyy-MM-dd") + private Date endTime; + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1513.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1513.java new file mode 100644 index 0000000000..bbf6241b27 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1513.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +public class Issue1513 extends TestCase { + public void test_for_issue() throws Exception { + { + Model model = JSON.parseObject("{\"values\":[{\"id\":123}]}", new TypeReference>(){}); + assertNotNull(model.values); + assertEquals(1, model.values.length); + JSONObject object = (JSONObject) model.values[0]; + assertEquals(123, object.getIntValue("id")); + } + { + Model model = JSON.parseObject("{\"values\":[{\"id\":123}]}", new TypeReference>(){}); + assertNotNull(model.values); + assertEquals(1, model.values.length); + A a = model.values[0]; + assertEquals(123, a.id); + } + { + Model model = JSON.parseObject("{\"values\":[{\"value\":123}]}", new TypeReference>(){}); + assertNotNull(model.values); + assertEquals(1, model.values.length); + B b = model.values[0]; + assertEquals(123, b.value); + } + { + Model model = JSON.parseObject("{\"values\":[{\"age\":123}]}", new TypeReference>(){}); + assertNotNull(model.values); + assertEquals(1, model.values.length); + C c = model.values[0]; + assertEquals(123, c.age); + } + } + + public static class Model { + public T[] values; + } + + public static class A { + public int id; + } + + public static class B { + public int value; + } + + public static class C { + public int age; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1524.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1524.java new file mode 100644 index 0000000000..55c890b6a8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1524.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.NameFilter; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import junit.framework.TestCase; + +import java.io.IOException; +import java.lang.reflect.Type; + +public class Issue1524 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.oldValue = new Value(); + + String json = JSON.toJSONString(model, new NameFilter() { + public String process(Object object, String name, Object value) { + if ("oldValue".equals(name)) { + return "old_value"; + } + return name; + } + }); + System.out.println(json); + } + + public static class Model { + @JSONField(serializeUsing = ValueSerializer.class) + public Value oldValue; + } + + public static class Value { + + } + + public static class ValueSerializer implements ObjectSerializer { + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + serializer.write("xx"); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1529.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1529.java new file mode 100644 index 0000000000..642cf1a7cf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1529.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +public class Issue1529 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"isId\":false,\"Id\":138042533,\"name\":\"example\",\"height\":172}"; + Person person = JSON.parseObject(text, Person.class); + assertEquals(138042533, person.Id); + assertEquals("example", person.name); + assertEquals(172.0D, person.height); + } + + public static class Person { + private int Id; + public String name; + public double height; + + public int getId() { + return Id; + } + + public void setId(int id) { + if (id <= 1) { + throw new IllegalArgumentException(); + } + Id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1548.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1548.java new file mode 100644 index 0000000000..22a0062e3a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1548.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.io.Serializable; +import java.util.List; + +public class Issue1548 extends TestCase { + public void test_for_issue() throws Exception { + String msg = "[{\"doc\":{\"bottomprice\":80,\"cashpool_isdeleted\":0,\"shopcityid\":190,\"timerange\":\"2017-10-25;2017-10-26\",\"launchentityid\":3048,\"bidprice\":700,\"targetitems\":\"{}\",\"type\":0,\"slottagid\":44,\"targetid\":330048,\"entity_isdeleted\":0,\"bu\":2,\"target_isdeleted\":0,\"shopid\":6067941,\"slotids\":\"50041,10233,50051,10033,50061,50001,10099,10133,50101,10051\",\"launchscope\":0,\"productid\":74,\"creativeid\":300048,\"dpentitystatus\":1,\"accountid\":20151002,\"entitytype\":4,\"launchplatforms\":\"\",\"iszhuantou\":0,\"dpentityid\":6067941,\"timeslotperiod\":\"0,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\",\"templateid\":23,\"category1\":246,\"launch_isdeleted\":0,\"cashpoolid\":20151002,\"creative_isdeleted\":0,\"settlementstatus\":1,\"cityid\":\"190\",\"planid\":1042007,\"categoryid\":\"10 246\",\"price\":700,\"shoptype\":10,\"plan_isdeleted\":0,\"launchid\":30000048,\"creativeext\":\"{\\\"content\\\":\\\"啊啊啊啊啊啊啊啊\\\",\\\"title\\\":\\\"啊啊啊啊啊\\\",\\\"smartPic\\\":0,\\\"mobUrl\\\":\\\"https://evt.dianping.com/midas/1activities/3809/index.html?dpid=7997757988618737578&cityid=1&longitude=121.41543&latitude=31.21684&token=&product=dpapp&area=pc\\\",\\\"mtMobUrl\\\":\\\"https://evt.dianping.com/midas/1activities/3809/index.html?dpid=7997757988618737578&cityid=1&longitude=121.41543&latitude=31.21684&token=&product=dpapp&area=mtapp\\\"}\",\"chargetype\":1,\"channel\":0,\"generatedchannel\":0,\"promotype\":2},\"meta\":{\"LSN\":2077395,\"AREA\":\"engine-searchcpc\",\"PRIMARY_KEY\":[\"creativeid\",\"targetid\"],\"SECONDARY_KEY\":[\"planid\",\"shopid\",\"launchentityid\",\"launchid\",\"cashpoolid\"],\"TYPE\":\"UPDATE\"}}]"; + // JSONArray.parse(msg); + JSON.parseArray(msg).toJavaList(PublishDoc.class); + } + + public static class PublishDoc implements Serializable { + + public static final String LSN_META_NAME = "LSN"; + public static final String DOCTYPE_META_NAME = "TYPE"; + public static final String AREA_META_NAME = "AREA"; + public static final String PRIMARY_KEY_META_NAME = "PRIMARY_KEY"; + public static final String SECONDARY_KEY_META_NAME = "SECONDARY_KEY"; + + private JSONObject meta; + private JSONObject doc; + + public PublishDoc() { + this.meta = new JSONObject(); + this.doc = new JSONObject(); + } + + + @JSONField(serialize = false) + public void addMeta(String name, Object value) { + this.meta.put(name, value); + } + + @JSONField(serialize = false) + public Object getMeta(String name) { + return this.meta.get(name); + } + + + + @Override + public String toString() { + return JSON.toJSONString(this); + } + } + + public static enum DocType{ + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1555.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1555.java new file mode 100644 index 0000000000..7935826e3f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1555.java @@ -0,0 +1,89 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.PropertyNamingStrategy; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; + +public class Issue1555 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.userId = 1001; + model.userName = "test"; + String text = JSON.toJSONString(model); + assertEquals("{\"userName\":\"test\",\"user_id\":1001}", text); + + Model model2 = JSON.parseObject(text, Model.class); + + assertEquals(1001, model2.userId); + assertEquals("test", model2.userName); + } + + /** + * 当某个字段有JSONField注解,JSONField中name属性不存在,json属性名也要用类上的属性名转换策略 + * @throws Exception + */ + public void test_when_JSONField_have_not_name_attr() throws Exception { + ModelTwo modelTwo = new ModelTwo(); + modelTwo.userId = 1001; + modelTwo.userName = "test"; + String text = JSON.toJSONString(modelTwo); + assertEquals("{\"userName\":\"test\",\"user_id\":\"1001\"}", text); + + Model model2 = JSON.parseObject(text, Model.class); + + assertEquals(1001, model2.userId); + assertEquals("test", model2.userName); + } + + @JSONType(naming = PropertyNamingStrategy.SnakeCase) + public static class Model { + private int userId; + @JSONField(name = "userName") + private String userName; + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + } + + @JSONType(naming = PropertyNamingStrategy.SnakeCase) + public static class ModelTwo { + /** + * 此字段准备序列化为字符串类型 + */ + @JSONField(serializeUsing = StringSerializer.class) + private int userId; + @JSONField(name = "userName") + private String userName; + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1556.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1556.java new file mode 100644 index 0000000000..5404d617c2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1556.java @@ -0,0 +1,183 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.io.Serializable; +import java.util.Date; + +public class Issue1556 extends TestCase { + public void test_for_issue() throws Exception { + ClassForData classForData = new ClassForData(); + classForData.setDataName("dataname"); + SubCommonClass commonClass = new SubCommonClass(new Date()); + + FirstSubClass firstSubClass = new FirstSubClass(); + firstSubClass.setAddr("It is addr"); + firstSubClass.setCommonInfo(commonClass); + + SecondSubClass secondSubClass = new SecondSubClass(); + secondSubClass.setName("It is name"); + secondSubClass.setCommonInfo(firstSubClass.getCommonInfo()); + + classForData.setFirst(firstSubClass); + classForData.setSecond(secondSubClass); + + ApiResult apiResult = ApiResult.valueOfSuccess(classForData); + ParserConfig config = new ParserConfig(); + config.setAutoTypeSupport(true); + + String jsonString = JSON.toJSONString(apiResult, SerializerFeature.WriteClassName);//这里加上SerializerFeature.DisableCircularReferenceDetect + System.out.println(jsonString); + Object obj = JSON.parse(jsonString, config);//这里加上Feature.DisableCircularReferenceDetect 这样的话 是可以避免空值的 ,但是$ref 还有啥意思呢 + System.out.println(JSON.toJSONString(obj)); + } + + public static class ApiResult implements Serializable { + private String msg; + private int code; + private T data; + + public ApiResult() { + } + + public ApiResult(int code, String msg,T data) { + this.code = code; + this.msg = msg; + this.data = data; + } + + public String getMsg() { + return msg; + } + public int getCode() { + return code; + } + public void setMsg(String msg) { + this.msg = msg; + } + + public void setCode(int code) { + this.code = code; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public static ApiResult valueOfSuccess(T data) { + return new ApiResult(0, "Success", data); + } + + } + + public static class ClassForData implements Serializable { + + private String dataName; + + private FirstSubClass first; + + private SecondSubClass second; + + + public String getDataName() { + return dataName; + } + + public void setDataName(String dataName) { + this.dataName = dataName; + } + + public FirstSubClass getFirst() { + return first; + } + + public void setFirst(FirstSubClass first) { + this.first = first; + } + + public SecondSubClass getSecond() { + return second; + } + + public void setSecond(SecondSubClass second) { + this.second = second; + } + } + + public static class FirstSubClass implements Serializable{ + + private String addr;//仅仅做下和second的区分 + + private SubCommonClass commonInfo; + + + public String getAddr() { + return addr; + } + + public void setAddr(String addr) { + this.addr = addr; + } + + public SubCommonClass getCommonInfo() { + return commonInfo; + } + + public void setCommonInfo(SubCommonClass commonInfo) { + this.commonInfo = commonInfo; + } + + } + + public static class SecondSubClass implements Serializable{ + + private String name; + + private SubCommonClass commonInfo; + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public SubCommonClass getCommonInfo() { + return commonInfo; + } + + public void setCommonInfo(SubCommonClass commonInfo) { + this.commonInfo = commonInfo; + } + } + + + public static class SubCommonClass implements Serializable { + + private Date demoDate; + + public SubCommonClass(){ + } + + public SubCommonClass(Date demoDate){ + this.demoDate = demoDate; + } + + public Date getDemoDate() { + return demoDate; + } + + public void setDemoDate(Date demoDate) { + this.demoDate = demoDate; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1558.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1558.java new file mode 100644 index 0000000000..42d9c973bf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1558.java @@ -0,0 +1,57 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import java.io.Serializable; + +public class Issue1558 extends TestCase { + public void test_for_issue() throws Exception { + ParserConfig config = new ParserConfig(); + config.setAutoTypeSupport(true); + String text = "{\"id\": \"439a3213-e734-4bf3-9870-2c471f43d651\", \"instance\": \"v1\", \"interface\": \"com.xxx.aplan.UICommands\", \"method\": \"start\", \"params\": [\"tony\"], \"@type\": \"com.alibaba.json.bvt.issue_1500.Issue1558$Request\"}"; + + JSON.parseObject(text, Request.class, config); + } + + @JSONType + public static class Request implements Serializable { + private String id; + private String instance; + private String _interface; + private String method; + private Object[] params; + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getInstance() { + return instance; + } + public void setInstance(String instance) { + this.instance = instance; + } + public String getInterface() { + return _interface; + } + public void setInterface(String _interface) { + this._interface = _interface; + } + public String getMethod() { + return method; + } + public void setMethod(String method) { + this.method = method; + } + public Object[] getParams() { + return params; + } + public void setParams(Object[] params) { + this.params = params; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1565.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1565.java new file mode 100644 index 0000000000..a1039b97cc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1565.java @@ -0,0 +1,3409 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.PropertyNamingStrategy; +import com.alibaba.fastjson.serializer.SerializeConfig; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.io.Serializable; +import java.util.List; + +/** + * Created by SongLing.Dong on 11/7/2017. + */ +public class Issue1565 extends TestCase{ + + public void test_testLargeBeanContainsOver256Field(){ + SerializeConfig serializeConfig = new SerializeConfig(); + serializeConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase; + +// SmallBean smallBean = new SmallBean(); +// smallBean.setId("S35669xxxxxxxxxxxxxx"); +// smallBean.setNetValueDate(20171105); +// +// System.out.println(JSON.toJSONString(smallBean, serializeConfig)); + + + LargeBean expectedBean = new LargeBean(); + expectedBean.setId("S35669"); + expectedBean.setNetValueDate(20171105); + String expectedStr = "{\"id\":\"S35669\",\"net_value_date\":20171105}"; + + String actualStr = JSON.toJSONString(expectedBean, serializeConfig); + JSONObject actualBean = JSON.parseObject(actualStr); + Assert.assertEquals(expectedStr, actualStr); + Assert.assertEquals(expectedBean.getId(), actualBean.getString("id")); + Assert.assertEquals(expectedBean.getNetValueDate(), actualBean.getInteger("net_value_date")); + + + + } + + public static class SmallBean implements Serializable{ + private String id; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Integer getNetValueDate() { + return netValueDate; + } + + public void setNetValueDate(Integer netValueDate) { + this.netValueDate = netValueDate; + } + + private Integer netValueDate; + } + + public static class LargeBean implements Serializable { + + /** + * 每页数量 + */ + private Integer pageSize; + + /** + * 获取第一个记录的下标 + */ + private Integer firstResult; + + /** + * 获取数量 + */ + private Integer fetchSize; + + /** + * 开始时间 + */ + private String startTime; + + /** + * 结束时间 + */ + private String endTime; + + /** + * 是否管理员标识 + */ + private Boolean isAdministrator; + + /** + * 排序方式 0:升序 1:倒序 + */ + private Byte sortMode; + + /** + * 排序字段名 + */ + private String sortFieldName; + + /** + * 排序字段值 + */ + private String sortFieldValue; + + /** + * 创建时间戳(毫秒) + */ + private Long createTimestamp; + + /** + * 上一次页码 + */ + private Integer lastPage; + + /** + * 查询类型 + */ + private Byte queryType; + + /** + * 分片键 + */ + private String shard; + + /** + * 净值日期,格式:yyyyMMdd + */ + private Integer netValueDate; + + /** + * 单位净值 + */ + private Float unitNetValue; + + /** + * 累计净值 + */ + private Float totalNetValue; + + /** + * 近一个月累计收益率 + */ + private Float nomTotalYield; + + /** + * 近半年累计收益率 + */ + private Float nhyTotalYield; + + /** + * 近一年累计收益率 + */ + private Float noyTotalYield; + + /** + * 本月累计收益率 + */ + private Float tmTotalYield; + + /** + * 本季度累计收益率 + */ + private Float tqTotalYield; + + /** + * 本年累计收益率 + */ + private Float tyTotalYield; + + /** + * 所有累计收益率 + */ + private Float allTotalYield; + + /** + * 近一个月年化收益率 + */ + private Float nomAnnualizedReturn; + + /** + * 近半年年化收益率 + */ + private Float nhyAnnualizedReturn; + + /** + * 近一年年化收益率 + */ + private Float noyAnnualizedReturn; + + /** + * 本月年化收益率 + */ + private Float tmAnnualizedReturn; + + /** + * 本季度年化收益率 + */ + private Float tqAnnualizedReturn; + + /** + * 本年年化收益率 + */ + private Float tyAnnualizedReturn; + + /** + * 所有年化收益率 + */ + private Float allAnnualizedReturn; + + /** + * 近一个月最大盈利幅度 + */ + private Float nomMaxProfitMargin; + + /** + * 近半年最大盈利幅度 + */ + private Float nhyMaxProfitMargin; + + /** + * 近一年最大盈利幅度 + */ + private Float noyMaxProfitMargin; + + /** + * 本月最大盈利幅度 + */ + private Float tmMaxProfitMargin; + + /** + * 本季度最大盈利幅度 + */ + private Float tqMaxProfitMargin; + + /** + * 本年最大盈利幅度 + */ + private Float tyMaxProfitMargin; + + /** + * 所有最大盈利幅度 + */ + private Float allMaxProfitMargin; + + /** + * 近一个月最大单次盈利 + */ + private Float nomMaxSingleProfit; + + /** + * 近半年最大单次盈利 + */ + private Float nhyMaxSingleProfit; + + /** + * 近一年最大单次盈利 + */ + private Float noyMaxSingleProfit; + + /** + * 本月最大单次盈利 + */ + private Float tmMaxSingleProfit; + + /** + * 本季度最大单次盈利 + */ + private Float tqMaxSingleProfit; + + /** + * 本年最大单次盈利 + */ + private Float tyMaxSingleProfit; + + /** + * 所有最大单次盈利 + */ + private Float allMaxSingleProfit; + + /** + * 近一个月最大连续盈利次数 + */ + private Integer nomMaxConProfitTime; + + /** + * 近半年最大连续盈利次数 + */ + private Integer nhyMaxConProfitTime; + + /** + * 近一年最大连续盈利次数 + */ + private Integer noyMaxConProfitTime; + + /** + * 本月最大连续盈利次数 + */ + private Integer tmMaxConProfitTime; + + /** + * 本季度最大连续盈利次数 + */ + private Integer tqMaxConProfitTime; + + /** + * 本年最大连续盈利次数 + */ + private Integer tyMaxConProfitTime; + + /** + * 所有最大连续盈利次数 + */ + private Integer allMaxConProfitTime; + + /** + * 所有最大连续盈利次数出现日期 + */ + private Integer allMaxConProfitTimeDate; + + /** + * 近一个月最大回撤 + */ + private Float nomMaxDrawdown; + + /** + * 近半年最大回撤 + */ + private Float nhyMaxDrawdown; + + /** + * 近一年最大回撤 + */ + private Float noyMaxDrawdown; + + /** + * 本月最大回撤 + */ + private Float tmMaxDrawdown; + + /** + * 本季度最大回撤 + */ + private Float tqMaxDrawdown; + + /** + * 本年最大回撤 + */ + private Float tyMaxDrawdown; + + /** + * 所有最大回撤 + */ + private Float allMaxDrawdown; + + /** + * 所有最大回撤出现日期 + */ + private Integer allMaxDrawdownDate; + + /** + * 近一个月最大单次回撤 + */ + private Float nomMaxSingleDrawdown; + + /** + * 近半年最大单次回撤 + */ + private Float nhyMaxSingleDrawdown; + + /** + * 近一年最大单次回撤 + */ + private Float noyMaxSingleDrawdown; + + /** + * 本月最大单次回撤 + */ + private Float tmMaxSingleDrawdown; + + /** + * 本季度最大单次回撤 + */ + private Float tqMaxSingleDrawdown; + + /** + * 本年最大单次回撤 + */ + private Float tyMaxSingleDrawdown; + + /** + * 所有最大单次回撤 + */ + private Float allMaxSingleDrawdown; + + /** + * 所有最大单次回撤出现日期 + */ + private Integer allMaxSingleDrawdownDate; + + /** + * 近一个月最大连续回撤次数 + */ + private Integer nomMaxConDrawdownTime; + + /** + * 近半年最大连续回撤次数 + */ + private Integer nhyMaxConDrawdownTime; + + /** + * 近一年最大连续回撤次数 + */ + private Integer noyMaxConDrawdownTime; + + /** + * 本月最大连续回撤次数 + */ + private Integer tmMaxConDrawdownTime; + + /** + * 本季度最大连续回撤次数 + */ + private Integer tqMaxConDrawdownTime; + + /** + * 本年最大连续回撤次数 + */ + private Integer tyMaxConDrawdownTime; + + /** + * 所有最大连续回撤次数 + */ + private Integer allMaxConDrawdownTime; + + /** + * 近一个月收益率标准差 + */ + private Float nomYieldStdDeviation; + + /** + * 近半年收益率标准差 + */ + private Float nhyYieldStdDeviation; + + /** + * 近一年收益率标准差 + */ + private Float noyYieldStdDeviation; + + /** + * 本月收益率标准差 + */ + private Float tmYieldStdDeviation; + + /** + * 本季度收益率标准差 + */ + private Float tqYieldStdDeviation; + + /** + * 本年收益率标准差 + */ + private Float tyYieldStdDeviation; + + /** + * 所有收益率标准差 + */ + private Float allYieldStdDeviation; + + /** + * 近一个月下行标准差 + */ + private Float nomDownStdDeviation; + + /** + * 近半年下行标准差 + */ + private Float nhyDownStdDeviation; + + /** + * 近一年下行标准差 + */ + private Float noyDownStdDeviation; + + /** + * 本月下行标准差 + */ + private Float tmDownStdDeviation; + + /** + * 本季度下行标准差 + */ + private Float tqDownStdDeviation; + + /** + * 本年下行标准差 + */ + private Float tyDownStdDeviation; + + /** + * 所有下行标准差 + */ + private Float allDownStdDeviation; + + /** + * 近一个月胜率 + */ + private Float nomWinRatio; + + /** + * 近半年胜率 + */ + private Float nhyWinRatio; + + /** + * 近一年胜率 + */ + private Float noyWinRatio; + + /** + * 本月胜率 + */ + private Float tmWinRatio; + + /** + * 本季度胜率 + */ + private Float tqWinRatio; + + /** + * 本年胜率 + */ + private Float tyWinRatio; + + /** + * 所有胜率 + */ + private Float allWinRatio; + + /** + * 近一个月贝塔系数 + */ + private Float nomBeta; + + /** + * 近半年贝塔系数 + */ + private Float nhyBeta; + + /** + * 近一年贝塔系数 + */ + private Float noyBeta; + + /** + * 本月贝塔系数 + */ + private Float tmBeta; + + /** + * 本季度贝塔系数 + */ + private Float tqBeta; + + /** + * 本年贝塔系数 + */ + private Float tyBeta; + + /** + * 所有贝塔系数 + */ + private Float allBeta; + + /** + * 近一个月阿尔法系数 + */ + private Float nomAlpha; + + /** + * 近半年阿尔法系数 + */ + private Float nhyAlpha; + + /** + * 近一年阿尔法系数 + */ + private Float noyAlpha; + + /** + * 本月阿尔法系数 + */ + private Float tmAlpha; + + /** + * 本季度阿尔法系数 + */ + private Float tqAlpha; + + /** + * 本年阿尔法系数 + */ + private Float tyAlpha; + + /** + * 所有阿尔法系数 + */ + private Float allAlpha; + + /** + * 近一个月詹森指数 + */ + private Float nomJansen; + + /** + * 近半年詹森指数 + */ + private Float nhyJansen; + + /** + * 近一年詹森指数 + */ + private Float noyJansen; + + /** + * 本月詹森指数 + */ + private Float tmJansen; + + /** + * 本季度詹森指数 + */ + private Float tqJansen; + + /** + * 本年詹森指数 + */ + private Float tyJansen; + + /** + * 所有詹森指数 + */ + private Float allJansen; + + /** + * 近一个月卡玛比率 + */ + private Float nomKumarRatio; + + /** + * 近半年卡玛比率 + */ + private Float nhyKumarRatio; + + /** + * 近一年卡玛比率 + */ + private Float noyKumarRatio; + + /** + * 本月卡玛比率 + */ + private Float tmKumarRatio; + + /** + * 本季度卡玛比率 + */ + private Float tqKumarRatio; + + /** + * 本年卡玛比率 + */ + private Float tyKumarRatio; + + /** + * 所有卡玛比率 + */ + private Float allKumarRatio; + + /** + * 近一个月夏普比率 + */ + private Float nomSharpeRatio; + + /** + * 近半年夏普比率 + */ + private Float nhySharpeRatio; + + /** + * 近一年夏普比率 + */ + private Float noySharpeRatio; + + /** + * 本月夏普比率 + */ + private Float tmSharpeRatio; + + /** + * 本季度夏普比率 + */ + private Float tqSharpeRatio; + + /** + * 本年夏普比率 + */ + private Float tySharpeRatio; + + /** + * 所有夏普比率 + */ + private Float allSharpeRatio; + + /** + * 近一个月索提若比率 + */ + private Float nomSortinoRatio; + + /** + * 近半年索提若比率 + */ + private Float nhySortinoRatio; + + /** + * 近一年索提若比率 + */ + private Float noySortinoRatio; + + /** + * 本月索提若比率 + */ + private Float tmSortinoRatio; + + /** + * 本季度索提若比率 + */ + private Float tqSortinoRatio; + + /** + * 本年索提若比率 + */ + private Float tySortinoRatio; + + /** + * 所有索提若比率 + */ + private Float allSortinoRatio; + + /** + * 近一个月赫斯特指数 + */ + private Float nomHurstIndex; + + /** + * 近半年赫斯特指数 + */ + private Float nhyHurstIndex; + + /** + * 近一年赫斯特指数 + */ + private Float noyHurstIndex; + + /** + * 本月赫斯特指数 + */ + private Float tmHurstIndex; + + /** + * 本季度赫斯特指数 + */ + private Float tqHurstIndex; + + /** + * 本年赫斯特指数 + */ + private Float tyHurstIndex; + + /** + * 所有赫斯特指数 + */ + private Float allHurstIndex; + + /** + * 近一个月VaR指标(95%) + */ + private Float nomVarIndex; + + /** + * 近半年VaR指标(95%) + */ + private Float nhyVarIndex; + + /** + * 近一年VaR指标(95%) + */ + private Float noyVarIndex; + + /** + * 本月VaR指标(95%) + */ + private Float tmVarIndex; + + /** + * 本季度VaR指标(95%) + */ + private Float tqVarIndex; + + /** + * 本年VaR指标(95%) + */ + private Float tyVarIndex; + + /** + * 所有VaR指标(95%) + */ + private Float allVarIndex; + + /** + * 近一个月VaR指标(99%) + */ + private Float nomVarIndex99; + + /** + * 近半年VaR指标(99%) + */ + private Float nhyVarIndex99; + + /** + * 近一年VaR指标(99%) + */ + private Float noyVarIndex99; + + /** + * 本月VaR指标(99%) + */ + private Float tmVarIndex99; + + /** + * 本季度VaR指标(99%) + */ + private Float tqVarIndex99; + + /** + * 本年VaR指标(99%) + */ + private Float tyVarIndex99; + + /** + * 所有VaR指标(99%) + */ + private Float allVarIndex99; + + /** + * 近一个月上行捕获率 + */ + private Float nomUpCaptureRate; + + /** + * 近半年上行捕获率 + */ + private Float nhyUpCaptureRate; + + /** + * 近一年上行捕获率 + */ + private Float noyUpCaptureRate; + + /** + * 本月上行捕获率 + */ + private Float tmUpCaptureRate; + + /** + * 本季度上行捕获率 + */ + private Float tqUpCaptureRate; + + /** + * 本年上行捕获率 + */ + private Float tyUpCaptureRate; + + /** + * 所有上行捕获率 + */ + private Float allUpCaptureRate; + + /** + * 近一个月下行捕获率 + */ + private Float nomDownCaptureRate; + + /** + * 近半年下行捕获率 + */ + private Float nhyDownCaptureRate; + + /** + * 近一年下行捕获率 + */ + private Float noyDownCaptureRate; + + /** + * 本月下行捕获率 + */ + private Float tmDownCaptureRate; + + /** + * 本季度下行捕获率 + */ + private Float tqDownCaptureRate; + + /** + * 本年下行捕获率 + */ + private Float tyDownCaptureRate; + + /** + * 所有下行捕获率 + */ + private Float allDownCaptureRate; + + /** + * 近一个月信息比率 + */ + private Float nomInfoRatio; + + /** + * 近半年信息比率 + */ + private Float nhyInfoRatio; + + /** + * 近一年信息比率 + */ + private Float noyInfoRatio; + + /** + * 本月信息比率 + */ + private Float tmInfoRatio; + + /** + * 本季度信息比率 + */ + private Float tqInfoRatio; + + /** + * 本年信息比率 + */ + private Float tyInfoRatio; + + /** + * 所有信息比率 + */ + private Float allInfoRatio; + + /** + * 近一个月策略波动率 + */ + private Float nomAlgorithmVolatility; + + /** + * 近半年策略波动率 + */ + private Float nhyAlgorithmVolatility; + + /** + * 近一年策略波动率 + */ + private Float noyAlgorithmVolatility; + + /** + * 本月策略波动率 + */ + private Float tmAlgorithmVolatility; + + /** + * 本季度策略波动率 + */ + private Float tqAlgorithmVolatility; + + /** + * 本年策略波动率 + */ + private Float tyAlgorithmVolatility; + + /** + * 所有策略波动率 + */ + private Float allAlgorithmVolatility; + + /** + * 近一个月M平方 + */ + private Float nomMSquare; + + /** + * 近半年M平方 + */ + private Float nhyMSquare; + + /** + * 近一年M平方 + */ + private Float noyMSquare; + + /** + * 本月M平方 + */ + private Float tmMSquare; + + /** + * 本季度M平方 + */ + private Float tqMSquare; + + /** + * 本年M平方 + */ + private Float tyMSquare; + + /** + * 所有M平方 + */ + private Float allMSquare; + + /** + * 近一个月特雷诺指数(TR) + */ + private Float nomTreynorIndex; + + /** + * 近半年特雷诺指数(TR) + */ + private Float nhyTreynorIndex; + + /** + * 近一年特雷诺指数(TR) + */ + private Float noyTreynorIndex; + + /** + * 本月特雷诺指数(TR) + */ + private Float tmTreynorIndex; + + /** + * 本季度特雷诺指数(TR) + */ + private Float tqTreynorIndex; + + /** + * 本年特雷诺指数(TR) + */ + private Float tyTreynorIndex; + + /** + * 所有特雷诺指数(TR) + */ + private Float allTreynorIndex; + + /** + * 基金产品ID(片键值) + */ + private String id; + + /** + * 基金产品名称 + */ + private String name; + + /** + * 基金产品短名称 + */ + private String shortName; + + /** + * 基金代码 + */ + private String code; + + /** + * 备案号 + */ + private String recordNumber; + + /** + * 基金类型 0:私募基金 1:公募基金 2:私有基金 + */ + private Byte fundType; + + /** + * 基金品种 0:开放式基金 1:货币型基金 2:理财型基金 3:分级型基金 4:场内交易型基金 + */ + private Byte fundBreed; + + /** + * 基金状态 0:存续中 1:已清盘 + */ + private Byte fundStatus; + + /** + * 申购状态,当基金类型=1:公募基金时该字段才存在 + */ + private String buyStatus; + + /** + * 赎回状态,当基金类型=1:公募基金时该字段才存在 + */ + private String redeemStatus; + + /** + * 备案日期,格式:yyyy-MM-dd + */ + private String recordDate; + + /** + * 成立日期,格式:yyyy-MM-dd + */ + private String createDate; + + /** + * 终止日期,格式:yyyy-MM-dd + */ + private String stopDate; + + /** + * 基金备案阶段 + */ + private String fundFilingStage; + + /** + * 基金投资类型 + */ + private String fundInvestmentType; + + /** + * 币种 + */ + private String currency; + + /** + * 管理类型 + */ + private String managerType; + + /** + * 托管人名称 + */ + private String managerName; + + /** + * 投资目标 + */ + private String investmentTarget; + + /** + * 主要投资领域,即投资范围 + */ + private String majorInvestAreas; + + /** + * 基金信息最后修改日期 + */ + private String fundLastModifyDate; + + /** + * 基金协会特别提示(针对基金) + */ + private String specialNote; + + /** + * 注册地址 + */ + private String registeredAddress; + + /** + * 投资策略 + */ + private String investmentStrategy; + + /** + * 投资子策略 + */ + private String investmentSubStrategy; + + /** + * 基金经理ID数组 + */ + private List fundManagerIds; + + /** + * 投顾公司ID + */ + private String companyId; + + /** + * 序号 + */ + private Long orderNum; + + /** + * 成立规模 + */ + private String createScale; + + /** + * 最新规模 + */ + private String latestScale; + + /** + * 产品基准代码 + */ + private String benchmark; + + /** + * 净值更新频率 + */ + private Byte netValueUpdateRate; + + /** + * 基金产品外部ID + */ + private String fundOuterId; + + /** + * 标签 + */ + private String tags; + + /** + * 备注 + */ + private String remark; + + /** + * 策略容量 + */ + private String strategyCapacity; + + /** + * 创建时间 + */ + private Long createTime; + + /** + * 创建者ID + */ + private String creatorId; + + /** + * 最后修改时间 + */ + private Long lastModifyTime; + + /** + * 最后修改者ID + */ + private String lastModifierId; + + /** + * 基金公司外部ID + */ + private String companyOuterId; + + /** + * 基金公司名称 + */ + private String companyName; + + /** + * 基金经理外部ID数组 + */ + private List managerOuterIds; + + /** + * 基金产品ID列表 + */ + private List fundIds; + + /** + * 投顾公司ID列表 + */ + private List companyIds; + + /** + * 开始年化收益率 + */ + private Float startAnnualizedReturn; + + /** + * 结束年化收益率 + */ + private Float endAnnualizedReturn; + + /** + * 时间区间 + */ + private String timeInterval; + + /** + * 基金经理姓名数组 + */ + private List fundManagerNames; + + /** + * 基金状态名称 0:存续中 1:已清盘 + */ + private String fundStatusName; + + /** + * 基金类型名称 0:私募基金 1:公募基金 2:私有基金' + */ + private String fundTypeName; + + /** + * 是否关注基金 0:否 1:是 + */ + private Byte isConcern; + + /** + * 配置权重(%) + */ + private Float configWeight; + + /** + * 净值日期字符串 yyyy-MM-dd格式 + */ + private String netValueDateString; + + /** + * 基金经理ID + */ + private String managerId; + + /** + * 用户标签ID + */ + private String tagId; + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } + + public Integer getFirstResult() { + return firstResult; + } + + public void setFirstResult(Integer firstResult) { + this.firstResult = firstResult; + } + + public Integer getFetchSize() { + return fetchSize; + } + + public void setFetchSize(Integer fetchSize) { + this.fetchSize = fetchSize; + } + + public String getStartTime() { + return startTime; + } + + public void setStartTime(String startTime) { + this.startTime = startTime; + } + + public String getEndTime() { + return endTime; + } + + public void setEndTime(String endTime) { + this.endTime = endTime; + } + + public Boolean getAdministrator() { + return isAdministrator; + } + + public void setAdministrator(Boolean administrator) { + isAdministrator = administrator; + } + + public Byte getSortMode() { + return sortMode; + } + + public void setSortMode(Byte sortMode) { + this.sortMode = sortMode; + } + + public String getSortFieldName() { + return sortFieldName; + } + + public void setSortFieldName(String sortFieldName) { + this.sortFieldName = sortFieldName; + } + + public String getSortFieldValue() { + return sortFieldValue; + } + + public void setSortFieldValue(String sortFieldValue) { + this.sortFieldValue = sortFieldValue; + } + + public Long getCreateTimestamp() { + return createTimestamp; + } + + public void setCreateTimestamp(Long createTimestamp) { + this.createTimestamp = createTimestamp; + } + + public Integer getLastPage() { + return lastPage; + } + + public void setLastPage(Integer lastPage) { + this.lastPage = lastPage; + } + + public Byte getQueryType() { + return queryType; + } + + public void setQueryType(Byte queryType) { + this.queryType = queryType; + } + + public String getShard() { + return shard; + } + + public void setShard(String shard) { + this.shard = shard; + } + + public Integer getNetValueDate() { + return netValueDate; + } + + public void setNetValueDate(Integer netValueDate) { + this.netValueDate = netValueDate; + } + + public Float getUnitNetValue() { + return unitNetValue; + } + + public void setUnitNetValue(Float unitNetValue) { + this.unitNetValue = unitNetValue; + } + + public Float getTotalNetValue() { + return totalNetValue; + } + + public void setTotalNetValue(Float totalNetValue) { + this.totalNetValue = totalNetValue; + } + + public Float getNomTotalYield() { + return nomTotalYield; + } + + public void setNomTotalYield(Float nomTotalYield) { + this.nomTotalYield = nomTotalYield; + } + + public Float getNhyTotalYield() { + return nhyTotalYield; + } + + public void setNhyTotalYield(Float nhyTotalYield) { + this.nhyTotalYield = nhyTotalYield; + } + + public Float getNoyTotalYield() { + return noyTotalYield; + } + + public void setNoyTotalYield(Float noyTotalYield) { + this.noyTotalYield = noyTotalYield; + } + + public Float getTmTotalYield() { + return tmTotalYield; + } + + public void setTmTotalYield(Float tmTotalYield) { + this.tmTotalYield = tmTotalYield; + } + + public Float getTqTotalYield() { + return tqTotalYield; + } + + public void setTqTotalYield(Float tqTotalYield) { + this.tqTotalYield = tqTotalYield; + } + + public Float getTyTotalYield() { + return tyTotalYield; + } + + public void setTyTotalYield(Float tyTotalYield) { + this.tyTotalYield = tyTotalYield; + } + + public Float getAllTotalYield() { + return allTotalYield; + } + + public void setAllTotalYield(Float allTotalYield) { + this.allTotalYield = allTotalYield; + } + + public Float getNomAnnualizedReturn() { + return nomAnnualizedReturn; + } + + public void setNomAnnualizedReturn(Float nomAnnualizedReturn) { + this.nomAnnualizedReturn = nomAnnualizedReturn; + } + + public Float getNhyAnnualizedReturn() { + return nhyAnnualizedReturn; + } + + public void setNhyAnnualizedReturn(Float nhyAnnualizedReturn) { + this.nhyAnnualizedReturn = nhyAnnualizedReturn; + } + + public Float getNoyAnnualizedReturn() { + return noyAnnualizedReturn; + } + + public void setNoyAnnualizedReturn(Float noyAnnualizedReturn) { + this.noyAnnualizedReturn = noyAnnualizedReturn; + } + + public Float getTmAnnualizedReturn() { + return tmAnnualizedReturn; + } + + public void setTmAnnualizedReturn(Float tmAnnualizedReturn) { + this.tmAnnualizedReturn = tmAnnualizedReturn; + } + + public Float getTqAnnualizedReturn() { + return tqAnnualizedReturn; + } + + public void setTqAnnualizedReturn(Float tqAnnualizedReturn) { + this.tqAnnualizedReturn = tqAnnualizedReturn; + } + + public Float getTyAnnualizedReturn() { + return tyAnnualizedReturn; + } + + public void setTyAnnualizedReturn(Float tyAnnualizedReturn) { + this.tyAnnualizedReturn = tyAnnualizedReturn; + } + + public Float getAllAnnualizedReturn() { + return allAnnualizedReturn; + } + + public void setAllAnnualizedReturn(Float allAnnualizedReturn) { + this.allAnnualizedReturn = allAnnualizedReturn; + } + + public Float getNomMaxProfitMargin() { + return nomMaxProfitMargin; + } + + public void setNomMaxProfitMargin(Float nomMaxProfitMargin) { + this.nomMaxProfitMargin = nomMaxProfitMargin; + } + + public Float getNhyMaxProfitMargin() { + return nhyMaxProfitMargin; + } + + public void setNhyMaxProfitMargin(Float nhyMaxProfitMargin) { + this.nhyMaxProfitMargin = nhyMaxProfitMargin; + } + + public Float getNoyMaxProfitMargin() { + return noyMaxProfitMargin; + } + + public void setNoyMaxProfitMargin(Float noyMaxProfitMargin) { + this.noyMaxProfitMargin = noyMaxProfitMargin; + } + + public Float getTmMaxProfitMargin() { + return tmMaxProfitMargin; + } + + public void setTmMaxProfitMargin(Float tmMaxProfitMargin) { + this.tmMaxProfitMargin = tmMaxProfitMargin; + } + + public Float getTqMaxProfitMargin() { + return tqMaxProfitMargin; + } + + public void setTqMaxProfitMargin(Float tqMaxProfitMargin) { + this.tqMaxProfitMargin = tqMaxProfitMargin; + } + + public Float getTyMaxProfitMargin() { + return tyMaxProfitMargin; + } + + public void setTyMaxProfitMargin(Float tyMaxProfitMargin) { + this.tyMaxProfitMargin = tyMaxProfitMargin; + } + + public Float getAllMaxProfitMargin() { + return allMaxProfitMargin; + } + + public void setAllMaxProfitMargin(Float allMaxProfitMargin) { + this.allMaxProfitMargin = allMaxProfitMargin; + } + + public Float getNomMaxSingleProfit() { + return nomMaxSingleProfit; + } + + public void setNomMaxSingleProfit(Float nomMaxSingleProfit) { + this.nomMaxSingleProfit = nomMaxSingleProfit; + } + + public Float getNhyMaxSingleProfit() { + return nhyMaxSingleProfit; + } + + public void setNhyMaxSingleProfit(Float nhyMaxSingleProfit) { + this.nhyMaxSingleProfit = nhyMaxSingleProfit; + } + + public Float getNoyMaxSingleProfit() { + return noyMaxSingleProfit; + } + + public void setNoyMaxSingleProfit(Float noyMaxSingleProfit) { + this.noyMaxSingleProfit = noyMaxSingleProfit; + } + + public Float getTmMaxSingleProfit() { + return tmMaxSingleProfit; + } + + public void setTmMaxSingleProfit(Float tmMaxSingleProfit) { + this.tmMaxSingleProfit = tmMaxSingleProfit; + } + + public Float getTqMaxSingleProfit() { + return tqMaxSingleProfit; + } + + public void setTqMaxSingleProfit(Float tqMaxSingleProfit) { + this.tqMaxSingleProfit = tqMaxSingleProfit; + } + + public Float getTyMaxSingleProfit() { + return tyMaxSingleProfit; + } + + public void setTyMaxSingleProfit(Float tyMaxSingleProfit) { + this.tyMaxSingleProfit = tyMaxSingleProfit; + } + + public Float getAllMaxSingleProfit() { + return allMaxSingleProfit; + } + + public void setAllMaxSingleProfit(Float allMaxSingleProfit) { + this.allMaxSingleProfit = allMaxSingleProfit; + } + + public Integer getNomMaxConProfitTime() { + return nomMaxConProfitTime; + } + + public void setNomMaxConProfitTime(Integer nomMaxConProfitTime) { + this.nomMaxConProfitTime = nomMaxConProfitTime; + } + + public Integer getNhyMaxConProfitTime() { + return nhyMaxConProfitTime; + } + + public void setNhyMaxConProfitTime(Integer nhyMaxConProfitTime) { + this.nhyMaxConProfitTime = nhyMaxConProfitTime; + } + + public Integer getNoyMaxConProfitTime() { + return noyMaxConProfitTime; + } + + public void setNoyMaxConProfitTime(Integer noyMaxConProfitTime) { + this.noyMaxConProfitTime = noyMaxConProfitTime; + } + + public Integer getTmMaxConProfitTime() { + return tmMaxConProfitTime; + } + + public void setTmMaxConProfitTime(Integer tmMaxConProfitTime) { + this.tmMaxConProfitTime = tmMaxConProfitTime; + } + + public Integer getTqMaxConProfitTime() { + return tqMaxConProfitTime; + } + + public void setTqMaxConProfitTime(Integer tqMaxConProfitTime) { + this.tqMaxConProfitTime = tqMaxConProfitTime; + } + + public Integer getTyMaxConProfitTime() { + return tyMaxConProfitTime; + } + + public void setTyMaxConProfitTime(Integer tyMaxConProfitTime) { + this.tyMaxConProfitTime = tyMaxConProfitTime; + } + + public Integer getAllMaxConProfitTime() { + return allMaxConProfitTime; + } + + public void setAllMaxConProfitTime(Integer allMaxConProfitTime) { + this.allMaxConProfitTime = allMaxConProfitTime; + } + + public Integer getAllMaxConProfitTimeDate() { + return allMaxConProfitTimeDate; + } + + public void setAllMaxConProfitTimeDate(Integer allMaxConProfitTimeDate) { + this.allMaxConProfitTimeDate = allMaxConProfitTimeDate; + } + + public Float getNomMaxDrawdown() { + return nomMaxDrawdown; + } + + public void setNomMaxDrawdown(Float nomMaxDrawdown) { + this.nomMaxDrawdown = nomMaxDrawdown; + } + + public Float getNhyMaxDrawdown() { + return nhyMaxDrawdown; + } + + public void setNhyMaxDrawdown(Float nhyMaxDrawdown) { + this.nhyMaxDrawdown = nhyMaxDrawdown; + } + + public Float getNoyMaxDrawdown() { + return noyMaxDrawdown; + } + + public void setNoyMaxDrawdown(Float noyMaxDrawdown) { + this.noyMaxDrawdown = noyMaxDrawdown; + } + + public Float getTmMaxDrawdown() { + return tmMaxDrawdown; + } + + public void setTmMaxDrawdown(Float tmMaxDrawdown) { + this.tmMaxDrawdown = tmMaxDrawdown; + } + + public Float getTqMaxDrawdown() { + return tqMaxDrawdown; + } + + public void setTqMaxDrawdown(Float tqMaxDrawdown) { + this.tqMaxDrawdown = tqMaxDrawdown; + } + + public Float getTyMaxDrawdown() { + return tyMaxDrawdown; + } + + public void setTyMaxDrawdown(Float tyMaxDrawdown) { + this.tyMaxDrawdown = tyMaxDrawdown; + } + + public Float getAllMaxDrawdown() { + return allMaxDrawdown; + } + + public void setAllMaxDrawdown(Float allMaxDrawdown) { + this.allMaxDrawdown = allMaxDrawdown; + } + + public Integer getAllMaxDrawdownDate() { + return allMaxDrawdownDate; + } + + public void setAllMaxDrawdownDate(Integer allMaxDrawdownDate) { + this.allMaxDrawdownDate = allMaxDrawdownDate; + } + + public Float getNomMaxSingleDrawdown() { + return nomMaxSingleDrawdown; + } + + public void setNomMaxSingleDrawdown(Float nomMaxSingleDrawdown) { + this.nomMaxSingleDrawdown = nomMaxSingleDrawdown; + } + + public Float getNhyMaxSingleDrawdown() { + return nhyMaxSingleDrawdown; + } + + public void setNhyMaxSingleDrawdown(Float nhyMaxSingleDrawdown) { + this.nhyMaxSingleDrawdown = nhyMaxSingleDrawdown; + } + + public Float getNoyMaxSingleDrawdown() { + return noyMaxSingleDrawdown; + } + + public void setNoyMaxSingleDrawdown(Float noyMaxSingleDrawdown) { + this.noyMaxSingleDrawdown = noyMaxSingleDrawdown; + } + + public Float getTmMaxSingleDrawdown() { + return tmMaxSingleDrawdown; + } + + public void setTmMaxSingleDrawdown(Float tmMaxSingleDrawdown) { + this.tmMaxSingleDrawdown = tmMaxSingleDrawdown; + } + + public Float getTqMaxSingleDrawdown() { + return tqMaxSingleDrawdown; + } + + public void setTqMaxSingleDrawdown(Float tqMaxSingleDrawdown) { + this.tqMaxSingleDrawdown = tqMaxSingleDrawdown; + } + + public Float getTyMaxSingleDrawdown() { + return tyMaxSingleDrawdown; + } + + public void setTyMaxSingleDrawdown(Float tyMaxSingleDrawdown) { + this.tyMaxSingleDrawdown = tyMaxSingleDrawdown; + } + + public Float getAllMaxSingleDrawdown() { + return allMaxSingleDrawdown; + } + + public void setAllMaxSingleDrawdown(Float allMaxSingleDrawdown) { + this.allMaxSingleDrawdown = allMaxSingleDrawdown; + } + + public Integer getAllMaxSingleDrawdownDate() { + return allMaxSingleDrawdownDate; + } + + public void setAllMaxSingleDrawdownDate(Integer allMaxSingleDrawdownDate) { + this.allMaxSingleDrawdownDate = allMaxSingleDrawdownDate; + } + + public Integer getNomMaxConDrawdownTime() { + return nomMaxConDrawdownTime; + } + + public void setNomMaxConDrawdownTime(Integer nomMaxConDrawdownTime) { + this.nomMaxConDrawdownTime = nomMaxConDrawdownTime; + } + + public Integer getNhyMaxConDrawdownTime() { + return nhyMaxConDrawdownTime; + } + + public void setNhyMaxConDrawdownTime(Integer nhyMaxConDrawdownTime) { + this.nhyMaxConDrawdownTime = nhyMaxConDrawdownTime; + } + + public Integer getNoyMaxConDrawdownTime() { + return noyMaxConDrawdownTime; + } + + public void setNoyMaxConDrawdownTime(Integer noyMaxConDrawdownTime) { + this.noyMaxConDrawdownTime = noyMaxConDrawdownTime; + } + + public Integer getTmMaxConDrawdownTime() { + return tmMaxConDrawdownTime; + } + + public void setTmMaxConDrawdownTime(Integer tmMaxConDrawdownTime) { + this.tmMaxConDrawdownTime = tmMaxConDrawdownTime; + } + + public Integer getTqMaxConDrawdownTime() { + return tqMaxConDrawdownTime; + } + + public void setTqMaxConDrawdownTime(Integer tqMaxConDrawdownTime) { + this.tqMaxConDrawdownTime = tqMaxConDrawdownTime; + } + + public Integer getTyMaxConDrawdownTime() { + return tyMaxConDrawdownTime; + } + + public void setTyMaxConDrawdownTime(Integer tyMaxConDrawdownTime) { + this.tyMaxConDrawdownTime = tyMaxConDrawdownTime; + } + + public Integer getAllMaxConDrawdownTime() { + return allMaxConDrawdownTime; + } + + public void setAllMaxConDrawdownTime(Integer allMaxConDrawdownTime) { + this.allMaxConDrawdownTime = allMaxConDrawdownTime; + } + + public Float getNomYieldStdDeviation() { + return nomYieldStdDeviation; + } + + public void setNomYieldStdDeviation(Float nomYieldStdDeviation) { + this.nomYieldStdDeviation = nomYieldStdDeviation; + } + + public Float getNhyYieldStdDeviation() { + return nhyYieldStdDeviation; + } + + public void setNhyYieldStdDeviation(Float nhyYieldStdDeviation) { + this.nhyYieldStdDeviation = nhyYieldStdDeviation; + } + + public Float getNoyYieldStdDeviation() { + return noyYieldStdDeviation; + } + + public void setNoyYieldStdDeviation(Float noyYieldStdDeviation) { + this.noyYieldStdDeviation = noyYieldStdDeviation; + } + + public Float getTmYieldStdDeviation() { + return tmYieldStdDeviation; + } + + public void setTmYieldStdDeviation(Float tmYieldStdDeviation) { + this.tmYieldStdDeviation = tmYieldStdDeviation; + } + + public Float getTqYieldStdDeviation() { + return tqYieldStdDeviation; + } + + public void setTqYieldStdDeviation(Float tqYieldStdDeviation) { + this.tqYieldStdDeviation = tqYieldStdDeviation; + } + + public Float getTyYieldStdDeviation() { + return tyYieldStdDeviation; + } + + public void setTyYieldStdDeviation(Float tyYieldStdDeviation) { + this.tyYieldStdDeviation = tyYieldStdDeviation; + } + + public Float getAllYieldStdDeviation() { + return allYieldStdDeviation; + } + + public void setAllYieldStdDeviation(Float allYieldStdDeviation) { + this.allYieldStdDeviation = allYieldStdDeviation; + } + + public Float getNomDownStdDeviation() { + return nomDownStdDeviation; + } + + public void setNomDownStdDeviation(Float nomDownStdDeviation) { + this.nomDownStdDeviation = nomDownStdDeviation; + } + + public Float getNhyDownStdDeviation() { + return nhyDownStdDeviation; + } + + public void setNhyDownStdDeviation(Float nhyDownStdDeviation) { + this.nhyDownStdDeviation = nhyDownStdDeviation; + } + + public Float getNoyDownStdDeviation() { + return noyDownStdDeviation; + } + + public void setNoyDownStdDeviation(Float noyDownStdDeviation) { + this.noyDownStdDeviation = noyDownStdDeviation; + } + + public Float getTmDownStdDeviation() { + return tmDownStdDeviation; + } + + public void setTmDownStdDeviation(Float tmDownStdDeviation) { + this.tmDownStdDeviation = tmDownStdDeviation; + } + + public Float getTqDownStdDeviation() { + return tqDownStdDeviation; + } + + public void setTqDownStdDeviation(Float tqDownStdDeviation) { + this.tqDownStdDeviation = tqDownStdDeviation; + } + + public Float getTyDownStdDeviation() { + return tyDownStdDeviation; + } + + public void setTyDownStdDeviation(Float tyDownStdDeviation) { + this.tyDownStdDeviation = tyDownStdDeviation; + } + + public Float getAllDownStdDeviation() { + return allDownStdDeviation; + } + + public void setAllDownStdDeviation(Float allDownStdDeviation) { + this.allDownStdDeviation = allDownStdDeviation; + } + + public Float getNomWinRatio() { + return nomWinRatio; + } + + public void setNomWinRatio(Float nomWinRatio) { + this.nomWinRatio = nomWinRatio; + } + + public Float getNhyWinRatio() { + return nhyWinRatio; + } + + public void setNhyWinRatio(Float nhyWinRatio) { + this.nhyWinRatio = nhyWinRatio; + } + + public Float getNoyWinRatio() { + return noyWinRatio; + } + + public void setNoyWinRatio(Float noyWinRatio) { + this.noyWinRatio = noyWinRatio; + } + + public Float getTmWinRatio() { + return tmWinRatio; + } + + public void setTmWinRatio(Float tmWinRatio) { + this.tmWinRatio = tmWinRatio; + } + + public Float getTqWinRatio() { + return tqWinRatio; + } + + public void setTqWinRatio(Float tqWinRatio) { + this.tqWinRatio = tqWinRatio; + } + + public Float getTyWinRatio() { + return tyWinRatio; + } + + public void setTyWinRatio(Float tyWinRatio) { + this.tyWinRatio = tyWinRatio; + } + + public Float getAllWinRatio() { + return allWinRatio; + } + + public void setAllWinRatio(Float allWinRatio) { + this.allWinRatio = allWinRatio; + } + + public Float getNomBeta() { + return nomBeta; + } + + public void setNomBeta(Float nomBeta) { + this.nomBeta = nomBeta; + } + + public Float getNhyBeta() { + return nhyBeta; + } + + public void setNhyBeta(Float nhyBeta) { + this.nhyBeta = nhyBeta; + } + + public Float getNoyBeta() { + return noyBeta; + } + + public void setNoyBeta(Float noyBeta) { + this.noyBeta = noyBeta; + } + + public Float getTmBeta() { + return tmBeta; + } + + public void setTmBeta(Float tmBeta) { + this.tmBeta = tmBeta; + } + + public Float getTqBeta() { + return tqBeta; + } + + public void setTqBeta(Float tqBeta) { + this.tqBeta = tqBeta; + } + + public Float getTyBeta() { + return tyBeta; + } + + public void setTyBeta(Float tyBeta) { + this.tyBeta = tyBeta; + } + + public Float getAllBeta() { + return allBeta; + } + + public void setAllBeta(Float allBeta) { + this.allBeta = allBeta; + } + + public Float getNomAlpha() { + return nomAlpha; + } + + public void setNomAlpha(Float nomAlpha) { + this.nomAlpha = nomAlpha; + } + + public Float getNhyAlpha() { + return nhyAlpha; + } + + public void setNhyAlpha(Float nhyAlpha) { + this.nhyAlpha = nhyAlpha; + } + + public Float getNoyAlpha() { + return noyAlpha; + } + + public void setNoyAlpha(Float noyAlpha) { + this.noyAlpha = noyAlpha; + } + + public Float getTmAlpha() { + return tmAlpha; + } + + public void setTmAlpha(Float tmAlpha) { + this.tmAlpha = tmAlpha; + } + + public Float getTqAlpha() { + return tqAlpha; + } + + public void setTqAlpha(Float tqAlpha) { + this.tqAlpha = tqAlpha; + } + + public Float getTyAlpha() { + return tyAlpha; + } + + public void setTyAlpha(Float tyAlpha) { + this.tyAlpha = tyAlpha; + } + + public Float getAllAlpha() { + return allAlpha; + } + + public void setAllAlpha(Float allAlpha) { + this.allAlpha = allAlpha; + } + + public Float getNomJansen() { + return nomJansen; + } + + public void setNomJansen(Float nomJansen) { + this.nomJansen = nomJansen; + } + + public Float getNhyJansen() { + return nhyJansen; + } + + public void setNhyJansen(Float nhyJansen) { + this.nhyJansen = nhyJansen; + } + + public Float getNoyJansen() { + return noyJansen; + } + + public void setNoyJansen(Float noyJansen) { + this.noyJansen = noyJansen; + } + + public Float getTmJansen() { + return tmJansen; + } + + public void setTmJansen(Float tmJansen) { + this.tmJansen = tmJansen; + } + + public Float getTqJansen() { + return tqJansen; + } + + public void setTqJansen(Float tqJansen) { + this.tqJansen = tqJansen; + } + + public Float getTyJansen() { + return tyJansen; + } + + public void setTyJansen(Float tyJansen) { + this.tyJansen = tyJansen; + } + + public Float getAllJansen() { + return allJansen; + } + + public void setAllJansen(Float allJansen) { + this.allJansen = allJansen; + } + + public Float getNomKumarRatio() { + return nomKumarRatio; + } + + public void setNomKumarRatio(Float nomKumarRatio) { + this.nomKumarRatio = nomKumarRatio; + } + + public Float getNhyKumarRatio() { + return nhyKumarRatio; + } + + public void setNhyKumarRatio(Float nhyKumarRatio) { + this.nhyKumarRatio = nhyKumarRatio; + } + + public Float getNoyKumarRatio() { + return noyKumarRatio; + } + + public void setNoyKumarRatio(Float noyKumarRatio) { + this.noyKumarRatio = noyKumarRatio; + } + + public Float getTmKumarRatio() { + return tmKumarRatio; + } + + public void setTmKumarRatio(Float tmKumarRatio) { + this.tmKumarRatio = tmKumarRatio; + } + + public Float getTqKumarRatio() { + return tqKumarRatio; + } + + public void setTqKumarRatio(Float tqKumarRatio) { + this.tqKumarRatio = tqKumarRatio; + } + + public Float getTyKumarRatio() { + return tyKumarRatio; + } + + public void setTyKumarRatio(Float tyKumarRatio) { + this.tyKumarRatio = tyKumarRatio; + } + + public Float getAllKumarRatio() { + return allKumarRatio; + } + + public void setAllKumarRatio(Float allKumarRatio) { + this.allKumarRatio = allKumarRatio; + } + + public Float getNomSharpeRatio() { + return nomSharpeRatio; + } + + public void setNomSharpeRatio(Float nomSharpeRatio) { + this.nomSharpeRatio = nomSharpeRatio; + } + + public Float getNhySharpeRatio() { + return nhySharpeRatio; + } + + public void setNhySharpeRatio(Float nhySharpeRatio) { + this.nhySharpeRatio = nhySharpeRatio; + } + + public Float getNoySharpeRatio() { + return noySharpeRatio; + } + + public void setNoySharpeRatio(Float noySharpeRatio) { + this.noySharpeRatio = noySharpeRatio; + } + + public Float getTmSharpeRatio() { + return tmSharpeRatio; + } + + public void setTmSharpeRatio(Float tmSharpeRatio) { + this.tmSharpeRatio = tmSharpeRatio; + } + + public Float getTqSharpeRatio() { + return tqSharpeRatio; + } + + public void setTqSharpeRatio(Float tqSharpeRatio) { + this.tqSharpeRatio = tqSharpeRatio; + } + + public Float getTySharpeRatio() { + return tySharpeRatio; + } + + public void setTySharpeRatio(Float tySharpeRatio) { + this.tySharpeRatio = tySharpeRatio; + } + + public Float getAllSharpeRatio() { + return allSharpeRatio; + } + + public void setAllSharpeRatio(Float allSharpeRatio) { + this.allSharpeRatio = allSharpeRatio; + } + + public Float getNomSortinoRatio() { + return nomSortinoRatio; + } + + public void setNomSortinoRatio(Float nomSortinoRatio) { + this.nomSortinoRatio = nomSortinoRatio; + } + + public Float getNhySortinoRatio() { + return nhySortinoRatio; + } + + public void setNhySortinoRatio(Float nhySortinoRatio) { + this.nhySortinoRatio = nhySortinoRatio; + } + + public Float getNoySortinoRatio() { + return noySortinoRatio; + } + + public void setNoySortinoRatio(Float noySortinoRatio) { + this.noySortinoRatio = noySortinoRatio; + } + + public Float getTmSortinoRatio() { + return tmSortinoRatio; + } + + public void setTmSortinoRatio(Float tmSortinoRatio) { + this.tmSortinoRatio = tmSortinoRatio; + } + + public Float getTqSortinoRatio() { + return tqSortinoRatio; + } + + public void setTqSortinoRatio(Float tqSortinoRatio) { + this.tqSortinoRatio = tqSortinoRatio; + } + + public Float getTySortinoRatio() { + return tySortinoRatio; + } + + public void setTySortinoRatio(Float tySortinoRatio) { + this.tySortinoRatio = tySortinoRatio; + } + + public Float getAllSortinoRatio() { + return allSortinoRatio; + } + + public void setAllSortinoRatio(Float allSortinoRatio) { + this.allSortinoRatio = allSortinoRatio; + } + + public Float getNomHurstIndex() { + return nomHurstIndex; + } + + public void setNomHurstIndex(Float nomHurstIndex) { + this.nomHurstIndex = nomHurstIndex; + } + + public Float getNhyHurstIndex() { + return nhyHurstIndex; + } + + public void setNhyHurstIndex(Float nhyHurstIndex) { + this.nhyHurstIndex = nhyHurstIndex; + } + + public Float getNoyHurstIndex() { + return noyHurstIndex; + } + + public void setNoyHurstIndex(Float noyHurstIndex) { + this.noyHurstIndex = noyHurstIndex; + } + + public Float getTmHurstIndex() { + return tmHurstIndex; + } + + public void setTmHurstIndex(Float tmHurstIndex) { + this.tmHurstIndex = tmHurstIndex; + } + + public Float getTqHurstIndex() { + return tqHurstIndex; + } + + public void setTqHurstIndex(Float tqHurstIndex) { + this.tqHurstIndex = tqHurstIndex; + } + + public Float getTyHurstIndex() { + return tyHurstIndex; + } + + public void setTyHurstIndex(Float tyHurstIndex) { + this.tyHurstIndex = tyHurstIndex; + } + + public Float getAllHurstIndex() { + return allHurstIndex; + } + + public void setAllHurstIndex(Float allHurstIndex) { + this.allHurstIndex = allHurstIndex; + } + + public Float getNomVarIndex() { + return nomVarIndex; + } + + public void setNomVarIndex(Float nomVarIndex) { + this.nomVarIndex = nomVarIndex; + } + + public Float getNhyVarIndex() { + return nhyVarIndex; + } + + public void setNhyVarIndex(Float nhyVarIndex) { + this.nhyVarIndex = nhyVarIndex; + } + + public Float getNoyVarIndex() { + return noyVarIndex; + } + + public void setNoyVarIndex(Float noyVarIndex) { + this.noyVarIndex = noyVarIndex; + } + + public Float getTmVarIndex() { + return tmVarIndex; + } + + public void setTmVarIndex(Float tmVarIndex) { + this.tmVarIndex = tmVarIndex; + } + + public Float getTqVarIndex() { + return tqVarIndex; + } + + public void setTqVarIndex(Float tqVarIndex) { + this.tqVarIndex = tqVarIndex; + } + + public Float getTyVarIndex() { + return tyVarIndex; + } + + public void setTyVarIndex(Float tyVarIndex) { + this.tyVarIndex = tyVarIndex; + } + + public Float getAllVarIndex() { + return allVarIndex; + } + + public void setAllVarIndex(Float allVarIndex) { + this.allVarIndex = allVarIndex; + } + + public Float getNomVarIndex99() { + return nomVarIndex99; + } + + public void setNomVarIndex99(Float nomVarIndex99) { + this.nomVarIndex99 = nomVarIndex99; + } + + public Float getNhyVarIndex99() { + return nhyVarIndex99; + } + + public void setNhyVarIndex99(Float nhyVarIndex99) { + this.nhyVarIndex99 = nhyVarIndex99; + } + + public Float getNoyVarIndex99() { + return noyVarIndex99; + } + + public void setNoyVarIndex99(Float noyVarIndex99) { + this.noyVarIndex99 = noyVarIndex99; + } + + public Float getTmVarIndex99() { + return tmVarIndex99; + } + + public void setTmVarIndex99(Float tmVarIndex99) { + this.tmVarIndex99 = tmVarIndex99; + } + + public Float getTqVarIndex99() { + return tqVarIndex99; + } + + public void setTqVarIndex99(Float tqVarIndex99) { + this.tqVarIndex99 = tqVarIndex99; + } + + public Float getTyVarIndex99() { + return tyVarIndex99; + } + + public void setTyVarIndex99(Float tyVarIndex99) { + this.tyVarIndex99 = tyVarIndex99; + } + + public Float getAllVarIndex99() { + return allVarIndex99; + } + + public void setAllVarIndex99(Float allVarIndex99) { + this.allVarIndex99 = allVarIndex99; + } + + public Float getNomUpCaptureRate() { + return nomUpCaptureRate; + } + + public void setNomUpCaptureRate(Float nomUpCaptureRate) { + this.nomUpCaptureRate = nomUpCaptureRate; + } + + public Float getNhyUpCaptureRate() { + return nhyUpCaptureRate; + } + + public void setNhyUpCaptureRate(Float nhyUpCaptureRate) { + this.nhyUpCaptureRate = nhyUpCaptureRate; + } + + public Float getNoyUpCaptureRate() { + return noyUpCaptureRate; + } + + public void setNoyUpCaptureRate(Float noyUpCaptureRate) { + this.noyUpCaptureRate = noyUpCaptureRate; + } + + public Float getTmUpCaptureRate() { + return tmUpCaptureRate; + } + + public void setTmUpCaptureRate(Float tmUpCaptureRate) { + this.tmUpCaptureRate = tmUpCaptureRate; + } + + public Float getTqUpCaptureRate() { + return tqUpCaptureRate; + } + + public void setTqUpCaptureRate(Float tqUpCaptureRate) { + this.tqUpCaptureRate = tqUpCaptureRate; + } + + public Float getTyUpCaptureRate() { + return tyUpCaptureRate; + } + + public void setTyUpCaptureRate(Float tyUpCaptureRate) { + this.tyUpCaptureRate = tyUpCaptureRate; + } + + public Float getAllUpCaptureRate() { + return allUpCaptureRate; + } + + public void setAllUpCaptureRate(Float allUpCaptureRate) { + this.allUpCaptureRate = allUpCaptureRate; + } + + public Float getNomDownCaptureRate() { + return nomDownCaptureRate; + } + + public void setNomDownCaptureRate(Float nomDownCaptureRate) { + this.nomDownCaptureRate = nomDownCaptureRate; + } + + public Float getNhyDownCaptureRate() { + return nhyDownCaptureRate; + } + + public void setNhyDownCaptureRate(Float nhyDownCaptureRate) { + this.nhyDownCaptureRate = nhyDownCaptureRate; + } + + public Float getNoyDownCaptureRate() { + return noyDownCaptureRate; + } + + public void setNoyDownCaptureRate(Float noyDownCaptureRate) { + this.noyDownCaptureRate = noyDownCaptureRate; + } + + public Float getTmDownCaptureRate() { + return tmDownCaptureRate; + } + + public void setTmDownCaptureRate(Float tmDownCaptureRate) { + this.tmDownCaptureRate = tmDownCaptureRate; + } + + public Float getTqDownCaptureRate() { + return tqDownCaptureRate; + } + + public void setTqDownCaptureRate(Float tqDownCaptureRate) { + this.tqDownCaptureRate = tqDownCaptureRate; + } + + public Float getTyDownCaptureRate() { + return tyDownCaptureRate; + } + + public void setTyDownCaptureRate(Float tyDownCaptureRate) { + this.tyDownCaptureRate = tyDownCaptureRate; + } + + public Float getAllDownCaptureRate() { + return allDownCaptureRate; + } + + public void setAllDownCaptureRate(Float allDownCaptureRate) { + this.allDownCaptureRate = allDownCaptureRate; + } + + public Float getNomInfoRatio() { + return nomInfoRatio; + } + + public void setNomInfoRatio(Float nomInfoRatio) { + this.nomInfoRatio = nomInfoRatio; + } + + public Float getNhyInfoRatio() { + return nhyInfoRatio; + } + + public void setNhyInfoRatio(Float nhyInfoRatio) { + this.nhyInfoRatio = nhyInfoRatio; + } + + public Float getNoyInfoRatio() { + return noyInfoRatio; + } + + public void setNoyInfoRatio(Float noyInfoRatio) { + this.noyInfoRatio = noyInfoRatio; + } + + public Float getTmInfoRatio() { + return tmInfoRatio; + } + + public void setTmInfoRatio(Float tmInfoRatio) { + this.tmInfoRatio = tmInfoRatio; + } + + public Float getTqInfoRatio() { + return tqInfoRatio; + } + + public void setTqInfoRatio(Float tqInfoRatio) { + this.tqInfoRatio = tqInfoRatio; + } + + public Float getTyInfoRatio() { + return tyInfoRatio; + } + + public void setTyInfoRatio(Float tyInfoRatio) { + this.tyInfoRatio = tyInfoRatio; + } + + public Float getAllInfoRatio() { + return allInfoRatio; + } + + public void setAllInfoRatio(Float allInfoRatio) { + this.allInfoRatio = allInfoRatio; + } + + public Float getNomAlgorithmVolatility() { + return nomAlgorithmVolatility; + } + + public void setNomAlgorithmVolatility(Float nomAlgorithmVolatility) { + this.nomAlgorithmVolatility = nomAlgorithmVolatility; + } + + public Float getNhyAlgorithmVolatility() { + return nhyAlgorithmVolatility; + } + + public void setNhyAlgorithmVolatility(Float nhyAlgorithmVolatility) { + this.nhyAlgorithmVolatility = nhyAlgorithmVolatility; + } + + public Float getNoyAlgorithmVolatility() { + return noyAlgorithmVolatility; + } + + public void setNoyAlgorithmVolatility(Float noyAlgorithmVolatility) { + this.noyAlgorithmVolatility = noyAlgorithmVolatility; + } + + public Float getTmAlgorithmVolatility() { + return tmAlgorithmVolatility; + } + + public void setTmAlgorithmVolatility(Float tmAlgorithmVolatility) { + this.tmAlgorithmVolatility = tmAlgorithmVolatility; + } + + public Float getTqAlgorithmVolatility() { + return tqAlgorithmVolatility; + } + + public void setTqAlgorithmVolatility(Float tqAlgorithmVolatility) { + this.tqAlgorithmVolatility = tqAlgorithmVolatility; + } + + public Float getTyAlgorithmVolatility() { + return tyAlgorithmVolatility; + } + + public void setTyAlgorithmVolatility(Float tyAlgorithmVolatility) { + this.tyAlgorithmVolatility = tyAlgorithmVolatility; + } + + public Float getAllAlgorithmVolatility() { + return allAlgorithmVolatility; + } + + public void setAllAlgorithmVolatility(Float allAlgorithmVolatility) { + this.allAlgorithmVolatility = allAlgorithmVolatility; + } + + public Float getNomMSquare() { + return nomMSquare; + } + + public void setNomMSquare(Float nomMSquare) { + this.nomMSquare = nomMSquare; + } + + public Float getNhyMSquare() { + return nhyMSquare; + } + + public void setNhyMSquare(Float nhyMSquare) { + this.nhyMSquare = nhyMSquare; + } + + public Float getNoyMSquare() { + return noyMSquare; + } + + public void setNoyMSquare(Float noyMSquare) { + this.noyMSquare = noyMSquare; + } + + public Float getTmMSquare() { + return tmMSquare; + } + + public void setTmMSquare(Float tmMSquare) { + this.tmMSquare = tmMSquare; + } + + public Float getTqMSquare() { + return tqMSquare; + } + + public void setTqMSquare(Float tqMSquare) { + this.tqMSquare = tqMSquare; + } + + public Float getTyMSquare() { + return tyMSquare; + } + + public void setTyMSquare(Float tyMSquare) { + this.tyMSquare = tyMSquare; + } + + public Float getAllMSquare() { + return allMSquare; + } + + public void setAllMSquare(Float allMSquare) { + this.allMSquare = allMSquare; + } + + public Float getNomTreynorIndex() { + return nomTreynorIndex; + } + + public void setNomTreynorIndex(Float nomTreynorIndex) { + this.nomTreynorIndex = nomTreynorIndex; + } + + public Float getNhyTreynorIndex() { + return nhyTreynorIndex; + } + + public void setNhyTreynorIndex(Float nhyTreynorIndex) { + this.nhyTreynorIndex = nhyTreynorIndex; + } + + public Float getNoyTreynorIndex() { + return noyTreynorIndex; + } + + public void setNoyTreynorIndex(Float noyTreynorIndex) { + this.noyTreynorIndex = noyTreynorIndex; + } + + public Float getTmTreynorIndex() { + return tmTreynorIndex; + } + + public void setTmTreynorIndex(Float tmTreynorIndex) { + this.tmTreynorIndex = tmTreynorIndex; + } + + public Float getTqTreynorIndex() { + return tqTreynorIndex; + } + + public void setTqTreynorIndex(Float tqTreynorIndex) { + this.tqTreynorIndex = tqTreynorIndex; + } + + public Float getTyTreynorIndex() { + return tyTreynorIndex; + } + + public void setTyTreynorIndex(Float tyTreynorIndex) { + this.tyTreynorIndex = tyTreynorIndex; + } + + public Float getAllTreynorIndex() { + return allTreynorIndex; + } + + public void setAllTreynorIndex(Float allTreynorIndex) { + this.allTreynorIndex = allTreynorIndex; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getShortName() { + return shortName; + } + + public void setShortName(String shortName) { + this.shortName = shortName; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getRecordNumber() { + return recordNumber; + } + + public void setRecordNumber(String recordNumber) { + this.recordNumber = recordNumber; + } + + public Byte getFundType() { + return fundType; + } + + public void setFundType(Byte fundType) { + this.fundType = fundType; + } + + public Byte getFundBreed() { + return fundBreed; + } + + public void setFundBreed(Byte fundBreed) { + this.fundBreed = fundBreed; + } + + public Byte getFundStatus() { + return fundStatus; + } + + public void setFundStatus(Byte fundStatus) { + this.fundStatus = fundStatus; + } + + public String getBuyStatus() { + return buyStatus; + } + + public void setBuyStatus(String buyStatus) { + this.buyStatus = buyStatus; + } + + public String getRedeemStatus() { + return redeemStatus; + } + + public void setRedeemStatus(String redeemStatus) { + this.redeemStatus = redeemStatus; + } + + public String getRecordDate() { + return recordDate; + } + + public void setRecordDate(String recordDate) { + this.recordDate = recordDate; + } + + public String getCreateDate() { + return createDate; + } + + public void setCreateDate(String createDate) { + this.createDate = createDate; + } + + public String getStopDate() { + return stopDate; + } + + public void setStopDate(String stopDate) { + this.stopDate = stopDate; + } + + public String getFundFilingStage() { + return fundFilingStage; + } + + public void setFundFilingStage(String fundFilingStage) { + this.fundFilingStage = fundFilingStage; + } + + public String getFundInvestmentType() { + return fundInvestmentType; + } + + public void setFundInvestmentType(String fundInvestmentType) { + this.fundInvestmentType = fundInvestmentType; + } + + public String getCurrency() { + return currency; + } + + public void setCurrency(String currency) { + this.currency = currency; + } + + public String getManagerType() { + return managerType; + } + + public void setManagerType(String managerType) { + this.managerType = managerType; + } + + public String getManagerName() { + return managerName; + } + + public void setManagerName(String managerName) { + this.managerName = managerName; + } + + public String getInvestmentTarget() { + return investmentTarget; + } + + public void setInvestmentTarget(String investmentTarget) { + this.investmentTarget = investmentTarget; + } + + public String getMajorInvestAreas() { + return majorInvestAreas; + } + + public void setMajorInvestAreas(String majorInvestAreas) { + this.majorInvestAreas = majorInvestAreas; + } + + public String getFundLastModifyDate() { + return fundLastModifyDate; + } + + public void setFundLastModifyDate(String fundLastModifyDate) { + this.fundLastModifyDate = fundLastModifyDate; + } + + public String getSpecialNote() { + return specialNote; + } + + public void setSpecialNote(String specialNote) { + this.specialNote = specialNote; + } + + public String getRegisteredAddress() { + return registeredAddress; + } + + public void setRegisteredAddress(String registeredAddress) { + this.registeredAddress = registeredAddress; + } + + public String getInvestmentStrategy() { + return investmentStrategy; + } + + public void setInvestmentStrategy(String investmentStrategy) { + this.investmentStrategy = investmentStrategy; + } + + public String getInvestmentSubStrategy() { + return investmentSubStrategy; + } + + public void setInvestmentSubStrategy(String investmentSubStrategy) { + this.investmentSubStrategy = investmentSubStrategy; + } + + public List getFundManagerIds() { + return fundManagerIds; + } + + public void setFundManagerIds(List fundManagerIds) { + this.fundManagerIds = fundManagerIds; + } + + public String getCompanyId() { + return companyId; + } + + public void setCompanyId(String companyId) { + this.companyId = companyId; + } + + public Long getOrderNum() { + return orderNum; + } + + public void setOrderNum(Long orderNum) { + this.orderNum = orderNum; + } + + public String getCreateScale() { + return createScale; + } + + public void setCreateScale(String createScale) { + this.createScale = createScale; + } + + public String getLatestScale() { + return latestScale; + } + + public void setLatestScale(String latestScale) { + this.latestScale = latestScale; + } + + public String getBenchmark() { + return benchmark; + } + + public void setBenchmark(String benchmark) { + this.benchmark = benchmark; + } + + public Byte getNetValueUpdateRate() { + return netValueUpdateRate; + } + + public void setNetValueUpdateRate(Byte netValueUpdateRate) { + this.netValueUpdateRate = netValueUpdateRate; + } + + public String getFundOuterId() { + return fundOuterId; + } + + public void setFundOuterId(String fundOuterId) { + this.fundOuterId = fundOuterId; + } + + public String getTags() { + return tags; + } + + public void setTags(String tags) { + this.tags = tags; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public String getStrategyCapacity() { + return strategyCapacity; + } + + public void setStrategyCapacity(String strategyCapacity) { + this.strategyCapacity = strategyCapacity; + } + + public Long getCreateTime() { + return createTime; + } + + public void setCreateTime(Long createTime) { + this.createTime = createTime; + } + + public String getCreatorId() { + return creatorId; + } + + public void setCreatorId(String creatorId) { + this.creatorId = creatorId; + } + + public Long getLastModifyTime() { + return lastModifyTime; + } + + public void setLastModifyTime(Long lastModifyTime) { + this.lastModifyTime = lastModifyTime; + } + + public String getLastModifierId() { + return lastModifierId; + } + + public void setLastModifierId(String lastModifierId) { + this.lastModifierId = lastModifierId; + } + + public String getCompanyOuterId() { + return companyOuterId; + } + + public void setCompanyOuterId(String companyOuterId) { + this.companyOuterId = companyOuterId; + } + + public String getCompanyName() { + return companyName; + } + + public void setCompanyName(String companyName) { + this.companyName = companyName; + } + + public List getManagerOuterIds() { + return managerOuterIds; + } + + public void setManagerOuterIds(List managerOuterIds) { + this.managerOuterIds = managerOuterIds; + } + + public List getFundIds() { + return fundIds; + } + + public void setFundIds(List fundIds) { + this.fundIds = fundIds; + } + + public List getCompanyIds() { + return companyIds; + } + + public void setCompanyIds(List companyIds) { + this.companyIds = companyIds; + } + + public Float getStartAnnualizedReturn() { + return startAnnualizedReturn; + } + + public void setStartAnnualizedReturn(Float startAnnualizedReturn) { + this.startAnnualizedReturn = startAnnualizedReturn; + } + + public Float getEndAnnualizedReturn() { + return endAnnualizedReturn; + } + + public void setEndAnnualizedReturn(Float endAnnualizedReturn) { + this.endAnnualizedReturn = endAnnualizedReturn; + } + + public String getTimeInterval() { + return timeInterval; + } + + public void setTimeInterval(String timeInterval) { + this.timeInterval = timeInterval; + } + + public List getFundManagerNames() { + return fundManagerNames; + } + + public void setFundManagerNames(List fundManagerNames) { + this.fundManagerNames = fundManagerNames; + } + + public String getFundStatusName() { + return fundStatusName; + } + + public void setFundStatusName(String fundStatusName) { + this.fundStatusName = fundStatusName; + } + + public String getFundTypeName() { + return fundTypeName; + } + + public void setFundTypeName(String fundTypeName) { + this.fundTypeName = fundTypeName; + } + + public Byte getIsConcern() { + return isConcern; + } + + public void setIsConcern(Byte isConcern) { + this.isConcern = isConcern; + } + + public Float getConfigWeight() { + return configWeight; + } + + public void setConfigWeight(Float configWeight) { + this.configWeight = configWeight; + } + + public String getNetValueDateString() { + return netValueDateString; + } + + public void setNetValueDateString(String netValueDateString) { + this.netValueDateString = netValueDateString; + } + + public String getManagerId() { + return managerId; + } + + public void setManagerId(String managerId) { + this.managerId = managerId; + } + + public String getTagId() { + return tagId; + } + + public void setTagId(String tagId) { + this.tagId = tagId; + } + } +} \ No newline at end of file diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1570.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1570.java new file mode 100644 index 0000000000..8053e40bf0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1570.java @@ -0,0 +1,59 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.List; + +public class Issue1570 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + assertEquals("{}", JSON.toJSONString(model, SerializerFeature.WriteNullBooleanAsFalse)); + assertEquals("{\"value\":\"\"}", JSON.toJSONString(model, SerializerFeature.WriteNullStringAsEmpty)); + } + + public void test_for_issue_int() throws Exception { + ModelInt model = new ModelInt(); + assertEquals("{}", JSON.toJSONString(model, SerializerFeature.WriteNullBooleanAsFalse)); + assertEquals("{\"value\":0}", JSON.toJSONString(model, SerializerFeature.WriteNullNumberAsZero)); + } + + public void test_for_issue_long() throws Exception { + ModelLong model = new ModelLong(); + assertEquals("{}", JSON.toJSONString(model, SerializerFeature.WriteNullBooleanAsFalse)); + assertEquals("{\"value\":0}", JSON.toJSONString(model, SerializerFeature.WriteNullNumberAsZero)); + } + + public void test_for_issue_bool() throws Exception { + ModelBool model = new ModelBool(); + assertEquals("{}", JSON.toJSONString(model, SerializerFeature.WriteNullNumberAsZero)); + assertEquals("{\"value\":false}", JSON.toJSONString(model, SerializerFeature.WriteNullBooleanAsFalse)); + } + + public void test_for_issue_list() throws Exception { + ModelList model = new ModelList(); + assertEquals("{}", JSON.toJSONString(model, SerializerFeature.WriteNullNumberAsZero)); + assertEquals("{\"value\":[]}", JSON.toJSONString(model, SerializerFeature.WriteNullListAsEmpty)); + } + + public static class Model { + public String value; + } + + public static class ModelInt { + public Integer value; + } + + public static class ModelLong { + public Long value; + } + + public static class ModelBool { + public Boolean value; + } + + public static class ModelList { + public List value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1570_private.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1570_private.java new file mode 100644 index 0000000000..0521893de4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1570_private.java @@ -0,0 +1,59 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.List; + +public class Issue1570_private extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + assertEquals("{}", JSON.toJSONString(model, SerializerFeature.WriteNullBooleanAsFalse)); + assertEquals("{\"value\":\"\"}", JSON.toJSONString(model, SerializerFeature.WriteNullStringAsEmpty)); + } + + public void test_for_issue_int() throws Exception { + ModelInt model = new ModelInt(); + assertEquals("{}", JSON.toJSONString(model, SerializerFeature.WriteNullBooleanAsFalse)); + assertEquals("{\"value\":0}", JSON.toJSONString(model, SerializerFeature.WriteNullNumberAsZero)); + } + + public void test_for_issue_long() throws Exception { + ModelLong model = new ModelLong(); + assertEquals("{}", JSON.toJSONString(model, SerializerFeature.WriteNullBooleanAsFalse)); + assertEquals("{\"value\":0}", JSON.toJSONString(model, SerializerFeature.WriteNullNumberAsZero)); + } + + public void test_for_issue_bool() throws Exception { + ModelBool model = new ModelBool(); + assertEquals("{}", JSON.toJSONString(model, SerializerFeature.WriteNullNumberAsZero)); + assertEquals("{\"value\":false}", JSON.toJSONString(model, SerializerFeature.WriteNullBooleanAsFalse)); + } + + public void test_for_issue_list() throws Exception { + ModelList model = new ModelList(); + assertEquals("{}", JSON.toJSONString(model, SerializerFeature.WriteNullNumberAsZero)); + assertEquals("{\"value\":[]}", JSON.toJSONString(model, SerializerFeature.WriteNullListAsEmpty)); + } + + private static class Model { + public String value; + } + + private static class ModelInt { + public Integer value; + } + + private static class ModelLong { + public Long value; + } + + private static class ModelBool { + public Boolean value; + } + + private static class ModelList { + public List value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1572.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1572.java new file mode 100644 index 0000000000..e743b6f56e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1572.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +import java.util.Map; +import java.util.Set; + +public class Issue1572 extends TestCase { + public void test_for_issue() throws Exception { + Person person = new Person(); + + person.setId("1001"); + + person.setName("1001"); + + Map pathValues = JSONPath.paths(person); + Set paths = pathValues.keySet(); + + assertEquals(3, paths.size()); + assertEquals("1001", pathValues.get("/id")); + assertEquals("1001", pathValues.get("/name")); + assertSame(person, pathValues.get("/")); + } + + public static class Person { + private String name; + private String id; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1576.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1576.java new file mode 100644 index 0000000000..d195884f62 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1576.java @@ -0,0 +1,118 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.List; + +public class Issue1576 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"code\":200,\"in_msg\":\"a\",\"out_msg\":\"a\",\"data\":[{\"title\":\"a\",\"url\":\"url\",\"content\":\"content\"}],\"client_id\":0,\"client_param\":0,\"userid\":0}"; + NewsDetail newsDetail = JSON.parseObject(json, NewsDetail.class); + assertNotNull(newsDetail); + } + + public static class NewsDetail { + + public int code; + public String in_msg; + public String out_msg; + public String client_id; + public String client_param; + public String userid; + public List data = new ArrayList(); + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getIn_msg() { + return in_msg; + } + + public void setIn_msg(String in_msg) { + this.in_msg = in_msg; + } + + public String getOut_msg() { + return out_msg; + } + + public void setOut_msg(String out_msg) { + this.out_msg = out_msg; + } + + public String getClient_id() { + return client_id; + } + + public void setClient_id(String client_id) { + this.client_id = client_id; + } + + public String getClient_param() { + return client_param; + } + + public void setClient_param(String client_param) { + this.client_param = client_param; + } + + public String getUserid() { + return userid; + } + + public void setUserid(String userid) { + this.userid = userid; + } + + public List getData() { + return data; + } + + public void setData(List data) { + this.data = data; + } + } + + public static class DataBean { + /** + * title : 中午 + * url : url + * content : content + */ + + public String title; + public String url; + public String content; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1580.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1580.java new file mode 100644 index 0000000000..50f9293824 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1580.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; +import junit.framework.TestCase; + +public class Issue1580 extends TestCase { + public void test_for_issue() throws Exception { + SimplePropertyPreFilter classAFilter = new SimplePropertyPreFilter(Model.class, "code"); + SerializeFilter[] filters =new SerializeFilter[]{classAFilter}; + + Model model = new Model(); + model.code = 1001; + model.name = "N1"; + + String json = JSON.toJSONString(model, filters, SerializerFeature.BeanToArray ); + assertEquals("[1001,null]", json); + } + + public static class Model { + private int code; + private String name; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1580_private.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1580_private.java new file mode 100644 index 0000000000..d5f5aa34b8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1580_private.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; +import junit.framework.TestCase; + +public class Issue1580_private extends TestCase { + public void test_for_issue() throws Exception { + SimplePropertyPreFilter classAFilter = new SimplePropertyPreFilter(Model.class, "code"); + SerializeFilter[] filters =new SerializeFilter[]{classAFilter}; + + Model model = new Model(); + model.code = 1001; + model.name = "N1"; + + String json = JSON.toJSONString(model, filters, SerializerFeature.BeanToArray ); + assertEquals("[1001,null]", json); + } + + private static class Model { + private int code; + private String name; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1582.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1582.java new file mode 100644 index 0000000000..901ad33b98 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1582.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +public class Issue1582 extends TestCase { + public void test_for_issue() throws Exception { + assertSame(Size.Big, JSON.parseObject("\"Big\"", Size.class)); + assertSame(Size.Big, JSON.parseObject("\"big\"", Size.class)); + assertNull(JSON.parseObject("\"Large\"", Size.class)); + assertSame(Size.LL, JSON.parseObject("\"L3\"", Size.class)); + + assertSame(Size.Small, JSON.parseObject("\"Little\"", Size.class)); + } + + public void test_for_issue_1() throws Exception { + JSONObject object = JSON.parseObject("{\"size\":\"Little\"}"); + Model model = object.toJavaObject(Model.class); + assertSame(Size.Small, model.size); + } + + public static class Model { + public Size size; + } + + public static enum Size { + Big, + + @JSONField(alternateNames = "Little") + Small, + + @JSONField(name = "L3") + LL + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1583.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1583.java new file mode 100644 index 0000000000..f40992c581 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1583.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Issue1583 extends TestCase { + public void test_issue() throws Exception { + Map> totalMap = new HashMap>(); + for (int i = 0; i < 10; i++) { + List list = new ArrayList(); + for (int j = 0; j < 2; j++) { + list.add("list" + j); + } + totalMap.put("map" + i, list); + } + List>> mapList = new ArrayList>>(totalMap.entrySet()); + String jsonString = JSON.toJSONString(mapList, SerializerFeature.DisableCircularReferenceDetect); + + System.out.println(jsonString); + List>> parse = JSON.parseObject(jsonString, new TypeReference>>>() {}); + System.out.println(parse); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1584.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1584.java new file mode 100644 index 0000000000..e474a15308 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1584.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.issue_1500; + +import clojure.lang.Obj; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import junit.framework.TestCase; + +import java.lang.reflect.Type; +import java.util.Collections; +import java.util.Map; + +public class Issue1584 extends TestCase { + public void test_for_issue() throws Exception { + ParserConfig config = new ParserConfig(); + + String json = "{\"k\":1,\"v\":\"A\"}"; + + { + Map.Entry entry = JSON.parseObject(json, Map.Entry.class, config); + assertEquals("v", entry.getKey()); + assertEquals("A", entry.getValue()); + } + + config.putDeserializer(Map.Entry.class, new ObjectDeserializer() { + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + JSONObject object = parser.parseObject(); + Object k = object.get("k"); + Object v = object.get("v"); + + return (T) Collections.singletonMap(k, v).entrySet().iterator().next(); + } + + public int getFastMatchToken() { + return 0; + } + }); + + Map.Entry entry = JSON.parseObject(json, Map.Entry.class, config); + assertEquals(1, entry.getKey()); + assertEquals("A", entry.getValue()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1588.java b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1588.java new file mode 100644 index 0000000000..6f1cf8848b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/Issue1588.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.text.SimpleDateFormat; +import java.util.Date; + +public class Issue1588 extends TestCase { + public void test_for_issue() throws Exception { + String dateString = "2017-11-17 00:00:00"; + Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateString); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("test", date); + System.out.println(jsonObject.toJSONString(jsonObject, SerializerFeature.UseISO8601DateFormat)); + System.out.println(JSONObject.toJSONStringWithDateFormat(jsonObject, "yyyy-MM-dd'T'HH:mm:ssXXX")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1500/StringSerializer.java b/src/test/java/com/alibaba/json/bvt/issue_1500/StringSerializer.java new file mode 100644 index 0000000000..43f2972ff5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1500/StringSerializer.java @@ -0,0 +1,15 @@ +package com.alibaba.json.bvt.issue_1500; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; + +import java.io.IOException; +import java.lang.reflect.Type; + +public class StringSerializer implements ObjectSerializer { + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { + serializer.write(String.valueOf(object)); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_field.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_field.java new file mode 100644 index 0000000000..b722d75206 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_field.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; + +public class Issue1603_field extends TestCase { + public void test_emptySet() throws Exception { + Model_1 m = JSON.parseObject("{\"values\":[\"a\"]}", Model_1.class); + assertEquals(0, m.values.size()); + } + + public void test_emptyList() throws Exception { + Model_2 m = JSON.parseObject("{\"values\":[\"a\"]}", Model_2.class); + assertEquals(0, m.values.size()); + } + + public void test_unmodifier() throws Exception { + Model_3 m = JSON.parseObject("{\"values\":[\"a\"]}", Model_3.class); + assertEquals(0, m.values.size()); + } + + public static class Model_1 { + public final Collection values = Collections.emptySet(); + } + + public static class Model_2 { + public final Collection values = Collections.emptyList(); + } + + public static class Model_3 { + public final Collection values = Collections.unmodifiableList(new ArrayList()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_getter.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_getter.java new file mode 100644 index 0000000000..10ba59e223 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_getter.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; + +public class Issue1603_getter extends TestCase { + public void test_emptySet() throws Exception { + Model_1 m = JSON.parseObject("{\"values\":[\"a\"]}", Model_1.class); + assertEquals(0, m.values.size()); + } + + public void test_emptyList() throws Exception { + Model_2 m = JSON.parseObject("{\"values\":[\"a\"]}", Model_2.class); + assertEquals(0, m.values.size()); + } + + public void test_unmodifier() throws Exception { + Model_3 m = JSON.parseObject("{\"values\":[\"a\"]}", Model_3.class); + assertEquals(0, m.values.size()); + } + + public static class Model_1 { + private final Collection values = Collections.emptySet(); + + public Collection getValues() { + return values; + } + } + + public static class Model_2 { + private final Collection values = Collections.emptyList(); + + public Collection getValues() { + return values; + } + } + + public static class Model_3 { + private final Collection values = Collections.unmodifiableList(new ArrayList()); + + public Collection getValues() { + return values; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_map.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_map.java new file mode 100644 index 0000000000..f5f179e54b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_map.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.*; + +public class Issue1603_map extends TestCase { + public void test_emptyMap() throws Exception { + Model_1 m = JSON.parseObject("{\"values\":{\"a\":1001}}", Model_1.class); + assertEquals(0, m.values.size()); + } + + public void test_unmodifiableMap() throws Exception { + Model_2 m = JSON.parseObject("{\"values\":{\"a\":1001}}", Model_2.class); + assertEquals(0, m.values.size()); + } + + public static class Model_1 { + public final Map values = Collections.emptyMap(); + } + + public static class Model_2 { + public final Map values = Collections.unmodifiableMap(new HashMap()); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_map_getter.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_map_getter.java new file mode 100644 index 0000000000..ad6ea2fd20 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_map_getter.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class Issue1603_map_getter extends TestCase { + public void test_emptyMap() throws Exception { + Model_1 m = JSON.parseObject("{\"values\":{\"a\":1001}}", Model_1.class); + assertEquals(0, m.values.size()); + } + + public void test_unmodifiableMap() throws Exception { + Model_2 m = JSON.parseObject("{\"values\":{\"a\":1001}}", Model_2.class); + assertEquals(0, m.values.size()); + } + + public static class Model_1 { + private final Map values = Collections.emptyMap(); + + public Map getValues() { + return values; + } + } + + public static class Model_2 { + private final Map values = Collections.unmodifiableMap(new HashMap()); + + public Map getValues() { + return values; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1611.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1611.java new file mode 100644 index 0000000000..5969c9f306 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1611.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +public class Issue1611 extends TestCase { + public void test_for_issue() throws Exception { + String pristineJson = "{\"data\":{\"lists\":[{\"Name\":\"Mark\"}]}}"; + JSONArray list = JSON.parseObject(pristineJson).getJSONObject("data").getJSONArray("lists"); + assertEquals(1, list.size()); + for (int i = 0; i < list.size(); i++) { + JSONObject sss = list.getJSONObject(i); + Model model = sss.toJavaObject(Model.class); + assertEquals("Mark", model.name); + } + + } + + public static class Model { + private String name; + + public Model(String name) { + this.name = name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1612.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1612.java new file mode 100644 index 0000000000..9bdfed5360 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1612.java @@ -0,0 +1,110 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import org.junit.Test; + +/** + *

Title: Issue1612

+ *

Description:

+ * + * @author Victor + * @version 1.0 + * @since 2017/11/27 + */ +public class Issue1612 { + + @Test + public void test() { + + RegResponse userRegResponse = testFastJson(User.class); + + User user = userRegResponse.getResult(); + System.out.println(user); + + } + + public static RegResponse testFastJson(Class clasz) { + + //把body解析成一个对象 + String body = "{\"retCode\":\"200\", \"result\":{\"name\":\"Zhangsan\",\"password\":\"123\"}}"; + + return JSON.parseObject(body, new TypeReference>(clasz) {}); + } +} + +class RegResponse { + + private String retCode; + private String retDesc; + private T result; + + public String getRetCode() { + return retCode; + } + + public void setRetCode(String retCode) { + this.retCode = retCode; + } + + public String getRetDesc() { + return retDesc; + } + + public void setRetDesc(String retDesc) { + this.retDesc = retDesc; + } + + public T getResult() { + return result; + } + + public void setResult(T result) { + this.result = result; + } + + @Override + public String toString() { + return "RegResponse{" + + "retCode='" + retCode + '\'' + + ", retDesc='" + retDesc + '\'' + + ", result=" + result + + '}'; + } +} + +class User { + + public User(){} + public User(String username, String password) { + this.username = username; + this.password = password; + } + + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + return "User{" + + "username='" + username + '\'' + + ", password='" + password + '\'' + + '}'; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1627.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1627.java new file mode 100644 index 0000000000..6b8c0eb6e0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1627.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +public class Issue1627 extends TestCase { + public void test_for_issue() throws Exception { + String a = "{\"101a0.test-b\":\"tt\"}"; + Object o = JSON.parse(a); + String s = "101a0.test-b"; + assertTrue(JSONPath.contains(o, "$." + escapeString(s))); + } + + public static String escapeString(String s) { + StringBuilder buf = new StringBuilder(); + + for(int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if((c < 48 || c > 57) && (c < 65 || c > 90) && (c < 97 || c > 122)) { + buf.append("\\" + c); + } else { + buf.append(c); + } + } + + return buf.toString(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1628.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1628.java new file mode 100644 index 0000000000..31904fb4ce --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1628.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializeFilter; +import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +public class Issue1628 extends TestCase { + public void test_toJSONBytes() throws Exception { + Map map = new HashMap(); + map.put("a", 1001); + map.put("b", 2002); + byte[] bytes = JSON.toJSONBytes(map, new SimplePropertyPreFilter("a")); + assertEquals("{\"a\":1001}", new String(bytes)); + } + + public void test_toJSONBytes_1() throws Exception { + Map map = new HashMap(); + map.put("a", 1001); + map.put("b", 2002); + byte[] bytes = JSON.toJSONBytes(map, new SerializeFilter[] {new SimplePropertyPreFilter("a")}); + assertEquals("{\"a\":1001}", new String(bytes)); + } + + public void test_toJSONBytes_2() throws Exception { + Map map = new HashMap(); + map.put("a", 1001); + map.put("b", 2002); + byte[] bytes = JSON.toJSONBytes(map, SerializeConfig.globalInstance, new SimplePropertyPreFilter("a")); + assertEquals("{\"a\":1001}", new String(bytes)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1633.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1633.java new file mode 100644 index 0000000000..7b94869338 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1633.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +public class Issue1633 extends TestCase { + public void test_for_issue_int() throws Exception { + String text = "{123:\"abc\"}"; + JSONObject obj = JSON.parseObject(text, Feature.NonStringKeyAsString); + assertEquals("abc", obj.getString("123")); + } + + public void test_for_issue_bool() throws Exception { + String text = "{false:\"abc\"}"; + JSONObject obj = JSON.parseObject(text, Feature.NonStringKeyAsString); + assertEquals("abc", obj.getString("false")); + } +} \ No newline at end of file diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1635.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1635.java new file mode 100644 index 0000000000..8f563ba5e8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1635.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.PascalNameFilter; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.List; + +public class Issue1635 extends TestCase { + public static class Foo { + public String name; + public Integer BarCount; + public Boolean flag; + public List list; + + public Foo(String name, Integer barCount) { + this.name = name; + BarCount = barCount; + } + } + + public void test_issue() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(false); + Foo foo = new Foo(null, null); + String json = JSON.toJSONString(foo + , config, new PascalNameFilter() + , SerializerFeature.WriteNullBooleanAsFalse + , SerializerFeature.WriteNullNumberAsZero + , SerializerFeature.WriteNullStringAsEmpty + , SerializerFeature.WriteNullListAsEmpty + ); + assertEquals("{\"BarCount\":0,\"Flag\":false,\"List\":[],\"Name\":\"\"}", json); + } + + public void test_issue_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setAsmEnable(false); + Foo foo = new Foo(null, null); + String json = JSON.toJSONString(foo + , config, new PascalNameFilter() + , SerializerFeature.WriteNullBooleanAsFalse + , SerializerFeature.WriteNullNumberAsZero + , SerializerFeature.WriteNullStringAsEmpty + , SerializerFeature.WriteNullListAsEmpty + , SerializerFeature.BeanToArray + ); + assertEquals("[0,false,[],\"\"]", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1636.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1636.java new file mode 100644 index 0000000000..7761ecd974 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1636.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +public class Issue1636 extends TestCase { + public void test_for_issue_1() throws Exception { + Item1 item = JSON.parseObject("{\"modelId\":1001}", Item1.class); + assertEquals(1001, item.modelId); + } + + public void test_for_issue_2() throws Exception { + Item2 item = JSON.parseObject("{\"modelId\":1001}", Item2.class); + assertEquals(1001, item.modelId); + } + + public static class Item1 { + @JSONField + private int modelId; + + @JSONCreator + public Item1(@JSONField int modelId){ + // 这里为零 + this.modelId=modelId; + } + } + + public static class Item2 { + private int modelId; + + @JSONCreator + public Item2(int modelId){ + // 这里为零 + this.modelId=modelId; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1644.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1644.java new file mode 100644 index 0000000000..caa9319bd6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1644.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.sql.Time; + +public class Issue1644 extends TestCase { + public void test_for_issue() throws Exception { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("time", 1324138987429L); + + Time time = jsonObject.getObject("time", java.sql.Time.class); + assertEquals(1324138987429L, time.getTime()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1645.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1645.java new file mode 100644 index 0000000000..30ac710b4e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1645.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.time.LocalDateTime; + +public class Issue1645 extends TestCase { + public void test_for_issue() throws Exception { + String test = "{\"name\":\"test\",\"testDateTime\":\"2017-12-08 14:55:16\"}"; + JSON.toJSONString(JSON.parseObject(test).toJavaObject(TestDateClass.class), SerializerFeature.PrettyFormat); + } + + public static class TestDateClass{ + public String name; + public LocalDateTime testDateTime; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1647.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1647.java new file mode 100644 index 0000000000..c21dc0be0f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1647.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.PropertyNamingStrategy; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; + +import java.util.Arrays; +import java.util.List; + +public class Issue1647 extends TestCase { + public void test_for_issue() throws Exception { + Params params = new Params() + .setVerificationIds(Arrays.asList(new String[]{"a", "b"})) + .setWithFields(true); + + String json = JSON.toJSONString(params); + System.out.println(json); + params = JSON.parseObject(json, Params.class); + assertEquals("{\"verification_ids\":[\"a\",\"b\"],\"with_fields\":true}", JSON.toJSONString(params)); + } + + @JSONType(naming = PropertyNamingStrategy.SnakeCase) + public static class Params { + + private boolean withFields; + + private List verificationIds; + + public boolean isWithFields() { + return withFields; + } + + public Params setWithFields(boolean withFields) { + this.withFields = withFields; + return this; + } + + public List getVerificationIds() { + return verificationIds; + } + + public Params setVerificationIds(List verificationIds) { + this.verificationIds = verificationIds; + return this; + } + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1649.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1649.java new file mode 100644 index 0000000000..f1615f0e4e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1649.java @@ -0,0 +1,59 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +public class Issue1649 extends TestCase { + public void test_for_issue() throws Exception { + Apple apple = new Apple(); + String json = JSON.toJSONString(apple); + assertEquals("{\"color\":\"\",\"productCity\":\"\",\"size\":0}", json); + } + + @JSONType(serialzeFeatures = {SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteMapNullValue}) + public static class Apple { + + // @JSONField(serialzeFeatures = {SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteMapNullValue}) + private String color; + private String productCity; + private int size; + + public String getColor() { + return color; + } + + public Apple setColor(String color) { + this.color = color; + return this; + } + + public int getSize() { + return size; + } + + public Apple setSize(int size) { + this.size = size; + return this; + } + + public String getProductCity() { + return productCity; + } + + public Apple setProductCity(String productCity) { + this.productCity = productCity; + return this; + } + + @Override + public String toString() { + return JSON.toJSONString(this); + } + + public static void main(String[] args) { + System.out.println(JSON.toJSONString(new Apple())); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1649_private.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1649_private.java new file mode 100644 index 0000000000..4b74d0c008 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1649_private.java @@ -0,0 +1,59 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +public class Issue1649_private extends TestCase { + public void test_for_issue() throws Exception { + Apple apple = new Apple(); + String json = JSON.toJSONString(apple); + assertEquals("{\"color\":\"\",\"productCity\":\"\",\"size\":0}", json); + } + + @JSONType(serialzeFeatures = {SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteMapNullValue}) + private static class Apple { + + // @JSONField(serialzeFeatures = {SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteMapNullValue}) + private String color; + private String productCity; + private int size; + + public String getColor() { + return color; + } + + public Apple setColor(String color) { + this.color = color; + return this; + } + + public int getSize() { + return size; + } + + public Apple setSize(int size) { + this.size = size; + return this; + } + + public String getProductCity() { + return productCity; + } + + public Apple setProductCity(String productCity) { + this.productCity = productCity; + return this; + } + + @Override + public String toString() { + return JSON.toJSONString(this); + } + + public static void main(String[] args) { + System.out.println(JSON.toJSONString(new Apple())); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1653.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1653.java new file mode 100644 index 0000000000..cf599dc551 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1653.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.MapDeserializer; +import junit.framework.TestCase; +import org.apache.commons.collections4.map.*; + +import java.lang.reflect.Type; +import java.util.Map; + +public class Issue1653 extends TestCase { + public void test_for_issue() throws Exception { +ParserConfig config = new ParserConfig(); +MapDeserializer deserializer = new MapDeserializer() { + public Map createMap(Type type) { + return new CaseInsensitiveMap(); + } +}; +config.putDeserializer(Map.class, deserializer); + +CaseInsensitiveMap root = (CaseInsensitiveMap) JSON.parseObject("{\"val\":{}}", Map.class, config, Feature.CustomMapDeserializer); +CaseInsensitiveMap subMap = (CaseInsensitiveMap) root.get("val"); +assertEquals(0, subMap.size()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1657.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1657.java new file mode 100644 index 0000000000..a0865d37ed --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1657.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.HashMap; + +public class Issue1657 extends TestCase { + public void test_for_issue() throws Exception { + HashMap map = JSON.parseObject("\"\"", HashMap.class); + assertEquals(0, map.size()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1660.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1660.java new file mode 100644 index 0000000000..25214bbc2e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1660.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.util.*; + +public class Issue1660 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_issue() throws Exception { + Model model = new Model(); + model.values.add(new Date(1513755213202L)); + + String json = JSON.toJSONString(model); + assertEquals("{\"values\":[\"2017-12-20\"]}", json); + } + + public static class Model { + @JSONField(format = "yyyy-MM-dd") + private List values = new ArrayList(); + + public List getValues() { + return values; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1662.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1662.java new file mode 100644 index 0000000000..dabf710fce --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1662.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import junit.framework.TestCase; + +import java.io.IOException; +import java.lang.reflect.Type; + +public class Issue1662 extends TestCase { + public void test_for_issue() throws Exception { + + ParserConfig.getGlobalInstance().putDeserializer(Model.class, new ModelValueDeserializer()); + String json = "{\"value\":123}"; + Model model = JSON.parseObject(json, Model.class); + assertEquals("{\"value\":\"12300元\"}",JSON.toJSONString(model)); + + } + + public static class Model { + @JSONField(serializeUsing = ModelValueSerializer.class, deserializeUsing = ModelValueDeserializer.class) + public int value; + } + + public static class ModelValueSerializer implements ObjectSerializer { + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, + int features) throws IOException { + Integer value = (Integer) object; + String text = value + "元"; + serializer.write(text); + } + } + + public static class ModelValueDeserializer implements ObjectDeserializer { + + public Model deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + JSONObject obj = (JSONObject)parser.parse(); + Model model = new Model(); + model.value = obj.getInteger("value") * 100; + return model; + } + + public int getFastMatchToken() { + return 0; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1662_1.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1662_1.java new file mode 100644 index 0000000000..71c78bd46d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1662_1.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import junit.framework.TestCase; + +import java.io.IOException; +import java.lang.reflect.Type; + +public class Issue1662_1 extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"value\":123}"; + Model model = JSON.parseObject(json, Model.class); + assertEquals("{\"value\":\"12300元\"}",JSON.toJSONString(model)); + + } + + public static class Model { + @JSONField(serializeUsing = ModelValueSerializer.class, deserializeUsing = ModelValueDeserializer.class) + public int value; + } + + public static class ModelValueSerializer implements ObjectSerializer { + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, + int features) throws IOException { + Integer value = (Integer) object; + String text = value + "元"; + serializer.write(text); + } + } + + public static class ModelValueDeserializer implements ObjectDeserializer { + + public Integer deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + Object val = parser.parse(); + return ((Integer) val).intValue() * 100; + } + + public int getFastMatchToken() { + return 0; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1665.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1665.java new file mode 100644 index 0000000000..499e89dea8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1665.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.util.TypeUtils; +import junit.framework.TestCase; + +import java.util.Collection; + +public class Issue1665 extends TestCase { + public void test_for_issue() throws Exception { + TypeReference> typeReference = new TypeReference>() {}; + + + Collection collection = TypeUtils.cast(JSON.parse("[{\"id\":101}]"), typeReference.getType(), ParserConfig.getGlobalInstance()); + assertEquals(1, collection.size()); + Model model = collection.iterator().next(); + assertEquals(101, model.id); + } + + public static class Model { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1679.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1679.java new file mode 100644 index 0000000000..29c391a75f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1679.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.Date; + +public class Issue1679 extends TestCase { + + public void test_for_issue() throws Exception { + String json = "{\"create\":\"2018-01-10 08:30:00\"}"; + User user = JSON.parseObject(json, User.class); + assertEquals("\"2018-01-10T08:30:00+08:00\"", JSON.toJSONString(user.create, SerializerFeature.UseISO8601DateFormat)); + } + + public static class User{ + public Date create; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1683.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1683.java new file mode 100644 index 0000000000..483aa2d1f2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue1683.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +public class Issue1683 extends TestCase { + public void test_for_issue() throws Exception { + String line = "[2, \"浪漫奇侠\", \"雨天不打伞\", 4536]"; + BookDO book = JSON.parseObject(line, BookDO.class, Feature.SupportArrayToBean); + assertEquals(2L, book.bookId.longValue()); + assertEquals("浪漫奇侠", book.bookName); + assertEquals("雨天不打伞", book.authorName); + assertEquals(4536, book.wordCount.intValue()); + } + + @JSONType(orders = {"bookId", "bookName", "authorName", "wordCount"}) + public static class BookDO { + + private Long bookId; + + private String bookName; + + private String authorName; + + private Integer wordCount; + + + public Long getBookId() { + return bookId; + } + + public void setBookId(Long bookId) { + this.bookId = bookId; + } + + public String getBookName() { + return bookName; + } + + public void setBookName(String bookName) { + this.bookName = bookName; + } + + public String getAuthorName() { + return authorName; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public Integer getWordCount() { + return wordCount; + } + + public void setWordCount(Integer wordCount) { + this.wordCount = wordCount; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/Issue_for_gaorui.java b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue_for_gaorui.java new file mode 100644 index 0000000000..0d2c375521 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/Issue_for_gaorui.java @@ -0,0 +1,130 @@ +package com.alibaba.json.bvt.issue_1600; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +public class Issue_for_gaorui extends TestCase { + public void test_for_issue() throws Exception { + String json = "{\"@type\":\"java.util.HashMap\",\"COUPON\":[{\"@type\":\"com.alibaba.json.bvt.issue_1600.Issue_for_gaorui.PromotionTermDetail\",\"activityId\":\"1584034\",\"choose\":true,\"couponId\":1251068987,\"couponType\":\"limitp\",\"match\":true,\"realPrice\":{\"amount\":0.6,\"currency\":\"USD\"}}],\"grayTrade\":\"true\"}"; + + JSON.parseObject(json, Object.class, Feature.SupportAutoType); + } + + public static class PromotionTermDetail { + /** + * 卡券Id + */ + private Long couponId; + /** + * 营销Id + */ + private String promotionId; + /** + * 实际单价 + */ + private Money realPrice; + /** + * 活动Id + */ + private String activityId; + + /** + * 卡券类型 + */ + private String couponType; + + /** + * 是否能够获取到该优惠 + */ + private boolean isMatch = false; + /** + * 是否选择了该优惠 + */ + private boolean isChoose = false; + /** + * 未获取到优惠的原因 + */ + private String reasonForLose; + /** + * 未获取优惠的标识码 + */ + private String codeForLose; + + public Long getCouponId() { + return couponId; + } + + public void setCouponId(Long couponId) { + this.couponId = couponId; + } + + public String getPromotionId() { + return promotionId; + } + + public void setPromotionId(String promotionId) { + this.promotionId = promotionId; + } + + public Money getRealPrice() { + return realPrice; + } + + public void setRealPrice(Money realPrice) { + this.realPrice = realPrice; + } + + public String getActivityId() { + return activityId; + } + + public void setActivityId(String activityId) { + this.activityId = activityId; + } + + public String getCouponType() { + return couponType; + } + + public void setCouponType(String couponType) { + this.couponType = couponType; + } + + public boolean isMatch() { + return isMatch; + } + + public void setMatch(boolean match) { + isMatch = match; + } + + public boolean isChoose() { + return isChoose; + } + + public void setChoose(boolean choose) { + isChoose = choose; + } + + public String getReasonForLose() { + return reasonForLose; + } + + public void setReasonForLose(String reasonForLose) { + this.reasonForLose = reasonForLose; + } + + public String getCodeForLose() { + return codeForLose; + } + + public void setCodeForLose(String codeForLose) { + this.codeForLose = codeForLose; + } + } + + public static class Money { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/TestJson.java b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/TestJson.java new file mode 100644 index 0000000000..0f3186430f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/TestJson.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.issue_1600.issue_1699; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import java.io.Serializable; + +public class TestJson extends TestCase { + + public void test_for_issue() { + ParserConfig.getGlobalInstance().setAutoTypeSupport(true); + + System.out.println(JSON.VERSION); + + String event1 = "{\"@type\":\"com.alibaba.json.bvt.issue_1600.issue_1699.obj.RatingDetailBO\",\"amount\":285.600000,\"billId\":3945,\"bizId\":\"6000007==201712==USER_ID==2049884395&&CONTRACT_NO==\\\"no1513922344271\\\"\",\"bizTime\":\"2017-12-31 00:00:00\",\"bizType\":\"6000007\",\"currency\":\"CNY\",\"dealTime\":\"2017-12-23 14:11:03\",\"detailType\":\"CYCLE_CHARGING\",\"extendInfo\":{\"@type\":\"java.util.LinkedHashMap\",\"BUY_AMOUNT\":\"3\",\"P_BIZ_ID\":\"USER_ID==2049884395&&CONTRACT_NO==\\\"no1513922344271\\\"\",\"SETTLE_SIDE\":\"654321\",\"SETTLE_CYCLE_TYPE\":\"3\",\"AUCTION_PRICE\":\"119\",\"CALCULATE_RANGE\":\"STORE\",\"TOTAL_NUM\":\"1\",\"BILL_CYCLE\":\"201712\",\"IS_PRE_CHARGING\":\"false\",\"BRANCH_SHOP\":\"branchShop1\",\"CONTRACT_TYPE\":\"HEMA_CHARGING_PROD\",\"stepRateType\":\"3\",\"SOURCE_TYPE\":\"PURCHASE_ADJUST\",\"SETTLE_SIDE_NICK\":\"测试结算主体\",\"express_value\":\"USER_ID==2049884395&&CONTRACT_NO==\\\"no1513922344271\\\"\",\"BIZ_TIME\":\"2017-12-22 13:59:05\",\"TRADE_ID\":\"1513922344273\",\"QUANTITY\":\"3.000000\",\"MES_RECEIVE_TIME\":\"2017-12-22 13:59:05\",\"UN_TAX_UNIT_PRICE\":\"100.000000\",\"AUCTION_ID\":\"123\",\"AUCTION_NAME\":\"测试商品\",\"rate_value\":\"{\\\"extendInfo\\\":{},\\\"intervalValues\\\":[{\\\"max\\\":600.000000,\\\"min\\\":0.000000,\\\"rate\\\":0.600000},{\\\"max\\\":1000.000000,\\\"min\\\":600.000000,\\\"rate\\\":0.300000},{\\\"max\\\":999999999999.000000,\\\"min\\\":1000.000000,\\\"rate\\\":0.100000}]}\",\"CAT_ID\":\"16\",\"UNIT\":\"kilometer\",\"TERM_NAME\":\"盒马.合同返利.促销推广费\",\"USER_ID\":\"2049884395\",\"UNIT_PRICE\":\"119.000000\",\"tbRuleCode\":\"HM_SETTLE_CHARGING\",\"AMOUNT\":\"357.000000\",\"CAT_NAME\":\"水果\",\"EXTERNAL_NO\":\"HM==1513922344273\",\"CHANNEL\":\"online\",\"is_default_rate\":\"false\",\"CURRENCY\":\"CNY\",\"rate_rule_id\":\"300000531\",\"OTHER_USER_NICK\":\"甲方\",\"RATE_TYPE\":\"14\",\"ITEM_NAME\":\"盒马.促销推广费\",\"rate_rule_inst_id\":\"1009129180821\",\"TAX_RATE\":\"0.190000\",\"ITEM_CODE\":\"BILL_HM_6000007\",\"CONTRACT_SIDE\":\"12345\",\"UNTAX_AMOUNT\":\"300.000000\",\"CONTRACT_VERSION\":\"V001\",\"CONTRACT_NO\":\"no1513922344271\",\"P_TRADE_ID\":\"1513922344273\"},\"gmtCreate\":\"2017-12-23 14:11:03\",\"gmtModified\":\"2017-12-23 14:11:03\",\"id\":6235300020395,\"indexNum\":0,\"innerId\":6300120395,\"innerTable\":\"SETTLE_DATA\",\"isJoin\":\"FALSE\",\"itemId\":90000000007031,\"mesId\":3235,\"mesReceiveTime\":\"2017-12-22 13:59:05\",\"outBizId\":\"USER_ID==2049884395&&CONTRACT_NO==\\\"no1513922344271\\\"\",\"pTradeId\":3235,\"priority\":0,\"proration\":0.6,\"quantity\":476.000000,\"rateDefineId\":40000443,\"rateParams\":{\"@type\":\"java.util.LinkedHashMap\"},\"status\":\"SUCCESS\",\"tradeId\":3761,\"userId\":2049884395,\"userNick\":\"乙方\",\"version\":1}"; + Serializable obj = JSON.parseObject(event1, Serializable.class); + System.out.println(obj); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/FeeTypeMEnum.java b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/FeeTypeMEnum.java new file mode 100644 index 0000000000..088cd0ec98 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/FeeTypeMEnum.java @@ -0,0 +1,7 @@ +package com.alibaba.json.bvt.issue_1600.issue_1699.def; + +public enum FeeTypeMEnum { + TRADE, + REFUND; + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/InnerTypeMEnum.java b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/InnerTypeMEnum.java new file mode 100644 index 0000000000..a7aae6be4d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/InnerTypeMEnum.java @@ -0,0 +1,74 @@ +package com.alibaba.json.bvt.issue_1600.issue_1699.def; + +public enum InnerTypeMEnum { + + CHARGE_ORDER, + + PAY_ORDER, + + PAY_ORDER_DTL, + + SUB_DETAIL, + + BILL, + + FC_BILL, + + STEP_OPS_BILL, + + FC_USER_BILL, + + INIT, + + WRITEOFFBILL, + GW_MSG, + + REFUND_ORDER, + RATING_DETAIL, + + COUPON, + + SETTLE_BILL, + + SETTLEMENT_BILL, + + SETTLEMENT_BILL_SUM, + + WORKFLOW_INSTANCE, + + CONTRACT, + + WITHDRAW_ORDER, + + BANK_TRANSFER, + + SOURCE_DATA, + + SETTLE_DATA, + + CONTRACT_TERM_INST, + + MERGE_PAY_ORDER, + + FUNDS_TRANSFER_ORDER, + + SETTLE_POOL, + + SETTLE_POOL_JOURNAL, + + OFFLINE_REMITTANCE, + + OUT_SYSTEM_TRANSFER, + + HJ_EXECUTE_RULE, + + HJ_DISBURSE_INFO, + + USER_BILL, + + HJ_EXECUTE_PLAN + + ; + + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailIsJoinMEnum.java b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailIsJoinMEnum.java new file mode 100644 index 0000000000..950105090d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailIsJoinMEnum.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.issue_1600.issue_1699.def; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public enum RatingDetailIsJoinMEnum { + + FALSE, + TRUE; + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailStatusMEnum.java b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailStatusMEnum.java new file mode 100644 index 0000000000..3dddc527c7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailStatusMEnum.java @@ -0,0 +1,11 @@ +package com.alibaba.json.bvt.issue_1600.issue_1699.def; + +public enum RatingDetailStatusMEnum { + + INIT, + SUCCESS, + FAIL, + WAIT; + + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailTypeMEnum.java b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailTypeMEnum.java new file mode 100644 index 0000000000..cc99e0211e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailTypeMEnum.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.issue_1600.issue_1699.def; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public enum RatingDetailTypeMEnum { + + COMM, + FC, + PRE_FC, + USAGE, + HPTX, + SUB_MONTH_FC, + COMM_DAY_FC, + COMM_MONTH_FC, + ADJUST, + FOREX_COMM, + COMM_REALTIME_FC, + OVERSETTLE_COMM, + FC_RATING, + PRE_TREAT, + REALTIME_CHARGING, + CYCLE_CHARGING, + SHARE_CHARGING, + ; + + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/obj/RatingDetailBO.java b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/obj/RatingDetailBO.java new file mode 100644 index 0000000000..2f955d6760 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/obj/RatingDetailBO.java @@ -0,0 +1,463 @@ +package com.alibaba.json.bvt.issue_1600.issue_1699.obj; + +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.json.bvt.issue_1600.issue_1699.def.InnerTypeMEnum; +import com.alibaba.json.bvt.issue_1600.issue_1699.def.RatingDetailIsJoinMEnum; +import com.alibaba.json.bvt.issue_1600.issue_1699.def.*; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Currency; +import java.util.Date; +import java.util.Map; + +/** + * + */ +public class RatingDetailBO implements Serializable { + + private static final long serialVersionUID = 6413142622719509002L; + + /** + * * + */ + private Long id; + + /** + * 用户ID + */ + private Long userId; + + /** + * 用户NICK + */ + private String userNick; + + /** + * 消息ID + */ + private Long mesId; + + /** + * 事件类型, 枚举值参照:ra_event_object.type + */ + private String eventType; + + /** + * 唯一去重号 + */ + private String bizId; + + /** + * 序列号 + */ + private Integer indexNum; + + /** + * 业务类型(同原始消息) + */ + private String bizType; + + /** + * 业务交易号 + */ + private String outBizId; + + /** + * 主订单ID + */ + private Long pTradeId; + + /** + * 子订单ID + */ + private Long tradeId; + + /** + * 业务交易时间 + */ + private Date bizTime; + + /** + * 消息接收时间 + */ + private Date mesReceiveTime; + + /** + * 处理时间 + */ + private Date dealTime; + + /** + * 详单科目编号 + */ + private Long itemId; + + /** + * 详单类型: 1、普通详单 2、分成详单 3、预收分成详单 + */ + private RatingDetailTypeMEnum detailType; + + /** + * 原始金额 + */ + private BigDecimal quantity; + + /** + * 金额 + */ + private BigDecimal amount; + + /** + * 费率编号 + */ + private Long rateDefineId; + + /** + * 计费因子 + */ + private BigDecimal proration; + + /** + * 产品编号 + */ + private Long prodId; + + /** + * 扩展信息 + */ + private Map extendInfo; + + private Map rateParams; + + private Currency currency; + + private InnerTypeMEnum innerTable; + private Long innerId; + + public Map getRateParams() { + return rateParams; + } + + public void setRateParams(Map rateParams) { + this.rateParams = rateParams; + } + + public Currency getCurrency() { + return currency; + } + + public void setCurrency(Currency currency) { + this.currency = currency; + } + + public InnerTypeMEnum getInnerTable() { + return innerTable; + } + + public void setInnerTable(InnerTypeMEnum innerTable) { + this.innerTable = innerTable; + } + + public Long getInnerId() { + return innerId; + } + + public void setInnerId(Long innerId) { + this.innerId = innerId; + } + + public void setExtendInfo(Map extendInfo) { + this.extendInfo = extendInfo; + } + + /** + * 环境标识 + */ + private String ownSign; + + /** + * 帐单ID, 记账结束后回写 + */ + private Long billId; + + /** + * 版本编号 + */ + private Integer version; + + /** + * 是否合并付款: 0、否 1、是 + */ + private RatingDetailIsJoinMEnum isJoin; + + /** + * 优先级, 值越大,优先级越高 + */ + private Integer priority; + + /** + * 状态: 0、初始 1、处理成功; 2、处理失败; 3、等待合并; + */ + private RatingDetailStatusMEnum status; + + /** + * 创建时间 + */ + private Date gmtCreate; + + /** + * 修改时间 + */ + private Date gmtModified; + + /** + * 交易项目:0、交易;1、退款 + */ + private FeeTypeMEnum feeType; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getUserNick() { + return userNick; + } + + public void setUserNick(String userNick) { + this.userNick = userNick; + } + + public Long getMesId() { + return mesId; + } + + public void setMesId(Long mesId) { + this.mesId = mesId; + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public String getBizId() { + return bizId; + } + + public void setBizId(String bizId) { + this.bizId = bizId; + } + + public String getBizType() { + return bizType; + } + + public void setBizType(String bizType) { + this.bizType = bizType; + } + + public String getOutBizId() { + return outBizId; + } + + public void setOutBizId(String outBizId) { + this.outBizId = outBizId; + } + + public Long getpTradeId() { + return pTradeId; + } + + public void setpTradeId(Long pTradeId) { + this.pTradeId = pTradeId; + } + + public Long getTradeId() { + return tradeId; + } + + public void setTradeId(Long tradeId) { + this.tradeId = tradeId; + } + + public Date getBizTime() { + return bizTime; + } + + public void setBizTime(Date bizTime) { + this.bizTime = bizTime; + } + + public Date getMesReceiveTime() { + return mesReceiveTime; + } + + public void setMesReceiveTime(Date mesReceiveTime) { + this.mesReceiveTime = mesReceiveTime; + } + + public Date getDealTime() { + return dealTime; + } + + public void setDealTime(Date dealTime) { + this.dealTime = dealTime; + } + + public Long getItemId() { + return itemId; + } + + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + public Long getRateDefineId() { + return rateDefineId; + } + + public void setRateDefineId(Long rateDefineId) { + this.rateDefineId = rateDefineId; + } + + public Long getProdId() { + return prodId; + } + + public void setProdId(Long prodId) { + this.prodId = prodId; + } + + public String getOwnSign() { + return ownSign; + } + + public void setOwnSign(String ownSign) { + this.ownSign = ownSign; + } + + public Long getBillId() { + return billId; + } + + public void setBillId(Long billId) { + this.billId = billId; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public Integer getPriority() { + return priority; + } + + public void setPriority(Integer priority) { + this.priority = priority; + } + + public Date getGmtCreate() { + return gmtCreate; + } + + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + + public Date getGmtModified() { + return gmtModified; + } + + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } + + public RatingDetailTypeMEnum getDetailType() { + return detailType; + } + + public void setDetailType(RatingDetailTypeMEnum detailType) { + this.detailType = detailType; + } + + public RatingDetailIsJoinMEnum getIsJoin() { + return isJoin; + } + + public void setIsJoin(RatingDetailIsJoinMEnum isJoin) { + this.isJoin = isJoin; + } + + public RatingDetailStatusMEnum getStatus() { + return status; + } + + public void setStatus(RatingDetailStatusMEnum status) { + this.status = status; + } + + public FeeTypeMEnum getFeeType() { + return feeType; + } + + public void setFeeType(FeeTypeMEnum feeType) { + this.feeType = feeType; + } + + public Map getExtendInfo() { + return extendInfo; + } + + public BigDecimal getQuantity() { + return quantity; + } + + public void setQuantity(BigDecimal quantity) { + this.quantity = quantity; + } + + public BigDecimal getAmount() { + return amount; + } + + public void setAmount(BigDecimal amount) { + this.amount = amount; + } + + public BigDecimal getProration() { + return proration; + } + + public void setProration(BigDecimal proration) { + this.proration = proration; + } + + public Integer getIndexNum() { + return indexNum; + } + + public void setIndexNum(Integer indexNum) { + this.indexNum = indexNum; + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1723.java b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1723.java new file mode 100644 index 0000000000..8a70e32080 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1723.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.issue_1700; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +public class Issue1723 extends TestCase { + public void test_for_issue() throws Exception { + User user = JSON.parseObject("{\"age\":\"0.9390308260917664\"}", User.class); + assertEquals(0.9390308260917664F, user.age); + } + + public void test_for_issue_1() throws Exception { + User user = JSON.parseObject("{\"age\":\"8.200000000000001\"}", User.class); + assertEquals(8.200000000000001F, user.age); + } + + public void test_for_issue_2() throws Exception { + User user = JSON.parseObject("[\"8.200000000000001\"]", User.class, Feature.SupportArrayToBean); + assertEquals(8.200000000000001F, user.age); + } + + public static class User { + private float age; + public float getAge() { + return age; + } + public void setAge(float age) { + this.age = age; + } + @Override + public String toString() { + return "User{" + + "age=" + age + + '}'; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1725.java b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1725.java new file mode 100644 index 0000000000..8391930499 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1725.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.issue_1700; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +public class Issue1725 extends TestCase { + public void test_for_issue() throws Exception { + Map map= new HashMap(); + map.put("enumField", 0); + + AbstractBean bean = JSON.parseObject(JSON.toJSONString(map), ConcreteBean.class); + assertEquals(FieldEnum.A, bean.enumField); + } + + public static class AbstractBean { + public FieldEnum enumField; + } + + public static class ConcreteBean extends AbstractBean { + + } + + public static enum FieldEnum { A, B } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1727.java b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1727.java new file mode 100644 index 0000000000..d92cc345ce --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1727.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.issue_1700; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.util.Date; + +public class Issue1727 extends TestCase { + public void test_for_issue() throws Exception { + String jsonString = "{\"gmtCreate\":\"20180131214157805-0800\"}"; + JSONObject.parseObject(jsonString, Model.class); //正常解析 + JSONObject.toJavaObject(JSON.parseObject(jsonString), Model.class); + } + + public static class Model { + @JSONField(format="yyyyMMddHHmmssSSSZ") + public Date gmtCreate; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1733_jsonpath.java b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1733_jsonpath.java new file mode 100644 index 0000000000..4e0cf8eb51 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1733_jsonpath.java @@ -0,0 +1,72 @@ +package com.alibaba.json.bvt.issue_1700; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +public class Issue1733_jsonpath extends TestCase { + public void test_for_issue() throws Exception { + Order order = new Order(); + order.books.add(new Book(10, "动漫")); + order.books.add(new Book(50, "科幻")); + order.books.add(new Book(60, "历史")); + + String path = "$.books[price>20 && category = '科幻']"; + List result = (List) JSONPath.eval(order, path); + assertSame(1, result.size()); + assertSame(order.books.get(1), result.get(0)); + } + + public void test_for_issue_or() throws Exception { + Order order = new Order(); + order.books.add(new Book(10, "动漫")); + order.books.add(new Book(50, "科幻")); + order.books.add(new Book(60, "历史")); + + String path = "$.books[price>20||category = '科幻']"; + List result = (List) JSONPath.eval(order, path); + assertEquals(2, result.size()); + assertSame(order.books.get(1), result.get(0)); + assertSame(order.books.get(2), result.get(1)); + } + + public void test_for_issue_or_1() throws Exception { + Order order = new Order(); + order.books.add(new Book(10, "动漫")); + order.books.add(new Book(50, "科幻")); + order.books.add(new Book(60, "历史")); + + String path = "$.books[category = '动漫' ||category = '科幻']"; + List result = (List) JSONPath.eval(order, path); + assertEquals(2, result.size()); + assertSame(order.books.get(0), result.get(0)); + assertSame(order.books.get(1), result.get(1)); + } + + public static class Order { + public List books = new ArrayList(); + + } + + public static class Book { + public BigDecimal price; + public String category; + + public Book() { + + } + + public Book(int price, String category) { + this(new BigDecimal(price), category); + } + + public Book(BigDecimal price, String category) { + this.price = price; + this.category = category; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1739.java b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1739.java new file mode 100644 index 0000000000..0250963871 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1739.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.issue_1700; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +public class Issue1739 extends TestCase { + public void test_for_issue() throws Exception { + M0 model = new M0(); + model.data = new JSONObject(); + + String json = JSON.toJSONString(model); + assertEquals("{\"data\":{}}", json); + } + + public void test_for_issue_1() throws Exception { + M1 model = new M1(); + model.data = new JSONObject(); + + String json = JSON.toJSONString(model); + assertEquals("{}", json); + } + + public static class M0 { + private JSONObject data; + + @JSONField(deserialize = false) + public JSONObject getData() { + return data; + } + + public void setData(JSONObject data) { + this.data = data; + } + } + + public static class M1 { + private JSONObject data; + + @JSONField(serialize = false) + public JSONObject getData() { + return data; + } + + public void setData(JSONObject data) { + this.data = data; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1761.java b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1761.java new file mode 100644 index 0000000000..09ccce7bf9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1761.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.issue_1700; + +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +public class Issue1761 extends TestCase { + public void test_for_issue() throws Exception { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("null",""); + double d = jsonObject.getDoubleValue("null"); + assertEquals(d, 0.0D); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1763.java b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1763.java new file mode 100644 index 0000000000..847e718e53 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1763.java @@ -0,0 +1,72 @@ +package com.alibaba.json.bvt.issue_1700; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; + +public class Issue1763 extends TestCase { + public void test_for_issue() throws Exception { + String s = "{\"result\":{\"modelList\":[{\"sourceId\":\"81900002\"},{\"sourceId\":\"81900002\"},{\"sourceId\":\"81892012\"},{\"sourceId\":\"2062014\"},{\"sourceId\":\"2082007\"},{\"sourceId\":\"2082007\"},{\"sourceId\":\"2082007\"}]}}"; + + + Method method = ProcurementOrderInteractiveServiceForCloud.class.getMethod("queryOrderMateriel", Map.class); + Type type = method.getGenericReturnType(); + + BaseResult baseResult = JSON.parseObject(s, type); + InteractiveOrderMaterielQueryResult result = baseResult.getResult(); + + assertEquals(7, result.getModelList().size()); + assertEquals(InteractiveOrderMaterielModel.class, result.getModelList().get(0).getClass()); + } + + public static class BaseResult { + private T result; + + public T getResult() { + return result; + } + + public void setResult(T result) { + this.result = result; + } + } + + public static class BasePageQueryResult extends BaseResult{ + private List modelList; + + public List getModelList() { + return modelList; + } + + public void setModelList(List modelList) { + this.modelList = modelList; + } + } + + public static class InteractiveOrderMaterielModel { + private String sourceId; + + public String getSourceId() { + return sourceId; + } + + public void setSourceId(String sourceId) { + this.sourceId = sourceId; + } + } + + public static class InteractiveOrderMaterielQueryResult extends BasePageQueryResult { + + } + + public interface ProcurementOrderInteractiveServiceForCloud { + + BaseResult queryOrderMateriel(Map param); + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1764.java b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1764.java new file mode 100644 index 0000000000..08eda23640 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1764.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.issue_1700; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import static com.alibaba.fastjson.serializer.SerializerFeature.BrowserCompatible; + +public class Issue1764 extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.value = 9007199254741992L; + + String str = JSON.toJSONString(model); + assertEquals("{\"value\":\"9007199254741992\"}", str); + } + + public static class Model { + @JSONField(serialzeFeatures = BrowserCompatible) + public long value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1764_bean.java b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1764_bean.java new file mode 100644 index 0000000000..c078989c0d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1700/Issue1764_bean.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.issue_1700; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; + +import static com.alibaba.fastjson.serializer.SerializerFeature.BrowserCompatible; + +public class Issue1764_bean extends TestCase { + public void test_for_issue() throws Exception { + Model model = new Model(); + model.value = 9007199254741992L; + + String str = JSON.toJSONString(model); + assertEquals("{\"value\":\"9007199254741992\"}", str); + } + + @JSONType(serialzeFeatures = BrowserCompatible) + public static class Model { + public long value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk7/PathTest.java b/src/test/java/com/alibaba/json/bvt/jdk7/PathTest.java new file mode 100644 index 0000000000..fceaac3b71 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk7/PathTest.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.jdk7; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class PathTest extends TestCase { + public void test_for_path() throws Exception { + Model model = new Model(); + model.path = Paths.get("/root/fastjson"); + + String text = JSON.toJSONString(model); + System.out.println(text); + //windows下,输出为 + //Assert.assertEquals("{\"path\":\"\\root\\fastjson\"}", text); + + //linux ,mac + //Assert.assertEquals("{\"path\":\"/root/fastjson\"}", text); + + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.path.toString(), model2.path.toString()); + } + + public void test_for_null() throws Exception { + String text = "{\"path\":null}"; + + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertNull(model2.path); + } + + public static class Model { + public Path path; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/DoubleAdderTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/DoubleAdderTest.java new file mode 100644 index 0000000000..8081db38e8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/DoubleAdderTest.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.jdk8; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.concurrent.atomic.DoubleAdder; +import java.util.concurrent.atomic.LongAdder; + +/** + * Created by wenshao on 14/03/2017. + */ +public class DoubleAdderTest extends TestCase { + public void test_long_add() throws Exception { + DoubleAdder adder = new DoubleAdder(); + adder.add(3); + + String json = JSON.toJSONString(adder); + assertEquals("{\"value\":3.0}", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/DurationTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/DurationTest.java new file mode 100644 index 0000000000..771eb468db --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/DurationTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.Duration; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class DurationTest extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setDate(Duration.ofHours(3)); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getDate(), vo1.getDate()); + } + + public static class VO { + + private Duration date; + + public Duration getDate() { + return date; + } + + public void setDate(Duration date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/InstantTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/InstantTest.java new file mode 100644 index 0000000000..c6c18ef05f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/InstantTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.Instant; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class InstantTest extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setDate(Instant.now()); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getDate(), vo1.getDate()); + } + + public static class VO { + + private Instant date; + + public Instant getDate() { + return date; + } + + public void setDate(Instant date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest.java new file mode 100644 index 0000000000..222e5ba734 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalDate; +import java.util.Locale; +import java.util.TimeZone; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class LocalDateTest extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setDate(LocalDate.now()); + + String text = JSON.toJSONString(vo); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getDate(), vo1.getDate()); + } + + /** + * 方法描述: 测试时间戳转换为 日期 + * @author wuqiong 2017/11/21 16:48 + */ + public void test_for_long() throws Exception { + String text= "{\"date\":1511248447740}"; + VO vo =JSON.parseObject(text,VO.class); + Assert.assertEquals(2017, vo.date.getYear()); + Assert.assertEquals(11, vo.date.getMonthValue()); + Assert.assertEquals(21, vo.date.getDayOfMonth()); + } + + public static class VO { + + private LocalDate date; + + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest2.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest2.java new file mode 100644 index 0000000000..b3d531e1e1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest2.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalDate; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class LocalDateTest2 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2016-05-06T20:24:28.484\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public static class VO { + public LocalDate date; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest3.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest3.java new file mode 100644 index 0000000000..c502f50052 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest3.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalDate; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class LocalDateTest3 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2016-05-06\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public static class VO { + public LocalDate date; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest4.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest4.java new file mode 100644 index 0000000000..f8318fb97e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest4.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalDate; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class LocalDateTest4 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"20160506\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public static class VO { + public LocalDate date; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest5.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest5.java new file mode 100644 index 0000000000..13aa069d97 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest5.java @@ -0,0 +1,113 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalDate; +import java.util.Locale; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class LocalDateTest5 extends TestCase { + + private Locale origin; + + protected void setUp() throws Exception { + origin = Locale.getDefault(); + } + + protected void tearDown() throws Exception { + Locale.setDefault(origin); + } + + public void test_for_tw() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2016/05/06\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_jp() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2016年5月6日\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_kr() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2016년5월6일\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_us() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"05/26/2016\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(26, vo.date.getDayOfMonth()); + } + + public void test_for_eur() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"26/05/2016\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(26, vo.date.getDayOfMonth()); + } + + public void test_for_us_1() throws Exception { + Locale.setDefault(Locale.US); + VO vo = JSON.parseObject("{\"date\":\"05/06/2016\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(06, vo.date.getDayOfMonth()); + } + + public void test_for_br() throws Exception { + Locale.setDefault(new Locale("pt", "BR")); + VO vo = JSON.parseObject("{\"date\":\"06/05/2016\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_au() throws Exception { + Locale.setDefault(new Locale("en", "AU")); + VO vo = JSON.parseObject("{\"date\":\"06/05/2016\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_de() throws Exception { + Locale.setDefault(new Locale("pt", "BR")); + VO vo = JSON.parseObject("{\"date\":\"06.05.2016\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_in() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"06-05-2016\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public static class VO { + + public LocalDate date; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest.java new file mode 100644 index 0000000000..9a3e440c7e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest.java @@ -0,0 +1,73 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalDateTime; + +import com.alibaba.fastjson.serializer.SerializerFeature; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class LocalDateTimeTest extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setDate(LocalDateTime.now().minusNanos(10L)); + + String text = JSON.toJSONString(vo); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(JSON.toJSONString(vo.getDate()), JSON.toJSONString(vo1.getDate())); + } + + /** + * 方法描述: 测试LocalDateTime 转化时间戳等 操作 + * 问题点1、 LocalDateTime 进来的值无法确定其时区,所以此处统一按着系统时区走。 + * 问题点2、 如果设置 SerializerFeature.WriteDateUseDateFormat 时按着 "yyyy-MM-dd HH:mm:ss" 进行格式化 + * 问题点3: 如果设置 SerializerFeature.UseISO8601DateFormat 时按着ISO8601的标准 "yyyy-MM-dd'T'HH:mm:ss"进行格式化 + * 问题点4: + * 1)格式化LocalDateTime时, 默认格式成 时间戳格式, + * 2)如设置WriteDateUseDateFormat 按 "yyyy-MM-dd HH:mm:ss" 进行格式化 + * 3)如设置UseISO8601DateFormat 按ISO8601的标准 "yyyy-MM-dd'T'HH:mm:ss"进行格式化 + * 4)如设置WriteDateUseDateFormat、UseISO8601DateFormat 同时设置,则按ISO8601的标准 "yyyy-MM-dd'T'HH:mm:ss"进行格式化 + * @author wuqiong 2017/11/22 15:08 + */ + public void test_toJsonString_ofLong()throws Exception { + VO vo = new VO(); + vo.setDate(LocalDateTime.now()); + + String text1 = JSON.toJSONString(vo); + System.out.println(text1);//{"date":1511334591189} + VO vo1 = JSON.parseObject(text1, VO.class); + + String text2 = JSON.toJSONString(vo, SerializerFeature.WriteDateUseDateFormat); + System.out.println(text2);//{"date":"2017-11-22 15:09:51"} + VO vo2 = JSON.parseObject(text2, VO.class); + + String text3 = JSON.toJSONString(vo, SerializerFeature.UseISO8601DateFormat); + System.out.println(text3);//{"date":"2017-11-22T15:09:51"} + VO vo3 = JSON.parseObject(text3, VO.class); + + String text4 = JSON.toJSONString(vo, SerializerFeature.UseISO8601DateFormat, SerializerFeature.WriteDateUseDateFormat); + System.out.println(text4);//{"date":"2017-11-22T15:09:51"} + VO vo4 = JSON.parseObject(text4, VO.class); + + + } + + public static class VO { + + private LocalDateTime date; + + public LocalDateTime getDate() { + return date; + } + + public void setDate(LocalDateTime date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest2.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest2.java new file mode 100644 index 0000000000..0340ec3323 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest2.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalDateTime; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class LocalDateTimeTest2 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2011-12-03\"}", VO.class); + + Assert.assertEquals(2011, vo.date.getYear()); + Assert.assertEquals(12, vo.date.getMonthValue()); + Assert.assertEquals(03, vo.date.getDayOfMonth()); + Assert.assertEquals(0, vo.date.getHour()); + Assert.assertEquals(0, vo.date.getMinute()); + Assert.assertEquals(0, vo.date.getSecond()); + } + + public static class VO { + public LocalDateTime date; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest3.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest3.java new file mode 100644 index 0000000000..2cb382811c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest3.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalDateTime; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class LocalDateTimeTest3 extends TestCase { + + public void test_for_issue() throws Exception { + String text = "{\"date\":\"20111203\"}"; + VO vo = JSON.parseObject(text, VO.class); + + Assert.assertEquals(2011, vo.date.getYear()); + Assert.assertEquals(12, vo.date.getMonthValue()); + Assert.assertEquals(03, vo.date.getDayOfMonth()); + Assert.assertEquals(0, vo.date.getHour()); + Assert.assertEquals(0, vo.date.getMinute()); + Assert.assertEquals(0, vo.date.getSecond()); + + Assert.assertEquals(text, JSON.toJSONString(vo)); + } + + public static class VO { + @JSONField(format="yyyyMMdd") + public LocalDateTime date; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest3_private.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest3_private.java new file mode 100644 index 0000000000..cd474c23e2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest3_private.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalDateTime; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class LocalDateTimeTest3_private extends TestCase { + + public void test_for_issue() throws Exception { + String text = "{\"date\":\"20111203\"}"; + VO vo = JSON.parseObject(text, VO.class); + + Assert.assertEquals(2011, vo.date.getYear()); + Assert.assertEquals(12, vo.date.getMonthValue()); + Assert.assertEquals(03, vo.date.getDayOfMonth()); + Assert.assertEquals(0, vo.date.getHour()); + Assert.assertEquals(0, vo.date.getMinute()); + Assert.assertEquals(0, vo.date.getSecond()); + + Assert.assertEquals(text, JSON.toJSONString(vo)); + } + + private static class VO { + @JSONField(format="yyyyMMdd") + public LocalDateTime date; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest4.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest4.java new file mode 100644 index 0000000000..19158ea59b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest4.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalDateTime; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class LocalDateTimeTest4 extends TestCase { + + public void test_for_issue() throws Exception { + LocalDateTime dateTime = LocalDateTime.of(2016, 5, 6, 9, 3, 16); + VO vo = new VO(); + vo.setDate(dateTime); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"date\":\"2016-05-06 09:03:16\"}", text); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getDate(), vo1.getDate()); + } + + public static class VO { + + private LocalDateTime date; + + public LocalDateTime getDate() { + return date; + } + + public void setDate(LocalDateTime date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest5.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest5.java new file mode 100644 index 0000000000..f029f52093 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest5.java @@ -0,0 +1,166 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalDateTime; +import java.util.Locale; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class LocalDateTimeTest5 extends TestCase { + + private Locale origin; + + protected void setUp() throws Exception { + origin = Locale.getDefault(); + } + + protected void tearDown() throws Exception { + Locale.setDefault(origin); + } + + public void test_for_long() throws Exception { + VO vo = JSON.parseObject("{\"date\":1322874196000}", VO.class); + + Assert.assertEquals(2011, vo.date.getYear()); + Assert.assertEquals(12, vo.date.getMonthValue()); + Assert.assertEquals(3, vo.date.getDayOfMonth()); +// Assert.assertEquals(9, vo.date.getHour()); + Assert.assertEquals(3, vo.date.getMinute()); + Assert.assertEquals(16, vo.date.getSecond()); + Assert.assertEquals(0, vo.date.getNano()); + } + + public void test_for_normal() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2011-12-03 09:03:16\"}", VO.class); + + Assert.assertEquals(2011, vo.date.getYear()); + Assert.assertEquals(12, vo.date.getMonthValue()); + Assert.assertEquals(3, vo.date.getDayOfMonth()); + Assert.assertEquals(9, vo.date.getHour()); + Assert.assertEquals(3, vo.date.getMinute()); + Assert.assertEquals(16, vo.date.getSecond()); + Assert.assertEquals(0, vo.date.getNano()); + } + + public void test_for_iso() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2011-12-03T09:03:16\"}", VO.class); + + Assert.assertEquals(2011, vo.date.getYear()); + Assert.assertEquals(12, vo.date.getMonthValue()); + Assert.assertEquals(3, vo.date.getDayOfMonth()); + + Assert.assertEquals(9, vo.date.getHour()); + Assert.assertEquals(3, vo.date.getMinute()); + Assert.assertEquals(16, vo.date.getSecond()); + Assert.assertEquals(0, vo.date.getNano()); + } + + public void test_for_tw() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2016/05/06 09:03:16\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_jp() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2016年5月6日 09:03:16\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_cn() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2016年5月6日 9时3分16秒\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_kr() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2016년5월6일 09:03:16\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_us() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"05/26/2016 09:03:16\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(26, vo.date.getDayOfMonth()); + } + + public void test_for_eur() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"26/05/2016 09:03:16\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(26, vo.date.getDayOfMonth()); + } + + public void test_for_us_1() throws Exception { + Locale.setDefault(Locale.US); + VO vo = JSON.parseObject("{\"date\":\"05/06/2016 09:03:16\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(06, vo.date.getDayOfMonth()); + } + + public void test_for_br() throws Exception { + Locale.setDefault(new Locale("pt", "BR")); + VO vo = JSON.parseObject("{\"date\":\"06/05/2016 09:03:16\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_au() throws Exception { + Locale.setDefault(new Locale("en", "AU")); + VO vo = JSON.parseObject("{\"date\":\"06/05/2016 09:03:16\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + } + + public void test_for_de() throws Exception { + Locale.setDefault(new Locale("pt", "BR")); + VO vo = JSON.parseObject("{\"date\":\"06.05.2016 09:03:16\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + + Assert.assertEquals(9, vo.date.getHour()); + Assert.assertEquals(3, vo.date.getMinute()); + Assert.assertEquals(16, vo.date.getSecond()); + Assert.assertEquals(0, vo.date.getNano()); + } + + public void test_for_in() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"06-05-2016 09:03:16\"}", VO.class); + + Assert.assertEquals(2016, vo.date.getYear()); + Assert.assertEquals(5, vo.date.getMonthValue()); + Assert.assertEquals(6, vo.date.getDayOfMonth()); + + Assert.assertEquals(9, vo.date.getHour()); + Assert.assertEquals(3, vo.date.getMinute()); + Assert.assertEquals(16, vo.date.getSecond()); + Assert.assertEquals(0, vo.date.getNano()); + } + + public static class VO { + public LocalDateTime date; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest.java new file mode 100644 index 0000000000..f2feb8ee55 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalTime; +import java.util.Locale; +import java.util.TimeZone; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class LocalTimeTest extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setDate(LocalTime.now()); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getDate(), vo1.getDate()); + } + + /** + * 方法描述: 测试时间戳转换为 时间 + * @author wuqiong 2017/11/21 16:48 + */ + public void test_for_long() throws Exception { + String text= "{\"date\":1511248447740}"; + VO vo =JSON.parseObject(text,VO.class); + Assert.assertEquals(15, vo.date.getHour()); + Assert.assertEquals(14, vo.date.getMinute()); + Assert.assertEquals(07, vo.date.getSecond()); + } + + public static class VO { + + private LocalTime date; + + public LocalTime getDate() { + return date; + } + + public void setDate(LocalTime date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest2.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest2.java new file mode 100644 index 0000000000..ae7e47ab61 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest2.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalTime; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class LocalTimeTest2 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo1 = JSON.parseObject("{\"date\":\"20:30:55\"}", VO.class); + + Assert.assertEquals(20, vo1.date.getHour()); + Assert.assertEquals(30, vo1.date.getMinute()); + Assert.assertEquals(55, vo1.date.getSecond()); + } + + public static class VO { + + public LocalTime date; + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest3.java b/src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest3.java new file mode 100644 index 0000000000..1edfdc8c97 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest3.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.LocalTime; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class LocalTimeTest3 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo1 = JSON.parseObject("{\"date\":\"2016-05-05T20:24:28.484\"}", VO.class); + + Assert.assertEquals(20, vo1.date.getHour()); + Assert.assertEquals(24, vo1.date.getMinute()); + Assert.assertEquals(28, vo1.date.getSecond()); + Assert.assertEquals(484000000, vo1.date.getNano()); + } + + public static class VO { + + public LocalTime date; + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/LongAdderTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/LongAdderTest.java new file mode 100644 index 0000000000..b3263f3c2d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/LongAdderTest.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.jdk8; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.concurrent.atomic.LongAdder; + +/** + * Created by wenshao on 14/03/2017. + */ +public class LongAdderTest extends TestCase { + public void test_long_add() throws Exception { + LongAdder adder = new LongAdder(); + adder.add(3); + + String json = JSON.toJSONString(adder); + assertEquals("{\"value\":3}", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/OffseTimeTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/OffseTimeTest.java new file mode 100644 index 0000000000..9fe28e7823 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/OffseTimeTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.OffsetTime; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class OffseTimeTest extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setDate(OffsetTime.now()); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getDate(), vo1.getDate()); + } + + public static class VO { + + private OffsetTime date; + + public OffsetTime getDate() { + return date; + } + + public void setDate(OffsetTime date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/OffsetDateTimeTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/OffsetDateTimeTest.java new file mode 100644 index 0000000000..e201098ade --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/OffsetDateTimeTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.OffsetDateTime; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class OffsetDateTimeTest extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setDate(OffsetDateTime.now()); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getDate(), vo1.getDate()); + } + + public static class VO { + + private OffsetDateTime date; + + public OffsetDateTime getDate() { + return date; + } + + public void setDate(OffsetDateTime date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/OptionalDouble_Test.java b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalDouble_Test.java new file mode 100644 index 0000000000..4a324f5738 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalDouble_Test.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.jdk8; + +import java.util.OptionalDouble; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class OptionalDouble_Test extends TestCase { + + public void test_optional() throws Exception { + Model model = new Model(); + model.value = OptionalDouble.empty(); + + String text = JSON.toJSONString(model); + + Assert.assertEquals("{\"value\":null}", text); + + Model model2 = JSON.parseObject(text, Model.class); + + Assert.assertEquals(model2.value, model.value); + } + + + public static class Model { + public OptionalDouble value; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/OptionalInt_Test.java b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalInt_Test.java new file mode 100644 index 0000000000..2617803a90 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalInt_Test.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.jdk8; + +import java.util.OptionalInt; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class OptionalInt_Test extends TestCase { + + public void test_optional() throws Exception { + Model model = new Model(); + model.value = OptionalInt.empty(); + + String text = JSON.toJSONString(model); + + Assert.assertEquals("{\"value\":null}", text); + + Model model2 = JSON.parseObject(text, Model.class); + + Assert.assertEquals(model2.value, model.value); + } + + + public static class Model { + public OptionalInt value; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/OptionalLong_Test.java b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalLong_Test.java new file mode 100644 index 0000000000..bde946c112 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalLong_Test.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.jdk8; + +import java.util.OptionalLong; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class OptionalLong_Test extends TestCase { + + public void test_optional() throws Exception { + Model model = new Model(); + model.value = OptionalLong.empty(); + + String text = JSON.toJSONString(model); + + Assert.assertEquals("{\"value\":null}", text); + + Model model2 = JSON.parseObject(text, Model.class); + + Assert.assertEquals(model2.value, model.value); + } + + + public static class Model { + public OptionalLong value; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest.java new file mode 100644 index 0000000000..c0e67a639b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest.java @@ -0,0 +1,77 @@ +package com.alibaba.json.bvt.jdk8; + +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; +import java.util.OptionalLong; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class OptionalTest extends TestCase { + public void test_optional() throws Exception { + Optional val = Optional.of(3); + + String text = JSON.toJSONString(val); + + Assert.assertEquals("3", text); + + Optional val2 = JSON.parseObject(text, new TypeReference>() {}); + Assert.assertEquals(val.get(), val2.get()); + } + + public void test_optionalInt_present() throws Exception { + String text = JSON.toJSONString(OptionalInt.empty()); + + Assert.assertEquals("null", text); + } + + public void test_optionalInt() throws Exception { + OptionalInt val = OptionalInt.of(3); + + String text = JSON.toJSONString(val); + + Assert.assertEquals("3", text); + + OptionalInt val2 = JSON.parseObject(text, OptionalInt.class); + Assert.assertEquals(val.getAsInt(), val2.getAsInt()); + } + + public void test_optionalLong_present() throws Exception { + String text = JSON.toJSONString(OptionalLong.empty()); + + Assert.assertEquals("null", text); + } + + public void test_optionalLong() throws Exception { + OptionalLong val = OptionalLong.of(3); + + String text = JSON.toJSONString(val); + + Assert.assertEquals("3", text); + + OptionalLong val2 = JSON.parseObject(text, OptionalLong.class); + Assert.assertEquals(val.getAsLong(), val2.getAsLong()); + } + + public void test_optionalDouble_present() throws Exception { + String text = JSON.toJSONString(OptionalDouble.empty()); + + Assert.assertEquals("null", text); + } + + public void test_optionalDouble() throws Exception { + OptionalDouble val = OptionalDouble.of(3.1D); + + String text = JSON.toJSONString(val); + + Assert.assertEquals("3.1", text); + + OptionalDouble val2 = JSON.parseObject(text, OptionalDouble.class); + Assert.assertEquals(Double.toString(val.getAsDouble()), Double.toString(val2.getAsDouble())); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest2.java b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest2.java new file mode 100644 index 0000000000..ef49b000db --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest2.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.jdk8; + +import java.util.Optional; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class OptionalTest2 extends TestCase { + + public void test_optional() throws Exception { + Entity entity = new Entity(); + entity.setValue(Optional.of(123)); + + String text = JSON.toJSONString(entity); + + Assert.assertEquals("{\"value\":123}", text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + + Assert.assertEquals(entity.getValue().get(), entity2.getValue().get()); + } + + public static class Entity { + + private Optional value; + + public Optional getValue() { + return value; + } + + public void setValue(Optional value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest3.java b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest3.java new file mode 100644 index 0000000000..8b1e614962 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest3.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.jdk8; + +import java.util.Optional; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class OptionalTest3 extends TestCase { + + public void test_optional() throws Exception { + UserExt ext = new UserExt(); + ext.setValue(Optional.of(123)); + User user = new User(); + user.setExt(Optional.of(ext)); + + String text = JSON.toJSONString(user); + + Assert.assertEquals("{\"ext\":{\"value\":123}}", text); + + User user2 = JSON.parseObject(text, User.class); + + Assert.assertEquals(user.getExt().get().getValue().get(), user2.getExt().get().getValue().get()); + } + + public static class User { + + private Optional ext; + + public Optional getExt() { + return ext; + } + + public void setExt(Optional ext) { + this.ext = ext; + } + + } + + public static class UserExt { + + private Optional value; + + public Optional getValue() { + return value; + } + + public void setValue(Optional value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest4.java b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest4.java new file mode 100644 index 0000000000..d1c1981ccf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest4.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.jdk8; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.Optional; + +/** + * Created by wenshao on 02/04/2017. + */ +public class OptionalTest4 extends TestCase { + public void test_for_issue() throws Exception { + JsonResult result = new JsonResult(); + result.a = Optional.empty(); + result.b = Optional.empty(); + + String json = JSON.toJSONString(result); + System.out.println(json); + } + + public static class JsonResult { + public Object a; + public Optional b; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest_empty.java b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest_empty.java new file mode 100644 index 0000000000..08e4298f15 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest_empty.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.jdk8; + +import java.util.Optional; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class OptionalTest_empty extends TestCase { + + public void test_optional() throws Exception { + Model model = new Model(); + model.value = Optional.empty(); + + String text = JSON.toJSONString(model); + + Assert.assertEquals("{\"value\":null}", text); + + Model model2 = JSON.parseObject(text, Model.class); + + Assert.assertEquals(model2.value, model.value); + } + + + public static class Model { + public Optional value; + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/PeriodTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/PeriodTest.java new file mode 100644 index 0000000000..12ce8b9194 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/PeriodTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.Period; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class PeriodTest extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setDate(Period.of(3, 2, 11)); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getDate(), vo1.getDate()); + } + + public static class VO { + + private Period date; + + public Period getDate() { + return date; + } + + public void setDate(Period date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/ZoneIdTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/ZoneIdTest.java new file mode 100644 index 0000000000..cf207ac4eb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/ZoneIdTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.ZoneId; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ZoneIdTest extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setDate(ZoneId.of("Europe/Paris")); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getDate(), vo1.getDate()); + } + + public static class VO { + + private ZoneId date; + + public ZoneId getDate() { + return date; + } + + public void setDate(ZoneId date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/ZonedDateTimeTest.java b/src/test/java/com/alibaba/json/bvt/jdk8/ZonedDateTimeTest.java new file mode 100644 index 0000000000..cd5aad3327 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/ZonedDateTimeTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.jdk8; + +import java.time.ZonedDateTime; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ZonedDateTimeTest extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.setDate(ZonedDateTime.now()); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getDate(), vo1.getDate()); + } + + public static class VO { + + private ZonedDateTime date; + + public ZonedDateTime getDate() { + return date; + } + + public void setDate(ZonedDateTime date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jdk8/ZonedDateTimeTest2.java b/src/test/java/com/alibaba/json/bvt/jdk8/ZonedDateTimeTest2.java new file mode 100644 index 0000000000..c5f45626cd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jdk8/ZonedDateTimeTest2.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.jdk8; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.time.ZonedDateTime; +import java.time.temporal.TemporalField; + +public class ZonedDateTimeTest2 extends TestCase { + + public void test_for_issue() throws Exception { + VO vo = new VO(); + vo.date = ZonedDateTime.now(); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.date.getSecond(), vo1.date.getSecond()); + } + + public static class VO { + @JSONField(format="yyyy-MM-dd HH:mm:ss") + public ZonedDateTime date; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jsonfield/JSONFieldTest_0.java b/src/test/java/com/alibaba/json/bvt/jsonfield/JSONFieldTest_0.java new file mode 100644 index 0000000000..1d7af04b09 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jsonfield/JSONFieldTest_0.java @@ -0,0 +1,86 @@ +package com.alibaba.json.bvt.jsonfield; + +import java.lang.reflect.Field; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.FieldDeserializer; +import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +import junit.framework.TestCase; + +public class JSONFieldTest_0 extends TestCase { + + public void test_0() throws Exception { + VO vo = new VO(); + vo.setF0(100); + vo.setF1(101); + vo.setF2(102); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + Assert.assertEquals("{\"f2\":102,\"f1\":101,\"f0\":100}", text); + + VO vo_decoded = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.f0, vo_decoded.f0); + Assert.assertEquals(vo.f1, vo_decoded.f1); + Assert.assertEquals(vo.f2, vo_decoded.f2); + + JavaBeanDeserializer javaBeanDeser = null; + + ObjectDeserializer deser = ParserConfig.getGlobalInstance().getDeserializer(VO.class); + javaBeanDeser = (JavaBeanDeserializer) deser; + + Field field = JavaBeanDeserializer.class.getDeclaredField("sortedFieldDeserializers"); + field.setAccessible(true); + FieldDeserializer[] fieldDeserList = (FieldDeserializer[]) field.get(javaBeanDeser); + + Assert.assertEquals(3, fieldDeserList.length); + Assert.assertEquals("f2", fieldDeserList[0].fieldInfo.name); + Assert.assertEquals("f1", fieldDeserList[1].fieldInfo.name); + Assert.assertEquals("f0", fieldDeserList[2].fieldInfo.name); + } + + public static class VO { + + @JSONField(ordinal = 3) + private int f0; + + @JSONField(ordinal = 2) + private int f1; + + @JSONField(ordinal = 1) + private int f2; + + public int getF0() { + return f0; + } + + public void setF0(int f0) { + this.f0 = f0; + } + + public int getF1() { + return f1; + } + + public void setF1(int f1) { + this.f1 = f1; + } + + public int getF2() { + return f2; + } + + public void setF2(int f2) { + this.f2 = f2; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jsonfield/JSONFieldTest_1.java b/src/test/java/com/alibaba/json/bvt/jsonfield/JSONFieldTest_1.java new file mode 100644 index 0000000000..e01f3030e9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jsonfield/JSONFieldTest_1.java @@ -0,0 +1,92 @@ +package com.alibaba.json.bvt.jsonfield; + +import java.lang.reflect.Field; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.FieldDeserializer; +import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +import junit.framework.TestCase; + +public class JSONFieldTest_1 extends TestCase { + + public void test_0() throws Exception { + VO vo = new VO(); + vo.setF0(100); + vo.setF1(101); + vo.setF2(102); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + Assert.assertEquals("{\"f2\":102,\"f1\":101,\"f0\":100}", text); + + VO vo_decoded = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.f0, vo_decoded.f0); + Assert.assertEquals(vo.f1, vo_decoded.f1); + Assert.assertEquals(vo.f2, vo_decoded.f2); + + JavaBeanDeserializer javaBeanDeser = null; + + ObjectDeserializer deser = ParserConfig.getGlobalInstance().getDeserializer(VO.class); + javaBeanDeser = (JavaBeanDeserializer) deser; + + Field field = JavaBeanDeserializer.class.getDeclaredField("sortedFieldDeserializers"); + field.setAccessible(true); + FieldDeserializer[] fieldDeserList = (FieldDeserializer[]) field.get(javaBeanDeser); + + Assert.assertEquals(3, fieldDeserList.length); + Assert.assertEquals("f2", fieldDeserList[0].fieldInfo.name); + Assert.assertEquals("f1", fieldDeserList[1].fieldInfo.name); + Assert.assertEquals("f0", fieldDeserList[2].fieldInfo.name); + } + + public static class VO { + + private int f0; + + + private int f1; + + + private int f2; + + @JSONField(ordinal = 3) + public int getF0() { + return f0; + } + + @JSONField(ordinal = 3) + public void setF0(int f0) { + this.f0 = f0; + } + + @JSONField(ordinal = 2) + public int getF1() { + return f1; + } + + @JSONField(ordinal = 2) + public void setF1(int f1) { + this.f1 = f1; + } + + @JSONField(ordinal = 1) + public int getF2() { + return f2; + } + + + @JSONField(ordinal = 1) + public void setF2(int f2) { + this.f2 = f2; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest.java b/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest.java new file mode 100644 index 0000000000..441ef0abed --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.jsonp; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPObject; +import junit.framework.TestCase; + +/** + * Created by wenshao on 21/02/2017. + */ +public class JSONPParseTest extends TestCase { + public void test_f() throws Exception { + String text = "callback ({'id':1, 'name':'idonans'} );"; + + JSONPObject jsonpObject = JSON.parseObject(text, JSONPObject.class); + assertEquals("callback", jsonpObject.getFunction()); + + assertEquals(1, jsonpObject.getParameters().size()); + JSONObject param = (JSONObject) jsonpObject.getParameters().get(0); + assertEquals(1, param.get("id")); + assertEquals("idonans", param.get("name")); + + String json = JSON.toJSONString(jsonpObject); + System.out.println(json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest1.java b/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest1.java new file mode 100644 index 0000000000..ee840a1006 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest1.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.jsonp; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPObject; +import junit.framework.TestCase; + +/** + * Created by wenshao on 21/02/2017. + */ +public class JSONPParseTest1 extends TestCase { + public void test_f() throws Exception { + String text = "callback /**/ ({'id':1, 'name':'idonans'} ); "; + + JSONPObject jsonpObject = JSON.parseObject(text, JSONPObject.class); + assertEquals("callback", jsonpObject.getFunction()); + + assertEquals(1, jsonpObject.getParameters().size()); + JSONObject param = (JSONObject) jsonpObject.getParameters().get(0); + assertEquals(1, param.get("id")); + assertEquals("idonans", param.get("name")); + + String json = JSON.toJSONString(jsonpObject); + System.out.println(json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest2.java b/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest2.java new file mode 100644 index 0000000000..f4955f8077 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest2.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.jsonp; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 21/02/2017. + */ +public class JSONPParseTest2 extends TestCase { + public void test_f() throws Exception { + String text = "parent.callback ({'id':1, 'name':'idonans'} ); /**/ "; + + JSONPObject jsonpObject = JSON.parseObject(text, JSONPObject.class); + assertEquals("parent.callback", jsonpObject.getFunction()); + + assertEquals(1, jsonpObject.getParameters().size()); + JSONObject param = (JSONObject) jsonpObject.getParameters().get(0); + assertEquals(1, param.get("id")); + assertEquals("idonans", param.get("name")); + + String json = JSON.toJSONString(jsonpObject); + assertEquals("parent.callback({\"name\":\"idonans\",\"id\":1})", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest3.java b/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest3.java new file mode 100644 index 0000000000..646567b31e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest3.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.jsonp; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 21/02/2017. + */ +public class JSONPParseTest3 extends TestCase { + public void test_f() throws Exception { + String text = "parent.callback ({'id':1, 'name':'ido)nans'},1,2 ); /**/ "; + + JSONPObject jsonpObject = (JSONPObject) JSON.parseObject(text, JSONPObject.class); + assertEquals("parent.callback", jsonpObject.getFunction()); + + assertEquals(3, jsonpObject.getParameters().size()); + JSONObject param = (JSONObject) jsonpObject.getParameters().get(0); + assertEquals(1, param.get("id")); + assertEquals("ido)nans", param.get("name")); + + String json = JSON.toJSONString(jsonpObject, SerializerFeature.BrowserSecure); + assertEquals("/**/parent.callback({\"name\":\"ido\\u0029nans\",\"id\":1},1,2)", json); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithPairMixedTypesTest.java b/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithPairMixedTypesTest.java new file mode 100644 index 0000000000..00e09699b0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithPairMixedTypesTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by wenshao on 06/08/2017. + */ +public class ClassWithPairMixedTypesTest extends TestCase { + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("ClassWithPairMixedTypes"); + + String json = "{\"person\":{\"first\":\"wenshao\",\"second\":99}}"; + Object obj = JSON.parseObject(json, clazz); + assertEquals("{\"person\":{\"first\":\"wenshao\",\"second\":99}}", JSON.toJSONString(obj)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/ClassWithPairMixedTypes.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("ClassWithPairMixedTypes", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithPairTest.java b/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithPairTest.java new file mode 100644 index 0000000000..cb441a410f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithPairTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by wenshao on 06/08/2017. + */ +public class ClassWithPairTest extends TestCase { + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("ClassWithPair"); + + String json = "{\"name\":{\"first\":\"shaojin\",\"second\":\"wen\"},\"age\":99}"; + Object obj = JSON.parseObject(json, clazz); + assertEquals("{\"age\":99,\"name\":{\"first\":\"shaojin\",\"second\":\"wen\"}}", JSON.toJSONString(obj)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/ClassWithPair.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("ClassWithPair", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithRangesTest.java b/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithRangesTest.java new file mode 100644 index 0000000000..6e542eebd3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithRangesTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by wenshao on 06/08/2017. + */ +public class ClassWithRangesTest extends TestCase { + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("ClassWithRanges"); + + String json = "{\"ages\":{\"start\":18,\"end\":40},\"distance\":{\"start\":5,\"end\":50}}"; + Object obj = JSON.parseObject(json, clazz); + assertEquals("{\"ages\":{\"first\":18,\"last\":0,\"start\":18,\"step\":1},\"distance\":{\"first\":5,\"last\":0,\"start\":5,\"step\":1}}", JSON.toJSONString(obj)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/ClassWithRanges.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("ClassWithRanges", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithTripleTest.java b/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithTripleTest.java new file mode 100644 index 0000000000..9b75e20429 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/ClassWithTripleTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by wenshao on 06/08/2017. + */ +public class ClassWithTripleTest extends TestCase { + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("ClassWithTriple"); + + String json = "{\"name\":{\"first\":\"wen\",\"second\":\"shaojin\",\"third\":99}}"; + Object obj = JSON.parseObject(json, clazz); + assertEquals("{\"age\":0,\"name\":{\"first\":\"wen\",\"second\":\"shaojin\",\"third\":\"99\"}}", JSON.toJSONString(obj)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/ClassWithTriple.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("ClassWithTriple", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/Class_WithPrimaryAndSecondaryConstructorTest.java b/src/test/java/com/alibaba/json/bvt/kotlin/Class_WithPrimaryAndSecondaryConstructorTest.java new file mode 100644 index 0000000000..492793ad1f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/Class_WithPrimaryAndSecondaryConstructorTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by wenshao on 06/08/2017. + */ +public class Class_WithPrimaryAndSecondaryConstructorTest extends TestCase { + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("Class_WithPrimaryAndSecondaryConstructor"); + + String json = "{\"name\":\"John Smith\",\"age\":30}"; + Object obj = JSON.parseObject(json, clazz); + assertEquals("{\"age\":30,\"name\":\"John Smith\"}", JSON.toJSONString(obj)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/Class_WithPrimaryAndSecondaryConstructor.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("Class_WithPrimaryAndSecondaryConstructor", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/DataClassSimpleTest.java b/src/test/java/com/alibaba/json/bvt/kotlin/DataClassSimpleTest.java new file mode 100644 index 0000000000..fd77d544bc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/DataClassSimpleTest.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.util.ASMUtils; +import junit.framework.TestCase; +import kotlin.reflect.KFunction; +import kotlin.reflect.KParameter; +import kotlin.reflect.jvm.internal.KClassImpl; +import org.apache.commons.io.IOUtils; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by wenshao on 05/08/2017. + */ +public class DataClassSimpleTest extends TestCase { + + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("DataClassSimple"); + + String[] names = ASMUtils.lookupParameterNames(clazz.getConstructors()[0]); + System.out.println(JSON.toJSONString(names)); + + String json = "{\"a\":1001,\"b\":1002}"; + Object obj = JSON.parseObject(json, clazz); + assertEquals("{\"a\":1001,\"b\":1002}", JSON.toJSONString(obj)); + + } + + public static class ExtClassLoader extends ClassLoader { + Map resources = new HashMap(); + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/DataClassSimple.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + resources.put("DataClassSimple.class", bytes); + + super.defineClass("DataClassSimple", bytes, 0, bytes.length); + } + } + + public InputStream getResourceAsStream(String name) { + byte[] bytes = resources.get(name); + if (bytes != null) { + return new ByteArrayInputStream(bytes); + } + return super.getResourceAsStream(name); + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/DataClassTest.java b/src/test/java/com/alibaba/json/bvt/kotlin/DataClassTest.java new file mode 100644 index 0000000000..709db510c9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/DataClassTest.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by wenshao on 05/08/2017. + */ +public class DataClassTest extends TestCase { + + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("DataClass"); + + String json = "{\"aa\":1001,\"bb\":1002}"; + Object obj = JSON.parseObject(json, clazz); + assertEquals("{\"aa\":1001,\"bb\":1002}", JSON.toJSONString(obj)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/DataClass.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("DataClass", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/Issue1420.java b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1420.java new file mode 100644 index 0000000000..d525babef8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1420.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +public class Issue1420 extends TestCase { + public void test_for_issue() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("A"); + + String json = "{\"id\":1,\"name\":\"a\"}"; + Object obj = JSON.parseObject(json, clazz); + assertEquals("{\"id\":1,\"name\":\"a\"}", JSON.toJSONString(obj)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/A.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("A", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/Issue1462.java b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1462.java new file mode 100644 index 0000000000..5d3e4fb4df --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1462.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by wenshao on 05/08/2017. + */ +public class Issue1462 extends TestCase { + + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("ObjectA"); + + String json = "{\"a\":1001,\"b\":1002}"; + Object obj = JSON.parseObject(json, clazz); + assertEquals("{\"a\":\"b\",\"b\":\"b\"}", JSON.toJSONString(obj)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/ObjectA.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("ObjectA", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/Issue1483.java b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1483.java new file mode 100644 index 0000000000..e8397cbb4c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1483.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by wenshao on 05/08/2017. + */ +public class Issue1483 extends TestCase { + + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("Person"); + + String json = "{\"age\":99,\"name\":\"robohorse\",\"desc\":\"xx\"}"; + Object obj = JSON.parseObject(json, clazz); + assertSame(clazz, obj.getClass()); +// + for (int i = 0; i < 10; ++i) { + String text = JSON.parseObject(JSON.toJSONString(obj), Feature.OrderedField).toJSONString(); + assertEquals("{\"age\":99,\"desc\":\"xx\",\"name\":\"robohorse\"}", text); + } + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/Person.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("Person", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/Issue1524.java b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1524.java new file mode 100644 index 0000000000..7f0e66a0ab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1524.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Constructor; + +public class Issue1524 extends TestCase { + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("DataClass"); + + Constructor constructor = clazz.getConstructor(String.class, String.class); + Object object = constructor.newInstance("ccc", "ddd"); + String json = JSON.toJSONString(object); + assertEquals("{\"Id\":\"ccc\",\"Name\":\"ddd\"}", json); + + Object object2 = JSON.parseObject(json, clazz); + String json2 = JSON.toJSONString(object2); + assertEquals("{\"Id\":\"ccc\",\"Name\":\"ddd\"}", json2); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/issue1526/DataClass.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("DataClass", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/Issue1543.java b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1543.java new file mode 100644 index 0000000000..376478c8eb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1543.java @@ -0,0 +1,57 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class Issue1543 extends TestCase { + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazzUser = classLoader.loadClass("User1"); + + Map map = new HashMap(); + map.put("id", 1); + map.put("name", "test1"); + + JSON.parseObject(JSON.toJSONString(map), clazzUser); + } + + public void test_cluster() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazzCluster = classLoader.loadClass("Cluster"); + + Object cluster = JSON.parseObject(JSON.toJSONString(Collections.singletonMap("cluster_enabled", 1)), clazzCluster); + assertEquals("{\"cluster_enabled\":1}", JSON.toJSONString(cluster)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/issue1543/User1.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("User1", bytes, 0, bytes.length); + } + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/issue1543/Cluster.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("Cluster", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/Issue1547.java b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1547.java new file mode 100644 index 0000000000..34cf8db66f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1547.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Constructor; + +public class Issue1547 extends TestCase { + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("Head"); + + Object head = JSON.parseObject("{\"msg\":\"mmm\",\"code\":\"ccc\"}", clazz); + assertEquals("{\"code\":\"ccc\",\"msg\":\"mmm\"}", JSON.toJSONString(head)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/issue1547/Head.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("Head", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/Issue1569.java b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1569.java new file mode 100644 index 0000000000..ef8a24aa7e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1569.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +public class Issue1569 extends TestCase { + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("Issue1569_User"); + + String json = "{\"loginName\":\"san\",\"userId\":1}"; + Object head = JSON.parseObject(json, clazz); + assertEquals(json, JSON.toJSONString(head)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/Issue1569_User.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("Issue1569_User", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/Issue1750.java b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1750.java new file mode 100644 index 0000000000..4db82b3f59 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/Issue1750.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +public class Issue1750 extends TestCase { + public void test_user() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("Issue1750_ProcessBO"); + + String json = "{\n" + + "\t\"masterId\": \"1111111111111\",\n" + + "\t\"processId\": \"222222222222222\",\n" + + "\t\"taskId\": \"33333333333333\",\n" + + "\t\"taskName\": \"44444444444444\"\n" + + "}"; + Object obj = JSON.parseObject(json, clazz); + String result = JSON.toJSONString(obj); + System.out.println(result); + assertEquals("{\"masterId\":\"1111111111111\",\"processId\":\"222222222222222\",\"taskId\":\"33333333333333\",\"taskName\":\"44444444444444\"}", result); + } + + private static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/Issue1750_ProcessBO.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("Issue1750_ProcessBO", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/ResponseKotlin2Test.java b/src/test/java/com/alibaba/json/bvt/kotlin/ResponseKotlin2Test.java new file mode 100644 index 0000000000..1589daf9a6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/ResponseKotlin2Test.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by wenshao on 10/08/2017. + */ +public class ResponseKotlin2Test extends TestCase { + public void test_kotlin() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("ResponseKotlin2"); + + String json = "{\"text\":\"robohorse\",\"value\":99}"; + Object obj = JSON.parseObject(json, clazz); + assertEquals("{\"text\":\"robohorse\",\"value\":99}", JSON.toJSONString(obj)); + + String json2 = "{\"text\":\"robohorse\"}"; + Object obj2 = JSON.parseObject(json2, clazz); + assertEquals("{\"text\":\"robohorse\"}", JSON.toJSONString(obj2)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/ResponseKotlin2.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("ResponseKotlin2", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/kotlin/ResponseKotlinTest.java b/src/test/java/com/alibaba/json/bvt/kotlin/ResponseKotlinTest.java new file mode 100644 index 0000000000..ce10af0ad6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/kotlin/ResponseKotlinTest.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.kotlin; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by wenshao on 10/08/2017. + */ +public class ResponseKotlinTest extends TestCase { + public void test_kotlin() throws Exception { + ExtClassLoader classLoader = new ExtClassLoader(); + Class clazz = classLoader.loadClass("ResponseKotlin"); + + String json = "{\"text\":\"robohorse\",\"value\":99}"; + Object obj = JSON.parseObject(json, clazz); + assertEquals("{\"text\":\"robohorse\",\"value\":99}", JSON.toJSONString(obj)); + + String json2 = "{\"text\":\"robohorse\"}"; + Object obj2 = JSON.parseObject(json2, clazz); + assertEquals("{\"text\":\"robohorse\"}", JSON.toJSONString(obj2)); + } + + public static class ExtClassLoader extends ClassLoader { + + public ExtClassLoader() throws IOException { + super(Thread.currentThread().getContextClassLoader()); + + { + byte[] bytes; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/ResponseKotlin.clazz"); + bytes = IOUtils.toByteArray(is); + is.close(); + + super.defineClass("ResponseKotlin", bytes, 0, bytes.length); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/naming/ListCaseTest.java b/src/test/java/com/alibaba/json/bvt/naming/ListCaseTest.java new file mode 100644 index 0000000000..a5a6151864 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/naming/ListCaseTest.java @@ -0,0 +1,72 @@ +package com.alibaba.json.bvt.naming; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 09/02/2017. + */ +public class ListCaseTest extends TestCase { + public void test_0() throws Exception { + String result = "{\"code\":\"SUCCESS\",\"msg\":\"success\",\"SUCCESS\":true,\"obj\":[\"10.55.251.213\"]}"; + T4QueryResult t4TaskApiResult = JSON.parseObject(result, T4QueryResult.class); + System.out.println(JSON.toJSONString(t4TaskApiResult)); + + } + + public static class Model { + public List values; + } + + public static class T4QueryResult { + + @JSONField(name = "OBJ") + private List obj; + + @JSONField(name = "MSG") + private String msg; + + @JSONField(name = "CODE") + private String code; + + @JSONField(name = "SUCCESS") + private Boolean success; + + public List getObj() { + return obj; + } + + public void setObj(List obj) { + this.obj = obj; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public Boolean getSuccess() { + return success; + } + + public void setSuccess(Boolean success) { + this.success = success; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/naming/NamingSerTest.java b/src/test/java/com/alibaba/json/bvt/naming/NamingSerTest.java new file mode 100644 index 0000000000..0807a7714a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/naming/NamingSerTest.java @@ -0,0 +1,90 @@ +package com.alibaba.json.bvt.naming; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.PropertyNamingStrategy; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializeConfig; + +import junit.framework.TestCase; + +public class NamingSerTest extends TestCase { + + public void test_snake() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase; + + Model model = new Model(); + model.personId = 1001; + String text = JSON.toJSONString(model, config); + Assert.assertEquals("{\"person_id\":1001}", text); + + ParserConfig parserConfig = new ParserConfig(); + parserConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase; + Model model2 = JSON.parseObject(text, Model.class, parserConfig); + Assert.assertEquals(model.personId, model2.personId); + + Model model3 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.personId, model3.personId); + } + + public void test_kebab() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.propertyNamingStrategy = PropertyNamingStrategy.KebabCase; + + Model model = new Model(); + model.personId = 1001; + String text = JSON.toJSONString(model, config); + Assert.assertEquals("{\"person-id\":1001}", text); + + ParserConfig parserConfig = new ParserConfig(); + parserConfig.propertyNamingStrategy = PropertyNamingStrategy.KebabCase; + Model model2 = JSON.parseObject(text, Model.class, parserConfig); + Assert.assertEquals(model.personId, model2.personId); + + Model model3 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.personId, model3.personId); + } + + public void test_pascal() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.propertyNamingStrategy = PropertyNamingStrategy.PascalCase; + + Model model = new Model(); + model.personId = 1001; + String text = JSON.toJSONString(model, config); + Assert.assertEquals("{\"PersonId\":1001}", text); + + ParserConfig parserConfig = new ParserConfig(); + parserConfig.propertyNamingStrategy = PropertyNamingStrategy.PascalCase; + Model model2 = JSON.parseObject(text, Model.class, parserConfig); + Assert.assertEquals(model.personId, model2.personId); + + Model model3 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.personId, model3.personId); + } + + public void test_camel() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.propertyNamingStrategy = PropertyNamingStrategy.CamelCase; + + Model model = new Model(); + model.personId = 1001; + String text = JSON.toJSONString(model, config); + Assert.assertEquals("{\"personId\":1001}", text); + + ParserConfig parserConfig = new ParserConfig(); + parserConfig.propertyNamingStrategy = PropertyNamingStrategy.CamelCase; + Model model2 = JSON.parseObject(text, Model.class, parserConfig); + Assert.assertEquals(model.personId, model2.personId); + + Model model3 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.personId, model3.personId); + } + + public static class Model { + + public int personId; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/AEHuangliang2Test.java b/src/test/java/com/alibaba/json/bvt/parser/AEHuangliang2Test.java new file mode 100644 index 0000000000..a3960cd228 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/AEHuangliang2Test.java @@ -0,0 +1,395 @@ +package com.alibaba.json.bvt.parser; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.json.bvtVO.ae.huangliang2.*; +import junit.framework.TestCase; + +import java.lang.reflect.Type; + +/** + * Created by wenshao on 09/05/2017. + */ +public class AEHuangliang2Test extends TestCase { + static String jsonData = "{\n" + + " \"areas\": [\n" + + " {\n" + + " \"@type\": \"section\",\n" + + " \"templateId\": \"grid\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"column-count\":\"2\",\n" + + " \"aspect-ratio\":\"2\",\n" + + " \"margins\":\"16 0 16 16\",\n" + + " \"background-color\": \"#ffffff\",\n" + + " \"column-gap\": \"10\"\n" + + " },\n" + + " \"children\": [\n" + + " {\n" + + " \"@type\": \"section\",\n" + + " \"templateId\": \"grid\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"column-count\":\"2\",\n" + + " \"aspect-ratio\":\"2\",\n" + + " \"margins\":\"16 0 16 16\",\n" + + " \"background-color\": \"#ffffff\",\n" + + " \"column-gap\": \"10\"\n" + + " },\n" + + " \"children\": [\n" + + " {\n" + + " \"@type\": \"floorV2\",\n" + + " \"templateId\": \"base\",\n" + + " \"image\": \"http://xxx\",\n" + + " \"fields\": [\n" + + " {\n" + + " \"index\": 0,\n" + + " \"value\": \"xxxx\",\n" + + " \"type\": \"text\",\n" + + " \"track\": {\n" + + " \"name\": \"track name\",\n" + + " \"params\": {\n" + + " \"trackParam1\": \"trackParam1\"\n" + + " }\n" + + " },\n" + + " \"extInfo\": {\n" + + " \"likeByMe\": \"true\",\n" + + " \"isFollowed\": \"true\"\n" + + " },\n" + + " \"action\": {\n" + + " \"type\": \"click\",\n" + + " \"action\": \"aecmd://nativie/invokeApi?name=key1&likeId=111&likeByMe=true\"\n" + + " }\n" + + " }\n" + + " ],\n" + + " \"bizId\": \"banner-myae-1-746877468\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"background-color\": \"#000000\"\n" + + " },\n" + + " \"isTest\": false\n" + + " },\n" + + " {\n" + + " \"@type\": \"floorV2\",\n" + + " \"templateId\": \"base\",\n" + + " \"image\": \"http://xxx\",\n" + + " \"fields\": [\n" + + " {\n" + + " \"index\": 0,\n" + + " \"value\": \"xxxx\",\n" + + " \"type\": \"text\",\n" + + " \"track\": {\n" + + " \"name\": \"track name\",\n" + + " \"params\": {\n" + + " \"trackParam1\": \"trackParam1\"\n" + + " }\n" + + " },\n" + + " \"action\": {\n" + + " \"type\": \"click\",\n" + + " \"action\": \"aecmd://xxxx\"\n" + + " }\n" + + " }\n" + + " ],\n" + + " \"extInfo\": {\n" + + " \"likeByMe\": \"true\"\n" + + " },\n" + + " \"bizId\": \"banner-myae-1-746877468\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"background-color\": \"#ffc1c1\"\n" + + " },\n" + + " \"isTest\": false\n" + + " }\n" + + " ]\n" + + " },\n" + + " {\n" + + " \"@type\": \"floorV2\",\n" + + " \"templateId\": \"base\",\n" + + " \"image\": \"http://xxx\",\n" + + " \"fields\": [\n" + + " {\n" + + " \"index\": 0,\n" + + " \"value\": \"xxxx\",\n" + + " \"type\": \"text\",\n" + + " \"track\": {\n" + + " \"name\": \"track name\",\n" + + " \"params\": {\n" + + " \"trackParam1\": \"trackParam1\"\n" + + " }\n" + + " },\n" + + " \"extInfo\": {\n" + + " \"likeByMe\": \"true\",\n" + + " \"isFollowed\": \"true\"\n" + + " },\n" + + " \"action\": {\n" + + " \"type\": \"click\",\n" + + " \"action\": \"aecmd://nativie/invokeApi?name=key1&likeId=111&likeByMe=true\"\n" + + " }\n" + + " }\n" + + " ],\n" + + " \"bizId\": \"banner-myae-1-746877468\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"background-color\": \"#000000\"\n" + + " },\n" + + " \"isTest\": false\n" + + " },\n" + + " {\n" + + " \"@type\": \"floorV2\",\n" + + " \"templateId\": \"base\",\n" + + " \"image\": \"http://xxx\",\n" + + " \"fields\": [\n" + + " {\n" + + " \"index\": 0,\n" + + " \"value\": \"xxxx\",\n" + + " \"type\": \"text\",\n" + + " \"track\": {\n" + + " \"name\": \"track name\",\n" + + " \"params\": {\n" + + " \"trackParam1\": \"trackParam1\"\n" + + " }\n" + + " },\n" + + " \"action\": {\n" + + " \"type\": \"click\",\n" + + " \"action\": \"aecmd://xxxx\"\n" + + " }\n" + + " }\n" + + " ],\n" + + " \"extInfo\": {\n" + + " \"likeByMe\": \"true\"\n" + + " },\n" + + " \"bizId\": \"banner-myae-1-746877468\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"background-color\": \"#ffc1c1\"\n" + + " },\n" + + " \"isTest\": false\n" + + " }\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"version\": 3,\n" + + " \"currency\": \"RUB\"\n" + + " }"; + + static String floordata = "{\n" + + " \"isTest\": true,\n" + + " \"mockResult\": {\n" + + " \"body\": {\n" + + " \"areas\": [\n" + + " {\n" + + " \"@type\": \"section\",\n" + + " \"templateId\": \"grid\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"column-count\":\"2\",\n" + + " \"aspect-ratio\":\"2\",\n" + + " \"margins\":\"16 0 16 16\",\n" + + " \"background-color\": \"#ffffff\",\n" + + " \"column-gap\": \"10\"\n" + + " },\n" + + " \"children\": [\n" + + " {\n" + + " \"@type\": \"section\",\n" + + " \"templateId\": \"grid\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"column-count\":\"2\",\n" + + " \"aspect-ratio\":\"2\",\n" + + " \"margins\":\"16 0 16 16\",\n" + + " \"background-color\": \"#ffffff\",\n" + + " \"column-gap\": \"10\"\n" + + " },\n" + + " \"children\": [\n" + + " {\n" + + " \"@type\": \"floorV2\",\n" + + " \"templateId\": \"base\",\n" + + " \"image\": \"http://xxx\",\n" + + " \"fields\": [\n" + + " {\n" + + " \"index\": 0,\n" + + " \"value\": \"xxxx\",\n" + + " \"type\": \"text\",\n" + + " \"track\": {\n" + + " \"name\": \"track name\",\n" + + " \"params\": {\n" + + " \"trackParam1\": \"trackParam1\"\n" + + " }\n" + + " },\n" + + " \"extInfo\": {\n" + + " \"likeByMe\": \"true\",\n" + + " \"isFollowed\": \"true\"\n" + + " },\n" + + " \"action\": {\n" + + " \"type\": \"click\",\n" + + " \"action\": \"aecmd://nativie/invokeApi?name=key1&likeId=111&likeByMe=true\"\n" + + " }\n" + + " }\n" + + " ],\n" + + " \"bizId\": \"banner-myae-1-746877468\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"background-color\": \"#000000\"\n" + + " },\n" + + " \"isTest\": false\n" + + " },\n" + + " {\n" + + " \"@type\": \"floorV2\",\n" + + " \"templateId\": \"base\",\n" + + " \"image\": \"http://xxx\",\n" + + " \"fields\": [\n" + + " {\n" + + " \"index\": 0,\n" + + " \"value\": \"xxxx\",\n" + + " \"type\": \"text\",\n" + + " \"track\": {\n" + + " \"name\": \"track name\",\n" + + " \"params\": {\n" + + " \"trackParam1\": \"trackParam1\"\n" + + " }\n" + + " },\n" + + " \"action\": {\n" + + " \"type\": \"click\",\n" + + " \"action\": \"aecmd://xxxx\"\n" + + " }\n" + + " }\n" + + " ],\n" + + " \"extInfo\": {\n" + + " \"likeByMe\": \"true\"\n" + + " },\n" + + " \"bizId\": \"banner-myae-1-746877468\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"background-color\": \"#ffc1c1\"\n" + + " },\n" + + " \"isTest\": false\n" + + " }\n" + + " ]\n" + + " },\n" + + " {\n" + + " \"@type\": \"floorV2\",\n" + + " \"templateId\": \"base\",\n" + + " \"image\": \"http://xxx\",\n" + + " \"fields\": [\n" + + " {\n" + + " \"index\": 0,\n" + + " \"value\": \"xxxx\",\n" + + " \"type\": \"text\",\n" + + " \"track\": {\n" + + " \"name\": \"track name\",\n" + + " \"params\": {\n" + + " \"trackParam1\": \"trackParam1\"\n" + + " }\n" + + " },\n" + + " \"extInfo\": {\n" + + " \"likeByMe\": \"true\",\n" + + " \"isFollowed\": \"true\"\n" + + " },\n" + + " \"action\": {\n" + + " \"type\": \"click\",\n" + + " \"action\": \"aecmd://nativie/invokeApi?name=key1&likeId=111&likeByMe=true\"\n" + + " }\n" + + " }\n" + + " ],\n" + + " \"bizId\": \"banner-myae-1-746877468\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"background-color\": \"#000000\"\n" + + " },\n" + + " \"isTest\": false\n" + + " },\n" + + " {\n" + + " \"@type\": \"floorV2\",\n" + + " \"templateId\": \"base\",\n" + + " \"image\": \"http://xxx\",\n" + + " \"fields\": [\n" + + " {\n" + + " \"index\": 0,\n" + + " \"value\": \"xxxx\",\n" + + " \"type\": \"text\",\n" + + " \"track\": {\n" + + " \"name\": \"track name\",\n" + + " \"params\": {\n" + + " \"trackParam1\": \"trackParam1\"\n" + + " }\n" + + " },\n" + + " \"action\": {\n" + + " \"type\": \"click\",\n" + + " \"action\": \"aecmd://xxxx\"\n" + + " }\n" + + " }\n" + + " ],\n" + + " \"extInfo\": {\n" + + " \"likeByMe\": \"true\"\n" + + " },\n" + + " \"bizId\": \"banner-myae-1-746877468\",\n" + + " \"style\": {\n" + + " \"card\" : \"true\",\n" + + " \"background-color\": \"#ffc1c1\"\n" + + " },\n" + + " \"isTest\": false\n" + + " }\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"version\": 3,\n" + + " \"currency\": \"RUB\"\n" + + " },\n" + + " \"head\": {\n" + + " \"message\": \"\",\n" + + " \"serverTime\": 1489473042814,\n" + + " \"code\": \"200\",\n" + + " \"ab\": \"yepxf_B\"\n" + + " }\n" + + "}\n" + + "}"; + + public void test_for_issue() throws Exception { + ParserConfig.getGlobalInstance().putDeserializer(Area.class, new ObjectDeserializer() { + + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + JSONObject jsonObject = (JSONObject) parser.parse(); + String areaType; + + if (jsonObject.get("type") instanceof String) { + areaType = (String) jsonObject.get("type"); + } else { + return null; + } + if (Area.TYPE_SECTION.equals(areaType)) { + String text = jsonObject.toJSONString(); + return (T) JSON.parseObject(text, Section.class); + } else if (Area.TYPE_FLOORV1.equals(areaType)) { + String text = jsonObject.toJSONString(); + return (T) JSON.parseObject(text, FloorV1.class); + } else if (Area.TYPE_FLOORV2.equals(areaType)) { + String text = jsonObject.toJSONString(); + return (T) JSON.parseObject(text, FloorV2.class); + } + + return null; + } + + public int getFastMatchToken() { + return JSONToken.LBRACE; + } + }); + + ParserConfig.getGlobalInstance().addAccept("section"); + ParserConfig.getGlobalInstance().addAccept("floorV2"); + + + MockResult data = JSON.parseObject(floordata, MockResult.class); + String mockResultJson = JSON.toJSONString(data.mockResult); + NetResponse response = JSON.parseObject(mockResultJson, NetResponse.class); + + String bodyJson = JSON.toJSONString(response.body); + System.out.println(bodyJson); + FloorPageData pageData = JSON.parseObject(bodyJson, FloorPageData.class); + assertNotNull(pageData.areas); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/AETest.java b/src/test/java/com/alibaba/json/bvt/parser/AETest.java new file mode 100644 index 0000000000..c34a37d582 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/AETest.java @@ -0,0 +1,72 @@ +package com.alibaba.json.bvt.parser; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.json.bvtVO.ae.*; +import junit.framework.TestCase; + +import java.lang.reflect.Type; +import java.util.Arrays; + +/** + * Created by wenshao on 08/05/2017. + */ +public class AETest extends TestCase { + static String jsonData = "{\n" + + " \"areaList\":[\n" + + " {\n" + + " \"type\":\"floor\",\n" + + " \"name\":\"I'm floor\",\n" + + " \"children\":[{\n" + + " \"type\":\"item\",\n" + + " \"name\":\"I'm item 0\"\n" + + " },\n" + + " {\n" + + " \"type\":\"item\",\n" + + " \"name\":\"I'm item 1\"\n" + + " }\n" + + "\n" + + " ]\n" + + " },{\n" + + " \"type\":\"item\",\n" + + " \"name\":\"I'm item 2\"\n" + + " }\n" + + " ]\n" + + "}"; + + public void test_for_ae() throws Exception { + ParserConfig.getGlobalInstance().putDeserializer(Area.class, new ObjectDeserializer() { + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + JSONObject jsonObject = (JSONObject) parser.parse(); + String areaType; + + if (jsonObject.get("type") instanceof String) { + areaType = (String) jsonObject.get("type"); + } else { + return null; + } + if (Area.TYPE_FLOOR.equals(areaType)) { + return (T) JSON.toJavaObject(jsonObject, Floor.class); + } else if (Area.TYPE_ITEM.equals(areaType)) { + return (T) JSON.toJavaObject(jsonObject, Item.class); + } + + return null; + } + + public int getFastMatchToken() { + return JSONToken.LBRACE; + } + }); + + + Data data = JSON.parseObject(jsonData, Data.class); + + Item item = (Item) ((Floor)(data.areaList.get(0))).children.get(0); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/Alipay1213.java b/src/test/java/com/alibaba/json/bvt/parser/Alipay1213.java new file mode 100644 index 0000000000..3c9a031f00 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/Alipay1213.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.parser; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; +import org.apache.commons.io.FileUtils; + +import java.io.File; + +/** + * Created by wenshao on 13/12/2016. + */ +public class Alipay1213 extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"resultObj\":{\"assetSize\":{},\"chargeTypeList\":[\"A\"],\"fundManagerMapList\":[{},{}],\"fundRateConvertList\":[{},{},{}],\"fundRateOperate\":{},\"fundRatePurchaseList\":[{\"fixedRate\":{},\"maxAmount\":{},\"minAmount\":{}}],\"fundRateRedeemList\":[{\"fixedRate\":{}}],\"fundRateSubscribeList\":[{\"fixedRate\":{},\"maxAmount\":{},\"minAmount\":{}}],\"fundRatingList\":[{},{}],\"fundRuleConvertList\":[{},{}],\"fundRuleConvertVoList\":[{\"fundRateConvertList\":[{\"$ref\":\"$.resultObj.fundRateConvertList[0]\"},{\"$ref\":\"$.resultObj.fundRateConvertList[1]\"}],\"fundRuleConvert\":{\"$ref\":\"$.resultObj.fundRuleConvertList[0]\"}},{\"fundRateConvertList\":[{\"$ref\":\"$.resultObj.fundRateConvertList[2]\"}],\"fundRuleConvert\":{\"$ref\":\"$.resultObj.fundRuleConvertList[1]\"}}]}}"; + JSONObject root = JSON.parseObject(text); + + JSONObject resultObj = root.getJSONObject("resultObj"); + assertNotNull(resultObj); + + JSONArray fundRuleConvertVoList = resultObj.getJSONArray("fundRuleConvertVoList"); + assertNotNull(fundRuleConvertVoList); + + JSONArray fundRateConvertList = fundRuleConvertVoList.getJSONObject(0).getJSONArray("fundRateConvertList"); + assertNotNull(fundRateConvertList); + + assertNotNull(fundRateConvertList.get(0)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/AmbiguousTest.java b/src/test/java/com/alibaba/json/bvt/parser/AmbiguousTest.java new file mode 100644 index 0000000000..b25441c048 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/AmbiguousTest.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 16/8/31. + */ +public class AmbiguousTest extends TestCase { + public void test_for_issue() throws Exception { + String text = "{\"items\":{\"id\":101}}"; + Model model = JSON.parseObject(text, Model.class); + assertEquals(1, model.items.size()); + } + + public static class Model { + public List items; + } + + public static class Item { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/AsmParserTest0.java b/src/test/java/com/alibaba/json/bvt/parser/AsmParserTest0.java new file mode 100755 index 0000000000..6e01e79ad4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/AsmParserTest0.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class AsmParserTest0 extends TestCase { + + public void test_asm() throws Exception { + A a = JSON.parseObject("{\"f1\":123}", A.class); + Assert.assertNotNull(a.getF2()); + } + + public static class A { + + private int f1; + + private B f2 = new B(); + + public int getF1() { + return f1; + } + + public void setF1(int f1) { + this.f1 = f1; + } + + public B getF2() { + return f2; + } + + public void setF2(B f2) { + this.f2 = f2; + } + + } + + public static class B { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/AsmParserTest1.java b/src/test/java/com/alibaba/json/bvt/parser/AsmParserTest1.java new file mode 100755 index 0000000000..e30b37054c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/AsmParserTest1.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.parser; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class AsmParserTest1 extends TestCase { + + public void test_asm() throws Exception { + A a = JSON.parseObject("{\"f1\":123}", A.class); + Assert.assertEquals(123, a.getF1()); + Assert.assertNotNull(a.getF2()); + } + + public static class A { + + private int f1; + + private List f2 = new ArrayList(); + + public int getF1() { + return f1; + } + + public void setF1(int f1) { + this.f1 = f1; + } + + + public List getF2() { + return f2; + } + + + public void setF2(List f2) { + this.f2 = f2; + } + + } + + public static class B { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/AtomicIntegerComptableAndroidTest.java b/src/test/java/com/alibaba/json/bvt/parser/AtomicIntegerComptableAndroidTest.java new file mode 100644 index 0000000000..d8e2f7b244 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/AtomicIntegerComptableAndroidTest.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.parser; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +/** + * Created by wenshao on 20/03/2017. + */ +public class AtomicIntegerComptableAndroidTest extends TestCase { + public void test_for_compatible_zero() throws Exception { + String text = "{\"andIncrement\":-1,\"andDecrement\":0}"; + + assertEquals(0, JSON.parseObject(text, AtomicInteger.class).intValue()); + } + + public void test_for_compatible_six() throws Exception { + String text = "{\"andIncrement\":5,\"andDecrement\":6}"; + + assertEquals(6, JSON.parseObject(text, AtomicInteger.class).intValue()); + } + + public void test_for_compatible_five() throws Exception { + String text = "{\"andDecrement\":6,\"andIncrement\":5}"; + + assertEquals(5, JSON.parseObject(text, AtomicInteger.class).intValue()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/AtomicLongComptableAndroidTest.java b/src/test/java/com/alibaba/json/bvt/parser/AtomicLongComptableAndroidTest.java new file mode 100644 index 0000000000..a295afcbd0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/AtomicLongComptableAndroidTest.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.parser; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +/** + * Created by wenshao on 20/03/2017. + */ +public class AtomicLongComptableAndroidTest extends TestCase { + public void test_for_compatible_zero() throws Exception { + String text = "{\"andIncrement\":-1,\"andDecrement\":0}"; + + assertEquals(0, JSON.parseObject(text, AtomicLong.class).intValue()); + } + + public void test_for_compatible_six() throws Exception { + String text = "{\"andIncrement\":5,\"andDecrement\":6}"; + + assertEquals(6, JSON.parseObject(text, AtomicLong.class).intValue()); + } + + public void test_for_compatible_five() throws Exception { + String text = "{\"andDecrement\":6,\"andIncrement\":5}"; + + assertEquals(5, JSON.parseObject(text, AtomicLong.class).intValue()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/BigDecimalKeyFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/BigDecimalKeyFieldTest.java new file mode 100644 index 0000000000..3d4a6173df --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/BigDecimalKeyFieldTest.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.parser; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class BigDecimalKeyFieldTest extends TestCase { + public void test_for_bigdecimal_key() throws Exception { + Map obj = JSON.parseObject("{1234.56:\"abc\"}", HashMap.class); + Map.Entry entry = obj.entrySet().iterator().next(); + Assert.assertEquals("abc", entry.getValue()); + Assert.assertEquals(new BigDecimal("1234.56"), entry.getKey()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/BigListStringFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/BigListStringFieldTest.java new file mode 100644 index 0000000000..e13190625d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/BigListStringFieldTest.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class BigListStringFieldTest extends TestCase { + public void test_list() throws Exception { + Model model = new Model(); + model.values = new ArrayList(10000); + for (int i = 0; i < 10000; ++i) { + String value = random(100); + model.values.add(value); + } + String text = JSON.toJSONString(model); + Model model2 = JSON.parseObject(text, Model.class); + + Assert.assertEquals(model.values, model2.values); + } + public static class Model { + public List values; + } + + public String random(int count) { + Random random = new Random(); + + char[] chars = new char[count]; + for (int i = 0; i < count; ++i) { + chars[i] = (char) random.nextInt(); + } + + return new String(chars); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/BigListStringFieldTest_private.java b/src/test/java/com/alibaba/json/bvt/parser/BigListStringFieldTest_private.java new file mode 100644 index 0000000000..1cf78daf74 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/BigListStringFieldTest_private.java @@ -0,0 +1,71 @@ +package com.alibaba.json.bvt.parser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class BigListStringFieldTest_private extends TestCase { + public void test_list() throws Exception { + Model model = new Model(); + model.values = new ArrayList(10000); + for (int i = 0; i < 10000; ++i) { + String value = random(100); + model.values.add(value); + } + String text = JSON.toJSONString(model); + Model model2 = JSON.parseObject(text, Model.class); + + Assert.assertEquals(model.values, model2.values); + } + + public void test_list_browserComptible() throws Exception { + Model model = new Model(); + model.values = new ArrayList(10000); + for (int i = 0; i < 10000; ++i) { + String value = random(100); + model.values.add(value); + } + String text = JSON.toJSONString(model, SerializerFeature.BrowserCompatible); + Model model2 = JSON.parseObject(text, Model.class); + + Assert.assertEquals(model.values, model2.values); + } + + public void test_list_browserSecure() throws Exception { + Model model = new Model(); + model.values = new ArrayList(10000); + for (int i = 0; i < 10000; ++i) { + String value = random(100); + model.values.add(value); + } + String text = JSON.toJSONString(model, SerializerFeature.BrowserSecure); + + text = text.replaceAll("<", "<"); + text = text.replaceAll(">", ">"); + Model model2 = JSON.parseObject(text, Model.class); + + Assert.assertEquals(model.values, model2.values); + } + + private static class Model { + public List values; + } + + public String random(int count) { + Random random = new Random(); + + char[] chars = new char[count]; + for (int i = 0; i < count; ++i) { + chars[i] = (char) random.nextInt(256); + } + + return new String(chars); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/BigSpecailKeyTest.java b/src/test/java/com/alibaba/json/bvt/parser/BigSpecailKeyTest.java new file mode 100644 index 0000000000..ce4e54b125 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/BigSpecailKeyTest.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.parser; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class BigSpecailKeyTest extends TestCase { + public void test_big_special_key() throws Exception { + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < 16; ++i) { + buf.append('\\'); + buf.append('\"'); + char[] chars = new char[1024]; + Arrays.fill(chars, '0'); + buf.append(chars); + } + + String key = buf.toString(); + + Map map = new HashMap(); + map.put(key, 1001); + + String text = JSON.toJSONString(map); + JSONObject obj = JSON.parseObject(text); + Assert.assertEquals(map.get(key), obj.get(key)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/BigSpecailKeyTest2.java b/src/test/java/com/alibaba/json/bvt/parser/BigSpecailKeyTest2.java new file mode 100644 index 0000000000..52e9790b01 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/BigSpecailKeyTest2.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.parser; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class BigSpecailKeyTest2 extends TestCase { + public void test_big_special_key() throws Exception { + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < 16; ++i) { + char[] chars = new char[2048]; + Arrays.fill(chars, '0'); + buf.append(chars); + + buf.append('\\'); + buf.append('\"'); + } + + String key = buf.toString(); + + Map map = new HashMap(); + map.put(key, 1001); + + String text = JSON.toJSONString(map); + JSONObject obj = JSON.parseObject(text); + Assert.assertEquals(map.get(key), obj.get(key)); + } + + public void test_big_special_key_2() throws Exception { + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < 16; ++i) { + char[] chars = new char[300]; + Arrays.fill(chars, '0'); + buf.append(chars); + + buf.append('\\'); + buf.append('\"'); + } + + String key = buf.toString(); + + Map map = new HashMap(); + map.put(key, 1001); + + String text = JSON.toJSONString(map); + JSONObject obj = JSON.parseObject(text); + Assert.assertEquals(map.get(key), obj.get(key)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/BigSpecailStringTest.java b/src/test/java/com/alibaba/json/bvt/parser/BigSpecailStringTest.java new file mode 100644 index 0000000000..0f8b7ecf8d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/BigSpecailStringTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.parser; + +import java.util.Arrays; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class BigSpecailStringTest extends TestCase { + public void test_big_special_key() throws Exception { + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < 16; ++i) { + buf.append('\\'); + buf.append('\"'); + char[] chars = new char[1024]; + Arrays.fill(chars, '0'); + buf.append(chars); + } + + String text = buf.toString(); + + String json = JSON.toJSONString(text); + + String text2 = (String) JSON.parse(json); + Assert.assertEquals(text, text2); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest.java new file mode 100644 index 0000000000..8ad8b37822 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest.java @@ -0,0 +1,73 @@ +package com.alibaba.json.bvt.parser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class BigStringFieldTest extends TestCase { + public void test_bigFieldString() throws Exception { + Model model = new Model(); + model.f0 = random(1024); + model.f1 = random(1024); + model.f2 = random(1024); + model.f3 = random(1024); + model.f4 = random(1024); + + String text = JSON.toJSONString(model); + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model2.f0, model.f0); + Assert.assertEquals(model2.f1, model.f1); + Assert.assertEquals(model2.f2, model.f2); + Assert.assertEquals(model2.f3, model.f3); + Assert.assertEquals(model2.f4, model.f4); + } + + public void test_list() throws Exception { + List list = new ArrayList(); + for (int i = 0; i < 1000; ++i) { + Model model = new Model(); + model.f0 = random(64); + model.f1 = random(64); + model.f2 = random(64); + model.f3 = random(64); + model.f4 = random(64); + list.add(model); + } + String text = JSON.toJSONString(list); + List list2 = JSON.parseObject(text, new TypeReference>() {}); + Assert.assertEquals(list.size(), list2.size()); + for (int i = 0; i < 1000; ++i) { + Assert.assertEquals(list.get(i).f0, list2.get(i).f0); + Assert.assertEquals(list.get(i).f1, list2.get(i).f1); + Assert.assertEquals(list.get(i).f2, list2.get(i).f2); + Assert.assertEquals(list.get(i).f3, list2.get(i).f3); + Assert.assertEquals(list.get(i).f4, list2.get(i).f4); + } + } + + public String random(int count) { + Random random = new Random(); + + char[] chars = new char[count]; + for (int i = 0; i < count; ++i) { + chars[i] = (char) random.nextInt(); + } + + return new String(chars); + } + + public static class Model { + public String f0; + public String f1; + public String f2; + public String f3; + public String f4; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest_private.java b/src/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest_private.java new file mode 100644 index 0000000000..e6c811ceb2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest_private.java @@ -0,0 +1,98 @@ +package com.alibaba.json.bvt.parser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class BigStringFieldTest_private extends TestCase { + public void test_bigFieldString() throws Exception { + Model model = new Model(); + model.f0 = random(1024); + model.f1 = random(1024); + model.f2 = random(1024); + model.f3 = random(1024); + model.f4 = random(1024); + + String text = JSON.toJSONString(model); + Model model2 = JSON.parseObject(text, Model.class); + assertEquals(model2.f0, model.f0); + assertEquals(model2.f1, model.f1); + assertEquals(model2.f2, model.f2); + assertEquals(model2.f3, model.f3); + assertEquals(model2.f4, model.f4); + } + + public void test_list() throws Exception { + List list = new ArrayList(); + for (int i = 0; i < 1000; ++i) { + Model model = new Model(); + model.f0 = random(64); + model.f1 = random(64); + model.f2 = random(64); + model.f3 = random(64); + model.f4 = random(64); + list.add(model); + } + String text = JSON.toJSONString(list); + List list2 = JSON.parseObject(text, new TypeReference>() {}); + assertEquals(list.size(), list2.size()); + for (int i = 0; i < 1000; ++i) { + assertEquals(list.get(i).f0, list2.get(i).f0); + assertEquals(list.get(i).f1, list2.get(i).f1); + assertEquals(list.get(i).f2, list2.get(i).f2); + assertEquals(list.get(i).f3, list2.get(i).f3); + assertEquals(list.get(i).f4, list2.get(i).f4); + } + } + + public void test_list_browserSecure() throws Exception { + List list = new ArrayList(); + for (int i = 0; i < 1000; ++i) { + Model model = new Model(); + model.f0 = random(64); + model.f1 = random(64); + model.f2 = random(64); + model.f3 = random(64); + model.f4 = random(64); + list.add(model); + } + String text = JSON.toJSONString(list, SerializerFeature.BrowserSecure); + + List list2 = JSON.parseObject(text, new TypeReference>() {}); + assertEquals(list.size(), list2.size()); + for (int i = 0; i < 1000; ++i) { + assertEquals(list.get(i).f0, list2.get(i).f0); + assertEquals(list.get(i).f1, list2.get(i).f1); + assertEquals(list.get(i).f2, list2.get(i).f2); + assertEquals(list.get(i).f3, list2.get(i).f3); + assertEquals(list.get(i).f4, list2.get(i).f4); + } + } + + public String random(int count) { + Random random = new Random(); + + char[] chars = new char[count]; + for (int i = 0; i < count; ++i) { + chars[i] = (char) random.nextInt(); + } + + return new String(chars); + } + + private static class Model { + public String f0; + public String f1; + public String f2; + public String f3; + public String f4; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ClassTest.java b/src/test/java/com/alibaba/json/bvt/parser/ClassTest.java new file mode 100755 index 0000000000..eebbce77fa --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ClassTest.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.parser; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class ClassTest extends TestCase { + + public void test_class_array() throws Exception { + String text = "{\"clazz\":\"[Ljava.lang.String;\",\"value\":\"[\\\"武汉银行\\\"]\"}"; + + VO vo = JSON.parseObject(text, VO.class); + + Assert.assertEquals(String[].class, vo.getClazz()); + } + + public void test_class() throws Exception { + String text = "{\"clazz\":\"Ljava.lang.String;\",\"value\":\"[\\\"武汉银行\\\"]\"}"; + + VO vo = JSON.parseObject(text, VO.class); + Assert.assertEquals(String.class, vo.getClazz()); + } + + public static class VO { + + private Class clazz; + private Object value; + + public Class getClazz() { + return clazz; + } + + public void setClazz(Class clazz) { + this.clazz = clazz; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/CommentTest.java b/src/test/java/com/alibaba/json/bvt/parser/CommentTest.java new file mode 100644 index 0000000000..4da56aa1b9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/CommentTest.java @@ -0,0 +1,75 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class CommentTest extends TestCase { + + public void test_0() throws Exception { + String text = "{ // aa" // + + "\n}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(0, obj.size()); + } + + public void test_1() throws Exception { + String text = "{ // aa" // + + "\n\"value\":1001}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(1, obj.size()); + Assert.assertEquals(1001, obj.get("value")); + } + + public void test_2() throws Exception { + String text = "{ /* aa */ \"value\":1001}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(1, obj.size()); + Assert.assertEquals(1001, obj.get("value")); + } + + public void test_3() throws Exception { + String text = "{ \"value\":/* aa */1001}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(1, obj.size()); + Assert.assertEquals(1001, obj.get("value")); + } + + public void test_4() throws Exception { + String text = "{ \"value\":1001/* aa */}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(1, obj.size()); + Assert.assertEquals(1001, obj.get("value")); + } + + public void test_5() throws Exception { + Exception error = null; + try { + String text = "{ \"value\":1001/ * aa */}"; + JSON.parse(text); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_6() throws Exception { + String text = "{'a':1, 'b':2 /***/ }"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(2, obj.size()); + Assert.assertEquals(1, obj.get("a")); + Assert.assertEquals(2, obj.get("b")); + } + + public void test_7() throws Exception { + String text = "{'a':1, 'b':2 /**/ }"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(2, obj.size()); + Assert.assertEquals(1, obj.get("a")); + Assert.assertEquals(2, obj.get("b")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/CreateInstanceErrorTest.java b/src/test/java/com/alibaba/json/bvt/parser/CreateInstanceErrorTest.java new file mode 100644 index 0000000000..44459ce721 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/CreateInstanceErrorTest.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class CreateInstanceErrorTest extends TestCase { + + public void test_ordered_field() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"id\":1001}", Model.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public Model(){ + throw new UnsupportedOperationException(); + } + + public int id; + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/CreateInstanceErrorTest2.java b/src/test/java/com/alibaba/json/bvt/parser/CreateInstanceErrorTest2.java new file mode 100644 index 0000000000..2532930917 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/CreateInstanceErrorTest2.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser; + +import java.util.HashMap; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class CreateInstanceErrorTest2 extends TestCase { + + public void test_ordered_field() throws Exception { + Exception error = null; + try { + Model model = JSON.parseObject("{\"value\":{\"@type\":\"com.alibaba.json.bvt.parser.CreateInstanceErrorTest2$MyMap\"}}", Model.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public Object value; + } + + public static class MyMap extends HashMap { + public MyMap(){ + throw new UnsupportedOperationException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/DateParserTest.java b/src/test/java/com/alibaba/json/bvt/parser/DateParserTest.java new file mode 100755 index 0000000000..102261c2cb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/DateParserTest.java @@ -0,0 +1,137 @@ +package com.alibaba.json.bvt.parser; + +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; + +public class DateParserTest extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date_new() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("new Date(1294552193254)"); + + java.util.Date date = parser.parseObject(java.util.Date.class); + + Assert.assertEquals(new java.util.Date(1294552193254L), date); + parser.close(); + } + + public void test_date_new_1() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("new Date(1294552193254)"); + + java.util.Date date = (java.util.Date) parser.parse(); + + Assert.assertEquals(new java.util.Date(1294552193254L), date); + parser.close(); + } + + public void test_date_0() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("1294552193254"); + + java.util.Date date = parser.parseObject(java.util.Date.class); + + Assert.assertEquals(new java.util.Date(1294552193254L), date); + parser.close(); + } + + public void test_date_1() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + features = Feature.config(features, Feature.AllowISO8601DateFormat, true); + DefaultJSONParser parser = new DefaultJSONParser("\"2011-01-09T13:49:53.254\"", ParserConfig.getGlobalInstance(), features); + + java.util.Date date = parser.parseObject(java.util.Date.class); + + Assert.assertEquals(new java.util.Date(1294552193254L), date); + parser.close(); + } + + public void test_date_2() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + DefaultJSONParser parser = new DefaultJSONParser("new Date(1294552193254)", ParserConfig.getGlobalInstance(), features); + + java.util.Date date = parser.parseObject(java.util.Date.class); + + Assert.assertEquals(new java.util.Date(1294552193254L), date); + parser.close(); + } + + public void test_date_3() throws Exception { + java.util.Date date = JSON.parseObject("\"2011-01-09T13:49:53\"", java.util.Date.class, Feature.AllowISO8601DateFormat); + + Assert.assertEquals(new java.util.Date(1294552193000L), date); + } + + public void test_date_4() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + features = Feature.config(features, Feature.AllowISO8601DateFormat, true); + DefaultJSONParser parser = new DefaultJSONParser("\"2011-01-09\"", ParserConfig.getGlobalInstance(), features); + + java.util.Date date = parser.parseObject(java.util.Date.class); + + Assert.assertEquals(new java.util.Date(1294502400000L), date); + parser.close(); + } + + public void test_date_5() throws Exception { + JSONObject object = JSON.parseObject("{d:'2011-01-09T13:49:53'}", Feature.AllowISO8601DateFormat); + Assert.assertEquals(new java.util.Date(1294552193000L), object.get("d")); + } + + public void test_date_6() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + features = Feature.config(features, Feature.AllowISO8601DateFormat, true); + + java.util.Date date = JSON.parseObject("{d:\"2011-01-09T13:49:53\"}", Entity.class, Feature.AllowISO8601DateFormat).getD(); + + Assert.assertEquals(new java.util.Date(1294552193000L), date); + } + + public void test_date_7() throws Exception { + Entity entity = JSON.parseObject("{d:'2011-01-09T13:49:53'}", Entity.class, Feature.AllowISO8601DateFormat); + java.util.Date date = entity.getD(); + + Assert.assertEquals(new java.util.Date(1294552193000L), date); + } + + public void test_date_error_0() throws Exception { + + JSONException error = null; + try { + DefaultJSONParser parser = new DefaultJSONParser("true"); + + parser.parseObject(java.util.Date.class); + parser.close(); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } + + public static class Entity { + + private Date d; + + public Date getD() { + return d; + } + + public void setD(Date d) { + this.d = d; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/DateParserTest_sql.java b/src/test/java/com/alibaba/json/bvt/parser/DateParserTest_sql.java new file mode 100755 index 0000000000..f61d2728d8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/DateParserTest_sql.java @@ -0,0 +1,67 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; + +@SuppressWarnings("deprecation") +public class DateParserTest_sql extends TestCase { + + public void f_test_date_0() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("1294552193254"); + + java.sql.Date date = parser.parseObject(java.sql.Date.class); + + Assert.assertEquals(new java.sql.Date(1294552193254L), date); + + parser.close(); + } + + public void test_date_1() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + features = Feature.config(features, Feature.AllowISO8601DateFormat, true); + DefaultJSONParser parser = new DefaultJSONParser("\"2011-01-09T13:49:53.254\"", ParserConfig.getGlobalInstance(), features); + + java.sql.Date date = parser.parseObject(java.sql.Date.class); + + Assert.assertEquals(new java.sql.Date(1294552193254L), date); + parser.close(); + } + + public void test_date_2() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + DefaultJSONParser parser = new DefaultJSONParser("new Date(1294552193254)", ParserConfig.getGlobalInstance(), features); + + java.sql.Date date = parser.parseObject(java.sql.Date.class); + + Assert.assertEquals(new java.sql.Date(1294552193254L), date); + parser.close(); + } + + public void test_date_3() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + features = Feature.config(features, Feature.AllowISO8601DateFormat, true); + DefaultJSONParser parser = new DefaultJSONParser("\"2011-01-09T13:49:53\"", ParserConfig.getGlobalInstance(), features); + + java.sql.Date date = parser.parseObject(java.sql.Date.class); + + Assert.assertEquals(new java.sql.Date(1294552193000L), date); + parser.close(); + } + + public void test_date_4() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + features = Feature.config(features, Feature.AllowISO8601DateFormat, true); + DefaultJSONParser parser = new DefaultJSONParser("\"2011-01-09\"", ParserConfig.getGlobalInstance(), features); + + java.sql.Date date = parser.parseObject(java.sql.Date.class); + + Assert.assertEquals(new java.sql.Date(1294502400000L), date); + parser.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/DateParserTest_sql_timestamp.java b/src/test/java/com/alibaba/json/bvt/parser/DateParserTest_sql_timestamp.java new file mode 100755 index 0000000000..cedea5b8c2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/DateParserTest_sql_timestamp.java @@ -0,0 +1,73 @@ +package com.alibaba.json.bvt.parser; + +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; + +@SuppressWarnings("deprecation") +public class DateParserTest_sql_timestamp extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void f_test_date_0() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("1294552193254"); + + java.sql.Timestamp date = parser.parseObject(java.sql.Timestamp.class); + + Assert.assertEquals(new java.sql.Timestamp(1294552193254L), date); + parser.close(); + } + + public void test_date_1() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + features = Feature.config(features, Feature.AllowISO8601DateFormat, true); + DefaultJSONParser parser = new DefaultJSONParser("\"2011-01-09T13:49:53.254\"", ParserConfig.getGlobalInstance(), features); + + java.sql.Timestamp date = parser.parseObject(java.sql.Timestamp.class); + + Assert.assertEquals(new java.sql.Timestamp(1294552193254L), date); + parser.close(); + } + + public void test_date_2() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + DefaultJSONParser parser = new DefaultJSONParser("new Date(1294552193254)", ParserConfig.getGlobalInstance(), features); + + java.sql.Timestamp date = parser.parseObject(java.sql.Timestamp.class); + + Assert.assertEquals(new java.sql.Timestamp(1294552193254L), date); + parser.close(); + } + + public void test_date_3() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + features = Feature.config(features, Feature.AllowISO8601DateFormat, true); + DefaultJSONParser parser = new DefaultJSONParser("\"2011-01-09T13:49:53\"", ParserConfig.getGlobalInstance(), features); + + java.sql.Timestamp date = parser.parseObject(java.sql.Timestamp.class); + + Assert.assertEquals(new java.sql.Timestamp(1294552193000L), date); + parser.close(); + } + + public void test_date_4() throws Exception { + int features = JSON.DEFAULT_PARSER_FEATURE; + features = Feature.config(features, Feature.AllowISO8601DateFormat, true); + DefaultJSONParser parser = new DefaultJSONParser("\"2011-01-09\"", ParserConfig.getGlobalInstance(), features); + + java.sql.Timestamp date = parser.parseObject(java.sql.Timestamp.class); + + Assert.assertEquals(new java.sql.Timestamp(1294502400000L), date); + parser.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/DateTest.java b/src/test/java/com/alibaba/json/bvt/parser/DateTest.java new file mode 100755 index 0000000000..85f37a1ea4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/DateTest.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.parser; + +import java.util.Date; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class DateTest extends TestCase { + + public void test_0() throws Exception { + Assert.assertNull(JSON.parseObject("", java.sql.Date.class)); + Assert.assertNull(JSON.parseObject(null, java.sql.Date.class)); + Assert.assertNull(JSON.parseObject("null", java.sql.Date.class)); + Assert.assertNull(JSON.parseObject("\"\"", java.sql.Date.class)); + + Assert.assertNull(JSON.parseObject("", java.util.Date.class)); + Assert.assertNull(JSON.parseObject(null, java.util.Date.class)); + Assert.assertNull(JSON.parseObject("null", java.util.Date.class)); + Assert.assertNull(JSON.parseObject("\"\"", java.util.Date.class)); + + Assert.assertNull(JSON.parseObject("", java.sql.Timestamp.class)); + Assert.assertNull(JSON.parseObject(null, java.sql.Timestamp.class)); + Assert.assertNull(JSON.parseObject("null", java.sql.Timestamp.class)); + Assert.assertNull(JSON.parseObject("\"\"", java.sql.Timestamp.class)); + + Assert.assertNull(JSON.parseObject("{date:\"\"}", Entity.class).getDate()); + } + + public static class Entity { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest.java old mode 100644 new mode 100755 similarity index 89% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest.java index d4eb3e8484..857d5d2e26 --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2101 Alibaba Group. + * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import static com.alibaba.fastjson.util.TypeUtils.castToBigDecimal; import static com.alibaba.fastjson.util.TypeUtils.castToBigInteger; @@ -38,17 +38,20 @@ import java.util.List; import java.util.Map; -import junit.framework.Assert; -import junit.framework.TestCase; +import org.junit.Assert; import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.util.TypeUtils; +import junit.framework.TestCase; + public class DefaultExtJSONParserTest extends TestCase { public void test_parseObject() { + new DefaultJSONParser("".toCharArray(), 0, ParserConfig.getGlobalInstance(), 0).close(); User user = new User(); user.setName("校长"); user.setAge(3); @@ -60,7 +63,7 @@ public void test_parseObject() { JSON.parseObject(jsonString); - DefaultExtJSONParser parser = new DefaultExtJSONParser(jsonString); + DefaultJSONParser parser = new DefaultJSONParser(jsonString); User user1 = new User(); parser.parseObject(user1); @@ -77,7 +80,7 @@ public void testCastCalendar() throws Exception { public void testCast() throws Exception { new TypeUtils(); - DefaultExtJSONParser parser = new DefaultExtJSONParser(""); + DefaultJSONParser parser = new DefaultJSONParser(""); Assert.assertNull(castToByte(null)); Assert.assertNull(castToShort(null)); @@ -131,7 +134,7 @@ public void testCast() throws Exception { } public void test_casterror2() { - DefaultExtJSONParser parser = new DefaultExtJSONParser(""); + DefaultJSONParser parser = new DefaultJSONParser(""); { Exception error = null; try { @@ -225,7 +228,7 @@ public void test_casterror2() { } public void test_casterror() { - DefaultExtJSONParser parser = new DefaultExtJSONParser(""); + DefaultJSONParser parser = new DefaultJSONParser(""); { Exception error = null; @@ -327,19 +330,19 @@ public void test_parseArrayWithType() throws Exception { Type[] types = method.getGenericParameterTypes(); { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); Assert.assertEquals(true, ((List) parser.parseArrayWithType(types[0])).get(0) instanceof Map); } { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); Assert.assertEquals(true, ((List) parser.parseArrayWithType(types[1])).get(0) instanceof User); } { Exception error = null; try { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseArrayWithType(types[2]); ; } catch (Exception ex) { @@ -349,14 +352,14 @@ public void test_parseArrayWithType() throws Exception { } { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); Assert.assertEquals(true, ((List) parser.parseArrayWithType(types[3])).get(0) instanceof User); } { Exception error = null; try { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseArrayWithType(types[4]); ; } catch (Exception ex) { @@ -366,7 +369,7 @@ public void test_parseArrayWithType() throws Exception { } { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); Assert.assertEquals(true, ((List) parser.parseArrayWithType(types[5])).get(0) instanceof User); } @@ -374,7 +377,7 @@ public void test_parseArrayWithType() throws Exception { Exception error = null; try { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseArrayWithType(types[6]); ; } catch (Exception ex) { @@ -392,7 +395,7 @@ public void test_parseArrayWithType_error_1() throws Exception { Exception error = null; try { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseArrayWithType(types[6]); ; } catch (Exception ex) { @@ -409,7 +412,7 @@ public static , T1 extends User> void f public void test_not_match() throws Exception { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123, \"kxxx\":33}]"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); Assert.assertEquals(true, (parser.parseArray(User.class).get(0) instanceof User)); } @@ -417,7 +420,7 @@ public void test_not_match_error() throws Exception { Exception error = null; try { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123, \"kxxx\":33}]"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); parser.config(Feature.IgnoreNotMatch, false); Assert.assertEquals(true, (parser.parseArray(User.class).get(0) instanceof User)); } catch (Exception ex) { @@ -431,7 +434,7 @@ public void test_error() throws Exception { Exception error = null; try { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123]"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseArray(User.class); } catch (Exception ex) { error = ex; @@ -442,7 +445,7 @@ public void test_error() throws Exception { Exception error = null; try { String text = "{\"reader\":3}"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseObject(ErrorObject.class); } catch (Exception ex) { error = ex; @@ -453,7 +456,7 @@ public void test_error() throws Exception { Exception error = null; try { String text = "{\"name\":3}"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseObject(ErrorObject2.class); } catch (Exception ex) { error = ex; @@ -494,7 +497,7 @@ public void test_error2() throws Exception { Exception error = null; try { String text = "{}"; - DefaultExtJSONParser parser = new DefaultExtJSONParser(text); + DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseArray(User.class); } catch (Exception ex) { error = ex; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_0.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_0.java old mode 100644 new mode 100755 similarity index 77% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_0.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_0.java index 3a9edf234c..9b17ce0d30 --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_0.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_0.java @@ -1,13 +1,13 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.math.BigDecimal; import java.util.Date; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; public class DefaultExtJSONParserTest_0 extends TestCase { @@ -16,31 +16,31 @@ protected void setUp() throws Exception { } public void test_0() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("123"); + DefaultJSONParser parser = new DefaultJSONParser("123"); Assert.assertEquals(new Integer(123), (Integer) parser.parse()); parser.config(Feature.IgnoreNotMatch, false); } public void test_1() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[]"); + DefaultJSONParser parser = new DefaultJSONParser("[]"); parser.parseArray(Class.class); } public void test_2() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{}"); + DefaultJSONParser parser = new DefaultJSONParser("{}"); parser.parseObject(Object.class); } public void test_3() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{}"); + DefaultJSONParser parser = new DefaultJSONParser("{}"); parser.parseObject(User.class); } public void test_error_0() throws Exception { JSONException error = null; try { - DefaultExtJSONParser parser = new DefaultExtJSONParser("123"); + DefaultJSONParser parser = new DefaultJSONParser("123"); parser.parseObject(Class.class); } catch (JSONException e) { error = e; @@ -51,7 +51,7 @@ public void test_error_0() throws Exception { public void test_error_1() throws Exception { JSONException error = null; try { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[{}]"); + DefaultJSONParser parser = new DefaultJSONParser("[{}]"); parser.parseArray(Class.class); } catch (JSONException e) { error = e; @@ -62,7 +62,7 @@ public void test_error_1() throws Exception { public void test_error_2() throws Exception { JSONException error = null; try { - DefaultExtJSONParser parser = new DefaultExtJSONParser( + DefaultJSONParser parser = new DefaultJSONParser( "{\"errorValue\":33}"); parser.parseArray(User.class); } catch (JSONException e) { @@ -74,7 +74,7 @@ public void test_error_2() throws Exception { public void test_error_3() throws Exception { JSONException error = null; try { - DefaultExtJSONParser parser = new DefaultExtJSONParser( + DefaultJSONParser parser = new DefaultJSONParser( "{\"age\"33}"); parser.parseArray(User.class); } catch (JSONException e) { @@ -86,7 +86,7 @@ public void test_error_3() throws Exception { public void test_error_4() throws Exception { JSONException error = null; try { - DefaultExtJSONParser parser = new DefaultExtJSONParser( + DefaultJSONParser parser = new DefaultJSONParser( "[\"age\":33}"); parser.parseObject(new User()); } catch (JSONException e) { diff --git a/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_1.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_1.java new file mode 100755 index 0000000000..2ec732ade8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_1.java @@ -0,0 +1,77 @@ +package com.alibaba.json.bvt.parser; + +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.json.test.entity.TestEntity; + +public class DefaultExtJSONParserTest_1 extends TestCase { + + public void test_0() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{\"f1\":true}"); + TestEntity entity = parser.parseObject(TestEntity.class); + Assert.assertEquals(true, entity.isF1()); + } + + public void test_1() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{\"f2\":true}"); + TestEntity entity = parser.parseObject(TestEntity.class); + Assert.assertEquals(Boolean.TRUE, entity.getF2()); + } + + public void f_test_2() throws Exception { + TestEntity a = new TestEntity(); + a.setF1(true); + a.setF2(Boolean.TRUE); + a.setF3((byte) 123); + a.setF4((byte) 123); + a.setF5((short) 123); + a.setF6((short) 123); + a.setF7((int) 123); + a.setF8((int) 123); + a.setF9((long) 123); + a.setF10((long) 123); + a.setF11(new BigInteger("123")); + a.setF12(new BigDecimal("123")); + a.setF13("abc"); + a.setF14(null); + a.setF15(12.34F); + a.setF16(12.35F); + a.setF17(12.345D); + a.setF18(12.345D); + + String text = JSON.toJSONString(a); + System.out.println(text); + + TestEntity b = new TestEntity(); + { + DefaultJSONParser parser = new DefaultJSONParser(text); + parser.parseObject(b); + } + + Assert.assertEquals("f1", a.isF1(), b.isF1()); + Assert.assertEquals("f2", a.getF2(), b.getF2()); + Assert.assertEquals("f3", a.getF3(), b.getF3()); + Assert.assertEquals("f4", a.getF4(), b.getF4()); + Assert.assertEquals("f5", a.getF5(), b.getF5()); + Assert.assertEquals("f6", a.getF6(), b.getF6()); + Assert.assertEquals("f7", a.getF7(), b.getF7()); + Assert.assertEquals("f8", a.getF8(), b.getF8()); + Assert.assertEquals("f9", a.getF9(), b.getF9()); + Assert.assertEquals(a.getF10(), b.getF10()); + Assert.assertEquals(a.getF11(), b.getF11()); + Assert.assertEquals(a.getF12(), b.getF12()); + Assert.assertEquals(a.getF13(), b.getF13()); + Assert.assertEquals(a.getF14(), b.getF14()); + Assert.assertEquals(a.getF15(), b.getF15()); + Assert.assertEquals(a.getF16(), b.getF16()); + Assert.assertEquals(a.getF17(), b.getF17()); + Assert.assertEquals(a.getF18(), b.getF18()); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_2.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_2.java new file mode 100755 index 0000000000..b1f13a01dc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_2.java @@ -0,0 +1,149 @@ +package com.alibaba.json.bvt.parser; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.json.bvt.parser.DefaultExtJSONParserTest.User; + +public class DefaultExtJSONParserTest_2 extends TestCase { + + public void test_0() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{'a':3}"); + parser.config(Feature.AllowSingleQuotes, true); + A a = parser.parseObject(A.class); + Assert.assertEquals(3, a.getA()); + } + + public void test_1() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{a:3}"); + parser.config(Feature.AllowUnQuotedFieldNames, true); + A a = parser.parseObject(A.class); + Assert.assertEquals(3, a.getA()); + } + + public void test_2() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{a:3}"); + parser.config(Feature.AllowUnQuotedFieldNames, true); + Map a = parser.parseObject(Map.class); + Assert.assertEquals(3, a.get("a")); + } + + public void test_3() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{a:3}"); + parser.config(Feature.AllowUnQuotedFieldNames, true); + HashMap a = parser.parseObject(HashMap.class); + Assert.assertEquals(3, a.get("a")); + } + + public void test_4() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{a:3}"); + parser.config(Feature.AllowUnQuotedFieldNames, true); + LinkedHashMap a = parser.parseObject(LinkedHashMap.class); + Assert.assertEquals(3, a.get("a")); + } + + public void test_error_0() throws Exception { + Exception error = null; + try { + String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123]"; + DefaultJSONParser parser = new DefaultJSONParser(text); + parser.parseArray(User.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + JSONException error = null; + try { + DefaultJSONParser parser = new DefaultJSONParser("{'a'3}"); + parser.config(Feature.AllowSingleQuotes, true); + parser.parseObject(A.class); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + JSONException error = null; + try { + DefaultJSONParser parser = new DefaultJSONParser("{a 3}"); + parser.config(Feature.AllowUnQuotedFieldNames, true); + parser.parseObject(A.class); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + JSONException error = null; + try { + DefaultJSONParser parser = new DefaultJSONParser("{"); + parser.config(Feature.AllowUnQuotedFieldNames, true); + parser.parseObject(A.class); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } + + public void test_error_4() throws Exception { + JSONException error = null; + try { + DefaultJSONParser parser = new DefaultJSONParser("{\"a\"3}"); + parser.parseObject(A.class); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } + + public void test_error_5() throws Exception { + JSONException error = null; + try { + DefaultJSONParser parser = new DefaultJSONParser("{a:3}"); + parser.config(Feature.AllowUnQuotedFieldNames, false); + parser.parseObject(A.class); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } + + public void test_error_6() throws Exception { + JSONException error = null; + try { + DefaultJSONParser parser = new DefaultJSONParser("{'a':3}"); + parser.config(Feature.AllowSingleQuotes, false); + parser.parseObject(A.class); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } + + public static class A { + + private int a; + + public int getA() { + return a; + } + + public void setA(int a) { + this.a = a; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_3.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_3.java old mode 100644 new mode 100755 similarity index 78% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_3.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_3.java index 5c0f93f8e4..77e1b2f3f4 --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_3.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_3.java @@ -1,26 +1,26 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.math.BigDecimal; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; public class DefaultExtJSONParserTest_3 extends TestCase { public void test_0() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{v1:3}"); + DefaultJSONParser parser = new DefaultJSONParser("{v1:3}"); parser.config(Feature.AllowUnQuotedFieldNames, true); A a = parser.parseObject(A.class); Assert.assertEquals(3, a.getV1()); } public void test_1() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{v1:'3'}"); + DefaultJSONParser parser = new DefaultJSONParser("{v1:'3'}"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.config(Feature.AllowSingleQuotes, true); A a = parser.parseObject(A.class); @@ -28,7 +28,7 @@ public void test_1() throws Exception { } public void test_2() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{v1:\"3\"}"); + DefaultJSONParser parser = new DefaultJSONParser("{v1:\"3\"}"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.config(Feature.AllowSingleQuotes, true); A a = parser.parseObject(A.class); @@ -36,7 +36,7 @@ public void test_2() throws Exception { } public void test_3() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{o1:{}}"); + DefaultJSONParser parser = new DefaultJSONParser("{o1:{}}"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.config(Feature.AllowSingleQuotes, true); A a = parser.parseObject(A.class); @@ -44,7 +44,7 @@ public void test_3() throws Exception { } public void test_4() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{v5:'3'}"); + DefaultJSONParser parser = new DefaultJSONParser("{v5:'3'}"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.config(Feature.AllowSingleQuotes, true); A a = parser.parseObject(A.class); @@ -52,7 +52,7 @@ public void test_4() throws Exception { } public void test_5() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{v5:\"3\"}"); + DefaultJSONParser parser = new DefaultJSONParser("{v5:\"3\"}"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.config(Feature.AllowSingleQuotes, true); A a = parser.parseObject(A.class); @@ -65,13 +65,13 @@ public void test_6() throws Exception { Assert.assertEquals(true, Feature.isEnabled(features, Feature.AllowSingleQuotes)); - DefaultExtJSONParser parser = new DefaultExtJSONParser("'abc'", ParserConfig.getGlobalInstance(), features); + DefaultJSONParser parser = new DefaultJSONParser("'abc'", ParserConfig.getGlobalInstance(), features); Assert.assertEquals("abc", parser.parse()); } public void test_7() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("123"); + DefaultJSONParser parser = new DefaultJSONParser("123"); ParserConfig mapping = new ParserConfig(); parser.setConfig(mapping); diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_4.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_4.java old mode 100644 new mode 100755 similarity index 83% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_4.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_4.java index f1846e26fa..23e4296a8d --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_4.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_4.java @@ -1,14 +1,14 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONObject; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; @@ -19,7 +19,7 @@ public void test_0() throws Exception { String[] tests = { "[1,2,3]", "[1,,2,3]", "[1,2,,,3]", "[1 2,,,3]", "[1 2 3]", "[1, 2, 3,,]", "[,,1, 2, 3,,]", }; for (String t : tests) { - DefaultExtJSONParser ext = new DefaultExtJSONParser(t); + DefaultJSONParser ext = new DefaultJSONParser(t); ext.config(Feature.AllowArbitraryCommas, true); List extRes = ext.parseArray(Object.class); Assert.assertEquals(res, extRes); @@ -42,16 +42,16 @@ public void test_1() throws Exception { "{,,'a':1,,,,'b':2,'c':3,,,,,}", }; for (String t : tests) { - DefaultExtJSONParser ext = new DefaultExtJSONParser(t); + DefaultJSONParser ext = new DefaultJSONParser(t); ext.config(Feature.AllowArbitraryCommas, true); JSONObject extRes = ext.parseObject(); - Assert.assertEquals(res.toString(), extRes.toString()); + Assert.assertEquals(res, extRes); DefaultJSONParser basic = new DefaultJSONParser(t); basic.config(Feature.AllowArbitraryCommas, true); JSONObject basicRes = basic.parseObject(); - Assert.assertEquals(res.toString(), basicRes.toString()); + Assert.assertEquals(res, basicRes); } } @@ -65,7 +65,7 @@ public void test_2() throws Exception { "{,,'a':1,,,,'b':2,,'c':3,,,,,}", }; for (String t : tests) { - DefaultExtJSONParser ext = new DefaultExtJSONParser(t); + DefaultJSONParser ext = new DefaultJSONParser(t); ext.config(Feature.AllowArbitraryCommas, true); A extRes = ext.parseObject(A.class); diff --git a/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_5.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_5.java new file mode 100755 index 0000000000..6bce91c985 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_5.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; + +public class DefaultExtJSONParserTest_5 extends TestCase { + + public void test_0() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{,,,,\"value\":3,\"id\":1}"); + parser.config(Feature.AllowArbitraryCommas, true); + Entity entity = new Entity(); + parser.parseObject(entity); + Assert.assertEquals(3, entity.getValue()); + } + + public void test_1() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{\"value\":3,\"id\":1}"); + parser.config(Feature.AllowArbitraryCommas, false); + Entity entity = new Entity(); + parser.parseObject(entity); + Assert.assertEquals(3, entity.getValue()); + } + + public static class Entity { + + private int value; + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_6.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_6.java old mode 100644 new mode 100755 similarity index 76% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_6.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_6.java index d04ac5418a..116c7f8f23 --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_6.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_6.java @@ -1,15 +1,15 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; public class DefaultExtJSONParserTest_6 extends TestCase { public void test_0() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{value:{,,,,\"value\":3,\"id\":1}}"); + DefaultJSONParser parser = new DefaultJSONParser("{value:{,,,,\"value\":3,\"id\":1}}"); parser.config(Feature.AllowArbitraryCommas, true); Entity entity = new Entity(); parser.parseObject(entity); @@ -17,7 +17,7 @@ public void test_0() throws Exception { } public void test_1() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{'value':{\"value\":3,\"id\":1}}"); + DefaultJSONParser parser = new DefaultJSONParser("{'value':{\"value\":3,\"id\":1}}"); parser.config(Feature.AllowArbitraryCommas, false); Entity entity = new Entity(); parser.parseObject(entity); diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_7.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_7.java old mode 100644 new mode 100755 similarity index 78% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_7.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_7.java index 5d1a68d731..0b91dfad1c --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParserTest_7.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_7.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.util.ArrayList; import java.util.List; @@ -8,13 +8,13 @@ import org.junit.Assert; import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; public class DefaultExtJSONParserTest_7 extends TestCase { public void test_parse() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("1"); + DefaultJSONParser parser = new DefaultJSONParser("1"); Assert.assertEquals(Integer.valueOf(1), parser.parse()); Exception error = null; @@ -27,14 +27,14 @@ public void test_parse() throws Exception { } public void test_parse_str() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("\"1\""); + DefaultJSONParser parser = new DefaultJSONParser("\"1\""); parser.config(Feature.AllowISO8601DateFormat, true); Assert.assertEquals("1", parser.parse()); } public void test_parseArray() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1]"); + DefaultJSONParser parser = new DefaultJSONParser("[1]"); parser.config(Feature.AllowArbitraryCommas, false); List list = new ArrayList(); parser.parseArray(String.class, list); @@ -42,7 +42,7 @@ public void test_parseArray() throws Exception { } public void test_parseArray_error() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,2}"); + DefaultJSONParser parser = new DefaultJSONParser("[1,2}"); parser.config(Feature.AllowArbitraryCommas, false); List list = new ArrayList(); diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParser_parseArray.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParser_parseArray.java old mode 100644 new mode 100755 similarity index 78% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParser_parseArray.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParser_parseArray.java index f344a80a8f..93bc751d53 --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParser_parseArray.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParser_parseArray.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.lang.reflect.Type; import java.math.BigDecimal; @@ -6,26 +6,26 @@ import java.util.Date; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.JSONToken; public class DefaultExtJSONParser_parseArray extends TestCase { public void test_0() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,2,,,3]"); + DefaultJSONParser parser = new DefaultJSONParser("[1,2,,,3]"); List list = new ArrayList(); parser.parseArray(int.class, list); Assert.assertEquals("[1, 2, 3]", list.toString()); } public void test_1() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,2,3]"); + DefaultJSONParser parser = new DefaultJSONParser("[1,2,3]"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(int.class, list); @@ -33,7 +33,7 @@ public void test_1() throws Exception { } public void test_2() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("['1','2','3']"); + DefaultJSONParser parser = new DefaultJSONParser("['1','2','3']"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(String.class, list); @@ -42,7 +42,7 @@ public void test_2() throws Exception { } public void test_3() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,2,3]"); + DefaultJSONParser parser = new DefaultJSONParser("[1,2,3]"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(BigDecimal.class, list); @@ -51,7 +51,7 @@ public void test_3() throws Exception { } public void test_4() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,2,3,null]"); + DefaultJSONParser parser = new DefaultJSONParser("[1,2,3,null]"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(BigDecimal.class, list); @@ -60,7 +60,7 @@ public void test_4() throws Exception { } public void test_5() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,2,3,null]"); + DefaultJSONParser parser = new DefaultJSONParser("[1,2,3,null]"); Object[] array = parser.parseArray(new Type[] { Integer.class, BigDecimal.class, Long.class, String.class }); Assert.assertEquals(new Integer(1), array[0]); Assert.assertEquals(new BigDecimal("2"), array[1]); @@ -69,7 +69,7 @@ public void test_5() throws Exception { } public void test_error() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{}"); + DefaultJSONParser parser = new DefaultJSONParser("{}"); Exception error = null; try { parser.parseArray(new ArrayList()); @@ -80,7 +80,7 @@ public void test_error() throws Exception { } public void test_6() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1.2]"); + DefaultJSONParser parser = new DefaultJSONParser("[1.2]"); parser.config(Feature.UseBigDecimal, false); ArrayList list = new ArrayList(); parser.parseArray(list); @@ -88,7 +88,7 @@ public void test_6() throws Exception { } public void test_7() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[\"2011-01-09T13:49:53.254\", \"xxx\", true, false, null, {}]"); + DefaultJSONParser parser = new DefaultJSONParser("[\"2011-01-09T13:49:53.254\", \"xxx\", true, false, null, {}]"); parser.config(Feature.AllowISO8601DateFormat, true); ArrayList list = new ArrayList(); parser.parseArray(list); @@ -101,21 +101,21 @@ public void test_7() throws Exception { } public void test_8() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("\"2011-01-09T13:49:53.254\""); + DefaultJSONParser parser = new DefaultJSONParser("\"2011-01-09T13:49:53.254\""); parser.config(Feature.AllowISO8601DateFormat, true); Object value = parser.parse(); Assert.assertEquals(new Date(1294552193254L), value); } public void test_9() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser(""); + DefaultJSONParser parser = new DefaultJSONParser(""); parser.config(Feature.AllowISO8601DateFormat, true); Object value = parser.parse(); Assert.assertEquals(null, value); } public void test_error_2() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{}"); + DefaultJSONParser parser = new DefaultJSONParser("{}"); Exception error = null; try { parser.accept(JSONToken.NULL); @@ -126,7 +126,7 @@ public void test_error_2() throws Exception { } public void test_10() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,2,3]"); + DefaultJSONParser parser = new DefaultJSONParser("[1,2,3]"); Object[] array = parser.parseArray(new Type[] { Integer[].class }); Integer[] values = (Integer[]) array[0]; Assert.assertEquals(new Integer(1), values[0]); @@ -135,31 +135,31 @@ public void test_10() throws Exception { } public void test_11() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1]"); + DefaultJSONParser parser = new DefaultJSONParser("[1]"); Object[] array = parser.parseArray(new Type[] { String.class }); Assert.assertEquals("1", array[0]); } public void test_12() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("['1']"); + DefaultJSONParser parser = new DefaultJSONParser("['1']"); Object[] array = parser.parseArray(new Type[] { int.class }); Assert.assertEquals(new Integer(1), array[0]); } public void test_13() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("['1']"); + DefaultJSONParser parser = new DefaultJSONParser("['1']"); Object[] array = parser.parseArray(new Type[] { Integer.class }); Assert.assertEquals(new Integer(1), array[0]); } public void test_14() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[]"); + DefaultJSONParser parser = new DefaultJSONParser("[]"); Object[] array = parser.parseArray(new Type[] {}); Assert.assertEquals(0, array.length); } public void test_15() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,null]"); + DefaultJSONParser parser = new DefaultJSONParser("[1,null]"); ArrayList list = new ArrayList(); parser.config(Feature.AllowISO8601DateFormat, false); parser.parseArray(String.class, list); @@ -168,7 +168,7 @@ public void test_15() throws Exception { } public void test_16() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[[1]]"); + DefaultJSONParser parser = new DefaultJSONParser("[[1]]"); parser.config(Feature.AllowISO8601DateFormat, false); Object[] array = parser.parseArray(new Type[] { new TypeReference>() { }.getType() }); @@ -176,14 +176,14 @@ public void test_16() throws Exception { } public void test_17() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[]"); + DefaultJSONParser parser = new DefaultJSONParser("[]"); Object[] array = parser.parseArray(new Type[] { Integer[].class }); Integer[] values = (Integer[]) array[0]; Assert.assertEquals(0, values.length); } public void test_18() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("null"); + DefaultJSONParser parser = new DefaultJSONParser("null"); parser.config(Feature.AllowISO8601DateFormat, false); List list = (List) parser.parseArrayWithType(new TypeReference>() { }.getType()); @@ -191,7 +191,7 @@ public void test_18() throws Exception { } public void test_error_var() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,2,null }"); + DefaultJSONParser parser = new DefaultJSONParser("[1,2,null }"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; @@ -204,7 +204,7 @@ public void test_error_var() throws Exception { } public void test_error_3() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,null }"); + DefaultJSONParser parser = new DefaultJSONParser("[1,null }"); ArrayList list = new ArrayList(); parser.config(Feature.AllowISO8601DateFormat, false); @@ -218,7 +218,7 @@ public void test_error_3() throws Exception { } public void test_error_4() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,null }"); + DefaultJSONParser parser = new DefaultJSONParser("[1,null }"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; @@ -231,7 +231,7 @@ public void test_error_4() throws Exception { } public void test_error_5() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,null }"); + DefaultJSONParser parser = new DefaultJSONParser("[1,null }"); ArrayList list = new ArrayList(); parser.config(Feature.AllowISO8601DateFormat, false); @@ -245,7 +245,7 @@ public void test_error_5() throws Exception { } public void test_error_6() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{1,null }"); + DefaultJSONParser parser = new DefaultJSONParser("{1,null }"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; @@ -258,7 +258,7 @@ public void test_error_6() throws Exception { } public void test_error_7() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("{1}"); + DefaultJSONParser parser = new DefaultJSONParser("{1}"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; @@ -271,7 +271,7 @@ public void test_error_7() throws Exception { } public void test_error_8() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[1,2,3 4]"); + DefaultJSONParser parser = new DefaultJSONParser("[1,2,3 4]"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParser_parseArray_2.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParser_parseArray_2.java old mode 100644 new mode 100755 similarity index 79% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParser_parseArray_2.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParser_parseArray_2.java index 7a2a5b219e..d5aeec18a9 --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultExtJSONParser_parseArray_2.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParser_parseArray_2.java @@ -1,21 +1,23 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; + import junit.framework.TestCase; import com.alibaba.fastjson.TypeReference; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; +@SuppressWarnings("deprecation") public class DefaultExtJSONParser_parseArray_2 extends TestCase { - public void test_0() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[['1']]"); + public void test_0() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("[['1']]"); parser.config(Feature.AllowISO8601DateFormat, false); List> list = (List>) parser.parseArrayWithType(new TypeReference>>() { }.getType()); @@ -23,7 +25,7 @@ public void test_0() throws Exception { } public void test_1() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("['1','2']"); + DefaultJSONParser parser = new DefaultJSONParser("['1','2']"); parser.config(Feature.AllowISO8601DateFormat, false); List list = new ArrayList(); parser.parseArray(Integer.class, list); @@ -32,7 +34,7 @@ public void test_1() throws Exception { } public void test_error_0() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("['1','2'}"); + DefaultJSONParser parser = new DefaultJSONParser("['1','2'}"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; @@ -46,7 +48,7 @@ public void test_error_0() throws Exception { } public void test_error_1() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[['1']]"); + DefaultJSONParser parser = new DefaultJSONParser("[['1']]"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; @@ -60,7 +62,7 @@ public void test_error_1() throws Exception { } public void test_error_2() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[new X()]"); + DefaultJSONParser parser = new DefaultJSONParser("[new X()]"); parser.config(Feature.AllowISO8601DateFormat, false); List list = new ArrayList(); @@ -74,7 +76,7 @@ public void test_error_2() throws Exception { } public void test_error_3() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[] a"); + DefaultJSONParser parser = new DefaultJSONParser("[] a"); parser.config(Feature.AllowISO8601DateFormat, false); List list = new ArrayList(); @@ -89,7 +91,7 @@ public void test_error_3() throws Exception { } public void test_error_4() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("['1','2'}"); + DefaultJSONParser parser = new DefaultJSONParser("['1','2'}"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; @@ -102,14 +104,14 @@ public void test_error_4() throws Exception { } public void test_error_5() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("[]"); + DefaultJSONParser parser = new DefaultJSONParser("[]"); parser.config(Feature.AllowISO8601DateFormat, false); Assert.assertEquals(1, parser.parseArray(new Type[] { Integer[].class }).length); } public void test_error_6() throws Exception { - DefaultExtJSONParser parser = new DefaultExtJSONParser("['1' 1 '2'}"); + DefaultJSONParser parser = new DefaultJSONParser("['1' 1 '2'}"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest2.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest2.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest2.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest2.java index 87a5cda3fb..045cf0db35 --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest2.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest2.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_charArray.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_charArray.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_charArray.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_charArray.java index 805ccca7cd..9182de1f70 --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_charArray.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_charArray.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.DefaultJSONParser; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_comma.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_comma.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_comma.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_comma.java index d4817a8b1c..4b4aa78377 --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_comma.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_comma.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_date.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_date.java old mode 100644 new mode 100755 similarity index 75% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_date.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_date.java index ab3cb5ec09..2a402221ae --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_date.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_date.java @@ -1,16 +1,26 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; +import java.text.SimpleDateFormat; import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; -import junit.framework.Assert; import junit.framework.TestCase; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; public class DefaultJSONParserTest_date extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + public void test_date() { String text = "{\"date\":\"2011-01-09T13:49:53.254\"}"; char[] chars = text.toCharArray(); @@ -47,4 +57,18 @@ public void test_date4() { JSONObject json = parser.parseObject(); Assert.assertEquals("xxxxx", json.get("1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst\t")); } + + public void test_dateFormat() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{}"); + parser.setDateFormat("yyyy-DD-mm"); + + SimpleDateFormat format = new SimpleDateFormat("yyyy-DD-mm", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + + parser.setDateFomrat(format); + parser.getDateFomartPattern(); + parser.getDateFormat(); + parser.parse(); + parser.close(); + } } diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_error.java b/src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_error.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_error.java rename to src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_error.java index 1b8c902d1c..f62cf84257 --- a/src/test/java/com/alibaba/json/test/bvt/parser/DefaultJSONParserTest_error.java +++ b/src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_error.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; diff --git a/src/test/java/com/alibaba/json/bvt/parser/EnumParserTest.java b/src/test/java/com/alibaba/json/bvt/parser/EnumParserTest.java new file mode 100755 index 0000000000..bc7a22af67 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/EnumParserTest.java @@ -0,0 +1,93 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.deserializer.EnumDeserializer; + +public class EnumParserTest extends TestCase { + + public void test_0() throws Exception { + String text = "\"A\""; + DefaultJSONParser parser = new DefaultJSONParser(text); + + Type type = parser.parseObject(Type.class); + Assert.assertEquals(Type.A, type); + } + + public void test_1() throws Exception { + String text = "0"; + DefaultJSONParser parser = new DefaultJSONParser(text); + + Type type = parser.parseObject(Type.class); + Assert.assertEquals(Type.A, type); + } + + public void test_error() throws Exception { + String text = "\"C\""; + DefaultJSONParser parser = new DefaultJSONParser(text); + + assertNull(parser.parseObject(Type.class)); + } + + public void test_error_1() throws Exception { + Exception error = null; + try { + String text = "4"; + DefaultJSONParser parser = new DefaultJSONParser(text); + + parser.parseObject(Type.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + Exception error = null; + try { + String text = "4"; + DefaultJSONParser parser = new DefaultJSONParser(text); + + parser.parseObject(TypeA.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + Exception error = null; + try { + String text = "4"; + DefaultJSONParser parser = new DefaultJSONParser(text); + + new EnumDeserializer(Object.class).deserialze(parser, Object.class, null); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_4() throws Exception { + Exception error = null; + try { + String text = "true"; + DefaultJSONParser parser = new DefaultJSONParser(text); + + new EnumDeserializer(Object.class).deserialze(parser, Object.class, null); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static enum Type { + A, B + } + + private static enum TypeA { + A, B + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/FastMatchCheckTest.java b/src/test/java/com/alibaba/json/bvt/parser/FastMatchCheckTest.java new file mode 100755 index 0000000000..02ec99264b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/FastMatchCheckTest.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.deserializer.NumberDeserializer; +import com.alibaba.fastjson.parser.deserializer.SqlDateDeserializer; +import com.alibaba.fastjson.serializer.AtomicCodec; +import com.alibaba.fastjson.serializer.CharacterCodec; +import com.alibaba.fastjson.serializer.MiscCodec; +import com.alibaba.fastjson.serializer.ObjectArrayCodec; + +import junit.framework.TestCase; + +public class FastMatchCheckTest extends TestCase { + public void test_match() throws Exception { + Assert.assertEquals(JSONToken.LBRACKET, AtomicCodec.instance.getFastMatchToken()); + Assert.assertEquals(JSONToken.LITERAL_STRING, MiscCodec.instance.getFastMatchToken()); + Assert.assertEquals(JSONToken.LITERAL_INT, NumberDeserializer.instance.getFastMatchToken()); + Assert.assertEquals(JSONToken.LITERAL_INT, SqlDateDeserializer.instance.getFastMatchToken()); + Assert.assertEquals(JSONToken.LBRACKET, ObjectArrayCodec.instance.getFastMatchToken()); + Assert.assertEquals(JSONToken.LITERAL_STRING, CharacterCodec.instance.getFastMatchToken()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/FeatureParserTest.java b/src/test/java/com/alibaba/json/bvt/parser/FeatureParserTest.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/parser/FeatureParserTest.java rename to src/test/java/com/alibaba/json/bvt/parser/FeatureParserTest.java index e55f567de5..0aa36f7bcb --- a/src/test/java/com/alibaba/json/test/bvt/parser/FeatureParserTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/FeatureParserTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/FeatureTest.java b/src/test/java/com/alibaba/json/bvt/parser/FeatureTest.java old mode 100644 new mode 100755 similarity index 89% rename from src/test/java/com/alibaba/json/test/bvt/parser/FeatureTest.java rename to src/test/java/com/alibaba/json/bvt/parser/FeatureTest.java index 2e7721e9bd..2bf172bd68 --- a/src/test/java/com/alibaba/json/test/bvt/parser/FeatureTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/FeatureTest.java @@ -1,11 +1,12 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; import junit.framework.TestCase; -import com.alibaba.fastjson.parser.CharTypes; +import org.junit.Assert; + import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.util.IOUtils; public class FeatureTest extends TestCase { @@ -20,7 +21,7 @@ public void test_default() throws Exception { } public void test_config() throws Exception { - new CharTypes(); + new IOUtils(); DefaultJSONParser parser = new DefaultJSONParser(""); diff --git a/src/test/java/com/alibaba/json/bvt/parser/InetSocketAddressTest.java b/src/test/java/com/alibaba/json/bvt/parser/InetSocketAddressTest.java new file mode 100755 index 0000000000..c35714b1cb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/InetSocketAddressTest.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.parser; + +import java.net.InetSocketAddress; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +public class InetSocketAddressTest extends TestCase { + + public void test_parse() throws Exception { + JSON.parseObject("{\"address\":'10.20.133.23',\"port\":123,\"xx\":33}", InetSocketAddress.class); + } + + public void test_parse_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"address\":'10.20.133.23',\"port\":'12.3',\"xx\":33}", InetSocketAddress.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONArrayParseTest.java b/src/test/java/com/alibaba/json/bvt/parser/JSONArrayParseTest.java old mode 100644 new mode 100755 similarity index 88% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONArrayParseTest.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONArrayParseTest.java index d754be188d..b451ada56d --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONArrayParseTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONArrayParseTest.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.util.List; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerAllowCommentTest.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerAllowCommentTest.java new file mode 100644 index 0000000000..2505a71fba --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerAllowCommentTest.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.parser; + +import java.io.IOException; +import java.io.InputStream; + +import junit.framework.TestCase; + +import org.apache.commons.io.IOUtils; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONLexerAllowCommentTest extends TestCase { + public void test_0() throws Exception { + + String jsonWithComment = "{ /*tes****\n\r\n*t*/\"a\":1 /*****test88888*****/ /*test*/ , /*test*/ //test\n //est\n \"b\":2}"; + JSONObject object = JSON.parseObject(jsonWithComment, Feature.AllowComment, Feature.OrderedField); + System.out.println(object.toJSONString()); + Assert.assertEquals("{\"a\":1,\"b\":2}",object.toJSONString()); + + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner(jsonWithComment, + Feature.AllowComment.getMask() | Feature.OrderedField.getMask())); + + JSONObject object1 = parser.parseObject(); + Assert.assertEquals("{\"a\":1,\"b\":2}",object1.toJSONString()); + System.out.println(object1.toJSONString()); + + } + + public void test_1() throws IOException { + String resource = "json/json_with_comment.json"; + InputStream is = Thread.currentThread().getContextClassLoader() + .getResourceAsStream(resource); + String text = IOUtils.toString(is); + is.close(); + + JSONObject object = JSON.parseObject(text, Feature.AllowComment, Feature.OrderedField); + System.out.println(object.toJSONString()); + + Assert + .assertEquals( + "{\"hello\":\"asafsadf\",\"test\":1,\"array\":[\"10000sfsaf\",100,{\"nihao\":{\"test\":\"sdfasdf\"}}],\"object\":{\"teset\":1000}}", + object.toJSONString()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest.java new file mode 100644 index 0000000000..e3881829f1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + + +public class JSONLexerTest extends TestCase { + public void test_0 () throws Exception { + StringBuilder buf = new StringBuilder("{\"value\":\""); + for (int i = 0; i < 256; ++i) { + buf.append('a'); + } + buf.append("\\n"); + buf.append("\"}"); + + JSONObject json = JSON.parseObject(buf.toString()); + Assert.assertEquals(257, json.getString("value").length()); + Assert.assertEquals('a', json.getString("value").charAt(255)); + Assert.assertEquals('\n', json.getString("value").charAt(256)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_10.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_10.java new file mode 100644 index 0000000000..9f7e60fab5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_10.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class JSONLexerTest_10 extends TestCase { + + public void test_a() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"type\":\"AAA", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + public VO(){ + + } + + private String type; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_11.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_11.java new file mode 100644 index 0000000000..c059c346ec --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_11.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.parser; + +import java.util.ArrayList; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class JSONLexerTest_11 extends TestCase { + + public void test_a() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"type\":[\"AAA\"]}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + public VO(){ + + } + + private MyList type; + + public MyList getType() { + return type; + } + + public void setType(MyList type) { + this.type = type; + } + + } + + public static class MyList extends ArrayList { + public MyList() { + throw new RuntimeException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_12.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_12.java new file mode 100644 index 0000000000..a8cdb5c263 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_12.java @@ -0,0 +1,76 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class JSONLexerTest_12 extends TestCase { + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"type\":92233720368547758071}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_a() throws Exception { + Assert.assertEquals(123L, JSON.parseObject("{\"vo\":{\"type\":123}}", A.class).getVo().getType()); + } + + public void test_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"vo\":{\"type\":123}[", A.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"vo\":{\"type\":123]", A.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class A { + + private VO vo; + + public VO getVo() { + return vo; + } + + public void setVo(VO vo) { + this.vo = vo; + } + + } + + public static class VO { + + public VO(){ + + } + + private long type; + + public long getType() { + return type; + } + + public void setType(long type) { + this.type = type; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_13.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_13.java new file mode 100644 index 0000000000..f72cb710a6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_13.java @@ -0,0 +1,76 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class JSONLexerTest_13 extends TestCase { + + public void test_e() throws Exception { + Assert.assertTrue(123e3D == JSON.parseObject("{\"vo\":{\"type\":123e3}}", A.class).getVo().getType()); + } + + public void test_E() throws Exception { + Assert.assertTrue(123e3D == JSON.parseObject("{\"vo\":{\"type\":123E3}}", A.class).getVo().getType()); + } + + public void test_e_plus() throws Exception { + Assert.assertTrue(123e3D == JSON.parseObject("{\"vo\":{\"type\":123e+3}}", A.class).getVo().getType()); + } + + public void test_E_plus() throws Exception { + Assert.assertTrue(123e3D == JSON.parseObject("{\"vo\":{\"type\":123E+3}}", A.class).getVo().getType()); + } + + public void test_e_minus() throws Exception { + Assert.assertTrue(123e-3D == JSON.parseObject("{\"vo\":{\"type\":123e-3}}", A.class).getVo().getType()); + } + + public void test_E_minus() throws Exception { + Assert.assertTrue(123e-3D == JSON.parseObject("{\"vo\":{\"type\":123E-3}}", A.class).getVo().getType()); + } + + public void test_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"vo\":{\"type\":123]", A.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class A { + + private VO vo; + + public VO getVo() { + return vo; + } + + public void setVo(VO vo) { + this.vo = vo; + } + + } + + public static class VO { + + public VO(){ + + } + + private double type; + + public double getType() { + return type; + } + + public void setType(double type) { + this.type = type; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_14.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_14.java new file mode 100644 index 0000000000..c5d32ec307 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_14.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class JSONLexerTest_14 extends TestCase { + + public void test_e() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append("{\"type\":'"); + for (int i = 0; i < 100; ++i) { + buf.append('a'); + } + buf.append("\\t"); + buf.append("'}"); + VO vo = JSON.parseObject(buf.toString(), VO.class); + String type = vo.getType(); + for (int i = 0; i < 100; ++i) { + Assert.assertEquals('a', type.charAt(i)); + } + Assert.assertEquals('\t', type.charAt(100)); + Assert.assertEquals(101, type.length()); + } + + + public static class VO { + public VO(){ + + } + + private String type; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_15.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_15.java new file mode 100644 index 0000000000..1b02aa3c61 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_15.java @@ -0,0 +1,15 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class JSONLexerTest_15 extends TestCase { + + public void test_e() throws Exception { + Assert.assertTrue(123e2D == ((Double) JSON.parse("123e2D")).doubleValue()); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_16.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_16.java new file mode 100644 index 0000000000..f910678da9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_16.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class JSONLexerTest_16 extends TestCase { + + public void test_0() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\0\":123}").get("\0")); + } + + public void test_1() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\1\":123}").get("\1")); + } + + public void test_2() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\2\":123}").get("\2")); + } + + public void test_3() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\3\":123}").get("\3")); + } + + public void test_4() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\4\":123}").get("\4")); + } + + public void test_5() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\5\":123}").get("\5")); + } + + public void test_6() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\6\":123}").get("\6")); + } + + public void test_7() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\7\":123}").get("\7")); + } + + public void test_8() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\b\":123}").get("\b")); + } + + public void test_9() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\t\":123}").get("\t")); + } + + public void test_10() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\n\":123}").get("\n")); + } + + public void test_39() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\'\":123}").get("\'")); + } + + public void test_40() throws Exception { + Assert.assertEquals(123, JSON.parseObject("{\"\\xFF\":123}").get("\u00FF")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_2.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_2.java new file mode 100644 index 0000000000..77ac62ef98 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_2.java @@ -0,0 +1,128 @@ +package com.alibaba.json.bvt.parser; + +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.TypeReference; + +public class JSONLexerTest_2 extends TestCase { + + public void test_0() throws Exception { + VO vo = (VO) JSON.parseObject("{\"@type\":\"com.alibaba.json.bvt.parser.JSONLexerTest_2$VO\"}", VO.class); + Assert.assertNotNull(vo); + } + + public void test_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"@type\":\"com.alibaba.json.bvt.parser.JSONLexerTest_2$VO1\"}", VO.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"@type\":\"com.alibaba.json.bvt.parser.JSONLexerTest_2$A\"}", VO.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_a() throws Exception { + P a = JSON.parseObject("{\"vo\":{\"@type\":\"com.alibaba.json.bvt.parser.JSONLexerTest_2$VO\"}}", P.class); + Assert.assertNotNull(a); + } + + public void test_list() throws Exception { + List list = JSON.parseObject("[{\"@type\":\"com.alibaba.json.bvt.parser.JSONLexerTest_2$VO\"}]", + new TypeReference>() { + }); + Assert.assertNotNull(list); + Assert.assertNotNull(list.get(0)); + } + + public void test_list_2() throws Exception { + List list = JSON.parseObject("[{\"@type\":\"com.alibaba.json.bvt.parser.JSONLexerTest_2$VO\"},{}]", + new TypeReference>() { + }); + Assert.assertNotNull(list); + Assert.assertEquals(2, list.size()); + Assert.assertNotNull(list.get(0)); + Assert.assertNotNull(list.get(1)); + } + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[{\"@type\":\"com.alibaba.json.bvt.parser.JSONLexerTest_2$VO\"}[]", + new TypeReference>() { + }); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class P { + + private VO vo; + + public VO getVo() { + return vo; + } + + public void setVo(VO vo) { + this.vo = vo; + } + + } + + public static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } + + public static class VO1 { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + } + + public static class A { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_3.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_3.java new file mode 100644 index 0000000000..232f135eed --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_3.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.parser; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class JSONLexerTest_3 extends TestCase { + + public void test_matchField() throws Exception { + JSON.parseObject("{\"val\":{}}", VO.class); + } + + public static class VO { + + private A value; + + public A getValue() { + return value; + } + + public void setValue(A value) { + this.value = value; + } + + } + + public static class A { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_4.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_4.java new file mode 100644 index 0000000000..4c4ef91333 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_4.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class JSONLexerTest_4 extends TestCase { + + public void test_scanFieldString() throws Exception { + VO vo = JSON.parseObject("{\"value\":\"abc\"}", VO.class); + Assert.assertEquals("abc", vo.getValue()); + } + + public static class VO { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_5.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_5.java new file mode 100644 index 0000000000..a8e073a4a6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_5.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.parser; + +import java.util.LinkedList; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class JSONLexerTest_5 extends TestCase { + + public void test_scanFieldString() throws Exception { + VO vo = JSON.parseObject("{\"values\":[\"abc\"]}", VO.class); + Assert.assertEquals("abc", vo.getValues().get(0)); + } + + public static class VO { + + public LinkedList values; + + public LinkedList getValues() { + return values; + } + + public void setValues(LinkedList values) { + this.values = values; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_6.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_6.java new file mode 100644 index 0000000000..7e4777492a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_6.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser; + +import java.util.LinkedList; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class JSONLexerTest_6 extends TestCase { + + public void test_scanFieldString() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"values\":[\"abc\"]}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + public MyList values; + + public MyList getValues() { + return values; + } + + public void setValues(MyList values) { + this.values = values; + } + } + + @SuppressWarnings("serial") + private class MyList extends LinkedList { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_7.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_7.java new file mode 100644 index 0000000000..fdfa74336f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_7.java @@ -0,0 +1,96 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class JSONLexerTest_7 extends TestCase { + + public void test_treeSet() throws Exception { + JSON.parse("TreeSet[]"); + } + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parse("T_eeSet[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + Exception error = null; + try { + JSON.parse("Tr_eSet[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + Exception error = null; + try { + JSON.parse("Tre_Set[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + Exception error = null; + try { + JSON.parse("Tree_et[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + + public void test_error_4() throws Exception { + Exception error = null; + try { + JSON.parse("TreeS_t[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + + public void test_error_5() throws Exception { + Exception error = null; + try { + JSON.parse("TreeSe_[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_6() throws Exception { + Exception error = null; + try { + JSON.parse("TreeSet_[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_7() throws Exception { + Exception error = null; + try { + JSON.parse("XreeSet[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_8.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_8.java new file mode 100644 index 0000000000..74177c94fe --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_8.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.parser.JSONReaderScanner; +import com.alibaba.fastjson.parser.JSONScanner; +import com.alibaba.fastjson.parser.JSONToken; + +public class JSONLexerTest_8 extends TestCase { + + public void test_ident() throws Exception { + JSONScanner lexer = new JSONScanner("123"); + lexer.nextIdent(); + org.junit.Assert.assertEquals(JSONToken.LITERAL_INT, lexer.token()); + lexer.close(); + } + + public void test_ident_2() throws Exception { + JSONScanner lexer = new JSONScanner("\uFEFF123"); + lexer.nextIdent(); + org.junit.Assert.assertEquals(JSONToken.LITERAL_INT, lexer.token()); + lexer.close(); + } + + public void test_ident_3() throws Exception { + JSONReaderScanner lexer = new JSONReaderScanner("\uFEFF123"); + lexer.nextIdent(); + org.junit.Assert.assertEquals(JSONToken.LITERAL_INT, lexer.token()); + lexer.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_9.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_9.java new file mode 100644 index 0000000000..6ae641752c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_9.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class JSONLexerTest_9 extends TestCase { + + public void test_ident() throws Exception { + JSON.parseObject("\"AAA\"", Type.class); + } + + public void test_a() throws Exception { + JSON.parseObject("{\"type\":\"AAA\"}", VO.class); + } + + public void test_b() throws Exception { + JSON.parseObject("{\"tt\":\"AA\"}", VO.class); + } + + public void test_value() throws Exception { + JSON.parseObject("{\"type\":'AAA'}", VO.class); + } + + public void test_value2() throws Exception { + JSON.parseObject("{\"type\":\"AAA\",id:0}", VO.class); + } + + public static class VO { + + public VO(){ + + } + + private Type type; + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } + + } + + public static enum Type { + AAA, BBB, CCC + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_set.java b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_set.java new file mode 100644 index 0000000000..1665609b44 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_set.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class JSONLexerTest_set extends TestCase { + + public void test_treeSet() throws Exception { + JSON.parse("Set[]"); + } + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parse("S_t[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + Exception error = null; + try { + JSON.parse("Se_[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + + public void test_error_2() throws Exception { + Exception error = null; + try { + JSON.parse("Set_[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + Exception error = null; + try { + JSON.parse("Xet[]"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_boolean.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_boolean.java new file mode 100644 index 0000000000..809ac67620 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_boolean.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest__entity_boolean extends TestCase { + + public void test_scanInt() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 10; ++i) { + if (i != 0) { + buf.append(','); + } + //1000000000000 + // + if (i % 2 == 0) { + buf.append("{\"id\":true}"); + } else { + buf.append("{\"id\":false}"); + } + + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + List array = parser.parseArray(VO.class); + for (int i = 0; i < array.size(); ++i) { + if (i % 2 == 0) { + Assert.assertEquals(true, array.get(i).getId()); + } else { + Assert.assertEquals(false, array.get(i).getId()); + } + } + } + + public static class VO { + + private boolean id; + + public boolean getId() { + return id; + } + + public void setId(boolean id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_double.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_double.java new file mode 100644 index 0000000000..4f0cf53f19 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_double.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest__entity_double extends TestCase { + + public void test_scanFloat() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 1024; ++i) { + if (i != 0) { + buf.append(','); + } + buf.append("{\"id\":" + i + ".0}"); + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + List array = parser.parseArray(VO.class); + for (int i = 0; i < array.size(); ++i) { + Assert.assertTrue((double) i == array.get(i).getId()); + } + parser.close(); + } + + public static class VO { + + private double id; + + public double getId() { + return id; + } + + public void setId(double id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_double_2.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_double_2.java new file mode 100644 index 0000000000..b8beb2520b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_double_2.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest__entity_double_2 extends TestCase { + + public void test_scanFloat() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 1024; ++i) { + if (i != 0) { + buf.append(','); + } + buf.append("{\"id\":" + i + ".0}"); + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + List array = parser.parseArray(VO.class); + for (int i = 0; i < array.size(); ++i) { + Assert.assertTrue(Integer.toString(i), (double) i == array.get(i).getId()); + } + parser.close(); + } + + private static class VO { + + private double id; + + public double getId() { + return id; + } + + public void setId(double id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_enum.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_enum.java new file mode 100644 index 0000000000..74f8533a2b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_enum.java @@ -0,0 +1,74 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest__entity_enum extends TestCase { + + public void test_scanInt() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 10; ++i) { + if (i != 0) { + buf.append(','); + } + //1000000000000 + // + Type type; + if (i % 3 == 0) { + type = Type.A; + } else if (i % 3 == 1) { + type = Type.AA; + } else { + type = Type.AAA; + } + buf.append("{\"id\":\"" + type.name() + "\"}"); + + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + List array = parser.parseArray(VO.class); + for (int i = 0; i < array.size(); ++i) { + Type type; + if (i % 3 == 0) { + type = Type.A; + } else if (i % 3 == 1) { + type = Type.AA; + } else { + type = Type.AAA; + } + + Assert.assertEquals(type, array.get(i).getId()); + } + } + + public static class VO { + + private Type id; + + public Type getId() { + return id; + } + + public void setId(Type id) { + this.id = id; + } + } + + public static enum Type { + A, AA, AAA + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_float.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_float.java new file mode 100644 index 0000000000..a2cb9c8f7f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_float.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest__entity_float extends TestCase { + + public void test_scanFloat() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 1024; ++i) { + if (i != 0) { + buf.append(','); + } + buf.append("{\"id\":" + i + ".0}"); + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + List array = parser.parseArray(VO.class); + for (int i = 0; i < array.size(); ++i) { + Assert.assertTrue((float) i == array.get(i).getId()); + } + parser.close(); + } + + public static class VO { + + private float id; + + public float getId() { + return id; + } + + public void setId(float id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_int.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_int.java new file mode 100644 index 0000000000..32b812fefc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_int.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest__entity_int extends TestCase { + + public void test_scanInt() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 1024; ++i) { + if (i != 0) { + buf.append(','); + } + buf.append("{\"id\":" + i + "}"); + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + List array = parser.parseArray(VO.class); + for (int i = 0; i < array.size(); ++i) { + Assert.assertEquals(i, array.get(i).getId()); + } + } + + public static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_long.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_long.java new file mode 100644 index 0000000000..8685927567 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_long.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest__entity_long extends TestCase { + + public void test_scanInt() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 10; ++i) { + if (i != 0) { + buf.append(','); + } + //1000000000000 + // + long value = (long) 1000000000000L + 1L + (long) i; + buf.append("{\"id\":" + value + "}"); + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + List array = parser.parseArray(VO.class); + for (int i = 0; i < array.size(); ++i) { + long value = (long) 1000000000000L + 1L + (long) i; + Assert.assertEquals(value, array.get(i).getId()); + } + } + + public static class VO { + + private long id; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_string.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_string.java new file mode 100644 index 0000000000..d732f54ba2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_string.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest__entity_string extends TestCase { + + public void test_scanInt() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 10; ++i) { + if (i != 0) { + buf.append(','); + } + //1000000000000 + // + buf.append("{\"id\":\"" + i + "\"}"); + + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + List array = parser.parseArray(VO.class); + for (int i = 0; i < array.size(); ++i) { + Assert.assertEquals(Integer.toString(i), array.get(i).getId()); + } + } + + public static class VO { + + private String id; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_stringList.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_stringList.java new file mode 100644 index 0000000000..50b95127e2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_stringList.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest__entity_stringList extends TestCase { + + public void test_scanInt() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 10; ++i) { + if (i != 0) { + buf.append(','); + } + //1000000000000 + // + buf.append("{\"id\":[\"" + i + "\",\"" + (10000 + i) + "\"]}"); + + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + List array = parser.parseArray(VO.class); + for (int i = 0; i < array.size(); ++i) { + Assert.assertEquals(2, array.get(i).getId().size()); + Assert.assertEquals(Integer.toString(i), array.get(i).getId().get(0)); + Assert.assertEquals(Integer.toString(10000 + i), array.get(i).getId().get(1)); + } + } + + public static class VO { + + private List id; + + public List getId() { + return id; + } + + public void setId(List id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__map_string.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__map_string.java new file mode 100644 index 0000000000..c518cf066a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__map_string.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest__map_string extends TestCase { + + public void test_scanInt() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 10; ++i) { + if (i != 0) { + buf.append(','); + } + // 1000000000000 + // + buf.append("{\"id\":\"" + i + "\"}"); + + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + JSONArray array = (JSONArray) parser.parse(); + for (int i = 0; i < array.size(); ++i) { + Assert.assertEquals(Integer.toString(i), array.getJSONObject(i).get("id")); + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_array_string.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_array_string.java new file mode 100644 index 0000000000..d3f25c8358 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_array_string.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest_array_string extends TestCase { + + public void test_scanInt() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 10; ++i) { + if (i != 0) { + buf.append(','); + } + // 1000000000000 + // + buf.append("\"" + i + "\""); + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + JSONArray array = (JSONArray) parser.parse(); + for (int i = 0; i < array.size(); ++i) { + Assert.assertEquals(Integer.toString(i), array.get(i)); + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_bytes.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_bytes.java new file mode 100644 index 0000000000..268bc2bed9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_bytes.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; + +public class JSONReaderScannerTest_bytes extends TestCase { + + public void test_e() throws Exception { + VO vo = new VO(); + vo.setValue("ABC".getBytes("UTF-8")); + + String text = JSON.toJSONString(vo); + + JSONReader reader = new JSONReader(new StringReader(text)); + VO vo2 = reader.readObject(VO.class); + Assert.assertEquals("ABC", new String(vo2.getValue())); + reader.close(); + } + + public static class VO { + + private byte[] value; + + public byte[] getValue() { + return value; + } + + public void setValue(byte[] value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_decimal.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_decimal.java new file mode 100644 index 0000000000..af464a1548 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_decimal.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; +import java.math.BigDecimal; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest_decimal extends TestCase { + + public void test_scanInt() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 1024; ++i) { + if (i != 0) { + buf.append(','); + } + buf.append(i + ".0"); + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + JSONArray array = (JSONArray) parser.parse(); + for (int i = 0; i < array.size(); ++i) { + BigDecimal value = new BigDecimal(i + ".0"); + Assert.assertEquals(value, array.get(i)); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_enum.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_enum.java new file mode 100644 index 0000000000..48c2e1926a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_enum.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReaderScannerTest_enum extends TestCase { + + public void test_e() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{type:'AA'}")); + VO vo2 = reader.readObject(VO.class); + Assert.assertEquals(Type.AA, vo2.getType()); + reader.close(); + } + + public static class VO { + + private Type type; + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } + + + } + + public static enum Type { + AA, BB, CC + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error.java new file mode 100644 index 0000000000..a3e859d016 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.parser; + +import java.io.IOException; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReaderScannerTest_error extends TestCase { + + public void test_e() throws Exception { + Exception error = null; + try { + new JSONReader(new MyReader()); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class MyReader extends java.io.Reader { + + @Override + public int read(char[] cbuf, int off, int len) throws IOException { + throw new IOException(); + } + + @Override + public void close() throws IOException { + // TODO Auto-generated method stub + + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error2.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error2.java new file mode 100644 index 0000000000..8419a63536 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error2.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReaderScannerTest_error2 extends TestCase { + + public void test_e() throws Exception { + Exception error = null; + try { + StringBuilder buf = new StringBuilder(); + buf.append("[{\"type\":\""); + for (int i = 0; i < 8180; ++i) { + buf.append('A'); + } + buf.append("\"}"); + JSONReader reader = new JSONReader(new StringReader(buf.toString())); + reader.readObject(); + reader.close(); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private String type; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error3.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error3.java new file mode 100644 index 0000000000..2f11733638 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error3.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReaderScannerTest_error3 extends TestCase { + + public void test_e() throws Exception { + Exception error = null; + try { + StringBuilder buf = new StringBuilder(); + buf.append("[{\"type\":\""); + for (int i = 0; i < 8180; ++i) { + buf.append('A'); + } + buf.append("\\t"); + JSONReader reader = new JSONReader(new StringReader(buf.toString())); + reader.readObject(); + reader.close(); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private String type; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error4.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error4.java new file mode 100644 index 0000000000..d0a190dc86 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error4.java @@ -0,0 +1,60 @@ +package com.alibaba.json.bvt.parser; + +import java.io.IOException; +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReaderScannerTest_error4 extends TestCase { + + public void test_e() throws Exception { + Exception error = null; + try { + StringBuilder buf = new StringBuilder(); + buf.append("[{\"type\":\""); + for (int i = 0; i < 8180; ++i) { + buf.append('A'); + } + buf.append("\\t"); + JSONReader reader = new JSONReader(new MyReader(buf.toString())); + reader.readObject(); + reader.close(); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private String type; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + } + + public static class MyReader extends StringReader { + + public MyReader(String s){ + super(s); + } + + public int read(char cbuf[], int off, int len) throws IOException { + int x = super.read(cbuf, off, len); + if (x < 0) { + throw new IOException(); + } + return x; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error5.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error5.java new file mode 100644 index 0000000000..19844d9d21 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error5.java @@ -0,0 +1,60 @@ +package com.alibaba.json.bvt.parser; + +import java.io.IOException; +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReaderScannerTest_error5 extends TestCase { + + public void test_e() throws Exception { + Exception error = null; + try { + StringBuilder buf = new StringBuilder(); + buf.append("[{\"type\":\""); + for (int i = 0; i < 8180; ++i) { + buf.append('A'); + } + buf.append("\\t"); + JSONReader reader = new JSONReader(new MyReader(buf.toString())); + reader.readObject(); + reader.close(); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private String type; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + } + + public static class MyReader extends StringReader { + + public MyReader(String s){ + super(s); + } + + public int read(char cbuf[], int off, int len) throws IOException { + int x = super.read(cbuf, off, len); + if (x < 0) { + return 0; + } + return x; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_int.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_int.java new file mode 100644 index 0000000000..56fc8c5f13 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_int.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest_int extends TestCase { + + public void test_scanInt() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 1024; ++i) { + if (i != 0) { + buf.append(','); + } + buf.append(i); + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + JSONArray array = (JSONArray) parser.parse(); + for (int i = 0; i < array.size(); ++i) { + Assert.assertEquals(i, ((Integer) array.get(i)).intValue()); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_jsonobject.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_jsonobject.java new file mode 100644 index 0000000000..1479643553 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_jsonobject.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONReader; + +public class JSONReaderScannerTest_jsonobject extends TestCase { + + public void test_e() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"type\\t\":'AA'}")); + JSONObject vo = new JSONObject(); + reader.readObject(vo); + Assert.assertEquals("AA", vo.get("type\t")); + reader.close(); + } + + public static class VO { + + private Type type; + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } + + + } + + public static enum Type { + AA, BB, CC + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_long.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_long.java new file mode 100644 index 0000000000..c5feb755ae --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_long.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.parser; + +import java.io.Reader; +import java.io.StringReader; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest_long extends TestCase { + + public void test_scanInt() throws Exception { + StringBuffer buf = new StringBuffer(); + buf.append('['); + for (int i = 0; i < 1024; ++i) { + if (i != 0) { + buf.append(','); + } + long value = (long) Integer.MAX_VALUE + 1L + (long) i; + buf.append(value); + } + buf.append(']'); + + Reader reader = new StringReader(buf.toString()); + + JSONReaderScanner scanner = new JSONReaderScanner(reader); + + DefaultJSONParser parser = new DefaultJSONParser(scanner); + JSONArray array = (JSONArray) parser.parse(); + for (int i = 0; i < array.size(); ++i) { + long value = (long) Integer.MAX_VALUE + 1L + (long) i; + Assert.assertEquals(value, ((Long) array.get(i)).longValue()); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_array.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_array.java new file mode 100644 index 0000000000..f8533169e9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_array.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.JSONScanner; + +public class JSONReaderTest_array_array extends TestCase { + + String text = "[[],[],[],[],[], [],[],[],[],[]]"; + + public void test_read() throws Exception { + + JSONReader reader = new JSONReader(new StringReader(text)); + reader.startArray(); + + int count = 0; + while (reader.hasNext()) { + Object item = reader.readObject(); + Assert.assertEquals(JSONArray.class, item.getClass()); + count++; + } + Assert.assertEquals(10, count); + + reader.endArray(); + reader.close(); + } + + public void test_read_1() throws Exception { + JSONReader reader = new JSONReader(new JSONScanner(text)); + reader.startArray(); + + int count = 0; + while (reader.hasNext()) { + Object item = reader.readObject(); + Assert.assertEquals(JSONArray.class, item.getClass()); + count++; + } + Assert.assertEquals(10, count); + + reader.endArray(); + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_array_2.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_array_2.java new file mode 100644 index 0000000000..4b52d0aa00 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_array_2.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.JSONScanner; + +public class JSONReaderTest_array_array_2 extends TestCase { + + String text = "[[],[],[],[],[], [],[],[],[],[]]"; + + public void test_read() throws Exception { + + JSONReader reader = new JSONReader(new StringReader(text)); + reader.startArray(); + + int count = 0; + while (reader.hasNext()) { + reader.startArray(); + reader.endArray(); + count++; + } + Assert.assertEquals(10, count); + + reader.endArray(); + reader.close(); + } + + public void test_read_1() throws Exception { + JSONReader reader = new JSONReader(new JSONScanner(text)); + reader.startArray(); + + int count = 0; + while (reader.hasNext()) { + reader.startArray(); + reader.endArray(); + count++; + } + Assert.assertEquals(10, count); + + reader.endArray(); + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_object.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_object.java new file mode 100644 index 0000000000..2a6e9adf73 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_object.java @@ -0,0 +1,73 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.JSONScanner; + +public class JSONReaderTest_array_object extends TestCase { + + String text = "[{},{},{},{},{} ,{},{},{},{},{}]"; + + public void test_read() throws Exception { + + JSONReader reader = new JSONReader(new StringReader(text)); + reader.startArray(); + + int count = 0; + while (reader.hasNext()) { + reader.readObject(); + count++; + } + Assert.assertEquals(10, count); + + reader.endArray(); + reader.close(); + } + + public void test_read_1() throws Exception { + JSONReader reader = new JSONReader(new JSONScanner(text)); + reader.startArray(); + + int count = 0; + while (reader.hasNext()) { + reader.readObject(); + count++; + } + Assert.assertEquals(10, count); + + reader.endArray(); + reader.close(); + } + + public void test_read_3() throws Exception { + JSONReader reader = new JSONReader(new JSONScanner(text)); + reader.startArray(); + + + + Assert.assertTrue(reader.hasNext()); + reader.startObject(); + reader.endObject(); + + Assert.assertTrue(reader.hasNext()); + reader.startObject(); + reader.endObject(); + + int count = 2; + + while (reader.hasNext()) { + reader.startObject(); + reader.endObject(); + count++; + } + Assert.assertEquals(10, count); + + reader.endArray(); + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_object_2.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_object_2.java new file mode 100644 index 0000000000..b561acc428 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_object_2.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.JSONScanner; + +public class JSONReaderTest_array_object_2 extends TestCase { + + String text = "[{},{},{},{},{} ,{},{},{},{},{}]"; + + public void test_read() throws Exception { + + JSONReader reader = new JSONReader(new StringReader(text)); + reader.startArray(); + + int count = 0; + while (reader.hasNext()) { + reader.startObject(); + reader.endObject(); + count++; + } + Assert.assertEquals(10, count); + + reader.endArray(); + reader.close(); + } + + public void test_read_1() throws Exception { + JSONReader reader = new JSONReader(new JSONScanner(text)); + reader.startArray(); + + int count = 0; + while (reader.hasNext()) { + reader.startObject(); + reader.endObject(); + count++; + } + Assert.assertEquals(10, count); + + reader.endArray(); + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_int.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_int.java new file mode 100644 index 0000000000..fb21d486bf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_int.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.JSONScanner; + +public class JSONReaderTest_object_int extends TestCase { + + public void test_read() throws Exception { + String text = "{\"f0\":0,\"f1\":1,\"f2\":2,\"f3\":3,\"f4\":4, " + // + "\"f5\":5,\"f6\":6,\"f7\":7,\"f8\":8,\"f9\":9}"; + JSONReader reader = new JSONReader(new StringReader(text)); + reader.startObject(); + + int count = 0; + while (reader.hasNext()) { + String key = (String) reader.readObject(); + Integer value = reader.readInteger(); + count++; + } + Assert.assertEquals(10, count); + + reader.endObject(); + reader.close(); + } + + public void test_read_1() throws Exception { + String text = "[{},{},{},{},{} ,{},{},{},{},{}]"; + JSONReader reader = new JSONReader(new JSONScanner(text)); + reader.startArray(); + + int count = 0; + while (reader.hasNext()) { + reader.readObject(); + count++; + } + Assert.assertEquals(10, count); + + reader.endArray(); + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_int_unquote.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_int_unquote.java new file mode 100644 index 0000000000..e6e8ff0d9c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_int_unquote.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.JSONScanner; + +public class JSONReaderTest_object_int_unquote extends TestCase { + + String text = "{f0:0,f1:1,f2:2,f3:3,f4:4, " + // + "f5:5,f6:6,f7:7,f8:8,f9:9}"; + + public void test_read() throws Exception { + + JSONReader reader = new JSONReader(new StringReader(text)); + reader.startObject(); + + int count = 0; + while (reader.hasNext()) { + String key = (String) reader.readObject(); + Integer value = reader.readInteger(); + count++; + } + Assert.assertEquals(10, count); + + reader.endObject(); + reader.close(); + } + + public void test_read_1() throws Exception { + JSONReader reader = new JSONReader(new JSONScanner(text)); + reader.startObject(); + + int count = 0; + while (reader.hasNext()) { + String key = (String) reader.readObject(); + Integer value = reader.readInteger(); + count++; + } + Assert.assertEquals(10, count); + + reader.endObject(); + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_long.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_long.java new file mode 100644 index 0000000000..d6da5c574e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_long.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.JSONScanner; + +public class JSONReaderTest_object_long extends TestCase { + + String text = "{\"f0\":0,\"f1\":1,\"f2\":2,\"f3\":3,\"f4\":4, " + // + "\"f5\":5,\"f6\":6,\"f7\":7,\"f8\":8,\"f9\":9}"; + + public void test_read() throws Exception { + + JSONReader reader = new JSONReader(new StringReader(text)); + + reader.startObject(); + + int count = 0; + while (reader.hasNext()) { + String key = (String) reader.readObject(); + Long value = reader.readLong(); + count++; + } + Assert.assertEquals(10, count); + + reader.endObject(); + reader.close(); + } + + public void test_read_1() throws Exception { + JSONReader reader = new JSONReader(new JSONScanner(text)); + + reader.startObject(); + + int count = 0; + while (reader.hasNext()) { + String key = (String) reader.readObject(); + Long value = reader.readLong(); + count++; + } + Assert.assertEquals(10, count); + + reader.endObject(); + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_object.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_object.java new file mode 100644 index 0000000000..bdc8bd0627 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_object.java @@ -0,0 +1,88 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.JSONScanner; + +public class JSONReaderTest_object_object extends TestCase { + + String text = "{\"f0\":{},\"f1\":{},\"f2\":{},\"f3\":{},\"f4\":{}, " + // + "\"f5\":{},\"f6\":{},\"f7\":{},\"f8\":{},\"f9\":{}}"; + + public void test_read() throws Exception { + + JSONReader reader = new JSONReader(new StringReader(text)); + reader.startObject(); + + int count = 0; + while (reader.hasNext()) { + String key = (String) reader.readObject(); + Object value = reader.readObject(); + Assert.assertNotNull(key); + Assert.assertNotNull(value); + count++; + } + Assert.assertEquals(10, count); + + reader.endObject(); + reader.close(); + } + + public void test_read_1() throws Exception { + JSONReader reader = new JSONReader(new JSONScanner(text)); + reader.startObject(); + + int count = 0; + while (reader.hasNext()) { + String key = (String) reader.readObject(); + Object value = reader.readObject(); + + Assert.assertNotNull(key); + Assert.assertNotNull(value); + + count++; + } + Assert.assertEquals(10, count); + + reader.endObject(); + reader.close(); + } + + public void test_read_2() throws Exception { + JSONReader reader = new JSONReader(new JSONScanner("{{}:{},{}:{}}")); + reader.startObject(); + + Assert.assertTrue(reader.hasNext()); + reader.startObject(); + reader.endObject(); + + reader.startObject(); + reader.endObject(); + + Assert.assertTrue(reader.hasNext()); + reader.startObject(); + reader.endObject(); + + reader.startObject(); + reader.endObject(); + + Assert.assertFalse(reader.hasNext()); + + reader.endObject(); + + Exception error = null; + try { + reader.hasNext(); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_string.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_string.java new file mode 100644 index 0000000000..41e61b0ff1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_string.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.JSONScanner; + +public class JSONReaderTest_object_string extends TestCase { + + String text = "{\"f0\":\"0\",\"f1\":\"1\",\"f2\":\"2\",\"f3\":\"3\",\"f4\":\"4\", " + // + "\"f5\":\"5\",\"f6\":\"6\",\"f7\":\"7\",\"f8\":\"8\",\"f9\":\"9\"}"; + + public void test_read() throws Exception { + + JSONReader reader = new JSONReader(new StringReader(text)); + + reader.startObject(); + + int count = 0; + while (reader.hasNext()) { + String key = (String) reader.readObject(); + String value = reader.readString(); + count++; + } + Assert.assertEquals(10, count); + + reader.endObject(); + reader.close(); + } + + public void test_read_1() throws Exception { + JSONReader reader = new JSONReader(new JSONScanner(text)); + + reader.startObject(); + + int count = 0; + while (reader.hasNext()) { + String key = (String) reader.readObject(); + Long value = reader.readLong(); + count++; + } + Assert.assertEquals(10, count); + + reader.endObject(); + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReader_error.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReader_error.java new file mode 100644 index 0000000000..00e2297f5f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReader_error.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReader_error extends TestCase { + + public void test_0() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[]")); + + Exception error = null; + try { + reader.hasNext(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + } + + public void test_1() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"id\":123}")); + + reader.startObject(); + reader.readObject(); + + Exception error = null; + try { + reader.hasNext(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONReader_top.java b/src/test/java/com/alibaba/json/bvt/parser/JSONReader_top.java new file mode 100644 index 0000000000..5131ec8ce9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONReader_top.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReader_top extends TestCase { + + public void test_int() throws Exception { + JSONReader reader = new JSONReader(new StringReader("123")); + + Assert.assertEquals(new Integer(123), reader.readInteger()); + + reader.close(); + } + + public void test_long() throws Exception { + JSONReader reader = new JSONReader(new StringReader("123")); + + Assert.assertEquals(new Long(123), reader.readLong()); + + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_ISO8601.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_ISO8601.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_ISO8601.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_ISO8601.java index f9a775f5fe..b98554969c --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_ISO8601.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_ISO8601.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.Feature; @@ -13,7 +13,8 @@ public void test_0() throws Exception { Assert.assertEquals(false, new JSONScanner("1").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("3").scanISO8601DateIfMatch()); - Assert.assertEquals(false, new JSONScanner("3000-10-02").scanISO8601DateIfMatch()); + Assert.assertEquals(true, new JSONScanner("3000-10-02").scanISO8601DateIfMatch()); + Assert.assertEquals(false, new JSONScanner("4000-10-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("1997").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("1997-2-2").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("1997-02-02").scanISO8601DateIfMatch()); @@ -88,8 +89,8 @@ public void test_0() throws Exception { Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:A0").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T00:00:00").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:00.").scanISO8601DateIfMatch()); - Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:00.0").scanISO8601DateIfMatch()); - Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:00.00").scanISO8601DateIfMatch()); + Assert.assertEquals(true, new JSONScanner("2000-02-10T00:00:00.0").scanISO8601DateIfMatch()); + Assert.assertEquals(true, new JSONScanner("2000-02-10T00:00:00.00").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T00:00:00.000").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:00.A00").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:00.!00").scanISO8601DateIfMatch()); diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest__nextToken.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest__nextToken.java old mode 100644 new mode 100755 similarity index 98% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest__nextToken.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest__nextToken.java index 9cd0486da0..9a91e77ae5 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest__nextToken.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest__nextToken.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.JSONScanner; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest__x.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest__x.java old mode 100644 new mode 100755 similarity index 88% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest__x.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest__x.java index 58fe0312b4..7f6c46c470 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest__x.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest__x.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_colon.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_colon.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_colon.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_colon.java index 3528ef5960..68ad4bcd86 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_colon.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_colon.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; @@ -10,7 +10,7 @@ /** * 测试字符':'的处理 * - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public class JSONScannerTest_colon extends TestCase { diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_false.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_false.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_false.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_false.java index 218533e8c5..e5c4b1919f --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_false.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_false.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_ident.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_ident.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_ident.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_ident.java index f1b4721a46..f10578ac14 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_ident.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_ident.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.JSONScanner; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_int.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_int.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_int.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_int.java index a58674809b..0bea2becec --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_int.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_int.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.JSONScanner; @@ -8,7 +8,7 @@ /** * parseInt * - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public class JSONScannerTest_int extends TestCase { diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_isEOF.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_isEOF.java new file mode 100755 index 0000000000..3c7650e8df --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_isEOF.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.JSONScanner; +import com.alibaba.fastjson.parser.JSONToken; + +public class JSONScannerTest_isEOF extends TestCase { + + public void test_0() throws Exception { + String text = "{} "; + JSONObject obj = JSON.parseObject(text); + Assert.assertEquals(0, obj.size()); + } + + public void test_1() throws Exception { + JSONScanner lexer = new JSONScanner(" "); + lexer.nextToken(); + Assert.assertTrue(lexer.token() == JSONToken.EOF); + } + + public void test_2() throws Exception { + JSONScanner lexer = new JSONScanner("1 "); + lexer.nextToken(); + lexer.nextToken(); + Assert.assertTrue(lexer.token() == JSONToken.EOF); + } + + public void test_3() throws Exception { + JSONScanner lexer = new JSONScanner(" {}"); + lexer.nextToken(); + Assert.assertTrue(lexer.token() != JSONToken.EOF); + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_long.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_long.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_long.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_long.java index 8b15ddc733..a68f4b9fe8 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_long.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_long.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.JSONScanner; @@ -8,7 +8,7 @@ /** * parseLong * - * @author wenshao + * @author wenshao[szujobs@hotmail.com] */ public class JSONScannerTest_long extends TestCase { diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_new.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_new.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_new.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_new.java index 1c5dc40716..9c6c0567f6 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_new.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_new.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_null.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_null.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_null.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_null.java index 4251ee08b2..4b76da914e --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_null.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_null.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldBoolean.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldBoolean.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldBoolean.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldBoolean.java index 0865ffd029..f882fcde4e --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldBoolean.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldBoolean.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -37,11 +37,7 @@ public void test_3() throws Exception { Assert.assertEquals(true, obj.getValue()); } - public void test_4() throws Exception { - String text = "{\"value\":false,id:2}"; - VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(false, obj.getValue()); - } + public void test_5() throws Exception { String text = "{\"value\":false}"; diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldBoolean_unquote.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldBoolean_unquote.java new file mode 100644 index 0000000000..e7a749499d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldBoolean_unquote.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.json.bvt.parser.JSONScannerTest_scanFieldBoolean.VO; + +public class JSONScannerTest_scanFieldBoolean_unquote extends TestCase { + + public void test_4() throws Exception { + String text = "{\"value\":false,id:2}"; + VO obj = JSON.parseObject(text, VO.class); + Assert.assertEquals(false, obj.getValue()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldDouble.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldDouble.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldDouble.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldDouble.java index a6c155273a..c35c9a5f73 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldDouble.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldDouble.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -11,43 +11,43 @@ public class JSONScannerTest_scanFieldDouble extends TestCase { public void test_0() throws Exception { String text = "{\"value\":1.0}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(1D, obj.getValue()); + Assert.assertTrue(1D == obj.getValue()); } public void test_1() throws Exception { String text = "{\"value\":\"1\"}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(1D, obj.getValue()); + Assert.assertTrue(1D == obj.getValue()); } public void test_2() throws Exception { String text = "{\"f1\":2,\"value\":1.0}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(1D, obj.getValue()); + Assert.assertTrue(1D == obj.getValue()); } public void test_3() throws Exception { String text = "{\"value\":1.01}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(1.01D, obj.getValue()); + Assert.assertTrue(1.01D == obj.getValue()); } public void test_4() throws Exception { String text = "{\"value\":1.}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(1D, obj.getValue()); + Assert.assertTrue(1D == obj.getValue()); } public void test_5() throws Exception { String text = "{\"value\":922337203685477580723}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(922337203685477580723D, obj.getValue()); + Assert.assertTrue(922337203685477580723D == obj.getValue()); } public void test_error_2() throws Exception { JSONException error = null; try { - String text = "{\"value\":32D}"; + String text = "{\"value\":32K}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldFloat.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldFloat.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldFloat.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldFloat.java index 8f9e5aa0f9..e0da50ad00 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldFloat.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldFloat.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -12,9 +12,10 @@ public class JSONScannerTest_scanFieldFloat extends TestCase { public void test_0() throws Exception { String text = "{\"value\":1.0}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(1F, obj.getValue()); + Assert.assertTrue(1F == obj.getValue()); } + @SuppressWarnings("resource") public void test_isBlank() throws Exception { String text = " {\"value\":1.0}"; Assert.assertTrue(!new JSONScanner(text).isBlankInput()); @@ -23,37 +24,37 @@ public void test_isBlank() throws Exception { public void test_1() throws Exception { String text = "{\"value\":\"1\"}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(1F, obj.getValue()); + Assert.assertTrue(1F == obj.getValue()); } public void test_2() throws Exception { String text = "{\"f1\":2,\"value\":1.0}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(1F, obj.getValue()); + Assert.assertTrue(1F == obj.getValue()); } public void test_3() throws Exception { String text = "{\"value\":1.01}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(1.01F, obj.getValue()); + Assert.assertTrue(1.01F == obj.getValue()); } public void test_4() throws Exception { String text = "{\"value\":1.}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(1F, obj.getValue()); + Assert.assertTrue(1F == obj.getValue()); } public void test_error_1() throws Exception { String text = "{\"value\":922337203685477580723}"; VO obj = JSON.parseObject(text, VO.class); - Assert.assertEquals(922337203685477580723F, obj.getValue()); + Assert.assertTrue(922337203685477580723F == obj.getValue()); } public void test_error_2() throws Exception { JSONException error = null; try { - String text = "{\"value\":32D}"; + String text = "{\"value\":32M}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldInt.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldInt.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldInt.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldInt.java index 0f59497ae1..0ed2775975 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldInt.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldInt.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -34,7 +34,7 @@ public void test_error_1() throws Exception { public void test_error_2() throws Exception { JSONException error = null; try { - String text = "{\"value\":32D}"; + String text = "{\"value\":32O}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldLong.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldLong.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldLong.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldLong.java index 2876e0f9dd..9ed14f8f84 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldLong.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldLong.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -14,6 +14,7 @@ public void test_0() throws Exception { Assert.assertEquals(1, obj.getValue()); } + /** public void test_1() throws Exception { JSONException error = null; try { @@ -28,7 +29,7 @@ public void test_1() throws Exception { public void test_2() throws Exception { JSONException error = null; try { - String text = "{\"value\":32D}"; + String text = "{\"value\":32RR}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; @@ -90,7 +91,7 @@ public void test_error_7() throws Exception { } Assert.assertNotNull(error); } - +*/ public static class VO { private long value; diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldString.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldString.java new file mode 100755 index 0000000000..79f173ab41 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldString.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class JSONScannerTest_scanFieldString extends TestCase { + + public void test_0() throws Exception { + String text = "{\"value\":1}"; + VO obj = JSON.parseObject(text, VO.class); + Assert.assertEquals("1", obj.getValue()); + } + + public void test_1() throws Exception { + String text = "{\"value\":\"1\"}"; + VO obj = JSON.parseObject(text, VO.class); + Assert.assertEquals("1", obj.getValue()); + } + + public void test_2() throws Exception { + String text = "{\"value\":\"1\\t\"}"; + VO obj = JSON.parseObject(text, VO.class); + Assert.assertEquals("1\t", obj.getValue()); + } + + public void test_3() throws Exception { + String text = "{\"value\":\"1\\n\"}"; + VO obj = JSON.parseObject(text, VO.class); + Assert.assertEquals("1\n", obj.getValue()); + } + + public void test_error_0() { + Exception error = null; + try { + String text = "{\"value\":\"1\\n\""; + JSON.parseObject(text, VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldStringArray.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldStringArray.java old mode 100644 new mode 100755 similarity index 96% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldStringArray.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldStringArray.java index 1595762dfd..ec5e62e17e --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_scanFieldStringArray.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldStringArray.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -55,7 +55,7 @@ public void test_string_error() throws Exception { } catch (JSONException e) { error = e; } - Assert.assertNotNull(error); + //Assert.assertNotNull(error); } public void test_string_error_2() throws Exception { diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldString_error.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldString_error.java new file mode 100644 index 0000000000..bd3bb187be --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldString_error.java @@ -0,0 +1,68 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class JSONScannerTest_scanFieldString_error extends TestCase { + + public void f_test_error_0() { + Exception error = null; + try { + String text = "{\"value\":\"1\\n\""; + JSON.parseObject(text, VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void f_test_error_1() { + Exception error = null; + try { + String text = "{\"value\":\"1\"}}"; + JSON.parseObject(text, VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() { + Exception error = null; + try { + String text = "{\"value\":\"1\"}1"; + JSON.parseObject(text, VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() { + Exception error = null; + try { + String text = "{\"value\":\"1\"1"; + JSON.parseObject(text, VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + + public static class VO { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanSymbol.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanSymbol.java new file mode 100755 index 0000000000..393a5e5113 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanSymbol.java @@ -0,0 +1,79 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.parser.JSONScanner; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.SymbolTable; + +/** + * 测试字符':'的处理 + * + * @author wenshao[szujobs@hotmail.com] + */ +public class JSONScannerTest_scanSymbol extends TestCase { + + public void test_0() throws Exception { + JSONScanner lexer = new JSONScanner("\"value\":\"aa\\n\""); + long hashCode = lexer.scanFieldSymbol("\"value\":".toCharArray()); + assertEquals(0, hashCode); + Assert.assertEquals(JSONScanner.NOT_MATCH, lexer.matchStat()); + } + + public void test_1() throws Exception { + JSONScanner lexer = new JSONScanner("\"value\":\"aa\"},"); + long hashCode = lexer.scanFieldSymbol("\"value\":".toCharArray()); + Assert.assertEquals(fnv_hash("aa"), hashCode); + Assert.assertEquals(JSONScanner.END, lexer.matchStat()); + Assert.assertEquals(JSONToken.COMMA, lexer.token()); + } + + public void test_2() throws Exception { + JSONScanner lexer = new JSONScanner("\"value\":\"aa\"}]"); + long hashCode = lexer.scanFieldSymbol("\"value\":".toCharArray()); + Assert.assertEquals(fnv_hash("aa"), hashCode); + Assert.assertEquals(JSONScanner.END, lexer.matchStat()); + Assert.assertEquals(JSONToken.RBRACKET, lexer.token()); + } + + public void test_3() throws Exception { + JSONScanner lexer = new JSONScanner("\"value\":\"aa\"}}"); + long hashCode = lexer.scanFieldSymbol("\"value\":".toCharArray()); + Assert.assertEquals(fnv_hash("aa"), hashCode); + Assert.assertEquals(JSONScanner.END, lexer.matchStat()); + Assert.assertEquals(JSONToken.RBRACE, lexer.token()); + } + + public void test_4() throws Exception { + JSONScanner lexer = new JSONScanner("\"value\":\"aa\"}"); + long hashCode = lexer.scanFieldSymbol("\"value\":".toCharArray()); + Assert.assertEquals(fnv_hash("aa"), hashCode); + Assert.assertEquals(JSONScanner.END, lexer.matchStat()); + Assert.assertEquals(JSONToken.EOF, lexer.token()); + } + + public void test_6() throws Exception { + JSONScanner lexer = new JSONScanner("\"value\":\"aa\"}{"); + long hashCode = lexer.scanFieldSymbol("\"value\":".toCharArray()); + Assert.assertEquals(0, hashCode); + Assert.assertEquals(JSONScanner.NOT_MATCH, lexer.matchStat()); + } + + public void test_7() throws Exception { + JSONScanner lexer = new JSONScanner("\"value\":\"aa\""); + long hashCode = lexer.scanFieldSymbol("\"value\":".toCharArray()); + Assert.assertEquals(0, hashCode); + Assert.assertEquals(JSONScanner.NOT_MATCH, lexer.matchStat()); + } + + static long fnv_hash(String text) { + long hash = 0xcbf29ce484222325L; + for (int i = 0; i < text.length(); ++i) { + char c = text.charAt(i); + hash ^= c; + hash *= 0x100000001b3L; + } + return hash; + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_singQuoteString.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_singQuoteString.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_singQuoteString.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_singQuoteString.java index bc3a3ee47d..ea827edad3 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_singQuoteString.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_singQuoteString.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -34,7 +34,7 @@ public void test_string() throws Exception { StringBuilder buf = new StringBuilder(); buf.append('\''); - buf.append("\\\\\\/\\b\\f\\n\\r\\t\\u" + Integer.toHexString('中')); + buf.append("\\\\\\/\\b\\f\\n\\r\t\\u" + Integer.toHexString('中')); buf.append('\''); buf.append('\u2001'); @@ -48,7 +48,7 @@ public void test_string() throws Exception { String stringVal = lexer.stringVal(); - Assert.assertEquals("\"\\\\/\\b\\f\\n\\r\t中\"", JSON.toJSONString(stringVal)); + Assert.assertEquals("\"\\\\/\\b\\f\\n\\r\\t中\"", JSON.toJSONString(stringVal)); JSON.toJSONString(stringVal); } diff --git a/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_symbol.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_symbol.java new file mode 100755 index 0000000000..571682d5bc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_symbol.java @@ -0,0 +1,162 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.JSONScanner; +import com.alibaba.fastjson.parser.SymbolTable; + +/** + * test symbol + * + * @author wenshao[szujobs@hotmail.com] + */ +public class JSONScannerTest_symbol extends TestCase { + + public void test_0() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"name\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("name".equals(symbol)); + lexer.close(); + } + + public void test_1() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick name\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("nick name".equals(symbol)); + lexer.close(); + } + + public void test_2() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick \\\"name\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("nick \"name" == symbol); + lexer.close(); + } + + public void test_3() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick \\\\name\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("nick \\name" == symbol); + lexer.close(); + } + + public void test_4() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick \\/name\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("nick /name" == symbol); + lexer.close(); + } + + public void test_5() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick \\bname\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("nick \bname" == symbol); + lexer.close(); + } + + public void test_6() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick \\f name\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("nick \f name" == symbol); + lexer.close(); + } + + public void test_7() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick \\F name\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("nick \f name" == symbol); + lexer.close(); + } + + public void test_8() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick \\n name\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("nick \n name" == symbol); + lexer.close(); + } + + public void test_9() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick \\r name\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("nick \r name" == symbol); + lexer.close(); + } + + public void test_10() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick \\t name\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("nick \t name" == symbol); + lexer.close(); + } + + public void test_11() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick \\u4e2d name\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("nick 中 name" == symbol); + lexer.close(); + } + + public void test_12() throws Exception { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner( + "\"\\tabcdefghijklmnopqrstuvwxyz01234567890abcdefghijklmnopqrstuvwxyz01234567890abcdefghijklmnopqrstuvwxyz01234567890abcdefghijklmnopqrstuvwxyz01234567890\""); + String symbol = lexer.scanSymbol(symbolTable, '"'); + Assert.assertTrue("\tabcdefghijklmnopqrstuvwxyz01234567890abcdefghijklmnopqrstuvwxyz01234567890abcdefghijklmnopqrstuvwxyz01234567890abcdefghijklmnopqrstuvwxyz01234567890" == symbol); + lexer.close(); + } + + public void test_error() throws Exception { + JSONException error = null; + try { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"nick \\a name\""); + lexer.scanSymbol(symbolTable, '"'); + lexer.close(); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + JSONException error = null; + try { + SymbolTable symbolTable = new SymbolTable(512); + + JSONScanner lexer = new JSONScanner("\"name"); + lexer.scanSymbol(symbolTable, '"'); + lexer.close(); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_true.java b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_true.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_true.java rename to src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_true.java index f5f9dce906..8a991dcdb8 --- a/src/test/java/com/alibaba/json/test/bvt/parser/JSONScannerTest_true.java +++ b/src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_true.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; diff --git a/src/test/java/com/alibaba/json/bvt/parser/MapResetTest.java b/src/test/java/com/alibaba/json/bvt/parser/MapResetTest.java new file mode 100755 index 0000000000..9ff14fa958 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/MapResetTest.java @@ -0,0 +1,60 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class MapResetTest extends TestCase { + + public void test_0() throws Exception { + Book book = new Book(); + +// book.setMetadata(new MetaData()); + String text = JSON.toJSONString(book); + + System.out.println(text); + + Book book2 = JSON.parseObject(text, Book.class); + System.out.println(JSON.toJSONString(book2)); + } + + public static class Book { + + private int id; + private int pageCountNum; + + private MetaData metadata; + + public int getPageCountNum() { + return pageCountNum; + } + + public void setPageCountNum(int pageCountNum) { + this.pageCountNum = pageCountNum; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public MetaData getMetadata() { + return metadata; + } + + public void setMetadata(MetaData metadata) { + this.metadata = metadata; + } + + + + + } + + public static class MetaData { + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/NullCheckTest.java b/src/test/java/com/alibaba/json/bvt/parser/NullCheckTest.java old mode 100644 new mode 100755 similarity index 81% rename from src/test/java/com/alibaba/json/test/bvt/parser/NullCheckTest.java rename to src/test/java/com/alibaba/json/bvt/parser/NullCheckTest.java index fa0b31f5b7..ce47f098ec --- a/src/test/java/com/alibaba/json/test/bvt/parser/NullCheckTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/NullCheckTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/OrderedFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/OrderedFieldTest.java new file mode 100644 index 0000000000..4b63c96e5b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/OrderedFieldTest.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class OrderedFieldTest extends TestCase { + public void test_ordered_field() throws Exception { + String text = "{\"id\":1001}"; + Model model = JSON.parseObject(text, Model.class, Feature.OrderedField); + Assert.assertEquals(1001, model.getId()); + String text2 = JSON.toJSONString(model); + Assert.assertEquals(text, text2); + + } + + public static interface Model { + public int getId(); + public void setId(int value); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ParseContextTest.java b/src/test/java/com/alibaba/json/bvt/parser/ParseContextTest.java new file mode 100644 index 0000000000..52125bf043 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ParseContextTest.java @@ -0,0 +1,14 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.ParseContext; + + +public class ParseContextTest extends TestCase { + public void test_toString() throws Exception { + Assert.assertEquals("$", new ParseContext(null, new Object(), "id").toString()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ParseRestTest.java b/src/test/java/com/alibaba/json/bvt/parser/ParseRestTest.java new file mode 100644 index 0000000000..a419c45536 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ParseRestTest.java @@ -0,0 +1,59 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class ParseRestTest extends TestCase { + + public void test_parseRest_0() throws Exception { + String text = "{\"f3\":333,\"f2\":222}"; + Entity entity = JSON.parseObject(text, Entity.class); + Assert.assertEquals(0, entity.getF0()); + Assert.assertEquals(0, entity.getF1()); + Assert.assertEquals(222, entity.getF2()); + Assert.assertEquals(333, entity.getF3()); + } + + public static class Entity { + + private int f0; + private int f1; + private int f2; + private int f3; + + public int getF0() { + return f0; + } + + public void setF0(int f0) { + this.f0 = f0; + } + + public int getF1() { + return f1; + } + + public void setF1(int f1) { + this.f1 = f1; + } + + public int getF2() { + return f2; + } + + public void setF2(int f2) { + this.f2 = f2; + } + + public int getF3() { + return f3; + } + + public void setF3(int f3) { + this.f3 = f3; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest.java b/src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest.java new file mode 100644 index 0000000000..1c76057bea --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest.java @@ -0,0 +1,95 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ParserSpecialCharTest extends TestCase { + + public void test_0() throws Exception { + Assert.assertEquals("\0", JSON.parseObject("{\"value\":\"\\0\"}", VO.class).getValue()); + } + + public void test_1() throws Exception { + Assert.assertEquals("\1", JSON.parseObject("{\"value\":\"\\1\"}", VO.class).getValue()); + } + + public void test_2() throws Exception { + Assert.assertEquals("\2", JSON.parseObject("{\"value\":\"\\2\"}", VO.class).getValue()); + } + + public void test_3() throws Exception { + Assert.assertEquals("\3", JSON.parseObject("{\"value\":\"\\3\"}", VO.class).getValue()); + } + + public void test_4() throws Exception { + Assert.assertEquals("\4", JSON.parseObject("{\"value\":\"\\4\"}", VO.class).getValue()); + } + + public void test_5() throws Exception { + Assert.assertEquals("\5", JSON.parseObject("{\"value\":\"\\5\"}", VO.class).getValue()); + } + + public void test_6() throws Exception { + Assert.assertEquals("\6", JSON.parseObject("{\"value\":\"\\6\"}", VO.class).getValue()); + } + + public void test_7() throws Exception { + Assert.assertEquals("\7", JSON.parseObject("{\"value\":\"\\7\"}", VO.class).getValue()); + } + + public void test_8() throws Exception { + Assert.assertEquals("\b", JSON.parseObject("{\"value\":\"\\b\"}", VO.class).getValue()); + } + + public void test_9() throws Exception { + Assert.assertEquals("\t", JSON.parseObject("{\"value\":\"\\t\"}", VO.class).getValue()); + } + + public void test_10() throws Exception { + Assert.assertEquals("\n", JSON.parseObject("{\"value\":\"\\n\"}", VO.class).getValue()); + } + + public void test_11() throws Exception { + Assert.assertEquals("\u000B", JSON.parseObject("{\"value\":\"\\v\"}", VO.class).getValue()); + } + + public void test_12() throws Exception { + Assert.assertEquals("\f", JSON.parseObject("{\"value\":\"\\f\"}", VO.class).getValue()); + } + + public void test_13() throws Exception { + Assert.assertEquals("\r", JSON.parseObject("{\"value\":\"\\r\"}", VO.class).getValue()); + } + + public void test_34() throws Exception { + Assert.assertEquals("\"", JSON.parseObject("{\"value\":\"\\\"\"}", VO.class).getValue()); + } + + public void test_39() throws Exception { + Assert.assertEquals("'", JSON.parseObject("{\"value\":\"\\'\"}", VO.class).getValue()); + } + + public void test_47() throws Exception { + Assert.assertEquals("/", JSON.parseObject("{\"value\":\"\\/\"}", VO.class).getValue()); + } + + public void test_92() throws Exception { + Assert.assertEquals("\\", JSON.parseObject("{\"value\":\"\\\\\"}", VO.class).getValue()); + } + public static class VO { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest_map.java b/src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest_map.java new file mode 100644 index 0000000000..4ec6577464 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest_map.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ParserSpecialCharTest_map extends TestCase { + + public void test_0() throws Exception { + Assert.assertEquals("\0", JSON.parseObject("{'value':'\\0'}").getString("value")); + } + + public void test_1() throws Exception { + Assert.assertEquals("\1", JSON.parseObject("{'value':'\\1'}").getString("value")); + } + + public void test_2() throws Exception { + Assert.assertEquals("\2", JSON.parseObject("{'value':'\\2'}").getString("value")); + } + + public void test_3() throws Exception { + Assert.assertEquals("\3", JSON.parseObject("{'value':'\\3'}").getString("value")); + } + + public void test_4() throws Exception { + Assert.assertEquals("\4", JSON.parseObject("{'value':'\\4'}").getString("value")); + } + + public void test_5() throws Exception { + Assert.assertEquals("\5", JSON.parseObject("{'value':'\\5'}").getString("value")); + } + + public void test_6() throws Exception { + Assert.assertEquals("\6", JSON.parseObject("{'value':'\\6'}").getString("value")); + } + + public void test_7() throws Exception { + Assert.assertEquals("\7", JSON.parseObject("{'value':'\\7'}").getString("value")); + } + + public void test_8() throws Exception { + Assert.assertEquals("\b", JSON.parseObject("{'value':'\\b'}").getString("value")); + } + + public void test_9() throws Exception { + Assert.assertEquals("\t", JSON.parseObject("{'value':'\\t'}").getString("value")); + } + + public void test_10() throws Exception { + Assert.assertEquals("\n", JSON.parseObject("{'value':'\\n'}").getString("value")); + } + + public void test_11() throws Exception { + Assert.assertEquals("\u000B", JSON.parseObject("{'value':'\\v'}").getString("value")); + } + + public void test_12() throws Exception { + Assert.assertEquals("\f", JSON.parseObject("{'value':'\\f'}").getString("value")); + } + + public void test_13() throws Exception { + Assert.assertEquals("\r", JSON.parseObject("{'value':'\\r'}").getString("value")); + } + + public void test_34() throws Exception { + Assert.assertEquals("\"", JSON.parseObject("{'value':'\\\"'}").getString("value")); + } + + public void test_39() throws Exception { + Assert.assertEquals("'", JSON.parseObject("{'value':'\\''}").getString("value")); + } + + public void test_47() throws Exception { + Assert.assertEquals("/", JSON.parseObject("{'value':'\\/'}").getString("value")); + } + + public void test_92() throws Exception { + Assert.assertEquals("\\", JSON.parseObject("{'value':'\\\\'}").getString("value")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest_map_singleQuote.java b/src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest_map_singleQuote.java new file mode 100644 index 0000000000..d06678555b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest_map_singleQuote.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ParserSpecialCharTest_map_singleQuote extends TestCase { + + public void test_0() throws Exception { + Assert.assertEquals("\0", JSON.parseObject("{\"value\":\"\\0\"}").getString("value")); + } + + public void test_1() throws Exception { + Assert.assertEquals("\1", JSON.parseObject("{\"value\":\"\\1\"}").getString("value")); + } + + public void test_2() throws Exception { + Assert.assertEquals("\2", JSON.parseObject("{\"value\":\"\\2\"}").getString("value")); + } + + public void test_3() throws Exception { + Assert.assertEquals("\3", JSON.parseObject("{\"value\":\"\\3\"}").getString("value")); + } + + public void test_4() throws Exception { + Assert.assertEquals("\4", JSON.parseObject("{\"value\":\"\\4\"}").getString("value")); + } + + public void test_5() throws Exception { + Assert.assertEquals("\5", JSON.parseObject("{\"value\":\"\\5\"}").getString("value")); + } + + public void test_6() throws Exception { + Assert.assertEquals("\6", JSON.parseObject("{\"value\":\"\\6\"}").getString("value")); + } + + public void test_7() throws Exception { + Assert.assertEquals("\7", JSON.parseObject("{\"value\":\"\\7\"}").getString("value")); + } + + public void test_8() throws Exception { + Assert.assertEquals("\b", JSON.parseObject("{\"value\":\"\\b\"}").getString("value")); + } + + public void test_9() throws Exception { + Assert.assertEquals("\t", JSON.parseObject("{\"value\":\"\\t\"}").getString("value")); + } + + public void test_10() throws Exception { + Assert.assertEquals("\n", JSON.parseObject("{\"value\":\"\\n\"}").getString("value")); + } + + public void test_11() throws Exception { + Assert.assertEquals("\u000B", JSON.parseObject("{\"value\":\"\\v\"}").getString("value")); + } + + public void test_12() throws Exception { + Assert.assertEquals("\f", JSON.parseObject("{\"value\":\"\\f\"}").getString("value")); + } + + public void test_13() throws Exception { + Assert.assertEquals("\r", JSON.parseObject("{\"value\":\"\\r\"}").getString("value")); + } + + public void test_34() throws Exception { + Assert.assertEquals("\"", JSON.parseObject("{\"value\":\"\\\"\"}").getString("value")); + } + + public void test_39() throws Exception { + Assert.assertEquals("'", JSON.parseObject("{\"value\":\"\\'\"}").getString("value")); + } + + public void test_47() throws Exception { + Assert.assertEquals("/", JSON.parseObject("{\"value\":\"\\/\"}").getString("value")); + } + + public void test_92() throws Exception { + Assert.assertEquals("\\", JSON.parseObject("{\"value\":\"\\\\\"}").getString("value")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/PrivateConstrunctorTest.java b/src/test/java/com/alibaba/json/bvt/parser/PrivateConstrunctorTest.java new file mode 100644 index 0000000000..1db9cfb944 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/PrivateConstrunctorTest.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.parser; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 2016/10/22. + */ +public class PrivateConstrunctorTest extends TestCase { + + public void test_parse() throws Exception { + JSON.parseObject("{}", Hidden.class); + } + + public static class Hidden { + private Hidden() {} + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ProductViewTest.java b/src/test/java/com/alibaba/json/bvt/parser/ProductViewTest.java new file mode 100755 index 0000000000..ff5cb56b91 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ProductViewTest.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.parser; + +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class ProductViewTest extends TestCase { + public void test_parse() throws Exception { + String text = "{\"code\":0,\"message\":\"Register Successfully!\",\"status\":\"OK\"}"; + Map map = JSON.parseObject(text, Map.class); + System.out.println(map.get("code").getClass()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicBooleanTest.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicBooleanTest.java new file mode 100644 index 0000000000..44ee971132 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicBooleanTest.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.parser; + +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ReadOnlyAtomicBooleanTest extends TestCase { + + public void test_readOnly() throws Exception { + Model model = new Model(); + model.value.set(true); + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"value\":true}", text); + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.value.get(), model2.value.get()); + } + + public static class Model { + private final AtomicBoolean value = new AtomicBoolean(); + + public AtomicBoolean getValue() { + return value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicBooleanTest_field.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicBooleanTest_field.java new file mode 100644 index 0000000000..3649eef466 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicBooleanTest_field.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.parser; + +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ReadOnlyAtomicBooleanTest_field extends TestCase { + + public void test_readOnly() throws Exception { + Model model = new Model(); + model.value.set(true); + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"value\":true}", text); + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.value.get(), model2.value.get()); + } + + public static class Model { + public final AtomicBoolean value = new AtomicBoolean(); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicIntegerTest.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicIntegerTest.java new file mode 100644 index 0000000000..c2118b3d98 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicIntegerTest.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.parser; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ReadOnlyAtomicIntegerTest extends TestCase { + + public void test_readOnly() throws Exception { + Model model = new Model(); + model.value.set(1001); + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"value\":1001}", text); + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.value.get(), model2.value.get()); + } + + public static class Model { + private final AtomicInteger value = new AtomicInteger(); + + public AtomicInteger getValue() { + return value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicIntegerTest_field.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicIntegerTest_field.java new file mode 100644 index 0000000000..1e0dfb6ad9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicIntegerTest_field.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.parser; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ReadOnlyAtomicIntegerTest_field extends TestCase { + + public void test_readOnly() throws Exception { + Model model = new Model(); + model.value.set(1001); + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"value\":1001}", text); + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.value.get(), model2.value.get()); + } + + public static class Model { + public final AtomicInteger value = new AtomicInteger(); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicLongTest.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicLongTest.java new file mode 100644 index 0000000000..0d26287a05 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicLongTest.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.parser; + +import java.util.concurrent.atomic.AtomicLong; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ReadOnlyAtomicLongTest extends TestCase { + + public void test_readOnly() throws Exception { + Model model = new Model(); + model.value.set(1001); + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"value\":1001}", text); + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.value.get(), model2.value.get()); + } + + public static class Model { + private final AtomicLong value = new AtomicLong(); + + public AtomicLong getValue() { + return value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicLongTest_field.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicLongTest_field.java new file mode 100644 index 0000000000..7e351593ab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicLongTest_field.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.parser; + +import java.util.concurrent.atomic.AtomicLong; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ReadOnlyAtomicLongTest_field extends TestCase { + + public void test_readOnly() throws Exception { + Model model = new Model(); + model.value.set(1001); + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"value\":1001}", text); + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model.value.get(), model2.value.get()); + } + + public static class Model { + public final AtomicLong value = new AtomicLong(); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest.java new file mode 100644 index 0000000000..cbad13506f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.parser; + +import java.util.List; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class ReadOnlyCollectionTest extends TestCase { + + public void test_readOnlyNullList() throws Exception { + String text = "{\"list\":[]}"; + Entity entity = JSON.parseObject(text, Entity.class); + Assert.assertNotNull(entity); + } + + public static class Entity { + + private List list; + + public List getList() { + return list; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest_final_field.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest_final_field.java new file mode 100644 index 0000000000..f7140545bf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest_final_field.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.parser; + +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ReadOnlyCollectionTest_final_field extends TestCase { + + public void test_readOnlyNullList() throws Exception { + String text = "{\"list\":[1,2,3]}"; + Entity entity = JSON.parseObject(text, Entity.class); + Assert.assertNull(entity.list); + } + + public static class Entity { + + public final List list = null; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest_final_field_null.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest_final_field_null.java new file mode 100644 index 0000000000..725236692c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest_final_field_null.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.parser; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ReadOnlyCollectionTest_final_field_null extends TestCase { + + public void test_readOnlyNullList() throws Exception { + String text = "{\"list\":[1,2,3]}"; + Entity entity = JSON.parseObject(text, Entity.class); + Assert.assertNotNull(entity); + Assert.assertEquals(3, entity.list.size()); + } + + public static class Entity { + + public final List list = new ArrayList(); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest.java new file mode 100644 index 0000000000..27f6406d86 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.parser; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ReadOnlyMapTest extends TestCase { + + public void test_readOnlyNullList() throws Exception { + String text = "{\"values\":{\"a\":{}}}"; + Entity entity = JSON.parseObject(text, Entity.class); + Assert.assertNotNull(entity); + Assert.assertNotNull(entity.values.get("a")); + Assert.assertTrue(entity.values.get("a") instanceof A); + } + + public static class Entity { + + private final Map values = new HashMap(); + + public Map getValues() { + return values; + } + + } + + public static class A { + public A() { + + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest2.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest2.java new file mode 100644 index 0000000000..7da19935e3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest2.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser; + +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ReadOnlyMapTest2 extends TestCase { + + public void test_readOnlyNullList() throws Exception { + String text = "{\"values\":{\"a\":{}}}"; + Entity entity = JSON.parseObject(text, Entity.class); + Assert.assertNotNull(entity); + Assert.assertNull(entity.values); + } + + public static class Entity { + + private Map values; + + public Map getValues() { + return values; + } + + } + + public static class A { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest2_final_field.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest2_final_field.java new file mode 100644 index 0000000000..4b4db35227 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest2_final_field.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.parser; + +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ReadOnlyMapTest2_final_field extends TestCase { + + public void test_readOnlyNullList() throws Exception { + String text = "{\"values\":{\"a\":{}}}"; + Entity entity = JSON.parseObject(text, Entity.class); + Assert.assertNotNull(entity); + Assert.assertNull(entity.values); + } + + public static class Entity { + + public final Map values = null; + + + } + + public static class A { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest_final_field.java b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest_final_field.java new file mode 100644 index 0000000000..2fa20b6b9f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest_final_field.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.parser; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ReadOnlyMapTest_final_field extends TestCase { + + public void test_readOnlyNullList() throws Exception { + String text = "{\"values\":{\"a\":{}}}"; + Entity entity = JSON.parseObject(text, Entity.class); + Assert.assertNotNull(entity); + Assert.assertNotNull(entity.values.get("a")); + Assert.assertTrue(entity.values.get("a") instanceof A); + } + + public static class Entity { + + public final Map values = new HashMap(); + + } + + public static class A { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/RedundantTest.java b/src/test/java/com/alibaba/json/bvt/parser/RedundantTest.java new file mode 100644 index 0000000000..3d240d1f99 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/RedundantTest.java @@ -0,0 +1,70 @@ +package com.alibaba.json.bvt.parser; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.deserializer.ExtraProcessor; +import com.alibaba.fastjson.parser.deserializer.ExtraTypeProvider; + +public class RedundantTest extends TestCase { + + public void test_extra() throws Exception { + ExtraProcessor processor = new ExtraProcessor() { + public void processExtra(Object object, String key, Object value) { + VO vo = (VO) object; + vo.getAttributes().put(key, value); + } + }; + + VO vo = JSON.parseObject("{\"id\":123,\"name\":\"abc\"}", VO.class, processor); + Assert.assertEquals(123, vo.getId()); + Assert.assertEquals("abc", vo.getAttributes().get("name")); + } + + public void test_extraWithType() throws Exception { + class MyExtraProcessor implements ExtraProcessor, ExtraTypeProvider { + public void processExtra(Object object, String key, Object value) { + VO vo = (VO) object; + vo.getAttributes().put(key, value); + } + + public Type getExtraType(Object object, String key) { + if ("value".equals(key)) { + return int.class; + } + return null; + } + }; + ExtraProcessor processor = new MyExtraProcessor(); + + VO vo = JSON.parseObject("{\"id\":123,\"value\":\"123456\"}", VO.class, processor); + Assert.assertEquals(123, vo.getId()); + Assert.assertEquals(123456, vo.getAttributes().get("value")); + } + + + public static class VO { + + private int id; + private Map attributes = new HashMap(); + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Map getAttributes() { + return attributes; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/TestException.java b/src/test/java/com/alibaba/json/bvt/parser/TestException.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/parser/TestException.java rename to src/test/java/com/alibaba/json/bvt/parser/TestException.java index c82d945c1c..89c52354f9 --- a/src/test/java/com/alibaba/json/test/bvt/parser/TestException.java +++ b/src/test/java/com/alibaba/json/bvt/parser/TestException.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.util.List; diff --git a/src/test/java/com/alibaba/json/bvt/parser/TestInitStringFieldAsEmpty.java b/src/test/java/com/alibaba/json/bvt/parser/TestInitStringFieldAsEmpty.java new file mode 100755 index 0000000000..37bc78b430 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TestInitStringFieldAsEmpty.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +public class TestInitStringFieldAsEmpty extends TestCase { + + public void test_private() throws Exception { + VO1 vo1 = JSON.parseObject("{}", VO1.class, Feature.InitStringFieldAsEmpty); + Assert.assertEquals("", vo1.getValue()); + } + + public void test_public() throws Exception { + VO2 vo2 = JSON.parseObject("{}", VO2.class, Feature.InitStringFieldAsEmpty); + Assert.assertEquals("", vo2.getValue()); + } + + private static class VO1 { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } + + public static class VO2 { + + private String value; + + public VO2() { + + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/TestInitStringFieldAsEmpty2.java b/src/test/java/com/alibaba/json/bvt/parser/TestInitStringFieldAsEmpty2.java new file mode 100755 index 0000000000..1fa3f6843d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TestInitStringFieldAsEmpty2.java @@ -0,0 +1,78 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +public class TestInitStringFieldAsEmpty2 extends TestCase { + + public void test_public() throws Exception { + VO1 vo1 = JSON.parseObject("{\"id\":0,\"value\":33, \"o\":{}}", VO1.class, Feature.InitStringFieldAsEmpty); + Assert.assertEquals("", vo1.getName()); + Assert.assertEquals("", vo1.getO().getValue()); + } + + public static class VO1 { + + private int id; + + private String name; + + private int value; + + private VO2 o; + + public VO1(){ + + } + + public VO2 getO() { + return o; + } + + public void setO(VO2 o) { + this.o = o; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + + public static class VO2 { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/TestUTF8.java b/src/test/java/com/alibaba/json/bvt/parser/TestUTF8.java old mode 100644 new mode 100755 similarity index 97% rename from src/test/java/com/alibaba/json/test/bvt/parser/TestUTF8.java rename to src/test/java/com/alibaba/json/bvt/parser/TestUTF8.java index 24de867a31..b53725dd23 --- a/src/test/java/com/alibaba/json/test/bvt/parser/TestUTF8.java +++ b/src/test/java/com/alibaba/json/bvt/parser/TestUTF8.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/TestUTF8_2.java b/src/test/java/com/alibaba/json/bvt/parser/TestUTF8_2.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/parser/TestUTF8_2.java rename to src/test/java/com/alibaba/json/bvt/parser/TestUTF8_2.java index 67a4d17a7d..11f6148f0d --- a/src/test/java/com/alibaba/json/test/bvt/parser/TestUTF8_2.java +++ b/src/test/java/com/alibaba/json/bvt/parser/TestUTF8_2.java @@ -1,12 +1,12 @@ -package com.alibaba.json.test.bvt.parser; - -import junit.framework.Assert; -import junit.framework.TestCase; +package com.alibaba.json.bvt.parser; +import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; -import com.alibaba.fastjson.util.ThreadLocalCache; +import com.alibaba.json.bvt.util.ThreadLocalCacheTest; + +import junit.framework.TestCase; public class TestUTF8_2 extends TestCase { @@ -39,7 +39,7 @@ public void test_utf_3() throws Exception { } public void test_utf_4() throws Exception { - ThreadLocalCache.clearChars(); + ThreadLocalCacheTest.clearChars(); byte[] bytes = decodeHex("C2FF".toCharArray()); String content = new String(bytes, "UTF-8"); diff --git a/src/test/java/com/alibaba/json/bvt/parser/TypeReferenceTest.java b/src/test/java/com/alibaba/json/bvt/parser/TypeReferenceTest.java new file mode 100755 index 0000000000..26333e089e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeReferenceTest.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.parser; + +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class TypeReferenceTest extends TestCase { + + public void test_list() throws Exception { + List list = JSON.parseObject("[1,2,3]", new TypeReference>() {}); + Assert.assertEquals(1L, ((Long) list.get(0)).longValue()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest.java rename to src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest.java index c82904dc73..fb6e118db9 --- a/src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.lang.reflect.Method; import java.math.BigDecimal; @@ -242,17 +242,17 @@ public void test_cast_to_Timestamp_null() throws Exception { public void test_cast_to_Timestamp_null2() throws Exception { Assert.assertEquals(null, TypeUtils.castToTimestamp(null)); } - + public void test_cast_to_BigDecimal_same() throws Exception { BigDecimal value = new BigDecimal("123"); Assert.assertEquals(true, value == TypeUtils.castToBigDecimal(value)); } - + public void test_cast_to_BigInteger_same() throws Exception { BigInteger value = new BigInteger("123"); Assert.assertEquals(true, value == TypeUtils.castToBigInteger(value)); } - + public void test_cast_Array() throws Exception { Assert.assertEquals(Integer[].class, TypeUtils.cast(new ArrayList(), Integer[].class, null).getClass()); } @@ -354,13 +354,13 @@ public void test_error_2() throws Exception { Method method = TypeUtilsTest.class.getMethod("f", List.class); - JSONException error = null; + Throwable error = null; try { TypeUtils.cast(json, method.getGenericParameterTypes()[0], ParserConfig.getGlobalInstance()); - } catch (JSONException e) { - error = e; + } catch (JSONException ex) { + error = ex; } - Assert.assertNotNull(error); + assertNotNull(error); } public void test_3() throws Exception { diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest2.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest2.java old mode 100644 new mode 100755 similarity index 98% rename from src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest2.java rename to src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest2.java index 3047f10429..7e70b3f900 --- a/src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest2.java +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest2.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.lang.reflect.ParameterizedType; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest3.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest3.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest3.java rename to src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest3.java index a9499fb01b..0f30d5280b --- a/src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest3.java +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest3.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -27,13 +27,7 @@ public void test_enum_2() throws Exception { } public void test_error() throws Exception { - Exception error = null; - try { - TypeUtils.castToEnum("\"A1\"", Type.class, null); - } catch (Exception ex) { - error = ex; - } - Assert.assertNotNull(error); + assertNull(TypeUtils.castToEnum("\"A1\"", Type.class, null)); } public void test_error_1() throws Exception { diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest4.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest4.java old mode 100644 new mode 100755 similarity index 96% rename from src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest4.java rename to src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest4.java index 573f5a905e..6985b4a9c4 --- a/src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsTest4.java +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest4.java @@ -1,17 +1,19 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; -import junit.framework.Assert; import junit.framework.TestCase; +import org.junit.Assert; + import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.util.TypeUtils; +@SuppressWarnings("unchecked") public class TypeUtilsTest4 extends TestCase { public void test_array() throws Exception { diff --git a/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_cast.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_cast.java new file mode 100644 index 0000000000..3f6d02533d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_cast.java @@ -0,0 +1,99 @@ +package com.alibaba.json.bvt.parser; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Calendar; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.util.TypeUtils; + +public class TypeUtilsTest_cast extends TestCase { + + public void test_cast_0() throws Exception { + Assert.assertArrayEquals(new byte[0], TypeUtils.cast(new byte[0], byte[].class, null)); + } + + public void test_cast_1() throws Exception { + ParameterizedType parameterizedType = (ParameterizedType) new TypeReference>() {}.getType(); + Type type = parameterizedType.getActualTypeArguments()[0]; + Assert.assertEquals(null, TypeUtils.cast("", type, null)); + } + + public void test_castToDate_error() throws Exception { + Exception error = null; + try { + TypeUtils.cast(0, MyCalendar.class, null); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_castToDate_error_nullClass() throws Exception { + Exception error = null; + try { + TypeUtils.cast(0, (Class) null, null); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + @SuppressWarnings("serial") + private class MyCalendar extends Calendar { + + @Override + protected void computeTime() { + // TODO Auto-generated method stub + + } + + @Override + protected void computeFields() { + // TODO Auto-generated method stub + + } + + @Override + public void add(int field, int amount) { + // TODO Auto-generated method stub + + } + + @Override + public void roll(int field, boolean up) { + // TODO Auto-generated method stub + + } + + @Override + public int getMinimum(int field) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaximum(int field) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getGreatestMinimum(int field) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getLeastMaximum(int field) { + // TODO Auto-generated method stub + return 0; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToBytes.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToBytes.java new file mode 100644 index 0000000000..e70714ddc8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToBytes.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.util.TypeUtils; + +public class TypeUtilsTest_castToBytes extends TestCase { + + public void test_castToDate() throws Exception { + Assert.assertArrayEquals(new byte[0], TypeUtils.castToBytes(new byte[0])); + } + + public void test_castToDate_error() throws Exception { + Exception error = null; + try { + TypeUtils.castToBytes(new int[0]); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToDate.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToDate.java new file mode 100644 index 0000000000..77064a9748 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToDate.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.parser; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.util.TypeUtils; + +public class TypeUtilsTest_castToDate extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_castToDate() throws Exception { + JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; + Date date = TypeUtils.castToDate("2012-07-15 12:12:11"); + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + format.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals(format.parseObject("2012-07-15 12:12:11"), date); + JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + } + + public void test_castToDate_error() throws Exception { + Exception error = null; + try { + TypeUtils.castToDate("你妈你妈-MM-dd"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_castToDate_zero() throws Exception { + Assert.assertEquals(new Date(0), TypeUtils.castToDate("0")); + } + + public void test_castToDate_negative() throws Exception { + Assert.assertEquals(new Date(-1), TypeUtils.castToDate(-1)); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToJavaBean.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToJavaBean.java new file mode 100644 index 0000000000..80075d052b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToJavaBean.java @@ -0,0 +1,254 @@ +package com.alibaba.json.bvt.parser; + +import java.lang.reflect.Field; +import java.net.URL; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentMap; + +import com.alibaba.fastjson.parser.ParserConfig; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.JavaBeanSerializer; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.util.TypeUtils; + +import junit.framework.TestCase; + +public class TypeUtilsTest_castToJavaBean extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.parser.TypeUtilsTest_castToJavaBean."); + } + + public void test_castToJavaBean_StackTraceElement() throws Exception { + Map map = new HashMap(); + map.put("className", "java.lang.Object"); + map.put("methodName", "hashCode"); + StackTraceElement element = TypeUtils.castToJavaBean(map, StackTraceElement.class, null); + Assert.assertEquals("java.lang.Object", element.getClassName()); + Assert.assertEquals("hashCode", element.getMethodName()); + Assert.assertEquals(null, element.getFileName()); + } + + public void test_castToJavaBean_StackTraceElement_1() throws Exception { + Map map = new HashMap(); + map.put("className", "java.lang.Object"); + map.put("methodName", "hashCode"); + map.put("lineNumber", 12); + StackTraceElement element = TypeUtils.castToJavaBean(map, StackTraceElement.class, null); + Assert.assertEquals("java.lang.Object", element.getClassName()); + Assert.assertEquals("hashCode", element.getMethodName()); + Assert.assertEquals(null, element.getFileName()); + Assert.assertEquals(12, element.getLineNumber()); + } + + public void test_castToJavaBean_type() throws Exception { + Map map = new HashMap(); + map.put("@type", "java.lang.StackTraceElement"); + map.put("className", "java.lang.Object"); + map.put("methodName", "hashCode"); + map.put("lineNumber", 12); + StackTraceElement element = (StackTraceElement) TypeUtils.castToJavaBean(map, Object.class, null); + Assert.assertEquals("java.lang.Object", element.getClassName()); + Assert.assertEquals("hashCode", element.getMethodName()); + Assert.assertEquals(null, element.getFileName()); + Assert.assertEquals(12, element.getLineNumber()); + } + + public void test_error() throws Exception { + Map map = new HashMap(); + map.put("@type", "xxx"); + Exception error = null; + try { + TypeUtils.castToJavaBean(map, Object.class, null); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error2() throws Exception { + Map map = new HashMap(); + map.put("@type", ""); + Exception error = null; + try { + TypeUtils.castToJavaBean(map, Object.class, null); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_mapping() throws Exception { + addClassMapping("my_xxx", VO.class); + addClassMapping(null, VO.class); + Map map = new HashMap(); + map.put("@type", "my_xxx"); + map.put("id", 123); + VO vo = (VO) TypeUtils.castToJavaBean(map, Object.class); + Assert.assertEquals(123, vo.getId()); + TypeUtils.clearClassMapping(); + } + + public static void addClassMapping(String className, Class clazz) throws Exception { + Field field = TypeUtils.class.getDeclaredField("mappings"); + field.setAccessible(true); + field.get(null); + + ConcurrentMap> mappings = (ConcurrentMap>) field.get(null); + + if (className == null) { + className = clazz.getName(); + } + + mappings.put(className, clazz); + } + + public void test_interface() throws Exception { + Map map = new HashMap(); + map.put("id", 123); + VO vo = TypeUtils.castToJavaBean(map, VO.class); + Assert.assertEquals(123, vo.getId()); + } + + public void test_bean() throws Exception { + Map map = new HashMap(); + map.put("id", 123); + Entity vo = TypeUtils.castToJavaBean(map, Entity.class); + Assert.assertEquals(123, vo.getId()); + + Assert.assertEquals("{\"id\":123}", JSON.toJSONString(vo)); + } + + public void test_loadClass() throws Exception { + Assert.assertNull(TypeUtils.loadClass(null)); + Assert.assertNull(TypeUtils.loadClass("")); + } + + public void test_loadClass_1() throws Exception { + TypeUtils.clearClassMapping(); + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(new TestLoader()); + try { + Assert.assertEquals(VO.class, + TypeUtils.loadClass("com.alibaba.json.bvt.parser.TypeUtilsTest_castToJavaBean$VO")); + } finally { + Thread.currentThread().setContextClassLoader(contextClassLoader); + } + } + + public void test_loadClass_2() throws Exception { + TypeUtils.clearClassMapping(); + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(new TestLoader()); + try { + Assert.assertNull(TypeUtils.loadClass("xxx_xx")); + } finally { + Thread.currentThread().setContextClassLoader(contextClassLoader); + } + } + + public void test_bean_2() throws Exception { + Map map = new HashMap(); + map.put("id", 123); + PO vo = TypeUtils.castToJavaBean(map, PO.class); + Assert.assertEquals(123, vo.id); + + SerializeWriter out = new SerializeWriter(); + + try { + SerializeConfig config = new SerializeConfig(); + JSONSerializer serializer = new JSONSerializer(out, config); + config.put(PO.class, new JavaBeanSerializer(PO.class, Collections.singletonMap("id", "ID"))); + + serializer.write(vo); + + Assert.assertEquals("{\"ID\":123}", out.toString()); + } finally { + out.close(); + } + + + } + + public void test_bean_3() throws Exception { + Map map = new HashMap(); + map.put("id", 123); + PO vo = TypeUtils.castToJavaBean(map, PO.class); + Assert.assertEquals(123, vo.id); + + SerializeWriter out = new SerializeWriter(); + + try { + SerializeConfig config = new SerializeConfig(); + JSONSerializer serializer = new JSONSerializer(out, config); + config.put(PO.class, new JavaBeanSerializer(PO.class, Collections.singletonMap("id", (String) null))); + + serializer.write(vo); + + Assert.assertEquals("{}", out.toString()); + } finally { + out.close(); + } + + + } + + public static interface VO { + + void setId(int value); + + int getId(); + + ClassLoader getClassLoader(); + } + + public static class Entity { + + private int id; + protected String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + protected String getName() { + return name; + } + + protected void setName(String name) { + this.name = name; + } + + public ClassLoader getClassLoader() { + return Entity.class.getClassLoader(); + } + } + + private static class PO { + public int id; + } + + public static class TestLoader extends ClassLoader { + + public TestLoader(){ + super(null); + } + + public URL getResource(String name) { + return null; + } + + public Class loadClass(String name) throws ClassNotFoundException { + throw new ClassNotFoundException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToJavaBean_JSONType.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToJavaBean_JSONType.java new file mode 100644 index 0000000000..3eef7eb55a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToJavaBean_JSONType.java @@ -0,0 +1,120 @@ +package com.alibaba.json.bvt.parser; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.util.TypeUtils; + +public class TypeUtilsTest_castToJavaBean_JSONType extends TestCase { + + public void test_castToJavaBean() throws Exception { + Map map = new HashMap(); + map.put("id", 123); + map.put("name", "abc"); + VO vo = TypeUtils.castToJavaBean(map, VO.class, null); + Assert.assertEquals(123, vo.getId()); + Assert.assertEquals("abc", vo.getName()); + + Assert.assertEquals("{\"name\":\"abc\",\"id\":123}", JSON.toJSONString(vo)); + } + + public void test_castToJavaBean_v2() throws Exception { + Map map = new HashMap(); + map.put("id", 123); + map.put("name", "abc"); + V2 vo = TypeUtils.castToJavaBean(map, V2.class, null); + Assert.assertEquals(123, vo.getId()); + Assert.assertEquals("abc", vo.getName()); + + Assert.assertEquals("{\"name\":\"abc\",\"id\":123}", JSON.toJSONString(vo)); + } + + public void test_castToJavaBean_v3() throws Exception { + Map map = new HashMap(); + map.put("id", 123); + map.put("name", "abc"); + V3 vo = TypeUtils.castToJavaBean(map, V3.class, null); + Assert.assertEquals(123, vo.getId()); + Assert.assertEquals("abc", vo.getName()); + + Assert.assertEquals("{\"name\":\"abc\",\"id\":123}", JSON.toJSONString(vo)); + } + + @JSONType(orders={"name", "id"}) + public static class VO { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + + @JSONType(orders={"name"}) + public static class V2 { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + + @JSONType(orders={"name","xx"}) + public static class V3 { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_compatibleWithJavaBean.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_compatibleWithJavaBean.java new file mode 100644 index 0000000000..9c37048e9b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_compatibleWithJavaBean.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.util.TypeUtils; + +public class TypeUtilsTest_compatibleWithJavaBean extends TestCase { + + private boolean origin_compatibleWithJavaBean; + + protected void setUp() throws Exception { + origin_compatibleWithJavaBean = TypeUtils.compatibleWithJavaBean; + TypeUtils.compatibleWithJavaBean = true; + } + + protected void tearDown() throws Exception { + TypeUtils.compatibleWithJavaBean = origin_compatibleWithJavaBean; + } + + public void test_true() throws Exception { + String text = JSON.toJSONString(new VO(123)); + Assert.assertEquals("{\"ID\":123}", text); + Assert.assertEquals(123, JSON.parseObject(text, VO.class).getID()); + } + + public static class VO { + + private int id; + + public VO(){ + + } + + public VO(int id){ + this.id = id; + } + + public int getID() { + return id; + } + + public void setID(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_compatibleWithJavaBean_boolean.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_compatibleWithJavaBean_boolean.java new file mode 100644 index 0000000000..43f822f61f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_compatibleWithJavaBean_boolean.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.parser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.util.TypeUtils; + +public class TypeUtilsTest_compatibleWithJavaBean_boolean extends TestCase { + + private boolean origin_compatibleWithJavaBean; + + protected void setUp() throws Exception { + origin_compatibleWithJavaBean = TypeUtils.compatibleWithJavaBean; + TypeUtils.compatibleWithJavaBean = true; + } + + protected void tearDown() throws Exception { + TypeUtils.compatibleWithJavaBean = origin_compatibleWithJavaBean; + } + + public void test_true() throws Exception { + String text = JSON.toJSONString(new VO(true)); + Assert.assertEquals("{\"ID\":true}", text); + Assert.assertEquals(true, JSON.parseObject(text, VO.class).isID()); + } + + public static class VO { + + private boolean id; + + public VO(){ + + } + + public VO(boolean id){ + this.id = id; + } + + public boolean isID() { + return id; + } + + public void setID(boolean id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_interface.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_interface.java new file mode 100644 index 0000000000..1cd9959052 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_interface.java @@ -0,0 +1,136 @@ +package com.alibaba.json.bvt.parser; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.annotation.JSONField; + +public class TypeUtilsTest_interface extends TestCase { + + public void test_castToJavaBean() throws Exception { + VO vo = new VO(); + vo.setId(123); + vo.setName("abc"); + + Assert.assertEquals("{\"ID\":123,\"name\":\"abc\"}", JSON.toJSONString(vo)); + } + + public void test_parse() throws Exception { + VO vo = JSON.parseObject("{\"xid\":123,\"name\":\"abc\"}", VO.class); + + Assert.assertEquals(123, vo.getId()); + Assert.assertEquals("abc", vo.getName()); + } + + public void test_parse_var() throws Exception { + List list = JSON.parseObject("[]", new TypeReference>() { + }); + Assert.assertNotNull(list); + Assert.assertEquals(0, list.size()); + } + + public void test_deser() throws Exception { + JSON.parseObject("{\"id\":123}", new TypeReference(){}); + } + + public void test_deser2() throws Exception { + JSON.parseObject("{\"id\":123}", new TypeReference>(){}); + } + + public void test_deser2_x() throws Exception { + JSON.parseObject("{\"id\":123}", new TypeReference>(){}); + } + + public static class X_I extends X { + + } + + public static class X_X extends X { + + } + + public static class X { + + private T id; + + public X(){ + } + + public T getId() { + return id; + } + + public void setId(T id) { + this.id = id; + } + + } + + public static class VO implements IV { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getName(String xx) { + return null; + } + + public String getName(String xx, int v) { + // TODO Auto-generated method stub + return null; + } + + @JSONField(deserialize = false) + public void setName(int value) { + // TODO Auto-generated method stub + + } + + public void setName(int value, int x) { + // TODO Auto-generated method stub + + } + + } + + public static interface IV { + + @JSONField(name = "ID") + int getId(); + + @JSONField(name = "xid") + void setId(int value); + + @JSONField(name = "NAME") + String getName(String xx); + + @JSONField(name = "NAME") + String getName(String xx, int v); + + @JSONField(name = "xid_1") + void setName(int value); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_loadClass.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_loadClass.java new file mode 100644 index 0000000000..f05ef48d2a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_loadClass.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.parser; + +import org.junit.Assert; + +import com.alibaba.fastjson.util.TypeUtils; + +import junit.framework.TestCase; + +public class TypeUtilsTest_loadClass extends TestCase { + + public void test_loadClass() throws Exception { + Assert.assertSame(Entity.class, + TypeUtils.loadClass("com.alibaba.json.bvt.parser.TypeUtilsTest_loadClass$Entity", + Entity.class.getClassLoader())); + + Assert.assertSame(Entity.class, + TypeUtils.loadClass("com.alibaba.json.bvt.parser.TypeUtilsTest_loadClass$Entity", null)); + } + + public void test_error() throws Exception { + Assert.assertNull(TypeUtils.loadClass("com.alibaba.json.bvt.parser.TypeUtilsTest_loadClass.Entity", + Entity.class.getClassLoader())); + } + + public static class Entity { + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsToJSONTest.java b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsToJSONTest.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsToJSONTest.java rename to src/test/java/com/alibaba/json/bvt/parser/TypeUtilsToJSONTest.java index 6dd1ce6c71..da3f22f787 --- a/src/test/java/com/alibaba/json/test/bvt/parser/TypeUtilsToJSONTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/TypeUtilsToJSONTest.java @@ -1,10 +1,10 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/UTF8ByteArrayLexerTest_symbol.java b/src/test/java/com/alibaba/json/bvt/parser/UTF8ByteArrayLexerTest_symbol.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/parser/UTF8ByteArrayLexerTest_symbol.java rename to src/test/java/com/alibaba/json/bvt/parser/UTF8ByteArrayLexerTest_symbol.java index 5db9cd288f..bc739d568a --- a/src/test/java/com/alibaba/json/test/bvt/parser/UTF8ByteArrayLexerTest_symbol.java +++ b/src/test/java/com/alibaba/json/bvt/parser/UTF8ByteArrayLexerTest_symbol.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/UTF8ByteArrayParseTest.java b/src/test/java/com/alibaba/json/bvt/parser/UTF8ByteArrayParseTest.java old mode 100644 new mode 100755 similarity index 89% rename from src/test/java/com/alibaba/json/test/bvt/parser/UTF8ByteArrayParseTest.java rename to src/test/java/com/alibaba/json/bvt/parser/UTF8ByteArrayParseTest.java index be6be0ea1f..69867e4e56 --- a/src/test/java/com/alibaba/json/test/bvt/parser/UTF8ByteArrayParseTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/UTF8ByteArrayParseTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.parser; +package com.alibaba.json.bvt.parser; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/bvt/parser/UnquoteNameTest.java b/src/test/java/com/alibaba/json/bvt/parser/UnquoteNameTest.java new file mode 100644 index 0000000000..2660a507cb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/UnquoteNameTest.java @@ -0,0 +1,78 @@ +package com.alibaba.json.bvt.parser; + +import java.io.StringReader; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONReader; + +import junit.framework.TestCase; + +public class UnquoteNameTest extends TestCase { + public void test_unquote() throws Exception { + String text = "{_id:1001}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(1001, model._id); + } + + public void test_unquote_parse() throws Exception { + String text = "{ _id:1001}"; + + JSONObject model = JSON.parseObject(text); + Assert.assertEquals(1001, model.get("_id")); + } + + public void test_unquote_parse_1() throws Exception { + String text = "{ $id:1001}"; + + JSONObject model = JSON.parseObject(text); + Assert.assertEquals(1001, model.get("$id")); + } + + public void test_unquote_reader() throws Exception { + String text = "{_id:1001}"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertEquals(1001, model._id); + reader.close(); + } + + public void test_unquote_reader_parse() throws Exception { + String text = "{_id:1001}"; + + JSONReader reader = new JSONReader(new StringReader(text)); + JSONObject model = (JSONObject) reader.readObject(); + Assert.assertEquals(1001, model.get("_id")); + reader.close(); + } + + public void test_obj() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{_id:123}")); + + reader.startObject(); + Assert.assertEquals("_id", reader.readString()); + Assert.assertEquals(Integer.valueOf(123), reader.readInteger()); + reader.endObject(); + + reader.close(); + } + + public void test_obj_1() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{$id:123}")); + + reader.startObject(); + Assert.assertEquals("$id", reader.readString()); + Assert.assertEquals(Integer.valueOf(123), reader.readInteger()); + reader.endObject(); + + reader.close(); + } + + public static class Model { + public int _id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest.java b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest.java new file mode 100644 index 0000000000..e42e223ac6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest.java @@ -0,0 +1,73 @@ +package com.alibaba.json.bvt.parser.array; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class BeanToArrayTest extends TestCase { + + public void test_beanToArray_parse() throws Exception { + String text = "{\"go\":[[\"0\",[true,false],9999999999999,99,\"012345678901234567890123\",\"ftp://gfw.yma.co/x160\",\"xxxx\",\"9876543210123456\",[[\"m\",\"不要开心\",\"http://gfw.meiya.co\",\"123456@gg.com\",\"麻麻\",\"add\",null,\"9876543210123456\"]],null,[\"add\",\"ww\"],999,1234567890123]],\"success\":true}"; + GR result = JSON.parseObject(text, GR.class); + Assert.assertNotNull(result); + Assert.assertEquals(1, result.go.size()); + Assert.assertEquals("0", result.go.get(0).bi); + Assert.assertEquals(true, result.go.get(0).co.qu); + Assert.assertEquals(false, result.go.get(0).co.sa); + Assert.assertEquals(9999999999999L, result.go.get(0).gm.getTime()); + Assert.assertEquals(99, result.go.get(0).grCo); + } + + public static class GR { + public List go; + public boolean success; + } + + @JSONType(parseFeatures = Feature.SupportArrayToBean, serialzeFeatures=SerializerFeature.BeanToArray) + public static class GO { + + public String bi; + public CO co; + + public Date gm; + public int grCo; + public String grId; + public String grNa; + public String grIm; + public String ma; + public List me = new ArrayList(); + public int th = 500; + public List pe = new ArrayList(); + public String no; + public long ve; + } + + @JSONType(parseFeatures = Feature.SupportArrayToBean) + public static class MO { + + public String ope; + public String use; + public String log; + public String rea; + public String gro; + public String gen; + public String hea; + public String nic; + } + + @JSONType(parseFeatures = Feature.SupportArrayToBean) + public static class CO { + + public boolean sa; + public boolean qu; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest2.java b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest2.java new file mode 100644 index 0000000000..316c2fa7ef --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest2.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.parser.array; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class BeanToArrayTest2 extends TestCase { + + public void test_bool() throws Exception { + Model model = JSON.parseObject("[true,false]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(true, model.v1); + Assert.assertEquals(false, model.v2); + } + + public void test_bool_space() throws Exception { + Model model = JSON.parseObject("[true ,false ]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(true, model.v1); + Assert.assertEquals(false, model.v2); + } + + public void test_bool_num() throws Exception { + Model model = JSON.parseObject("[1,0]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(true, model.v1); + Assert.assertEquals(false, model.v2); + } + + public void test_bool_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[t,0]", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public boolean v1; + public boolean v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest3.java b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest3.java new file mode 100644 index 0000000000..6fa8427bf2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest3.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.array; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class BeanToArrayTest3 extends TestCase { + + public void test_array() throws Exception { + Model model = new Model(); + model.item = new Item(); + model.item.id = 1001; + + String text = JSON.toJSONString(model); + + Assert.assertEquals("{\"item\":[1001]}", text); + + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model2.item.id, model.item.id); + } + + public static class Model { + @JSONField(serialzeFeatures=SerializerFeature.BeanToArray, parseFeatures=Feature.SupportArrayToBean) + public Item item; + } + + public static class Item { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest3_private.java b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest3_private.java new file mode 100644 index 0000000000..bae1676211 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest3_private.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.array; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class BeanToArrayTest3_private extends TestCase { + + public void test_array() throws Exception { + Model model = new Model(); + model.item = new Item(); + model.item.id = 1001; + + String text = JSON.toJSONString(model); + + Assert.assertEquals("{\"item\":[1001]}", text); + + Model model2 = JSON.parseObject(text, Model.class); + Assert.assertEquals(model2.item.id, model.item.id); + } + + private static class Model { + @JSONField(serialzeFeatures=SerializerFeature.BeanToArray, parseFeatures=Feature.SupportArrayToBean) + public Item item; + } + + private static class Item { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_date.java b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_date.java new file mode 100644 index 0000000000..a685e926ba --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_date.java @@ -0,0 +1,71 @@ +package com.alibaba.json.bvt.parser.array; + +import java.io.StringReader; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.JSONReaderScanner; +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class BeanToArrayTest_date extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + long time = System.currentTimeMillis(); + Model model = JSON.parseObject("[" + time + "," + time + "]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(time, model.v1.getTime()); + Assert.assertEquals(time, model.v2.getTime()); + } + + public void test_date_reader() throws Exception { + long time = System.currentTimeMillis(); + Model model = new JSONReader(new StringReader("[" + time + "," + time + "]"), Feature.SupportArrayToBean).readObject(Model.class); + Assert.assertEquals(time, model.v1.getTime()); + Assert.assertEquals(time, model.v2.getTime()); + } + + public void test_date_null() throws Exception { + Model model = JSON.parseObject("[null,null]", Model.class, Feature.SupportArrayToBean); + Assert.assertNull(model.v1); + Assert.assertNull(model.v2); + } + + public void test_date_null_reader() throws Exception { + Model model = new JSONReader(new StringReader("[null,null]"), Feature.SupportArrayToBean).readObject(Model.class); + Assert.assertNull(model.v1); + Assert.assertNull(model.v2); + } + + public void test_date2() throws Exception { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + Model model = JSON.parseObject("[\"2016-01-01\",\"2016-01-02\"]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(dateFormat.parse("2016-01-01").getTime(), model.v1.getTime()); + Assert.assertEquals(dateFormat.parse("2016-01-02").getTime(), model.v2.getTime()); + } + + public void test_date2_reader() throws Exception { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + + Model model = new JSONReader(new StringReader("[\"2016-01-01\",\"2016-01-02\"]"), Feature.SupportArrayToBean).readObject(Model.class); + Assert.assertEquals(dateFormat.parse("2016-01-01").getTime(), model.v1.getTime()); + Assert.assertEquals(dateFormat.parse("2016-01-02").getTime(), model.v2.getTime()); + } + + public static class Model { + public Date v1; + public Date v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_date_private.java b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_date_private.java new file mode 100644 index 0000000000..64f31c473b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_date_private.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.parser.array; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class BeanToArrayTest_date_private extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + long time = System.currentTimeMillis(); + Model model = JSON.parseObject("[" + time + "," + time + "]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(time, model.v1.getTime()); + Assert.assertEquals(time, model.v2.getTime()); + } + + public void test_date_null() throws Exception { + Model model = JSON.parseObject("[null,null]", Model.class, Feature.SupportArrayToBean); + Assert.assertNull(model.v1); + Assert.assertNull(model.v2); + } + + public void test_date2() throws Exception { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + Model model = JSON.parseObject("[\"2016-01-01\",\"2016-01-02\"]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(dateFormat.parse("2016-01-01").getTime(), model.v1.getTime()); + Assert.assertEquals(dateFormat.parse("2016-01-02").getTime(), model.v2.getTime()); + } + + private static class Model { + public Date v1; + public Date v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_enum.java b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_enum.java new file mode 100644 index 0000000000..6436bb644d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_enum.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.parser.array; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class BeanToArrayTest_enum extends TestCase { + + public void test_enum() throws Exception { + Model model = JSON.parseObject("[\"A\",\"B\"]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(Type.A, model.v1); + Assert.assertEquals(Type.B, model.v2); + } + + public void test_enum_space() throws Exception { + Model model = JSON.parseObject("[\"A\" ,\"B\" ]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(Type.A, model.v1); + Assert.assertEquals(Type.B, model.v2); + } + + public void test_enum_num() throws Exception { + Model model = JSON.parseObject("[1,0]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(Type.B, model.v1); + Assert.assertEquals(Type.A, model.v2); + } + + public void test_enum_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[t,0]", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public Type v1; + public Type v2; + } + + public static enum Type { + A, B, C + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_enum_private.java b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_enum_private.java new file mode 100644 index 0000000000..683c787880 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_enum_private.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.parser.array; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class BeanToArrayTest_enum_private extends TestCase { + + public void test_enum() throws Exception { + Model model = JSON.parseObject("[\"A\",\"B\"]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(Type.A, model.v1); + Assert.assertEquals(Type.B, model.v2); + } + + public void test_enum_space() throws Exception { + Model model = JSON.parseObject("[\"A\" ,\"B\" ]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(Type.A, model.v1); + Assert.assertEquals(Type.B, model.v2); + } + + public void test_enum_num() throws Exception { + Model model = JSON.parseObject("[1,0]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(Type.B, model.v1); + Assert.assertEquals(Type.A, model.v2); + } + + public void test_enum_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[t,0]", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Model { + + public Type v1; + public Type v2; + } + + private static enum Type { + A, B, C + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_int.java b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_int.java new file mode 100644 index 0000000000..120a50125c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_int.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt.parser.array; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class BeanToArrayTest_int extends TestCase { + + public void test_int() throws Exception { + Model model = JSON.parseObject("[-100,100]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(-100L, model.v1); + Assert.assertEquals(100L, model.v2); + } + + public void test_int_space() throws Exception { + Model model = JSON.parseObject("[-100 ,100 ]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(-100L, model.v1); + Assert.assertEquals(100L, model.v2); + } + + public void test_int_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[-", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_int_error_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("[-1:", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_int_error_max() throws Exception { + Exception error = null; + try { + JSON.parseObject("[1,92233720368547758000}", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_bool_error_min() throws Exception { + Exception error = null; + try { + JSON.parseObject("[1,-92233720368547758000}", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + public int v1; + public int v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_long.java b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_long.java new file mode 100644 index 0000000000..e338fb2679 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_long.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt.parser.array; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class BeanToArrayTest_long extends TestCase { + + public void test_long() throws Exception { + Model model = JSON.parseObject("[-100,100]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(-100L, model.v1); + Assert.assertEquals(100L, model.v2); + } + + public void test_long_space() throws Exception { + Model model = JSON.parseObject("[-100 ,100 ]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(-100L, model.v1); + Assert.assertEquals(100L, model.v2); + } + + public void test_long_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[-", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_long_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("[-1:", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_long_error_max() throws Exception { + Exception error = null; + try { + JSON.parseObject("[1,92233720368547758000}", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_long_error_min() throws Exception { + Exception error = null; + try { + JSON.parseObject("[1,-92233720368547758000}", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + public long v1; + public long v2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_private.java b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_private.java new file mode 100644 index 0000000000..d96ea5beda --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_private.java @@ -0,0 +1,72 @@ +package com.alibaba.json.bvt.parser.array; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class BeanToArrayTest_private extends TestCase { + + public void test_beanToArray_parse() throws Exception { + String text = "{\"go\":[[\"0\",[true,false],9999999999999,99,\"012345678901234567890123\",\"ftp://gfw.yma.co/x160\",\"xxxx\",\"9876543210123456\",[[\"m\",\"不要开心\",\"http://gfw.meiya.co\",\"123456@gg.com\",\"麻麻\",\"add\",null,\"9876543210123456\"]],null,[\"add\",\"ww\"],999,1234567890123]],\"success\":true}"; + GR result = JSON.parseObject(text, GR.class); + Assert.assertNotNull(result); + Assert.assertEquals(1, result.go.size()); + Assert.assertEquals("0", result.go.get(0).bi); + Assert.assertEquals(true, result.go.get(0).co.qu); + Assert.assertEquals(false, result.go.get(0).co.sa); + Assert.assertEquals(9999999999999L, result.go.get(0).gm.getTime()); + Assert.assertEquals(99, result.go.get(0).grCo); + } + + public static class GR { + public List go; + public boolean success; + } + + @JSONType(parseFeatures = Feature.SupportArrayToBean) + private static class GO { + + public String bi; + public CO co; + + public Date gm; + public int grCo; + public String grId; + public String grNa; + public String grIm; + public String ma; + public List me = new ArrayList(); + public int th = 500; + public List pe = new ArrayList(); + public String no; + public long ve; + } + + @JSONType(parseFeatures = Feature.SupportArrayToBean) + private static class MO { + + public String ope; + public String use; + public String log; + public String rea; + public String gro; + public String gen; + public String hea; + public String nic; + } + + @JSONType(parseFeatures = Feature.SupportArrayToBean) + private static class CO { + + public boolean sa; + public boolean qu; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest0.java b/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest0.java new file mode 100644 index 0000000000..00da232b97 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest0.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.autoType; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 10/02/2017. + */ +public class AutoTypeTest0 extends TestCase { + public void test_0() throws Exception { + String text = "{\"@type\":\"com.alibaba.json.bvt.parser.autoType.AutoTypeTest0$Model\",\"id\":123}"; + Model model = JSON.parseObject(text, Model.class); + assertEquals(123, model.id); + + Model model2 = (Model) JSON.parse(text); + assertEquals(123, model2.id); + } + + public static class Model { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest1.java b/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest1.java new file mode 100644 index 0000000000..c9e4cc7f3d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest1.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.parser.autoType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +/** + * Created by wenshao on 10/02/2017. + */ +public class AutoTypeTest1 extends TestCase { + public void test_0() throws Exception { + ParserConfig config = new ParserConfig(); + config.setAutoTypeSupport(true); + + System.out.println(Model.class.isAnnotationPresent(JSONField.class)); + String text = "{\"@type\":\"com.alibaba.json.bvt.parser.autoType.AutoTypeTest1$Model\",\"id\":123}"; + + Model model2 = (Model) JSON.parseObject(text, Object.class, config); + assertEquals(123, model2.id); + } + + @JSONType + public static class Model { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest2_deny.java b/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest2_deny.java new file mode 100644 index 0000000000..210ad089b2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest2_deny.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.parser.autoType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +/** + * Created by wenshao on 10/02/2017. + */ +public class AutoTypeTest2_deny extends TestCase { + public void test_0() throws Exception { + ParserConfig config = new ParserConfig(); + + String text = "{\"@type\":\"com.sun.rowset.JdbcRowSetImpl\",\"dataSourceName\":\"rmi://ip:port/Object\",\"autoCommit\":true}"; + + Exception error = null; + try { + JSON.parse(text); + } catch (JSONException ex) { + error = ex; + } + + assertNotNull(error); + assertTrue(error.getMessage().startsWith("autoType is not support")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest3_deny.java b/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest3_deny.java new file mode 100644 index 0000000000..cddbf67a76 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/autoType/AutoTypeTest3_deny.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.parser.autoType; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +public class AutoTypeTest3_deny extends TestCase { + public void test_for_x() throws Exception { + Exception error = null; + try { + String json = "{\"@type\":\"java.util.logging.FileHandler\",\"pattern\":\"xxx.txt\"}"; + Object obj = JSON.parse(json, Feature.SupportAutoType); + } catch (Exception ex) { + error = ex; + } + assertNotNull(error); + } + + public void test_for_jar() throws Exception { + Exception error = null; + try { + String json = "{\"@type\":\"java.util.jar.JarFile.JarFile\",\"name\":\"xxx.txt\"}"; + Object obj = JSON.parse(json, Feature.SupportAutoType); + } catch (Exception ex) { + error = ex; + } + assertNotNull(error); + } + + public void test_for_array() throws Exception { + Exception error = null; + try { + String json = "{\"@type\":\"[java.util.jar.JarFile.JarFile\",\"name\":\"xxx.txt\"}"; + Object obj = JSON.parse(json, Feature.SupportAutoType); + } catch (Exception ex) { + ex.printStackTrace(); + error = ex; + } + assertNotNull(error); + } + + + public void test_for_array_1() throws Exception { + Exception error = null; + try { + String json = "{\"@type\":\"L[java.util.jar.JarFile.JarFile;\",\"name\":\"xxx.txt\"}"; + Object obj = JSON.parse(json, Feature.SupportAutoType); + } catch (Exception ex) { + ex.printStackTrace(); + error = ex; + } + assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/bug/Bug0.java b/src/test/java/com/alibaba/json/bvt/parser/bug/Bug0.java new file mode 100755 index 0000000000..7e64b1b477 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/bug/Bug0.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.parser.bug; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; + +public class Bug0 extends TestCase { + + public void test_0() throws Exception { + String text = "{a:1,b:2}"; + JSONObject json = JSON.parseObject(text, JSONObject.class); + Assert.assertEquals(1, json.getIntValue("a")); + Assert.assertEquals(2, json.getIntValue("b")); + } + + public void test_array_exception() throws Exception { + String text = "[1, 2]}"; + Exception error = null; + try { + JSON.parseObject(text, JSONArray.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/bug/Bug2.java b/src/test/java/com/alibaba/json/bvt/parser/bug/Bug2.java new file mode 100755 index 0000000000..18126b3f6f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/bug/Bug2.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.parser.bug; + +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +public class Bug2 extends TestCase { + + public void test_0() throws Exception { + String text = "{children:[{id:3}]}"; + Page page = JSON.parseObject(text, Page.class); + Assert.assertEquals(1, page.getChildren().size()); + + Assert.assertEquals(JSONObject.class, page.getChildren().get(0).getClass()); + } + + public void test_1() throws Exception { + String text = "{children:['aa']}"; + Page page = JSON.parseObject(text, Page.class); + Assert.assertEquals(1, page.getChildren().size()); + + Assert.assertEquals(String.class, page.getChildren().get(0).getClass()); + } + + public static class Page { + + private List children; + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + } + + public static class Result { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_lixianfeng.java b/src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_lixianfeng.java new file mode 100755 index 0000000000..7d01cfe995 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_lixianfeng.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.parser.bug; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +/** + * 这个bug由李先锋反馈 + * @author wenshao + * + */ +public class Bug_for_lixianfeng extends TestCase { + + public void test_long_list() throws Exception { + String str = "{\"id\":14281,\"name\":\"test\",\"canPurchase\":1,\"categoryId\":955063}"; + + JSON.parseObject(str, Te.class); + } + + public static class Te { + + private Long id; + private String name; + private List catIds; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCatIds() { + return catIds; + } + + public void setCatIds(List catIds) { + this.catIds = catIds; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_yihaodian.java b/src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_yihaodian.java new file mode 100755 index 0000000000..8e2f8ee8ec --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_yihaodian.java @@ -0,0 +1,3032 @@ +package com.alibaba.json.bvt.parser.bug; + +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class Bug_for_yihaodian extends TestCase { + + public void test_for_long_list() throws Exception { + String str = "{\"backOperatorId\":14281,\"batchNum\":0,\"canPurchase\":1,\"categoryId\":955063}"; + Te ob = JSON.parseObject(str, Te.class); + } + + public static class Te { + + /** 产品ID */ + private Long id; + /** 要删除产品的ID */ + private String deletedProductId; + /** 产品编码 */ + private String productCode; + /** 产品名 */ + private String productCname; + /** 产品名前面的品牌名 */ + private String productBrandName; + /** 产品名英文 */ + private String productEname; + /** 产品销售类别 */ + private Integer productSaleType; + /** 产品品牌Id */ + private Long brandId; + /** 产品品牌 */ + private String brandName; + + /** 市场价 */ + private Double productListPrice; + /** 分类Id */ + private Long categoryId; + /** 旧分类Id */ + private Long oldCategoryId; + /** 旧扩展类别 **/ + private Long oldExtendCategoryId; + /** 厂商ID,默认为1 */ + private Long mfid; + /** productCanBeChange */ + private Integer productCanBeChange; + /** productChangeDay */ + private Integer productChangeDay; + /** productCanBeReturn */ + private Integer productCanBeReturn; + /** productReturnDay */ + private Integer productReturnDay; + /** 能否维修 */ + private Integer productCanBeRepair; + /** 能否维修 */ + private Integer productCanBeRepairDay; + /** 安装信息 */ + private Integer productNeedInstallation; + /** 条形码 */ + private String ean13; + /** sku */ + private String sku; + /** 长 */ + private Double length; + /** 宽 */ + private Double width; + /** 高 */ + private Double height; + /** 净重 */ + private Double weight; + /** keepTemperature */ + private String keepTemperature; + /** keepHumidity */ + private String keepHumidity; + /** 产品简称 */ + private String productSname; + /** keepSpecCondition */ + private String keepSpecCondition; + /** productQualityAssuranceDay */ + private Integer productQualityAssuranceDay; + /** 是否已删除 */ + private Integer isDeleted; + /** 单位 */ + private String unit; + /** 进价 */ + private Double inPrice; + /** volume */ + private Double volume; + /** countryOfOrgn */ + private Long countryOfOrgn; + /** 主图ID */ + private Long defaultPictureId; + /** 主图URL */ + private String defaultPictureUrl; + /** color */ + private String color; + /** currencyId */ + private Long currencyId; + /** 毛重 */ + private Double grossWeight; + /** format */ + private String format; + /** 易碎品 0 不是 1是 */ + private String isFragile; + /** 向上0 不是 1是 */ + private String putOnDirection; + /** 贵重品0 不是 1是 */ + private String isValuables; + /** 液体0 不是 1是 */ + private String isLiquid; + /** 防交叉污染0 不是 1是 */ + private String isCrossContamination; + /** 16进制的颜色代码,如#FF00AA */ + private String colorNumber; + /** 尺码 */ + private String productSize; + /** 替换后的尺码 */ + private String replaceProductSize; + /** 销售技巧 */ + private String saleSkill; + /** 本商品作为赠品时的处理方法 */ + private String dispositionInstruct; + /** 产地 */ + private String placeOfOrigin; + /** 产品页面标题 */ + private String productSeoTitle; + /** 产品页面属性关键字 */ + private String productSeoKeyword; + /** 产品页面属性描述 */ + private String productSeoDescription; + /** 后台产品配件说明 */ + private String accessoryDescription; + /** 是否需要单独开票 */ + private Integer needInvoice; + /** 清仓原因 */ + private String clearCause; + /** 默认商品条码ID */ + private Long defaultBarcodeId; + /** 广告词 */ + private String adWord; + /** 是否是3c产品(0:非3C,1:3C产品) */ + private Integer isCcc; + /** N件购 */ + private Integer shoppingCount; + /** 是否为赠品 */ + private Integer productIsGift; + /** 是否可以退换货 0:不可以 1:可以 */ + private Integer canReturnAndChange; + /** 是否需要检测 0:不需要 1:需要 */ + private Integer needExamine; + /** 1:新增未审核;2:编辑待审核;3:审核未通过;4:审核通过;5:文描审核失败;6:图片审核失败 */ + private Integer verifyFlg; + /** 审核者 */ + private Long verifyBy; + /** 审核日时 */ + + /** 商品登记者 */ + private Long registerBy; + /** 商品登记日时 */ + + /** 商品登记者联系电话 */ + private String registerPhone; + /** 审核备注 */ + private String verifyRemark; + /** 批量数 */ + private Integer batchNum; + /** 是否只限本地配送0: 不限制 1:限制 (粉状/液体/膏状) */ + private Integer localLimit; + /** 一包的数量 */ + private Integer stdPackQty; + /** 正式表产品ID */ + private Long fromalProductId; + /** 是否强制发票 */ + private Integer isMustInvoice; + /** 审核失败原因 */ + private Integer verifyFailureType; + /** 产品类型 0:普通产品 1:主系列产品 2:子系列产品 3:捆绑产品 4:礼品卡 5: 虚拟商品 6:增值服务 */ + private Integer productType; + /** 是否能被采购 */ + private Integer canPurchase; + /** 标准包装箱sku */ + private String stdPackageSku; + /** 是否需要启用保质期控制 0:不启用 1:启用 */ + private Integer userExpireControl; + /** 批次规则ID */ + private Long batchRuleId; + /** 产品名称副标题 */ + private String nameSubtitle; + private String specialType; + /** 给经销商的批发价 */ + private Double batchPrice; + /** 是否需要批次控制 0:不需要 1:需要 */ + private Integer needBatchControl; + /** 销售税率 */ + private Double salesTax; + /** 外部产品编码 */ + private String outerId; + /** 商家ID */ + private Long merchantId; + /** 商家名称 */ + private String merchantName; + /** 商家产品主类别(用于报表统计) */ + private Long masterCategoryId; + + private Integer concernLevel; + /** 关注理由 */ + private String concernReason; + /** 是否可售 */ + private Integer canSale; + /** 是否显示 */ + private Integer canShow; + /** 产品销售税率 */ + private Long prodcutTaxRate; + /** 是否支持VIP0:不支持1:支持 */ + private Integer canVipDiscount; + /** 分类名称 */ + private String categoryName; + /** 销售价格 */ + private Double salePrice; + /** 库存 */ + private Long stockNum; + /** 商家类别名称 */ + private String merchantCategoryName; + /** 商家详情 */ + private String productDescription; + /** 是否可调拨 0:不可以 1:可以 */ + private Integer isTransfer; + /** 是否需要审核0:新增未提交;1:需要审核;2:编辑未提交 */ + private Integer isSubmit; + /** 审核失败类型 */ + private Integer verifyFailueType; + /** 产品拼音 */ + private String productSpell; + /** 产品名称前缀 */ + private String productNamePrefix; + /** 审核失败原因 */ + private String failueReason; + /** orgPicUrl */ + private String orgPicUrl; + /** 扩展分类名称 */ + private String subCategoryName; + /** 扩展分类ID */ + private Long subCategoryId; + /** 7天内日均销量 */ + private Integer dailySale; + /** 查看是否有主图 */ + private Integer picCount; + /** 强制下架原因 */ + private Integer underCarriageReason; + /** 强制下架原因-中文信息 */ + private String underCarriageReasonStr; + /** 异常信息 */ + private String errorMessage; + /** 库存预警数量 */ + private Integer alertStockCount; + + private String deliveryInfo; + /** 主图链接 */ + private String picUrl; + + /** 是否能分期0:不能 1:能 */ + private Integer canFenqi; + + private String season; + /** 是否是二次审核 */ + private Integer isDupAudit; + + private Integer viewFromTag; + + /** 产品售价 */ + private Double productNonMemberPrice; + /** 产品图片 */ + + /** 是否更新操作 */ + private Integer isUpdate; + /** merchantRpcVo */ + + /** 系列产品的颜色图片 */ + + /** 系列产品的尺码 */ + private List productSizeSet; + + /** 是否主产品 */ + private Boolean isMainProduct; + /** 从图片空间中返回图片ID和URL */ + private String productPicIdAndURL; + + private Integer isTemp; + /** 市场价和售价的比例 */ + private Double priceRate; + + private Integer picSpecialType; + private Integer exemptStatus; + + private String violationReasonIds; + + private String violationReasons; + + private Long remainTime; + + private Integer submitOrder; + + private Integer productSource; + + private Integer isKa; + /** KA商家创建时间 */ + private Integer kaMCreateTime; + /** 配送延长期 */ + private Integer deliveryDay; + /** 产品状态 */ + private Integer isEdit; + /** 操作人 */ + private Long backOperatorId; + /** 正式库pm_info_id */ + private Long formalPmInfoId; + /** 类别拼接字符串 */ + private String categoryStr; + /** 类别id拼接字符串 */ + private String categoryIdStr; + /** 扩展类别拼接字符串 */ + private String extendCategoryStr; + /** 扩展类别id拼接字符串 */ + private String extendCategoryIdStr; + /** 商家类别ID */ + private List masterCategoryIdList; + + private Long defaultWarehouseId; + + public Long getBackOperatorId() { + return backOperatorId; + } + + public void setBackOperatorId(Long backOperatorId) { + this.backOperatorId = backOperatorId; + } + + public Integer getIsDupAudit() { + return isDupAudit; + } + + public void setIsDupAudit(Integer isDupAudit) { + this.isDupAudit = isDupAudit; + } + + public Long getId() { + return id; + } + + public String getUnderCarriageReasonStr() { + return underCarriageReasonStr; + } + + public void setUnderCarriageReasonStr(String underCarriageReasonStr) { + this.underCarriageReasonStr = underCarriageReasonStr; + } + + /** + * 产品ID + * + * @param id 产品ID + */ + + public void setId(Long id) { + this.id = id; + } + + /** + * 产品编码 + * + * @return productCode + */ + + public String getProductCode() { + return productCode; + } + + /** + * 产品编码 + * + * @param productCode 产品编码 + */ + + public void setProductCode(String productCode) { + this.productCode = productCode; + } + + /** + * 产品名 + * + * @return productCname + */ + + public String getProductCname() { + return productCname; + } + + /** + * 产品名 + * + * @param productCname 产品名 + */ + + public void setProductCname(String productCname) { + this.productCname = productCname; + } + + /** + * 产品名英文 + * + * @return productEname + */ + + public String getProductEname() { + return productEname; + } + + /** + * 产品名英文 + * + * @param productEname 产品名英文 + */ + + public void setProductEname(String productEname) { + this.productEname = productEname; + } + + + /** + * 产品销售类别 + * + * @param productSaleType 产品销售类别 + */ + + public void setProductSaleType(Integer productSaleType) { + this.productSaleType = productSaleType; + } + + /** + * 产品品牌Id + * + * @return brandId + */ + + public Long getBrandId() { + return brandId; + } + + /** + * 产品品牌Id + * + * @param brandId 产品品牌Id + */ + + public void setBrandId(Long brandId) { + this.brandId = brandId; + } + + /** + * 产品品牌 + * + * @return brandName + */ + + public String getBrandName() { + return brandName; + } + + /** + * 产品品牌 + * + * @param brandName 产品品牌 + */ + + public void setBrandName(String brandName) { + this.brandName = brandName; + } + + /** + * 产品创建时间 + * + * @return createTime + */ + + /** + * 产品创建时间 + * + * @param createTime 产品创建时间 + */ + + /** + * 市场价 + * + * @return productListPrice + */ + + public Double getProductListPrice() { + return productListPrice; + } + + /** + * 市场价 + * + * @param productListPrice 市场价 + */ + + public void setProductListPrice(Double productListPrice) { + this.productListPrice = productListPrice; + } + + /** + * 分类Id + * + * @return categoryId + */ + + public Long getCategoryId() { + return categoryId; + } + + /** + * 分类Id + * + * @param categoryId 分类Id + */ + + public void setCategoryId(Long categoryId) { + this.categoryId = categoryId; + } + + /** + * 厂商ID默认为1 + * + * @return mfid + */ + + public Long getMfid() { + return mfid; + } + + /** + * 厂商ID默认为1 + * + * @param mfid 厂商ID默认为1 + */ + + public void setMfid(Long mfid) { + this.mfid = mfid; + } + + /** + * productCanBeChange + * + * @return productCanBeChange + */ + + public Integer getProductCanBeChange() { + return productCanBeChange; + } + + /** + * productCanBeChange + * + * @param productCanBeChange productCanBeChange + */ + + public void setProductCanBeChange(Integer productCanBeChange) { + this.productCanBeChange = productCanBeChange; + } + + /** + * productChangeDay + * + * @return productChangeDay + */ + + public Integer getProductChangeDay() { + return productChangeDay; + } + + /** + * productChangeDay + * + * @param productChangeDay productChangeDay + */ + + public void setProductChangeDay(Integer productChangeDay) { + this.productChangeDay = productChangeDay; + } + + /** + * productCanBeReturn + * + * @return productCanBeReturn + */ + + public Integer getProductCanBeReturn() { + return productCanBeReturn; + } + + /** + * productCanBeReturn + * + * @param productCanBeReturn productCanBeReturn + */ + + public void setProductCanBeReturn(Integer productCanBeReturn) { + this.productCanBeReturn = productCanBeReturn; + } + + /** + * productReturnDay + * + * @return productReturnDay + */ + + public Integer getProductReturnDay() { + return productReturnDay; + } + + /** + * productReturnDay + * + * @param productReturnDay productReturnDay + */ + + public void setProductReturnDay(Integer productReturnDay) { + this.productReturnDay = productReturnDay; + } + + /** + * 能否维修 + * + * @return productCanBeRepair + */ + + public Integer getProductCanBeRepair() { + return productCanBeRepair; + } + + /** + * 能否维修 + * + * @param productCanBeRepair 能否维修 + */ + + public void setProductCanBeRepair(Integer productCanBeRepair) { + this.productCanBeRepair = productCanBeRepair; + } + + /** + * 能否维修 + * + * @return productCanBeRepairDay + */ + + public Integer getProductCanBeRepairDay() { + return productCanBeRepairDay; + } + + /** + * 能否维修 + * + * @param productCanBeRepairDay 能否维修 + */ + + public void setProductCanBeRepairDay(Integer productCanBeRepairDay) { + this.productCanBeRepairDay = productCanBeRepairDay; + } + + /** + * 安装信息 + * + * @return productNeedInstallation + */ + + public Integer getProductNeedInstallation() { + return productNeedInstallation; + } + + /** + * 安装信息 + * + * @param productNeedInstallation 安装信息 + */ + + public void setProductNeedInstallation(Integer productNeedInstallation) { + this.productNeedInstallation = productNeedInstallation; + } + + /** + * 条形码 + * + * @return ean13 + */ + + public String getEan13() { + return ean13; + } + + /** + * 条形码 + * + * @param ean13 条形码 + */ + + public void setEan13(String ean13) { + this.ean13 = ean13; + } + + /** + * sku + * + * @return sku + */ + + public String getSku() { + return sku; + } + + /** + * sku + * + * @param sku sku + */ + + public void setSku(String sku) { + this.sku = sku; + } + + /** + * 长 + * + * @return length + */ + + public Double getLength() { + return length; + } + + /** + * 长 + * + * @param length 长 + */ + + public void setLength(Double length) { + this.length = length; + } + + /** + * 宽 + * + * @return width + */ + + public Double getWidth() { + return width; + } + + /** + * 宽 + * + * @param width 宽 + */ + + public void setWidth(Double width) { + this.width = width; + } + + /** + * 高 + * + * @return height + */ + + public Double getHeight() { + return height; + } + + /** + * 高 + * + * @param height 高 + */ + + public void setHeight(Double height) { + this.height = height; + } + + /** + * 净重 + * + * @return weight + */ + + public Double getWeight() { + return weight; + } + + /** + * 净重 + * + * @param weight 净重 + */ + + public void setWeight(Double weight) { + this.weight = weight; + } + + /** + * keepTemperature + * + * @return keepTemperature + */ + + public String getKeepTemperature() { + return keepTemperature; + } + + /** + * keepTemperature + * + * @param keepTemperature keepTemperature + */ + + public void setKeepTemperature(String keepTemperature) { + this.keepTemperature = keepTemperature; + } + + /** + * keepHumidity + * + * @return keepHumidity + */ + + public String getKeepHumidity() { + return keepHumidity; + } + + /** + * keepHumidity + * + * @param keepHumidity keepHumidity + */ + + public void setKeepHumidity(String keepHumidity) { + this.keepHumidity = keepHumidity; + } + + /** + * keepSpecCondition + * + * @return keepSpecCondition + */ + + public String getKeepSpecCondition() { + return keepSpecCondition; + } + + /** + * keepSpecCondition + * + * @param keepSpecCondition keepSpecCondition + */ + + public void setKeepSpecCondition(String keepSpecCondition) { + this.keepSpecCondition = keepSpecCondition; + } + + /** + * productQualityAssuranceDay + * + * @return productQualityAssuranceDay + */ + + public Integer getProductQualityAssuranceDay() { + return productQualityAssuranceDay; + } + + /** + * productQualityAssuranceDay + * + * @param productQualityAssuranceDay productQualityAssuranceDay + */ + + public void setProductQualityAssuranceDay(Integer productQualityAssuranceDay) { + this.productQualityAssuranceDay = productQualityAssuranceDay; + } + + /** + * 是否已删除 + * + * @return isDeleted + */ + + public Integer getIsDeleted() { + return isDeleted; + } + + /** + * 是否已删除 + * + * @param isDeleted 是否已删除 + */ + + public void setIsDeleted(Integer isDeleted) { + this.isDeleted = isDeleted; + } + + /** + * 单位 + * + * @return unit + */ + + public String getUnit() { + return unit; + } + + /** + * 单位 + * + * @param unit 单位 + */ + + public void setUnit(String unit) { + this.unit = unit; + } + + /** + * 进价 + * + * @return inPrice + */ + + public Double getInPrice() { + return inPrice; + } + + /** + * 进价 + * + * @param inPrice 进价 + */ + + public void setInPrice(Double inPrice) { + this.inPrice = inPrice; + } + + /** + * volume + * + * @return volume + */ + + public Double getVolume() { + return volume; + } + + /** + * volume + * + * @param volume volume + */ + + public void setVolume(Double volume) { + this.volume = volume; + } + + /** + * countryOfOrgn + * + * @return countryOfOrgn + */ + + public Long getCountryOfOrgn() { + return countryOfOrgn; + } + + /** + * countryOfOrgn + * + * @param countryOfOrgn countryOfOrgn + */ + + public void setCountryOfOrgn(Long countryOfOrgn) { + this.countryOfOrgn = countryOfOrgn; + } + + /** + * 主图ID + * + * @return defaultPictureId + */ + + public Long getDefaultPictureId() { + return defaultPictureId; + } + + /** + * 主图ID + * + * @param defaultPictureId 主图ID + */ + + public void setDefaultPictureId(Long defaultPictureId) { + this.defaultPictureId = defaultPictureId; + } + + /** + * 主图URL + * + * @return defaultPictureUrl + */ + + public String getDefaultPictureUrl() { + + return defaultPictureUrl; + } + + /** + * 主图URL + * + * @param defaultPictureUrl 主图URL + */ + + public void setDefaultPictureUrl(String defaultPictureUrl) { + this.defaultPictureUrl = defaultPictureUrl; + } + + /** + * color + * + * @return color + */ + + public String getColor() { + return color; + } + + /** + * color + * + * @param color color + */ + + public void setColor(String color) { + this.color = color; + } + + /** + * currencyId + * + * @return currencyId + */ + + public Long getCurrencyId() { + return currencyId; + } + + /** + * currencyId + * + * @param currencyId currencyId + */ + + public void setCurrencyId(Long currencyId) { + this.currencyId = currencyId; + } + + /** + * 毛重 + * + * @return grossWeight + */ + + public Double getGrossWeight() { + return grossWeight; + } + + /** + * 毛重 + * + * @param grossWeight 毛重 + */ + + public void setGrossWeight(Double grossWeight) { + this.grossWeight = grossWeight; + } + + /** + * format + * + * @return format + */ + + public String getFormat() { + return format; + } + + /** + * format + * + * @param format format + */ + + public void setFormat(String format) { + this.format = format; + } + + /** + * 易碎品0不是1是 + * + * @return isFragile + */ + + public String getIsFragile() { + return isFragile; + } + + /** + * 易碎品0不是1是 + * + * @param isFragile 易碎品0不是1是 + */ + + public void setIsFragile(String isFragile) { + this.isFragile = isFragile; + } + + /** + * 向上0不是1是 + * + * @return putOnDirection + */ + + public String getPutOnDirection() { + return putOnDirection; + } + + /** + * 向上0不是1是 + * + * @param putOnDirection 向上0不是1是 + */ + + public void setPutOnDirection(String putOnDirection) { + this.putOnDirection = putOnDirection; + } + + /** + * 贵重品0不是1是 + * + * @return isValuables + */ + + public String getIsValuables() { + return isValuables; + } + + /** + * 贵重品0不是1是 + * + * @param isValuables 贵重品0不是1是 + */ + + public void setIsValuables(String isValuables) { + this.isValuables = isValuables; + } + + /** + * 液体0不是1是 + * + * @return isLiquid + */ + + public String getIsLiquid() { + return isLiquid; + } + + /** + * 液体0不是1是 + * + * @param isLiquid 液体0不是1是 + */ + + public void setIsLiquid(String isLiquid) { + this.isLiquid = isLiquid; + } + + /** + * 防交叉污染0不是1是 + * + * @return isCrossContamination + */ + + public String getIsCrossContamination() { + return isCrossContamination; + } + + /** + * 防交叉污染0不是1是 + * + * @param isCrossContamination 防交叉污染0不是1是 + */ + + public void setIsCrossContamination(String isCrossContamination) { + this.isCrossContamination = isCrossContamination; + } + + /** + * 16进制的颜色代码如#FF00AA + * + * @return colorNumber + */ + + public String getColorNumber() { + return colorNumber; + } + + /** + * 16进制的颜色代码如#FF00AA + * + * @param colorNumber 16进制的颜色代码如#FF00AA + */ + + public void setColorNumber(String colorNumber) { + this.colorNumber = colorNumber; + } + + /** + * 尺码 + * + * @return productSize + */ + + public String getProductSize() { + return productSize; + } + + /** + * 尺码 + * + * @param productSize 尺码 + */ + + public void setProductSize(String productSize) { + this.productSize = productSize; + } + + /** + * 销售技巧 + * + * @return saleSkill + */ + + public String getSaleSkill() { + return saleSkill; + } + + /** + * 销售技巧 + * + * @param saleSkill 销售技巧 + */ + + public void setSaleSkill(String saleSkill) { + this.saleSkill = saleSkill; + } + + /** + * 本商品作为赠品时的处理方法 + * + * @return dispositionInstruct + */ + + public String getDispositionInstruct() { + return dispositionInstruct; + } + + /** + * 本商品作为赠品时的处理方法 + * + * @param dispositionInstruct 本商品作为赠品时的处理方法 + */ + + public void setDispositionInstruct(String dispositionInstruct) { + this.dispositionInstruct = dispositionInstruct; + } + + /** + * 产地 + * + * @return placeOfOrigin + */ + + public String getPlaceOfOrigin() { + return placeOfOrigin; + } + + /** + * 产地 + * + * @param placeOfOrigin 产地 + */ + + public void setPlaceOfOrigin(String placeOfOrigin) { + this.placeOfOrigin = placeOfOrigin; + } + + /** + * 产品页面标题 + * + * @return productSeoTitle + */ + + public String getProductSeoTitle() { + return productSeoTitle; + } + + /** + * 产品页面标题 + * + * @param productSeoTitle 产品页面标题 + */ + + public void setProductSeoTitle(String productSeoTitle) { + this.productSeoTitle = productSeoTitle; + } + + /** + * 产品页面属性关键字 + * + * @return productSeoKeyword + */ + + public String getProductSeoKeyword() { + return productSeoKeyword; + } + + /** + * 产品页面属性关键字 + * + * @param productSeoKeyword 产品页面属性关键字 + */ + + public void setProductSeoKeyword(String productSeoKeyword) { + this.productSeoKeyword = productSeoKeyword; + } + + /** + * 产品页面属性描述 + * + * @return productSeoDescription + */ + + public String getProductSeoDescription() { + return productSeoDescription; + } + + /** + * 产品页面属性描述 + * + * @param productSeoDescription 产品页面属性描述 + */ + + public void setProductSeoDescription(String productSeoDescription) { + this.productSeoDescription = productSeoDescription; + } + + /** + * 后台产品配件说明 + * + * @return accessoryDescription + */ + + public String getAccessoryDescription() { + return accessoryDescription; + } + + /** + * 后台产品配件说明 + * + * @param accessoryDescription 后台产品配件说明 + */ + + public void setAccessoryDescription(String accessoryDescription) { + this.accessoryDescription = accessoryDescription; + } + + /** + * 是否需要单独开票 + * + * @return needInvoice + */ + + public Integer getNeedInvoice() { + return needInvoice; + } + + /** + * 是否需要单独开票 + * + * @param needInvoice 是否需要单独开票 + */ + + public void setNeedInvoice(Integer needInvoice) { + this.needInvoice = needInvoice; + } + + /** + * 清仓原因 + * + * @return clearCause + */ + + public String getClearCause() { + return clearCause; + } + + /** + * 清仓原因 + * + * @param clearCause 清仓原因 + */ + + public void setClearCause(String clearCause) { + this.clearCause = clearCause; + } + + /** + * 默认商品条码ID + * + * @return defaultBarcodeId + */ + + public Long getDefaultBarcodeId() { + return defaultBarcodeId; + } + + /** + * 默认商品条码ID + * + * @param defaultBarcodeId 默认商品条码ID + */ + + public void setDefaultBarcodeId(Long defaultBarcodeId) { + this.defaultBarcodeId = defaultBarcodeId; + } + + /** + * 广告词 + * + * @return adWord + */ + + public String getAdWord() { + return adWord; + } + + /** + * 广告词 + * + * @param adWord 广告词 + */ + + public void setAdWord(String adWord) { + this.adWord = adWord; + } + + /** + * 是否是3c产品(0:非3C1:3C产品) + * + * @return isCcc + */ + + public Integer getIsCcc() { + return isCcc; + } + + /** + * 是否是3c产品(0:非3C1:3C产品) + * + * @param isCcc 是否是3c产品(0:非3C1:3C产品) + */ + + public void setIsCcc(Integer isCcc) { + this.isCcc = isCcc; + } + + /** + * N件购 + * + * @return shoppingCount + */ + + public Integer getShoppingCount() { + return shoppingCount; + } + + /** + * N件购 + * + * @param shoppingCount N件购 + */ + + public void setShoppingCount(Integer shoppingCount) { + this.shoppingCount = shoppingCount; + } + + /** + * 是否为赠品 + * + * @return productIsGift + */ + + public Integer getProductIsGift() { + return productIsGift; + } + + /** + * 是否为赠品 + * + * @param productIsGift 是否为赠品 + */ + + public void setProductIsGift(Integer productIsGift) { + this.productIsGift = productIsGift; + } + + /** + * 是否可以退换货0:不可以1:可以 + * + * @return canReturnAndChange + */ + + public Integer getCanReturnAndChange() { + return canReturnAndChange; + } + + /** + * 是否可以退换货0:不可以1:可以 + * + * @param canReturnAndChange 是否可以退换货0:不可以1:可以 + */ + + public void setCanReturnAndChange(Integer canReturnAndChange) { + this.canReturnAndChange = canReturnAndChange; + } + + /** + * 是否需要检测0:不需要1:需要 + * + * @return needExamine + */ + + public Integer getNeedExamine() { + return needExamine; + } + + /** + * 是否需要检测0:不需要1:需要 + * + * @param needExamine 是否需要检测0:不需要1:需要 + */ + + public void setNeedExamine(Integer needExamine) { + this.needExamine = needExamine; + } + + /** + * 1:新增未审核;2:编辑待审核;3:审核未通过;4:审核通过;5:文描审核失败;6:图片审核失败 + * + * @return verifyFlg + */ + + public Integer getVerifyFlg() { + return verifyFlg; + } + + /** + * 1:新增未审核;2:编辑待审核;3:审核未通过;4:审核通过;5:文描审核失败;6:图片审核失败 + * + * @param verifyFlg 1:新增未审核;2:编辑待审核;3:审核未通过;4:审核通过;5:文描审核失败;6:图片审核失败 + */ + + public void setVerifyFlg(Integer verifyFlg) { + this.verifyFlg = verifyFlg; + } + + /** + * 审核者 + * + * @return verifyBy + */ + + public Long getVerifyBy() { + return verifyBy; + } + + /** + * 审核者 + * + * @param verifyBy 审核者 + */ + + public void setVerifyBy(Long verifyBy) { + this.verifyBy = verifyBy; + } + + /** + * 审核日时 + * + * @return verifyAt + */ + + /** + * 审核日时 + * + * @param verifyAt 审核日时 + */ + + /** + * 商品登记者 + * + * @return registerBy + */ + + public Long getRegisterBy() { + return registerBy; + } + + /** + * 商品登记者 + * + * @param registerBy 商品登记者 + */ + + public void setRegisterBy(Long registerBy) { + this.registerBy = registerBy; + } + + /** + * 商品登记日时 + * + * @return registerAt + */ + + /** + * 商品登记日时 + * + * @param registerAt 商品登记日时 + */ + + /** + * 商品登记者联系电话 + * + * @return registerPhone + */ + + public String getRegisterPhone() { + return registerPhone; + } + + /** + * 商品登记者联系电话 + * + * @param registerPhone 商品登记者联系电话 + */ + + public void setRegisterPhone(String registerPhone) { + this.registerPhone = registerPhone; + } + + /** + * 审核备注 + * + * @return verifyRemark + */ + + public String getVerifyRemark() { + return verifyRemark; + } + + /** + * 审核备注 + * + * @param verifyRemark 审核备注 + */ + + public void setVerifyRemark(String verifyRemark) { + this.verifyRemark = verifyRemark; + } + + /** + * 批量数 + * + * @return batchNum + */ + + public Integer getBatchNum() { + return batchNum; + } + + /** + * 批量数 + * + * @param batchNum 批量数 + */ + + public void setBatchNum(Integer batchNum) { + this.batchNum = batchNum; + } + + /** + * 是否只限本地配送0:不限制1:限制(粉状液体膏状) + * + * @return localLimit + */ + + public Integer getLocalLimit() { + return localLimit; + } + + /** + * 是否只限本地配送0:不限制1:限制(粉状液体膏状) + * + * @param localLimit 是否只限本地配送0:不限制1:限制(粉状液体膏状) + */ + + public void setLocalLimit(Integer localLimit) { + this.localLimit = localLimit; + } + + /** + * 一包的数量 + * + * @return stdPackQty + */ + + public Integer getStdPackQty() { + return stdPackQty; + } + + /** + * 一包的数量 + * + * @param stdPackQty 一包的数量 + */ + + public void setStdPackQty(Integer stdPackQty) { + this.stdPackQty = stdPackQty; + } + + /** + * 正式表产品ID + * + * @return fromalProductId + */ + + public Long getFromalProductId() { + return fromalProductId; + } + + /** + * 正式表产品ID + * + * @param fromalProductId 正式表产品ID + */ + + public void setFromalProductId(Long fromalProductId) { + this.fromalProductId = fromalProductId; + } + + /** + * 是否强制发票 + * + * @return isMustInvoice + */ + + public Integer getIsMustInvoice() { + return isMustInvoice; + } + + /** + * 是否强制发票 + * + * @param isMustInvoice 是否强制发票 + */ + + public void setIsMustInvoice(Integer isMustInvoice) { + this.isMustInvoice = isMustInvoice; + } + + /** + * 审核失败原因 + * + * @return verifyFailureType + */ + + public Integer getVerifyFailureType() { + return verifyFailureType; + } + + /** + * 审核失败原因 + * + * @param verifyFailureType 审核失败原因 + */ + + public void setVerifyFailureType(Integer verifyFailureType) { + this.verifyFailureType = verifyFailureType; + } + + /** + * 产品类型0:普通产品1:主系列产品2:子系列产品3:捆绑产品4:礼品卡5:虚拟商品6:增值服务 + * + * @return productType + */ + + public Integer getProductType() { + return productType; + } + + /** + * 产品类型0:普通产品1:主系列产品2:子系列产品3:捆绑产品4:礼品卡5:虚拟商品6:增值服务 + * + * @param productType 产品类型0:普通产品1:主系列产品2:子系列产品3:捆绑产品4:礼品卡5:虚拟商品6:增值服务 + */ + + public void setProductType(Integer productType) { + this.productType = productType; + } + + /** + * 是否能被采购 + * + * @return canPurchase + */ + + public Integer getCanPurchase() { + return canPurchase; + } + + /** + * 是否能被采购 + * + * @param canPurchase 是否能被采购 + */ + + public void setCanPurchase(Integer canPurchase) { + this.canPurchase = canPurchase; + } + + /** + * 标准包装箱sku + * + * @return stdPackageSku + */ + + public String getStdPackageSku() { + return stdPackageSku; + } + + /** + * 标准包装箱sku + * + * @param stdPackageSku 标准包装箱sku + */ + + public void setStdPackageSku(String stdPackageSku) { + this.stdPackageSku = stdPackageSku; + } + + /** + * 是否需要启用保质期控制0:不启用1:启用 + * + * @return userExpireControl + */ + + public Integer getUserExpireControl() { + return userExpireControl; + } + + /** + * 是否需要启用保质期控制0:不启用1:启用 + * + * @param userExpireControl 是否需要启用保质期控制0:不启用1:启用 + */ + + public void setUserExpireControl(Integer userExpireControl) { + this.userExpireControl = userExpireControl; + } + + /** + * 批次规则ID + * + * @return batchRuleId + */ + + public Long getBatchRuleId() { + return batchRuleId; + } + + /** + * 批次规则ID + * + * @param batchRuleId 批次规则ID + */ + + public void setBatchRuleId(Long batchRuleId) { + this.batchRuleId = batchRuleId; + } + + /** + * 产品名称副标题 + * + * @return nameSubtitle + */ + + public String getNameSubtitle() { + return nameSubtitle; + } + + /** + * 产品名称副标题 + * + * @param nameSubtitle 产品名称副标题 + */ + + public void setNameSubtitle(String nameSubtitle) { + this.nameSubtitle = nameSubtitle; + } + + /** + * 产品特殊类型:1:医药;11:药品;12器械;14-18:处方药;50:电子凭证 + * + * @return specialType + */ + + public String getSpecialType() { + return specialType; + } + + /** + * 产品特殊类型:1:医药;11:药品;12器械;14-18:处方药;50:电子凭证 + * + * @param specialType 产品特殊类型:1:医药;11:药品;12器械;14-18:处方药;50:电子凭证 + */ + + public void setSpecialType(String specialType) { + this.specialType = specialType; + } + + /** + * 给经销商的批发价 + * + * @return batchPrice + */ + + public Double getBatchPrice() { + return batchPrice; + } + + /** + * 给经销商的批发价 + * + * @param batchPrice 给经销商的批发价 + */ + + public void setBatchPrice(Double batchPrice) { + this.batchPrice = batchPrice; + } + + /** + * 是否需要批次控制0:不需要1:需要 + * + * @return needBatchControl + */ + + public Integer getNeedBatchControl() { + return needBatchControl; + } + + /** + * 是否需要批次控制0:不需要1:需要 + * + * @param needBatchControl 是否需要批次控制0:不需要1:需要 + */ + + public void setNeedBatchControl(Integer needBatchControl) { + this.needBatchControl = needBatchControl; + } + + /** + * 销售税率 + * + * @return salesTax + */ + + public Double getSalesTax() { + return salesTax; + } + + /** + * 销售税率 + * + * @param salesTax 销售税率 + */ + + public void setSalesTax(Double salesTax) { + this.salesTax = salesTax; + } + + /** + * 外部产品编码 + * + * @return outerId + */ + + public String getOuterId() { + return outerId; + } + + /** + * 外部产品编码 + * + * @param outerId 外部产品编码 + */ + + public void setOuterId(String outerId) { + this.outerId = outerId; + } + + /** + * 商家ID + * + * @return merchantId + */ + + public Long getMerchantId() { + return merchantId; + } + + /** + * 商家ID + * + * @param merchantId 商家ID + */ + + public void setMerchantId(Long merchantId) { + this.merchantId = merchantId; + } + + /** + * 商家名称 + * + * @return merchantName + */ + + public String getMerchantName() { + return merchantName; + } + + /** + * 商家名称 + * + * @param merchantName 商家名称 + */ + + public void setMerchantName(String merchantName) { + this.merchantName = merchantName; + } + + /** + * 商家产品主类别(用于报表统计) + * + * @return masterCategoryId + */ + + public Long getMasterCategoryId() { + return masterCategoryId; + } + + /** + * 商家产品主类别(用于报表统计) + * + * @param masterCategoryId 商家产品主类别(用于报表统计) + */ + + public void setMasterCategoryId(Long masterCategoryId) { + this.masterCategoryId = masterCategoryId; + } + + /** + * 关注等级设置 + * + * @return concernLevel + */ + + public Integer getConcernLevel() { + return concernLevel; + } + + /** + * 关注等级设置 + * + * @param concernLevel 关注等级设置 + */ + + public void setConcernLevel(Integer concernLevel) { + this.concernLevel = concernLevel; + } + + /** + * 关注理由 + * + * @return concernReason + */ + + public String getConcernReason() { + return concernReason; + } + + /** + * 关注理由 + * + * @param concernReason 关注理由 + */ + + public void setConcernReason(String concernReason) { + this.concernReason = concernReason; + } + + /** + * 是否可售 + * + * @return canSale + */ + + public Integer getCanSale() { + return canSale; + } + + /** + * 是否可售 + * + * @param canSale 是否可售 + */ + + public void setCanSale(Integer canSale) { + this.canSale = canSale; + } + + /** + * 是否显示 + * + * @return canShow + */ + + public Integer getCanShow() { + return canShow; + } + + /** + * 是否显示 + * + * @param canShow 是否显示 + */ + + public void setCanShow(Integer canShow) { + this.canShow = canShow; + } + + /** + * 产品销售税率 + * + * @return prodcutTaxRate + */ + + public Long getProdcutTaxRate() { + return prodcutTaxRate; + } + + /** + * 产品销售税率 + * + * @param prodcutTaxRate 产品销售税率 + */ + + public void setProdcutTaxRate(Long prodcutTaxRate) { + this.prodcutTaxRate = prodcutTaxRate; + } + + /** + * 是否支持VIP0:不支持1:支持 + * + * @return canVipDiscount + */ + + public Integer getCanVipDiscount() { + return canVipDiscount; + } + + /** + * 是否支持VIP0:不支持1:支持 + * + * @param canVipDiscount 是否支持VIP0:不支持1:支持 + */ + + public void setCanVipDiscount(Integer canVipDiscount) { + this.canVipDiscount = canVipDiscount; + } + + /** + * 分类名称 + * + * @return categoryName + */ + + public String getCategoryName() { + return categoryName; + } + + /** + * 分类名称 + * + * @param categoryName 分类名称 + */ + + public void setCategoryName(String categoryName) { + this.categoryName = categoryName; + } + + /** + * 销售价格 + * + * @return salePrice + */ + + public Double getSalePrice() { + return salePrice; + } + + /** + * 销售价格 + * + * @param salePrice 销售价格 + */ + + public void setSalePrice(Double salePrice) { + this.salePrice = salePrice; + } + + /** + * 库存 + * + * @return stockNum + */ + + public Long getStockNum() { + return stockNum; + } + + /** + * 库存 + * + * @param stockNum 库存 + */ + + public void setStockNum(Long stockNum) { + this.stockNum = stockNum; + } + + /** + * 商家类别名称 + * + * @return merchantCategoryName + */ + + public String getMerchantCategoryName() { + return merchantCategoryName; + } + + /** + * 商家类别名称 + * + * @param merchantCategoryName 商家类别名称 + */ + + public void setMerchantCategoryName(String merchantCategoryName) { + this.merchantCategoryName = merchantCategoryName; + } + + /** + * 商家详情 + * + * @return productDescription + */ + + public String getProductDescription() { + return productDescription; + } + + /** + * 商家详情 + * + * @param productDescription 商家详情 + */ + + public void setProductDescription(String productDescription) { + this.productDescription = productDescription; + } + + /** + * 是否可调拨0:不可以1:可以 + * + * @return isTransfer + */ + + public Integer getIsTransfer() { + return isTransfer; + } + + /** + * 是否可调拨0:不可以1:可以 + * + * @param isTransfer 是否可调拨0:不可以1:可以 + */ + + public void setIsTransfer(Integer isTransfer) { + this.isTransfer = isTransfer; + } + + /** + * 是否需要审核0:新增未提交;1:需要审核;2:编辑未提交 + * + * @return isSubmit + */ + + public Integer getIsSubmit() { + return isSubmit; + } + + /** + * 是否需要审核0:新增未提交;1:需要审核;2:编辑未提交 + * + * @param isSubmit 是否需要审核0:新增未提交;1:需要审核;2:编辑未提交 + */ + + public void setIsSubmit(Integer isSubmit) { + this.isSubmit = isSubmit; + } + + /** + * 审核失败类型 + * + * @return verifyFailueType + */ + + public Integer getVerifyFailueType() { + return verifyFailueType; + } + + /** + * 审核失败类型 + * + * @param verifyFailueType 审核失败类型 + */ + + public void setVerifyFailueType(Integer verifyFailueType) { + this.verifyFailueType = verifyFailueType; + } + + /** + * 产品拼音 + * + * @return productSpell + */ + + public String getProductSpell() { + return productSpell; + } + + /** + * 产品拼音 + * + * @param productSpell 产品拼音 + */ + + public void setProductSpell(String productSpell) { + this.productSpell = productSpell; + } + + /** + * 产品名称前缀 + * + * @return productNamePrefix + */ + + public String getProductNamePrefix() { + return productNamePrefix; + } + + /** + * 产品名称前缀 + * + * @param productNamePrefix 产品名称前缀 + */ + + public void setProductNamePrefix(String productNamePrefix) { + this.productNamePrefix = productNamePrefix; + } + + /** + * 审核失败原因 + * + * @return failueReason + */ + + public String getFailueReason() { + return failueReason; + } + + /** + * 审核失败原因 + * + * @param failueReason 审核失败原因 + */ + + public void setFailueReason(String failueReason) { + this.failueReason = failueReason; + } + + /** + * orgPicUrl + * + * @return orgPicUrl + */ + + public String getOrgPicUrl() { + + return orgPicUrl; + } + + /** + * orgPicUrl + * + * @param orgPicUrl orgPicUrl + */ + + public void setOrgPicUrl(String orgPicUrl) { + this.orgPicUrl = orgPicUrl; + } + + /** + * 扩展分类名称 + * + * @return subCategoryName + */ + + public String getSubCategoryName() { + return subCategoryName; + } + + /** + * 扩展分类名称 + * + * @param subCategoryName 扩展分类名称 + */ + + public void setSubCategoryName(String subCategoryName) { + this.subCategoryName = subCategoryName; + } + + /** + * 扩展分类ID + * + * @return subCategoryId + */ + + public Long getSubCategoryId() { + return subCategoryId; + } + + /** + * 扩展分类ID + * + * @param subCategoryId 扩展分类ID + */ + + public void setSubCategoryId(Long subCategoryId) { + this.subCategoryId = subCategoryId; + } + + /** + * 7天内日均销量 + * + * @return dailySale + */ + + public Integer getDailySale() { + return dailySale; + } + + /** + * 7天内日均销量 + * + * @param dailySale 7天内日均销量 + */ + + public void setDailySale(Integer dailySale) { + this.dailySale = dailySale; + } + + /** + * 查看是否有主图 + * + * @return picCount + */ + + public Integer getPicCount() { + return picCount; + } + + /** + * 查看是否有主图 + * + * @param picCount 查看是否有主图 + */ + + public void setPicCount(Integer picCount) { + this.picCount = picCount; + } + + /** + * 强制下架原因 + * + * @return underCarriageReason + */ + + public Integer getUnderCarriageReason() { + return underCarriageReason; + } + + /** + * 强制下架原因 + * + * @param underCarriageReason 强制下架原因 + */ + + public void setUnderCarriageReason(Integer underCarriageReason) { + this.underCarriageReason = underCarriageReason; + } + + /** + * 异常信息 + * + * @return errorMessage + */ + + public String getErrorMessage() { + return errorMessage; + } + + /** + * 异常信息 + * + * @param errorMessage 异常信息 + */ + /** + * public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } 库存预警数量 + * + * @return alertStockCount + */ + + public Integer getAlertStockCount() { + return alertStockCount; + } + + /** + * 库存预警数量 + * + * @param alertStockCount 库存预警数量 + */ + + public void setAlertStockCount(Integer alertStockCount) { + this.alertStockCount = alertStockCount; + } + + /** + * 提交时间 + * + * @return submitTime + */ + /** + * public Date getSubmitTime() { return submitTime; } 提交时间 + * + * @param submitTime 提交时间 + */ + /** + * public void setSubmitTime(Date submitTime) { this.submitTime = submitTime; } holdPmPriceRpcVo + * + * @return holdPmPriceRpcVo + */ + + /** + * holdPmPriceRpcVo + * + * @param holdPmPrice holdPmPriceRpcVo + */ + + /** + * pmPriceRpcVo + * + * @return pmPriceRpcVo + */ + /** + * public PmPriceRpcVo getPmPrice() { return pmPrice; } pmPriceRpcVo + * + * @param pmPrice pmPriceRpcVo public void setPmPrice(PmPriceRpcVo pmPrice) { this.pmPrice = pmPrice; } + */ + public Long getFormalPmInfoId() { + return formalPmInfoId; + } + + public void setFormalPmInfoId(Long formalPmInfoId) { + this.formalPmInfoId = formalPmInfoId; + } + + /** + * 库存状况(产品预览页用) + * + * @return deliveryInfo + */ + + public String getDeliveryInfo() { + return deliveryInfo; + } + + /** + * 库存状况(产品预览页用) + * + * @param deliveryInfo 库存状况(产品预览页用) + */ + + public void setDeliveryInfo(String deliveryInfo) { + this.deliveryInfo = deliveryInfo; + } + + /** + * 主图链接 + * + * @return picUrl + */ + + public String getPicUrl() { + return picUrl; + } + + /** + * 主图链接 + * + * @param picUrl 主图链接 + */ + + public void setPicUrl(String picUrl) { + this.picUrl = picUrl; + } + + /** + * 跳到商品详情页的来源0:首次审核页面1:二次审核页面2:审核失败页面 + * + * @return viewFromTag + */ + + public Integer getViewFromTag() { + return viewFromTag; + } + + /** + * 跳到商品详情页的来源0:首次审核页面1:二次审核页面2:审核失败页面 + * + * @param viewFromTag 跳到商品详情页的来源0:首次审核页面1:二次审核页面2:审核失败页面 + */ + + public void setViewFromTag(Integer viewFromTag) { + this.viewFromTag = viewFromTag; + } + + public Double getProductNonMemberPrice() { + return productNonMemberPrice; + } + + /** + * 产品售价 + * + * @param productNonMemberPrice 产品售价 + */ + + public void setProductNonMemberPrice(Double productNonMemberPrice) { + this.productNonMemberPrice = productNonMemberPrice; + } + + public Integer getIsUpdate() { + return isUpdate; + } + + /** + * 是否更新操作 + * + * @param isUpdate 是否更新操作 + */ + + public void setIsUpdate(Integer isUpdate) { + this.isUpdate = isUpdate; + } + + public List getProductSizeSet() { + return productSizeSet; + } + + public void setProductSizeSet(List productSizeSet) { + this.productSizeSet = productSizeSet; + } + + public Boolean getIsMainProduct() { + return isMainProduct; + } + + /** + * 是否主产品 + * + * @param isMainProduct 是否主产品 + */ + + public void setIsMainProduct(Boolean isMainProduct) { + this.isMainProduct = isMainProduct; + } + + /** + * 从图片空间中返回图片ID和URL + * + * @return productPicIdAndURL + */ + + public String getProductPicIdAndURL() { + return productPicIdAndURL; + } + + /** + * 从图片空间中返回图片ID和URL + * + * @param productPicIdAndURL 从图片空间中返回图片ID和URL + */ + + public void setProductPicIdAndURL(String productPicIdAndURL) { + this.productPicIdAndURL = productPicIdAndURL; + } + + public Integer getIsTemp() { + return isTemp; + } + + /** + * isTemp + * + * @param isTemp isTemp + */ + + public void setIsTemp(Integer isTemp) { + this.isTemp = isTemp; + } + + public Double getPriceRate() { + return priceRate; + } + + public void setPriceRate(Double priceRate) { + this.priceRate = priceRate; + } + + public Integer getPicSpecialType() { + return picSpecialType; + } + + public void setPicSpecialType(Integer picSpecialType) { + this.picSpecialType = picSpecialType; + } + + public Integer getExemptStatus() { + return exemptStatus; + } + + public void setExemptStatus(Integer exemptStatus) { + this.exemptStatus = exemptStatus; + } + + public String getViolationReasonIds() { + return violationReasonIds; + } + + /** + * 免审商家新增字段:记录违规的原因 + * + * @param violationReasonIds 免审商家新增字段:记录违规的原因 + */ + + public void setViolationReasonIds(String violationReasonIds) { + this.violationReasonIds = violationReasonIds; + } + + /** + * 免审商家新增字段:记录违规的原因文字信息,逗号分隔 + * + * @return violationReasons + */ + + public String getViolationReasons() { + return violationReasons; + } + + public void setViolationReasons(String violationReasons) { + this.violationReasons = violationReasons; + } + + /** + * 违规限定修改剩余时间(毫秒数) + * + * @return remainTime + */ + + public Long getRemainTime() { + return remainTime; + } + + /** + * 违规限定修改剩余时间(毫秒数) + * + * @param remainTime 违规限定修改剩余时间(毫秒数) + */ + + public void setRemainTime(Long remainTime) { + this.remainTime = remainTime; + } + + public Integer getSubmitOrder() { + return submitOrder; + } + + public void setSubmitOrder(Integer submitOrder) { + this.submitOrder = submitOrder; + } + + public Integer getProductSource() { + return productSource; + } + + public void setProductSource(Integer productSource) { + this.productSource = productSource; + } + + public String getProductSname() { + return productSname; + } + + public void setProductSname(String productSname) { + this.productSname = productSname; + } + + public Integer getCanFenqi() { + return canFenqi; + } + + public void setCanFenqi(Integer canFenqi) { + this.canFenqi = canFenqi; + } + + public String getSeason() { + return season; + } + + public void setSeason(String season) { + this.season = season; + } + + public Integer getIsKa() { + return isKa; + } + + public void setIsKa(Integer isKa) { + this.isKa = isKa; + } + + public Integer getKaMCreateTime() { + return kaMCreateTime; + } + + public void setKaMCreateTime(Integer kaMCreateTime) { + this.kaMCreateTime = kaMCreateTime; + } + + public Integer getDeliveryDay() { + return deliveryDay; + } + + public void setDeliveryDay(Integer deliveryDay) { + this.deliveryDay = deliveryDay; + } + + public Integer getIsEdit() { + return isEdit; + } + + public void setIsEdit(Integer isEdit) { + this.isEdit = isEdit; + } + + public String getProductBrandName() { + return productBrandName; + } + + public void setProductBrandName(String productBrandName) { + this.productBrandName = productBrandName; + } + + /** + * 类别拼接字符串 + * + * @return categoryStr + */ + + public String getCategoryStr() { + return categoryStr; + } + + /** + * 类别拼接字符串 + * + * @param categoryStr 类别拼接字符串 + */ + + public void setCategoryStr(String categoryStr) { + this.categoryStr = categoryStr; + } + + /** + * 扩展类别拼接字符串 + * + * @return extendCategoryStr + */ + + public String getExtendCategoryStr() { + return extendCategoryStr; + } + + /** + * 扩展类别拼接字符串 + * + * @param extendCategoryStr 扩展类别拼接字符串 + */ + + public void setExtendCategoryStr(String extendCategoryStr) { + this.extendCategoryStr = extendCategoryStr; + } + + public String getCategoryIdStr() { + return categoryIdStr; + } + + public void setCategoryIdStr(String categoryIdStr) { + this.categoryIdStr = categoryIdStr; + } + + public String getExtendCategoryIdStr() { + return extendCategoryIdStr; + } + + + public Long getDefaultWarehouseId() { + return defaultWarehouseId; + } + + public void setDefaultWarehouseId(Long defaultWarehouseId) { + this.defaultWarehouseId = defaultWarehouseId; + } + + public Long getOldCategoryId() { + return oldCategoryId; + } + + public void setOldCategoryId(Long oldCategoryId) { + this.oldCategoryId = oldCategoryId; + } + + public Long getOldExtendCategoryId() { + return oldExtendCategoryId; + } + + public void setOldExtendCategoryId(Long oldExtendCategoryId) { + this.oldExtendCategoryId = oldExtendCategoryId; + } + + public String getDeletedProductId() { + return deletedProductId; + } + + public void setDeletedProductId(String deletedProductId) { + this.deletedProductId = deletedProductId; + } + + public String getReplaceProductSize() { + return replaceProductSize; + } + + public void setReplaceProductSize(String replaceProductSize) { + this.replaceProductSize = replaceProductSize; + } + + public List getMasterCategoryIdList() { + return masterCategoryIdList; + } + + public void setMasterCategoryIdList(List masterCategoryIdList) { + //this.masterCategoryIdList = masterCategoryIdList; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/bug/EmptyParseArrayTest.java b/src/test/java/com/alibaba/json/bvt/parser/bug/EmptyParseArrayTest.java new file mode 100644 index 0000000000..30a9db34c0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/bug/EmptyParseArrayTest.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.parser.bug; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class EmptyParseArrayTest extends TestCase { + public void test_0() throws Exception { + Assert.assertNull(JSON.parseArray("", VO.class)); + } + + public static class VO { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/bug/JSONObectNullTest.java b/src/test/java/com/alibaba/json/bvt/parser/bug/JSONObectNullTest.java new file mode 100644 index 0000000000..5a77f04fdb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/bug/JSONObectNullTest.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.parser.bug; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +/** + * Created by wenshao on 01/04/2017. + */ +public class JSONObectNullTest extends TestCase { + + public void test_for_null() throws Exception { + Model model = JSON.parseObject("{\"value\":null}", Model.class); + } + + public void test_for_null2() throws Exception { + JSON.parseObject("null"); + } + + public static class Model { + public JSONObject value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorFactoryTest.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorFactoryTest.java new file mode 100755 index 0000000000..55419076d4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorFactoryTest.java @@ -0,0 +1,59 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; + +public class JSONCreatorFactoryTest extends TestCase { + + public void test_create() throws Exception { + Entity entity = new Entity(123, "菜姐"); + String text = JSON.toJSONString(entity); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(entity.getId(), entity2.getId()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public void test_create_2() throws Exception { + Entity entity = new Entity(123, "菜姐"); + String text = JSON.toJSONString(entity); + + ParserConfig config = new ParserConfig(); + config.setAsmEnable(false); + + Entity entity2 = JSON.parseObject(text, Entity.class, config, 0); + Assert.assertEquals(entity.getId(), entity2.getId()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public static class Entity { + + private final int id; + private final String name; + + @JSONCreator + public static Entity create(@JSONField(name = "id") int id, @JSONField(name = "name") String name) { + return new Entity(id, name); + } + + private Entity(int id, String name){ + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest.java new file mode 100755 index 0000000000..7195e1fa23 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; + +public class JSONCreatorTest extends TestCase { + + public void test_create() throws Exception { + Entity entity = new Entity(123, "菜姐"); + String text = JSON.toJSONString(entity); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertEquals(entity.getId(), entity2.getId()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public void test_create_2() throws Exception { + Entity entity = new Entity(123, "菜姐"); + String text = JSON.toJSONString(entity); + + ParserConfig config = new ParserConfig(); + config.setAsmEnable(false); + + Entity entity2 = JSON.parseObject(text, Entity.class, config, 0); + Assert.assertEquals(entity.getId(), entity2.getId()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public static class Entity { + + private final int id; + private final String name; + + @JSONCreator + public Entity(@JSONField(name = "id") int id, @JSONField(name = "name") String name){ + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest2.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest2.java new file mode 100644 index 0000000000..029afce8b9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest2.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class JSONCreatorTest2 extends TestCase { + + public void test_create() throws Exception { + Entity vo = JSON.parseObject("{\"id\":1001,\"name\":\"wenshao\",\"obj\":{\"$ref\":\"..\"}}", Entity.class); + Assert.assertEquals(1001, vo.getId()); + Assert.assertEquals("wenshao", vo.getName()); + Assert.assertSame(vo, vo.getObj()); + } + + public void test_create_1() throws Exception { + Entity vo = JSON.parseObject("{\"id\":1001,\"name\":\"wenshao\",\"obj\":{\"$ref\":\"$\"}}", Entity.class); + Assert.assertEquals(1001, vo.getId()); + Assert.assertEquals("wenshao", vo.getName()); + Assert.assertSame(vo, vo.getObj()); + } + + public static class Entity { + + private final int id; + private final String name; + private final Object obj; + + @JSONCreator + public Entity(@JSONField(name = "id") int id, @JSONField(name = "name") String name, + @JSONField(name = "obj") Object obj){ + this.id = id; + this.name = name; + this.obj = obj; + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Object getObj() { + return obj; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest3.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest3.java new file mode 100644 index 0000000000..0577352f8e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest3.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class JSONCreatorTest3 extends TestCase { + + public void test_create_1() throws Exception { + Entity vo = JSON.parseObject("{\"id\":1001,\"name\":\"wenshao\",\"obj\":{\"$ref\":\"$\"}}", Entity.class); + Assert.assertEquals(1001, vo.getId()); + Assert.assertEquals("wenshao", vo.getName()); + Assert.assertSame(vo, vo.getObj()); + } + + public void test_create_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"id\":1001,\"name\":\"wenshao\",\"obj\":{\"$ref\":123}}", Entity.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_create_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"id\":1001,\"name\":\"wenshao\",\"obj\":{\"$ref\":\"$\",\"value\":123}}", Entity.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Entity { + + private final int id; + private final String name; + private final Entity obj; + + @JSONCreator + public Entity(@JSONField(name = "id") int id, @JSONField(name = "name") String name, + @JSONField(name = "obj") Entity obj){ + this.id = id; + this.name = name; + this.obj = obj; + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Entity getObj() { + return obj; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest4.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest4.java new file mode 100644 index 0000000000..e4480a566c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest4.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class JSONCreatorTest4 extends TestCase { + + public void test_create_error() throws Exception { + Entity entity = JSON.parseObject("{\"id\":1001,\"name\":\"wenshao\",\"obj\":{\"$ref\":\"$\"}}", Entity.class); + assertNotNull(entity); + assertEquals(1001, entity.id); + assertEquals("wenshao", entity.name); + assertSame(entity, entity.obj); + } + + public static class Entity { + + private final int id; + private final String name; + private Entity obj; + + @JSONCreator + public Entity(@JSONField(name = "id") int id, @JSONField(name = "name") String name, + Entity obj){ + this.id = id; + this.name = name; + this.obj = obj; + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Entity getObj() { + return obj; + } + + public void setObj(Entity obj) { + this.obj = obj; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest5.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest5.java new file mode 100644 index 0000000000..b68e549ee5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest5.java @@ -0,0 +1,57 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class JSONCreatorTest5 extends TestCase { + + public void test_create_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"id\":1001,\"name\":\"wenshao\",\"obj\":{\"$ref\":\"$\"}}", Entity.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Entity { + + private final int id; + private final String name; + private final Entity obj; + + private Entity(int id, String name, Entity obj) { + this.id = id; + this.name = name; + this.obj = obj; + } + + @JSONCreator + public static Entity create(@JSONField(name = "id") int id, @JSONField(name = "name") String name, + Entity obj){ + return new Entity(id, name, obj); + } + + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Entity getObj() { + return obj; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest6.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest6.java new file mode 100644 index 0000000000..7cb14371cf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest6.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class JSONCreatorTest6 extends TestCase { + + public void test_create_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"id\":1001,\"name\":\"wenshao\",\"obj\":{\"$ref\":\"$\"}}", Entity.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Entity { + + private final int id; + private final String name; + private final Entity obj; + + private Entity(int id, String name, Entity obj) { + this.id = id; + this.name = name; + this.obj = obj; + } + + @JSONCreator + public static Entity create(@JSONField(name = "id") int id, @JSONField(name = "name") String name, + @JSONField(name = "obj") Entity obj){ + return new Entity(id, name, obj); + } + + + @JSONCreator + public static Entity create1(@JSONField(name = "id") int id, @JSONField(name = "name") String name, + @JSONField(name = "obj") Entity obj){ + return new Entity(id, name, obj); + } + + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Entity getObj() { + return obj; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest7.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest7.java new file mode 100644 index 0000000000..6e2e5a26d9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest7.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser.creator; + +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class JSONCreatorTest7 extends TestCase { + + public void test_create() throws Exception { + Entity entity = JSON.parseObject("{\"values\":[{}]}", Entity.class); + Assert.assertEquals(1, entity.values.size()); + Assert.assertEquals(Value.class, entity.values.get(0).getClass()); + } + + + public static class Entity { + + private final List values; + + @JSONCreator + public Entity(@JSONField(name = "values") List values){ + this.values = values; + } + + public List getValues() { + return values; + } + + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest8.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest8.java new file mode 100644 index 0000000000..28716dc7ef --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest8.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser.creator; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.databind.annotation.JsonNaming; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.List; + +public class JSONCreatorTest8 extends TestCase { + + public void test_create() throws Exception { + String json = "{\"id\":1001,\"name\":\"wenshao\"}"; + Entity entity = JSON.parseObject(json, Entity.class); + assertEquals(1001, entity.id); + assertEquals("wenshao", entity.name); + } + + + public static class Entity { + private int id; + private String name; + + @JSONCreator + public Entity(@JSONField(name = "id") int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest9.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest9.java new file mode 100644 index 0000000000..2c82ee654b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest9.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser.creator; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +public class JSONCreatorTest9 extends TestCase { + public void test_for_yk() throws Exception { + String text = "{\"videoid\":\"XNzBxOCU0NjYxCg==\",\"videoName\":\"xxx\"}"; + + YoukuVideoDTO dto = JSON.parseObject(text, YoukuVideoDTO.class); + assertEquals("XNzBxOCU0NjYxCg==", dto.videoId); + assertEquals("xxx", dto.videoName); + + } + + public static class YoukuVideoDTO { + private String videoId; + + private String videoName; + + @JSONCreator + public YoukuVideoDTO(@JSONField(name = "videoid") String videoId) { + this.videoId = videoId; + } + + public String getVideoId() { + return videoId; + } + + public String getVideoName() { + return videoName; + } + + public void setVideoName(String videoName) { + this.videoName = videoName; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_boolean.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_boolean.java new file mode 100644 index 0000000000..70a21cc227 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_boolean.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser.creator; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class JSONCreatorTest_default_boolean extends TestCase { + + public void test_create() throws Exception { + Model model = JSON.parseObject("{\"name\":\"wenshao\"}", Model.class); + Assert.assertFalse(model.id); + Assert.assertEquals("wenshao", model.name); + } + + + public static class Model { + + private final boolean id; + private final String name; + + @JSONCreator + public Model(@JSONField(name="id") boolean id, @JSONField(name="name") String name) { + this.id = id; + this.name = name; + } + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_byte.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_byte.java new file mode 100644 index 0000000000..2683e7fdb6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_byte.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser.creator; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class JSONCreatorTest_default_byte extends TestCase { + + public void test_create() throws Exception { + Model model = JSON.parseObject("{\"name\":\"wenshao\"}", Model.class); + Assert.assertEquals(0, model.id); + Assert.assertEquals("wenshao", model.name); + } + + + public static class Model { + + private final byte id; + private final String name; + + @JSONCreator + public Model(@JSONField(name="id") byte id, @JSONField(name="name") String name) { + this.id = id; + this.name = name; + } + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_double.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_double.java new file mode 100644 index 0000000000..2f8051ed60 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_double.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser.creator; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class JSONCreatorTest_default_double extends TestCase { + + public void test_create() throws Exception { + Model model = JSON.parseObject("{\"name\":\"wenshao\"}", Model.class); + Assert.assertTrue(model.id == 0); + Assert.assertEquals("wenshao", model.name); + } + + + public static class Model { + + private final double id; + private final String name; + + @JSONCreator + public Model(@JSONField(name="id") double id, @JSONField(name="name") String name) { + this.id = id; + this.name = name; + } + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_float.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_float.java new file mode 100644 index 0000000000..10d83711cd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_float.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser.creator; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class JSONCreatorTest_default_float extends TestCase { + + public void test_create() throws Exception { + Model model = JSON.parseObject("{\"name\":\"wenshao\"}", Model.class); + Assert.assertTrue(model.id == 0); + Assert.assertEquals("wenshao", model.name); + } + + + public static class Model { + + private final float id; + private final String name; + + @JSONCreator + public Model(@JSONField(name="id") float id, @JSONField(name="name") String name) { + this.id = id; + this.name = name; + } + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_int.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_int.java new file mode 100644 index 0000000000..e3cc2e7ad4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_int.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser.creator; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class JSONCreatorTest_default_int extends TestCase { + + public void test_create() throws Exception { + Model model = JSON.parseObject("{\"name\":\"wenshao\"}", Model.class); + Assert.assertEquals(0, model.id); + Assert.assertEquals("wenshao", model.name); + } + + + public static class Model { + + private final int id; + private final String name; + + @JSONCreator + public Model(@JSONField(name="id") int id, @JSONField(name="name") String name) { + this.id = id; + this.name = name; + } + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_long.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_long.java new file mode 100644 index 0000000000..93f8f0ef25 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_long.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser.creator; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class JSONCreatorTest_default_long extends TestCase { + + public void test_create() throws Exception { + Model model = JSON.parseObject("{\"name\":\"wenshao\"}", Model.class); + Assert.assertEquals(0, model.id); + Assert.assertEquals("wenshao", model.name); + } + + + public static class Model { + + private final long id; + private final String name; + + @JSONCreator + public Model(@JSONField(name="id") long id, @JSONField(name="name") String name) { + this.id = id; + this.name = name; + } + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_short.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_short.java new file mode 100644 index 0000000000..d228e71592 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_short.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser.creator; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class JSONCreatorTest_default_short extends TestCase { + + public void test_create() throws Exception { + Model model = JSON.parseObject("{\"name\":\"wenshao\"}", Model.class); + Assert.assertEquals(0, model.id); + Assert.assertEquals("wenshao", model.name); + } + + + public static class Model { + + private final short id; + private final String name; + + @JSONCreator + public Model(@JSONField(name="id") short id, @JSONField(name="name") String name) { + this.id = id; + this.name = name; + } + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_double.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_double.java new file mode 100644 index 0000000000..008076ce6f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_double.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; + +public class JSONCreatorTest_double extends TestCase { + + public void test_create() throws Exception { + Entity entity = new Entity(123.45D, "菜姐"); + String text = JSON.toJSONString(entity); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertTrue(entity.getId() == entity2.getId()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public void test_create_2() throws Exception { + Entity entity = new Entity(123.45D, "菜姐"); + String text = JSON.toJSONString(entity); + + ParserConfig config = new ParserConfig(); + + Entity entity2 = JSON.parseObject(text, Entity.class, config, 0); + Assert.assertTrue(entity.getId() == entity2.getId()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public static class Entity { + + private final double id; + private final String name; + + @JSONCreator + public Entity(@JSONField(name = "id") double id, @JSONField(name = "name") String name){ + this.id = id; + this.name = name; + } + + public double getId() { + return id; + } + + public String getName() { + return name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_double_obj.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_double_obj.java new file mode 100644 index 0000000000..acb3cee3ef --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_double_obj.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; + +import junit.framework.TestCase; + +public class JSONCreatorTest_double_obj extends TestCase { + + public void test_create() throws Exception { + Entity entity = new Entity(123.45D, "菜姐"); + String text = JSON.toJSONString(entity); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertTrue(entity.getId().doubleValue() == entity2.getId().doubleValue()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public void test_create_2() throws Exception { + Entity entity = new Entity(123.45D, "菜姐"); + String text = JSON.toJSONString(entity); + + ParserConfig config = new ParserConfig(); + + Entity entity2 = JSON.parseObject(text, Entity.class, config, 0); + Assert.assertTrue(entity.getId().doubleValue() == entity2.getId().doubleValue()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public static class Entity { + + private final Double id; + private final String name; + + @JSONCreator + public Entity(@JSONField(name = "id") Double id, @JSONField(name = "name") String name){ + this.id = id; + this.name = name; + } + + public Double getId() { + return id; + } + + public String getName() { + return name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error.java new file mode 100644 index 0000000000..27e46a15bd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +public class JSONCreatorTest_error extends TestCase { + + public void test_create() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"id\":123,\"name\":\"abc\"}", Entity.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Entity { + + private final int id; + private final String name; + + @JSONCreator + public Entity(@JSONField(name = "id") int id, @JSONField(name = "name") String name){ + throw new UnsupportedOperationException(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error2.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error2.java new file mode 100644 index 0000000000..4d72eeb49d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error2.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.parser.creator; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +public class JSONCreatorTest_error2 extends TestCase { + + public void test_create() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"id\":123,\"name\":\"abc\"}", Entity.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Entity { + + private final int id; + private final String name; + + private Entity(int id, String name) { + this.id = id; + this.name = name; + } + + @JSONCreator + public static Entity create(@JSONField(name = "id") int id, @JSONField(name = "name") String name){ + throw new UnsupportedOperationException(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error3.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error3.java new file mode 100644 index 0000000000..f06c0fa227 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error3.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +public class JSONCreatorTest_error3 extends TestCase { + + public void test_create() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"id\":123,\"name\":\"abc\"}").toJavaObject(Entity.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Entity { + + private final int id; + private final String name; + + @JSONCreator + public Entity(@JSONField(name = "id") int id, @JSONField(name = "name") String name){ + throw new UnsupportedOperationException(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_float.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_float.java new file mode 100644 index 0000000000..e321df0478 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_float.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; + +public class JSONCreatorTest_float extends TestCase { + + public void test_create() throws Exception { + Entity entity = new Entity(123.45F, "菜姐"); + String text = JSON.toJSONString(entity); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertTrue(entity.getId() == entity2.getId()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public void test_create_2() throws Exception { + Entity entity = new Entity(123.45F, "菜姐"); + String text = JSON.toJSONString(entity); + + ParserConfig config = new ParserConfig(); + + Entity entity2 = JSON.parseObject(text, Entity.class, config, 0); + Assert.assertTrue(entity.getId() == entity2.getId()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public static class Entity { + + private final float id; + private final String name; + + @JSONCreator + public Entity(@JSONField(name = "id") float id, @JSONField(name = "name") String name){ + this.id = id; + this.name = name; + } + + public float getId() { + return id; + } + + public String getName() { + return name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_float_obj.java b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_float_obj.java new file mode 100644 index 0000000000..a3b3f05ff2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_float_obj.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.parser.creator; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; + +import junit.framework.TestCase; + +public class JSONCreatorTest_float_obj extends TestCase { + + public void test_create() throws Exception { + Entity entity = new Entity(123.45F, "菜姐"); + String text = JSON.toJSONString(entity); + + Entity entity2 = JSON.parseObject(text, Entity.class); + Assert.assertTrue(entity.getId().floatValue() == entity2.getId().floatValue()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public void test_create_2() throws Exception { + Entity entity = new Entity(123.45F, "菜姐"); + String text = JSON.toJSONString(entity); + + ParserConfig config = new ParserConfig(); + + Entity entity2 = JSON.parseObject(text, Entity.class, config, 0); + Assert.assertTrue(entity.getId().floatValue() == entity2.getId().floatValue()); + Assert.assertEquals(entity.getName(), entity2.getName()); + } + + public static class Entity { + + private final Float id; + private final String name; + + @JSONCreator + public Entity(@JSONField(name = "id") Float id, @JSONField(name = "name") String name){ + this.id = id; + this.name = name; + } + + public Float getId() { + return id; + } + + public String getName() { + return name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/AbstractSerializeTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/AbstractSerializeTest.java new file mode 100644 index 0000000000..4db79090fe --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/AbstractSerializeTest.java @@ -0,0 +1,93 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +public class AbstractSerializeTest extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.AbstractSerializeTest"); + + ObjectDeserializer serializerB = ParserConfig.getGlobalInstance().getDeserializer(B.class); + ParserConfig.getGlobalInstance().putDeserializer(A.class, serializerB); + } + + protected void tearDown() throws Exception { + ParserConfig.getGlobalInstance().putDeserializer(A.class, null); + } + + public void test_mapping_0() throws Exception { + String text = "{\"@type\":\"com.alibaba.json.bvt.parser.deser.AbstractSerializeTest$A\"}"; + + B b = (B) JSON.parse(text); + Assert.assertNotNull(b); + } + + public void test_mapping_1() throws Exception { + String text = "{\"@type\":\"com.alibaba.json.bvt.parser.deser.AbstractSerializeTest$A\",\"id\":123}"; + + B b = (B) JSON.parse(text); + Assert.assertNotNull(b); + Assert.assertEquals(123, b.getId()); + } + + public void test_mapping_2() throws Exception { + String text = "{\"@type\":\"com.alibaba.json.bvt.parser.deser.AbstractSerializeTest$A\",\"id\":234,\"name\":\"abc\"}"; + + B b = (B) JSON.parse(text); + Assert.assertNotNull(b); + Assert.assertEquals(234, b.getId()); + Assert.assertEquals("abc", b.getName()); + } + + public void test_mapping_group() throws Exception { + String text = "{\"a\":{\"id\":234,\"name\":\"abc\"}}"; + + G g = JSON.parseObject(text, G.class); + Assert.assertTrue(g.getA() instanceof B); + } + + public static class G { + + private A a; + + public A getA() { + return a; + } + + public void setA(A a) { + this.a = a; + } + + } + + public static abstract class A { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + } + + public static class B extends A { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/AbstractSerializeTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/AbstractSerializeTest2.java new file mode 100644 index 0000000000..3ed5cdebb3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/AbstractSerializeTest2.java @@ -0,0 +1,93 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.ParserConfig; + +public class AbstractSerializeTest2 extends TestCase { + + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.AbstractSerializeTest2"); + ParserConfig.global.addAccept("com.alibaba.json.bvt.parser.deser.AbstractSerializeTest2"); + } + + protected void tearDown() throws Exception { + ParserConfig.getGlobalInstance().putDeserializer(A.class, null); + } + + public void test_mapping_0() throws Exception { + String text = "{\"@type\":\"com.alibaba.json.bvt.parser.deser.AbstractSerializeTest2$A\"}"; + + B b = (B) JSON.parse(text); + Assert.assertNotNull(b); + } + + public void test_mapping_1() throws Exception { + String text = "{\"@type\":\"com.alibaba.json.bvt.parser.deser.AbstractSerializeTest2$A\",\"id\":123}"; + + B b = (B) JSON.parse(text); + Assert.assertNotNull(b); + Assert.assertEquals(123, b.getId()); + } + + public void test_mapping_2() throws Exception { + String text = "{\"@type\":\"com.alibaba.json.bvt.parser.deser.AbstractSerializeTest2$A\",\"id\":234,\"name\":\"abc\"}"; + + B b = (B) JSON.parse(text); + Assert.assertNotNull(b); + Assert.assertEquals(234, b.getId()); + Assert.assertEquals("abc", b.getName()); + } + + public void test_mapping_group() throws Exception { + String text = "{\"a\":{\"id\":234,\"name\":\"abc\"}}"; + + G g = JSON.parseObject(text, G.class); + Assert.assertTrue(g.getA() instanceof B); + } + + public static class G { + + private A a; + + public A getA() { + return a; + } + + public void setA(A a) { + this.a = a; + } + + } + + @JSONType(mappingTo = B.class) + public static abstract class A { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + } + + public static class B extends A { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/BigDecimalDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/BigDecimalDeserializerTest.java new file mode 100755 index 0000000000..0f95b6406b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/BigDecimalDeserializerTest.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.math.BigDecimal; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.BigDecimalCodec; + +public class BigDecimalDeserializerTest extends TestCase { + + public void test_bigdecimal() throws Exception { + Assert.assertEquals(BigDecimal.ZERO, JSON.parseObject("0", BigDecimal.class)); + Assert.assertEquals(BigDecimal.ZERO, JSON.parseObject("'0'", BigDecimal.class)); + Assert.assertEquals(new BigDecimal("0.0"), JSON.parseObject("0.0", BigDecimal.class)); + Assert.assertEquals(new BigDecimal("0.0"), JSON.parseObject("'0.0'", BigDecimal.class)); + + Assert.assertEquals(null, JSON.parseObject("null", BigDecimal.class)); + + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + Assert.assertEquals(null, BigDecimalCodec.instance.deserialze(parser, null, null)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/BigDecimalTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/BigDecimalTest.java new file mode 100755 index 0000000000..82438da02b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/BigDecimalTest.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.math.BigDecimal; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class BigDecimalTest extends TestCase { + public void test_null () throws Exception { + Assert.assertNull(JSON.parseObject("null", VO.class)); + Assert.assertNull(JSON.parseObject("{value:null}", VO.class).getValue()); + Assert.assertNull(JSON.parseObject("{'value':null}", VO.class).getValue()); + Assert.assertNull(JSON.parseObject("{\"value\":null}", VO.class).getValue()); + Assert.assertNull(JSON.parseArray("null", BigDecimal.class)); + Assert.assertNull(JSON.parseObject("null", BigDecimal.class)); + } + + public void test_postfix () throws Exception { + Assert.assertEquals(new BigDecimal ("123"), JSON.parseObject("123L", BigDecimal.class)); + Assert.assertEquals(new BigDecimal ("123"), JSON.parseObject("123D", BigDecimal.class)); + Assert.assertEquals(new BigDecimal ("123"), JSON.parseObject("123F", BigDecimal.class)); + Assert.assertEquals(new BigDecimal ("123"), JSON.parseObject("123S", BigDecimal.class)); + Assert.assertEquals(new BigDecimal ("123"), JSON.parseObject("123B", BigDecimal.class)); + } + + public void test_className() throws Exception { + Assert.assertEquals("123.", JSON.toJSONString(new BigDecimal("123"), SerializerFeature.WriteClassName)); + Assert.assertEquals("123.00", JSON.toJSONString(new BigDecimal("123.00"), SerializerFeature.WriteClassName)); + Assert.assertEquals("123.45", JSON.toJSONString(new BigDecimal("123.45"), SerializerFeature.WriteClassName)); + Assert.assertEquals(new BigDecimal("123"), JSON.parse("123.")); + } + + public static class VO { + + private BigDecimal value; + + public BigDecimal getValue() { + return value; + } + + public void setValue(BigDecimal value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/BigIntegerDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/BigIntegerDeserializerTest.java new file mode 100755 index 0000000000..24b398ec7c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/BigIntegerDeserializerTest.java @@ -0,0 +1,73 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.math.BigInteger; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class BigIntegerDeserializerTest extends TestCase { + + public void test_1() throws Exception { + + BigInteger value = JSON.parseObject("'123'", BigInteger.class); + + Assert.assertEquals(new BigInteger("123"), value); + } + + public void test_vo() throws Exception { + + VO vo = JSON.parseObject("{\"value\":123}", VO.class); + + Assert.assertEquals(new BigInteger("123"), vo.getValue()); + } + + public void test_vo_null() throws Exception { + + VO vo = JSON.parseObject("{\"value\":null}", VO.class); + + Assert.assertEquals(null, vo.getValue()); + } + + public void test_vo2() throws Exception { + + VO2 vo = JSON.parseObject("{\"value\":123}", VO2.class); + + Assert.assertEquals(new BigInteger("123"), vo.getValue()); + } + + public void test_array() throws Exception { + List list = JSON.parseArray("[123,345]", BigInteger.class); + Assert.assertEquals(new BigInteger("123"), list.get(0)); + Assert.assertEquals(new BigInteger("345"), list.get(1)); + } + + public static class VO { + + private BigInteger value; + + public BigInteger getValue() { + return value; + } + + public void setValue(BigInteger value) { + this.value = value; + } + } + + private static class VO2 { + + private BigInteger value; + + public BigInteger getValue() { + return value; + } + + public void setValue(BigInteger value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/BooleanDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/BooleanDeserializerTest.java new file mode 100755 index 0000000000..d4470a9f5f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/BooleanDeserializerTest.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.BooleanCodec; + +public class BooleanDeserializerTest extends TestCase { + + public void test_boolean() throws Exception { + Assert.assertEquals(Boolean.TRUE, JSON.parseObject("true", Boolean.class)); + Assert.assertEquals(Boolean.FALSE, JSON.parseObject("false", Boolean.class)); + + Assert.assertEquals(Boolean.TRUE, JSON.parseObject("'true'", Boolean.class)); + Assert.assertEquals(Boolean.FALSE, JSON.parseObject("'false'", Boolean.class)); + + Assert.assertEquals(Boolean.TRUE, JSON.parseObject("1", Boolean.class)); + Assert.assertEquals(Boolean.FALSE, JSON.parseObject("0", Boolean.class)); + + Assert.assertEquals(null, JSON.parseObject("null", Boolean.class)); + + { + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), + JSON.DEFAULT_PARSER_FEATURE); + Assert.assertEquals(null, BooleanCodec.instance.deserialze(parser, null, null)); + parser.close(); + } + Assert.assertEquals(JSONToken.TRUE, BooleanCodec.instance.getFastMatchToken()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/BooleanFieldDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/BooleanFieldDeserializerTest.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/BooleanFieldDeserializerTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/BooleanFieldDeserializerTest.java index 4e9c4b0325..61bf2dab4a --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/BooleanFieldDeserializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/BooleanFieldDeserializerTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/BooleanFieldDeserializerTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/BooleanFieldDeserializerTest2.java new file mode 100644 index 0000000000..2717fad9df --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/BooleanFieldDeserializerTest2.java @@ -0,0 +1,57 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +public class BooleanFieldDeserializerTest2 extends TestCase { + + public void test_0() throws Exception { + Entity a = JSON.parseObject("{\"f1\":true,\"f2\":null}", Entity.class); + Assert.assertEquals(true, a.getF1()); + Assert.assertEquals(null, a.getF2()); + } + + public void test_1() throws Exception { + Entity a = JSON.parseObject("{\"f1\":1,\"f2\":null}", Entity.class); + Assert.assertEquals(true, a.getF1()); + Assert.assertEquals(null, a.getF2()); + } + + public void test_2() throws Exception { + Entity a = JSON.parseObject("{\"f1\":\"true\",\"f2\":null}", Entity.class); + Assert.assertEquals(true, a.getF1()); + Assert.assertEquals(null, a.getF2()); + } + + public void test_3() throws Exception { + Entity a = JSON.parseObject("{\"f1\":false,\"f2\":null}", Entity.class); + Assert.assertEquals(false, a.getF1()); + Assert.assertEquals(null, a.getF2()); + } + + public static class Entity { + + private final Boolean f1; + private final Boolean f2; + + @JSONCreator + public Entity(@JSONField(name = "f1") Boolean f1, @JSONField(name = "f2") Boolean f2){ + this.f1 = f1; + this.f2 = f2; + } + + public Boolean getF1() { + return f1; + } + + public Boolean getF2() { + return f2; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/CharArrayDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/CharArrayDeserializerTest.java new file mode 100755 index 0000000000..917104c53d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/CharArrayDeserializerTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class CharArrayDeserializerTest extends TestCase { + + public void test_charArray() throws Exception { + Assert.assertEquals(null, JSON.parseObject("{}", VO.class).getValue()); + Assert.assertEquals(null, JSON.parseObject("{value:null}", VO.class).getValue()); + Assert.assertEquals(null, JSON.parseObject("{'value':null}", VO.class).getValue()); + Assert.assertEquals(null, JSON.parseObject("{\"value\":null}", VO.class).getValue()); + Assert.assertEquals(0, JSON.parseObject("{\"value\":\"\"}", VO.class).getValue().length); + Assert.assertEquals(2, JSON.parseObject("{\"value\":\"ab\"}", VO.class).getValue().length); + Assert.assertEquals("ab", new String(JSON.parseObject("{\"value\":\"ab\"}", VO.class).getValue())); + Assert.assertEquals("12", new String(JSON.parseObject("{\"value\":12}", VO.class).getValue())); + Assert.assertEquals("12", new String(JSON.parseObject("{\"value\":12L}", VO.class).getValue())); + Assert.assertEquals("12", new String(JSON.parseObject("{\"value\":12S}", VO.class).getValue())); + Assert.assertEquals("12", new String(JSON.parseObject("{\"value\":12B}", VO.class).getValue())); + Assert.assertEquals("{}", new String(JSON.parseObject("{\"value\":{}}", VO.class).getValue())); + } + + public static class VO { + + private char[] value; + + public char[] getValue() { + return value; + } + + public void setValue(char[] value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ClassTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ClassTest.java new file mode 100755 index 0000000000..5c9ccefbeb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ClassTest.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class ClassTest extends TestCase { + + public void test_null() throws Exception { + Assert.assertNull(JSON.parseObject("null", Class.class)); + Assert.assertNull(JSON.parseObject("null", Class[].class)); + Assert.assertNull(JSON.parseArray("null", Class.class)); + Assert.assertNull(JSON.parseObject("{value:null}", VO.class).getValue()); + } + + public void test_primitive() throws Exception { + Assert.assertEquals(byte.class, JSON.parseObject("\"byte\"", Class.class)); + Assert.assertEquals(short.class, JSON.parseObject("\"short\"", Class.class)); + Assert.assertEquals(int.class, JSON.parseObject("\"int\"", Class.class)); + Assert.assertEquals(long.class, JSON.parseObject("\"long\"", Class.class)); + Assert.assertEquals(float.class, JSON.parseObject("\"float\"", Class.class)); + Assert.assertEquals(double.class, JSON.parseObject("\"double\"", Class.class)); + Assert.assertEquals(char.class, JSON.parseObject("\"char\"", Class.class)); + Assert.assertEquals(boolean.class, JSON.parseObject("\"boolean\"", Class.class)); + } + + public void test_array() throws Exception { + Assert.assertEquals(int[].class, JSON.parseObject("\"[int\"", Class.class)); + Assert.assertEquals(int[][].class, JSON.parseObject("\"[[int\"", Class.class)); + Assert.assertEquals(int[][][][].class, JSON.parseObject("\"[[[[int\"", Class.class)); + } + + public static class VO { + + private Class value; + + public Class getValue() { + return value; + } + + public void setValue(Class value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/CollectionFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/CollectionFieldTest.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/CollectionFieldTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/CollectionFieldTest.java index e69a7121f8..d79df17128 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/CollectionFieldTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/CollectionFieldTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; import java.util.Collection; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ConcurrentHashMapDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ConcurrentHashMapDeserializerTest.java new file mode 100755 index 0000000000..8c970f1b61 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ConcurrentHashMapDeserializerTest.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.IdentityHashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class ConcurrentHashMapDeserializerTest extends TestCase { + @SuppressWarnings("rawtypes") + public void test_1 () throws Exception { + ConcurrentHashMap map = JSON.parseObject("{}", ConcurrentHashMap.class); + Assert.assertEquals(0, map.size()); + } + + @SuppressWarnings("rawtypes") + public void test_2() throws Exception { + ConcurrentMap map = JSON.parseObject("{}", ConcurrentMap.class); + Assert.assertEquals(0, map.size()); + } + + @SuppressWarnings("rawtypes") + public void test_className() throws Exception { + ConcurrentHashMap map = (ConcurrentHashMap) JSON.parse("{\"@type\":\"java.util.concurrent.ConcurrentHashMap\"}"); + Assert.assertEquals(0, map.size()); + } + + @SuppressWarnings("rawtypes") + public void test_className1() throws Exception { + IdentityHashMap map = (IdentityHashMap) JSON.parse("{\"@type\":\"java.util.IdentityHashMap\"}"); + Assert.assertEquals(0, map.size()); + } + + @SuppressWarnings("rawtypes") + public void test_className2() throws Exception { + IdentityHashMap map = (IdentityHashMap) JSON.parse("{\"@type\":\"java.util.IdentityHashMap\", \"id\":123}"); + Assert.assertEquals(1, map.size()); + } + + public void test_null () throws Exception { + Assert.assertEquals(null, JSON.parseObject("null", ConcurrentHashMap.class)); + Assert.assertEquals(null, JSON.parseObject("null", ConcurrentMap.class)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest.java new file mode 100644 index 0000000000..123d479b13 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ConstructorErrorTest extends TestCase { + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{}", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public Model(){ + throw new IllegalStateException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_initError.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_initError.java new file mode 100644 index 0000000000..5ee8edaefd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_initError.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ConstructorErrorTest_initError extends TestCase { + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{}", Model.class, Feature.InitStringFieldAsEmpty); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public Model(){ + + } + + public void setName(String name) { + throw new IllegalStateException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_initError_private.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_initError_private.java new file mode 100644 index 0000000000..732486f300 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_initError_private.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ConstructorErrorTest_initError_private extends TestCase { + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{}", Model.class, Feature.InitStringFieldAsEmpty); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Model { + + public Model(){ + + } + + public void setName(String name) { + throw new IllegalStateException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_inner.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_inner.java new file mode 100644 index 0000000000..5d0ae988ac --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_inner.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class ConstructorErrorTest_inner extends TestCase { + + public void test_error() throws Exception { + JSONObject obj = new JSONObject(); + obj.put("value", new JSONObject()); + Exception error = null; + try { + obj.toJavaObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + public Value value; + + public Model(){ + } + + public class Value { + public Value() { + throw new IllegalStateException(); + } + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_private.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_private.java new file mode 100644 index 0000000000..425621f8bc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_private.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ConstructorErrorTest_private extends TestCase { + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{}", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Model { + + public Model(){ + throw new IllegalStateException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest10.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest10.java new file mode 100644 index 0000000000..41a8987a6c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest10.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class DefaultObjectDeserializerTest10 extends TestCase { + + public void test_1() throws Exception { + T[] list = JSON.parseObject("[{}]", new TypeReference() { + }); + Assert.assertEquals(1, list.length); + Assert.assertNotNull(list[0]); + Assert.assertTrue(list[0] instanceof A); + } + + public static class A { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest11.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest11.java new file mode 100644 index 0000000000..d3e976c1fc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest11.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.json.bvt.parser.deser.DefaultObjectDeserializerTest4.Entity; + +public class DefaultObjectDeserializerTest11 extends TestCase { + + public void test_0() throws Exception { + A a = new A(); + DefaultJSONParser parser = new DefaultJSONParser("{\"id\":123}", ParserConfig.getGlobalInstance()); + parser.parseObject(a); + } + + public static class A { + + private long id; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest12.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest12.java new file mode 100644 index 0000000000..c0547c1963 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest12.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; + +public class DefaultObjectDeserializerTest12 extends TestCase { + + public void test_list() throws Exception { + A a = new A(); + DefaultJSONParser parser = new DefaultJSONParser("{\"values\":[]}", ParserConfig.getGlobalInstance()); + parser.parseObject(a); + parser.close(); + } + + public static class A { + + private List values; + + public List getValues() { + return values; + } + + public void setValues(List values) { + this.values = values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest2.java new file mode 100755 index 0000000000..1489c1b561 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest2.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.HashMap; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentMap; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; + +@SuppressWarnings("deprecation") +public class DefaultObjectDeserializerTest2 extends TestCase { + + + public void test_1() throws Exception { + String input = "{'map':{}}"; + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + + + SortedMap map = JSON.parseObject(input, new TypeReference>() { + }.getType()); + + Assert.assertEquals(TreeMap.class, map.get("map").getClass()); + } + + + + public void test_8() throws Exception { + String input = "{'map':{}}"; + + ConcurrentMap map = JSON.parseObject(input, new TypeReference>() { + }.getType()); + + Assert.assertEquals(HashMap.class, map.get("map").getClass()); + } + + public static interface Map1 extends Map { + + } + + public static class Map2 extends HashMap { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest3.java new file mode 100644 index 0000000000..cdb98f37da --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest3.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.HashMap; + +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +@SuppressWarnings("rawtypes") +public class DefaultObjectDeserializerTest3 extends TestCase { + protected void setUp() throws Exception { + ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.AbstractSerializeTest2"); + } + + public void test_0() throws Exception { + HashMap o = (HashMap) JSON.parse("{\"@type\":\"java.lang.Cloneable\"}"); + Assert.assertEquals(0, o.size()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest4.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest4.java new file mode 100755 index 0000000000..5fdb004e95 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest4.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; + +public class DefaultObjectDeserializerTest4 extends TestCase { + + public void test_0() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{\"id\":3, \"name\":\"xx\"}", ParserConfig.getGlobalInstance()); + + Entity entity = new Entity(); + parser.parseObject(entity); + } + + public void test_1() throws Exception { + JSON.parseObject("{\"id\":3, \"name\":\"xx\"}", Entity.class, 0, Feature.IgnoreNotMatch); + } + + public static class Entity { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest5.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest5.java new file mode 100644 index 0000000000..e7935e6e38 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest5.java @@ -0,0 +1,83 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class DefaultObjectDeserializerTest5 extends TestCase { + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[]", new TypeReference>() { + }); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject(",]", new TypeReference>() { + }); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("[{},{\"$ref\":0}]", + new TypeReference>>() { + }); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_4() throws Exception { + Exception error = null; + try { + JSON.parseObject("[{},{\"$ref\":\"$[0]\",}]", + new TypeReference>>() { + }); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_0() throws Exception { + List> list = JSON.parseObject("[{},{\"$ref\":\"$[0]\"}]", + new TypeReference>>() { + }); + Assert.assertSame(list.get(0), list.get(1)); + } + + public void test_1() throws Exception { + Map> map = JSON.parseObject("{\"1\":{},\"2\":{\"$ref\":\"$\"}}", + new TypeReference>>() { + }); + Assert.assertSame(map, map.get("2")); + } + + public void test_2() throws Exception { + Map> map = JSON.parseObject("{\"1\":{},\"2\":{\"$ref\":\"..\"}}", + new TypeReference>>() { + }); + Assert.assertSame(map, map.get("2")); + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest6.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest6.java new file mode 100644 index 0000000000..4871cc6c8a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest6.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +public class DefaultObjectDeserializerTest6 extends TestCase { + + public void test_0() throws Exception { + Entity vo = JSON.parseObject("{\"value\":{\"1\":{},\"2\":{\"$ref\":\"$.value.1\"}}}", Entity.class); + Assert.assertSame(vo.getValue().get("1"), vo.getValue().get("2")); + } + + public void test_1() throws Exception { + Entity vo = JSON.parseObject("{\"value\":{\"1\":{},\"2\":{\"$ref\":\"..\"}}}", Entity.class); + Assert.assertSame(vo.getValue(), vo.getValue().get("2")); + } + + public static class Entity { + + private final Map> value; + + @JSONCreator + public Entity(@JSONField(name = "value") Map> value){ + this.value = value; + } + + public Map> getValue() { + return value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest7.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest7.java new file mode 100644 index 0000000000..af4e8081f5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest7.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class DefaultObjectDeserializerTest7 extends TestCase { + + public void test_0() throws Exception { + VO vo = JSON.parseObject("{\"value\":[{\"id\":123}]}", new TypeReference>() { + }); + A a = vo.getValue()[0]; + Assert.assertEquals(123, a.getId()); + } + + public static class VO { + + private T[] value; + + public T[] getValue() { + return value; + } + + public void setValue(T[] value) { + this.value = value; + } + + } + + public static class A { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest8.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest8.java new file mode 100644 index 0000000000..f1bbfe3352 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest8.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class DefaultObjectDeserializerTest8 extends TestCase { + + public void test_1() throws Exception { + VO vo = JSON.parseObject("{\"value\":[{\"id\":123}]}", new TypeReference>() { + }); + Assert.assertNotNull(vo.getValue()[0]); + Assert.assertTrue(vo.getValue()[0] instanceof Map); + } + + public static class VO { + + private T[] value; + + public T[] getValue() { + return value; + } + + public void setValue(T[] value) { + this.value = value; + } + + } + + public static class A { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest9.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest9.java new file mode 100644 index 0000000000..f43b8502f1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest9.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class DefaultObjectDeserializerTest9 extends TestCase { + + public void test_1() throws Exception { + T[] list = JSON.parseObject("[{}]", new TypeReference() { + }); + Assert.assertEquals(1, list.length); + Assert.assertNotNull(list[0]); + Assert.assertTrue(list[0] instanceof Map); + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/DefaultObjectDeserializerTest_collection.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest_collection.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/DefaultObjectDeserializerTest_collection.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest_collection.java index 4a692d2000..e20edec672 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/DefaultObjectDeserializerTest_collection.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest_collection.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; import java.util.HashMap; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DoubleArrayFieldDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DoubleArrayFieldDeserializerTest.java new file mode 100644 index 0000000000..348b7ce047 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DoubleArrayFieldDeserializerTest.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class DoubleArrayFieldDeserializerTest extends TestCase { + + public void test_0() throws Exception { + Entity a = JSON.parseObject("{\"values\":[1,2]}", Entity.class); + Assert.assertTrue(1 == a.getValues()[0]); + Assert.assertTrue(2 == a.getValues()[1]); + } + + + public static class Entity { + + public double[] values; + + public double[] getValues() { + return values; + } + + public void setValues(double[] values) { + this.values = values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DoubleDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DoubleDeserializerTest.java new file mode 100755 index 0000000000..a150966f81 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DoubleDeserializerTest.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.NumberDeserializer; + +public class DoubleDeserializerTest extends TestCase { + + public void test_bigdecimal() throws Exception { + Assert.assertEquals(0, JSON.parseObject("0", Double.class).intValue()); + Assert.assertEquals(0, JSON.parseObject("0.0", Double.class).intValue()); + Assert.assertEquals(0, JSON.parseObject("'0'", Double.class).intValue()); + Assert.assertEquals(0, JSON.parseObject("'0'", double.class).intValue()); + Assert.assertEquals(null, JSON.parseObject("null", Double.class)); + + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + Assert.assertEquals(null, NumberDeserializer.instance.deserialze(parser, null, null)); + Assert.assertEquals(JSONToken.LITERAL_INT, NumberDeserializer.instance.getFastMatchToken()); + } +} + diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DoubleFieldDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DoubleFieldDeserializerTest.java new file mode 100644 index 0000000000..4598fccc70 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DoubleFieldDeserializerTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class DoubleFieldDeserializerTest extends TestCase { + + public void test_0() throws Exception { + Entity a = JSON.parseObject("{\"value\":123.45}", Entity.class); + Assert.assertTrue(123.45D == a.getValue()); + } + + public static class Entity { + + public Double value; + + public Double getValue() { + return value; + } + + public void setValue(Double value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/DupTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/DupTest.java new file mode 100644 index 0000000000..22aac8e8ea --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/DupTest.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 13/02/2017. + */ +public class DupTest extends TestCase { + public void test_dup() throws Exception { + String json = "{\"id\":1001,\"_id\":1002}"; + + Model model = JSON.parseObject(json, Model.class); + assertEquals(1001, model.id); + } + + public static class Model { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/EnumMapTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/EnumMapTest.java new file mode 100644 index 0000000000..2d7b45d8a1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/EnumMapTest.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.util.EnumMap; + +/** + * Created by wenshao on 2016/10/18. + */ +public class EnumMapTest extends TestCase { + public void test_for_enum_map() throws Exception { + EnumMap enumMap = new EnumMap(Type.class); + enumMap.put(Type.Big, "BIG"); + + String json = JSON.toJSONString(enumMap); + System.out.println(json); + EnumMap enumMap2 = JSON.parseObject(json, new TypeReference>(){}); + assertEquals(1, enumMap2.size()); + assertEquals(enumMap.get(Type.Big), enumMap2.get(Type.Big)); + } + + public static enum Type { + Big, Small + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/EnumTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/EnumTest.java new file mode 100755 index 0000000000..130e5253a7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/EnumTest.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.concurrent.TimeUnit; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +public class EnumTest extends TestCase { + + public void test_enum() throws Exception { + Assert.assertNull(JSON.parseObject("''", TimeUnit.class)); + } + + public void test_enum_1() throws Exception { + Assert.assertEquals(E.A, JSON.parseObject("0", E.class)); + } + + public void test_enum_3() throws Exception { + Assert.assertEquals(E.A, JSON.parseObject("{value:0}", Entity.class).getValue()); + } + + public void test_enum_2() throws Exception { + Assert.assertEquals(E.A, JSON.parseObject("'A'", E.class)); + } + + public void test_enum_error() throws Exception { + assertNull(JSON.parseObject("'123'", TimeUnit.class)); + } + + public void test_enum_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("12.3", TimeUnit.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static enum E { + A, B, C + } + + public static class Entity { + + private E value; + + public Entity(){ + + } + + public Entity(E value){ + super(); + this.value = value; + } + + public E getValue() { + return value; + } + + public void setValue(E value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FactoryTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FactoryTest.java new file mode 100755 index 0000000000..b34bf21af9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FactoryTest.java @@ -0,0 +1,106 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +public class FactoryTest extends TestCase { + + public void test_factory() throws Exception { + VO vo = JSON.parseObject("{\"b\":true,\"i\":33,\"l\":34,\"f\":45.}", VO.class); + Assert.assertEquals(true, vo.isB()); + Assert.assertEquals(33, vo.getI()); + Assert.assertEquals(34L, vo.getL()); + Assert.assertTrue(45f == vo.getF()); + JSON.parseObject("{\"b\":1,\"i\":33,\"l\":34,\"f\":45.}", VO.class); + } + + public void test_factory1() throws Exception { + V1 vo = JSON.parseObject("{\"b\":true,\"i\":33,\"l\":34,\"f\":45.}", V1.class); + Assert.assertEquals(true, vo.isB()); + Assert.assertEquals(33, vo.getI()); + Assert.assertEquals(34L, vo.getL()); + Assert.assertTrue(45f == vo.getF()); + JSON.parseObject("{\"b\":1,\"i\":33,\"l\":34,\"f\":45.}", V1.class); + + // JSON.parseObject("{\"b\":true,\"i\":33,\"l\":34,\"f\":45.}").toJavaObject(V1.class); + } + + public static class VO { + + private final boolean b; + private final int i; + private final long l; + private final float f; + + @JSONCreator + public VO(@JSONField(name = "b") boolean b, @JSONField(name = "i") int i, @JSONField(name = "l") long l, + @JSONField(name = "f") float f){ + super(); + this.b = b; + this.i = i; + this.l = l; + this.f = f; + } + + public float getF() { + return f; + } + + public boolean isB() { + return b; + } + + public int getI() { + return i; + } + + public long getL() { + return l; + } + + } + + public static class V1 { + + private boolean b; + private int i; + private long l; + private float f; + + private V1(boolean b) { + this.b = b; + } + + @JSONCreator + public static V1 create(@JSONField(name = "b") boolean b, @JSONField(name = "i") int i, + @JSONField(name = "l") long l, @JSONField(name = "f") float f) { + V1 v = new V1(b); + v.i = i; + v.l = l; + v.f = f; + + return v; + } + + public float getF() { + return f; + } + + public boolean isB() { + return b; + } + + public int getI() { + return i; + } + + public long getL() { + return l; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FactoryTest_error.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FactoryTest_error.java new file mode 100644 index 0000000000..042a7b1bb8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FactoryTest_error.java @@ -0,0 +1,59 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.json.bvt.parser.deser.FactoryTest.V1; + +import junit.framework.TestCase; + +public class FactoryTest_error extends TestCase { + + public void test_factory1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"b\":true,\"i\":33,\"l\":34,\"f\":45.}").toJavaObject(V1.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class V1 { + + private boolean b; + private int i; + private long l; + private float f; + + private V1(boolean b){ + this.b = b; + } + + @JSONCreator + public static V1 create(@JSONField(name = "b") boolean b, @JSONField(name = "i") int i, + @JSONField(name = "l") long l, @JSONField(name = "f") float f) { + throw new IllegalStateException(); + } + + public float getF() { + return f; + } + + public boolean isB() { + return b; + } + + public int getI() { + return i; + } + + public long getL() { + return l; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest.java old mode 100644 new mode 100755 similarity index 89% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldDeserializerTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest.java index c79104f5d9..14c5739446 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldDeserializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldDeserializerTest1.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest1.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldDeserializerTest1.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest1.java index 5122591fe8..e0c733122a --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldDeserializerTest1.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest1.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -12,7 +12,7 @@ public class FieldDeserializerTest1 extends TestCase { public void test_error() throws Exception { Exception error = null; try { - JSON.parseObject("{\"value\":[]}", Entity.class, 0); + JSON.parseObject("{\"value\":[-}", Entity.class, 0); } catch (JSONException ex) { error = ex; } diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest10.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest10.java new file mode 100644 index 0000000000..d8a4eef1f0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest10.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.junit.Assert; + + +public class FieldDeserializerTest10 extends TestCase { + public void test_0 () throws Exception { + Assert.assertEquals(Type.Big, JSON.parseObject("{\"id\":\"Big\"\t}", VO.class).id); + Assert.assertEquals(Type.Big, JSON.parseObject("{\"id\":\"Big\"\t}\n\t", VO.class).id); + Assert.assertEquals(Type.Big, JSON.parseObject("{\"id\":\"Big\" }", V1.class).id); + Assert.assertEquals(Type.Big, JSON.parseObject("{\"id\":\"Big\" }\n", V1.class).id); + Assert.assertEquals(Type.Big, JSON.parseObject("{\"id\":\"Big\" }\n\t", V1.class).id); + Assert.assertEquals(Type.Big, JSON.parseObject("{\"id\":\"Big\"\n}", V1.class).id); + } + + public static class VO { + public Type id; + } + + private static class V1 { + public Type id; + } + + public static enum Type { + Big, Small + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldDeserializerTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest2.java old mode 100644 new mode 100755 similarity index 75% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldDeserializerTest2.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest2.java index 3ae8d3864e..0aa8f7b175 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldDeserializerTest2.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest2.java @@ -1,11 +1,11 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; @@ -15,7 +15,7 @@ public void test_0() throws Exception { String input = "{,,,\"value\":null,,,,}"; int featureValues = 0; featureValues |= Feature.AllowArbitraryCommas.getMask(); - DefaultExtJSONParser parser = new DefaultExtJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); Entity object = new Entity(); parser.parseObject(object); @@ -26,7 +26,7 @@ public void test_1() throws Exception { int featureValues = 0; featureValues |= Feature.AllowArbitraryCommas.getMask(); featureValues |= Feature.IgnoreNotMatch.getMask(); - DefaultExtJSONParser parser = new DefaultExtJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); Entity object = new Entity(); parser.parseObject(object); @@ -37,7 +37,7 @@ public void test_error_1() throws Exception { try { String input = "{\"value\":null,\"id\":123}"; int featureValues = 0; - DefaultExtJSONParser parser = new DefaultExtJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); Entity object = new Entity(); parser.parseObject(object); diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest3.java new file mode 100755 index 0000000000..250053c37b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest3.java @@ -0,0 +1,59 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; + +public class FieldDeserializerTest3 extends TestCase { + + public void test_error_1() throws Exception { + Exception error = null; + try { + String input = "{\"value\":null}"; + int featureValues = 0; + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), + featureValues); + + Entity object = new Entity(); + parser.parseObject(object); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + Exception error = null; + try { + String input = "{,,\"value\":null}"; + int featureValues = 0; + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), + featureValues); + + Entity object = new Entity(); + parser.parseObject(object); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Entity { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + throw new RuntimeException(); + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest4.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest4.java new file mode 100644 index 0000000000..6c0e64e82d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest4.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + + +public class FieldDeserializerTest4 extends TestCase { + public void test_0 () throws Exception { + Assert.assertEquals(33, JSON.parseObject("{\"id\":33\t}", VO.class).id); + Assert.assertEquals(33, JSON.parseObject("{\"id\":33\t}\n\t", VO.class).id); + Assert.assertEquals(33, JSON.parseObject("{\"id\":33 }", V1.class).id); + Assert.assertEquals(33, JSON.parseObject("{\"id\":33 }\n\t", V1.class).id); + Assert.assertEquals(33, JSON.parseObject("{\"id\":33L}", V1.class).id); + } + + public static class VO { + public long id; + } + + private static class V1 { + public long id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest5.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest5.java new file mode 100755 index 0000000000..3ee90c8053 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest5.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + + +public class FieldDeserializerTest5 extends TestCase { + public void test_0 () throws Exception { + Assert.assertEquals(33, JSON.parseObject("{\"id\":33\t}", VO.class).id); + Assert.assertEquals(33, JSON.parseObject("{\"id\":33\t}\n\t", VO.class).id); + Assert.assertEquals(33, JSON.parseObject("{\"id\":33 }", V1.class).id); + Assert.assertEquals(33, JSON.parseObject("{\"id\":33 } ", V1.class).id); + Assert.assertEquals(33, JSON.parseObject("{\"id\":33 }\n", V1.class).id); + Assert.assertEquals(33, JSON.parseObject("{\"id\":33 }\t\n", V1.class).id); + Assert.assertEquals(33, JSON.parseObject("{\"id\":33L}", V1.class).id); + } + + public static class VO { + public int id; + } + + private static class V1 { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest6.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest6.java new file mode 100644 index 0000000000..5243207abf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest6.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + + +public class FieldDeserializerTest6 extends TestCase { + public void test_0 () throws Exception { + Assert.assertTrue(33F == JSON.parseObject("{\"id\":33\t}", VO.class).id); + Assert.assertTrue(33F == JSON.parseObject("{\"id\":33\t}\n\t", VO.class).id); + Assert.assertTrue(33F == JSON.parseObject("{\"id\":33 }", V1.class).id); + Assert.assertTrue(33F == JSON.parseObject("{\"id\":33 }\n\t", V1.class).id); + Assert.assertTrue(33F == JSON.parseObject("{\"id\":33L}", V1.class).id); + } + + public static class VO { + public float id; + } + + private static class V1 { + public float id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest7.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest7.java new file mode 100644 index 0000000000..0522911a4d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest7.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + + +public class FieldDeserializerTest7 extends TestCase { + public void test_0 () throws Exception { + Assert.assertTrue(33F == JSON.parseObject("{\"id\":33\t}", VO.class).id); + Assert.assertTrue(33F == JSON.parseObject("{\"id\":33\t}\n\t", VO.class).id); + Assert.assertTrue(33F == JSON.parseObject("{\"id\":33 }", V1.class).id); + Assert.assertTrue(33F == JSON.parseObject("{\"id\":33 }\n\t", V1.class).id); + Assert.assertTrue(33F == JSON.parseObject("{\"id\":33L}", V1.class).id); + } + + public static class VO { + public double id; + } + + private static class V1 { + public double id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest8.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest8.java new file mode 100644 index 0000000000..7880997816 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest8.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + + +public class FieldDeserializerTest8 extends TestCase { + public void test_0 () throws Exception { + Assert.assertEquals("33", JSON.parseObject("{\"id\":\"33\"\t}", VO.class).id); + Assert.assertEquals("33", JSON.parseObject("{\"id\":\"33\"\t}\n\t", VO.class).id); + Assert.assertEquals("33", JSON.parseObject("{\"id\":\"33\" }", V1.class).id); + Assert.assertEquals("33", JSON.parseObject("{\"id\":\"33\" }\n\t", V1.class).id); + Assert.assertEquals("33", JSON.parseObject("{\"id\":\"33\"\n}", V1.class).id); + } + + public static class VO { + public String id; + } + + private static class V1 { + public String id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest9.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest9.java new file mode 100644 index 0000000000..ba676ad9f4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest9.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.junit.Assert; + + +public class FieldDeserializerTest9 extends TestCase { + public void test_0 () throws Exception { + assertTrue(JSON.parseObject("{\"id\":true\t}", VO.class).id); + assertTrue(JSON.parseObject("{\"id\":true\t}\n\t", VO.class).id); + assertTrue(JSON.parseObject("{\"id\":true }", V1.class).id); + assertTrue(JSON.parseObject("{\"id\":true }\n\t", V1.class).id); + assertTrue(JSON.parseObject("{\"id\":true\n}", V1.class).id); + } + + public void test_1 () throws Exception { + assertFalse(JSON.parseObject("{\"id\":false\t}", VO.class).id); + assertFalse(JSON.parseObject("{\"id\":false\t}\n\t", VO.class).id); + assertFalse(JSON.parseObject("{\"id\":false }", V1.class).id); + assertFalse(JSON.parseObject("{\"id\":false }\n\t", V1.class).id); + assertFalse(JSON.parseObject("{\"id\":false\n}", V1.class).id); + } + + public static class VO { + public boolean id; + } + + private static class V1 { + public boolean id; + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldSerializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldSerializerTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest.java index 4710860fbd..6d775e49d2 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldSerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldSerializerTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest2.java old mode 100644 new mode 100755 similarity index 97% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldSerializerTest2.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest2.java index 9f61cf69e1..687289f983 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldSerializerTest2.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest2.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldSerializerTest3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest3.java old mode 100644 new mode 100755 similarity index 97% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldSerializerTest3.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest3.java index 7366c985e2..346c526cfd --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/FieldSerializerTest3.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest3.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest4.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest4.java new file mode 100644 index 0000000000..be9ba82b83 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest4.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.google.common.collect.Lists; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.List; + +/** + * Created By maxiaoyao + * Date: 2017/10/8 + * Time: 下午10:52 + */ +public class FieldSerializerTest4 { + @Test + public void testPattern() { + Result listResult = new Result(Lists.newArrayList()); + Result booleanResult = new Result(null); + String listJson = JSON.toJSONString( + listResult, + SerializerFeature.PrettyFormat + ); + String booleanJson = JSON.toJSONString( + booleanResult, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteNullListAsEmpty + ); + Assert.assertEquals("{\n\t\"data\":[]\n}", listJson); + Assert.assertEquals("{\n\t\n}", booleanJson); + } + + private static class Result{ + private T data; + + public Result(T data) { + this.data = data; + } + + public T getData() { + return data; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/FloatDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/FloatDeserializerTest.java new file mode 100755 index 0000000000..064010e0d8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/FloatDeserializerTest.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.FloatCodec; + +public class FloatDeserializerTest extends TestCase { + + public void test_bigdecimal() throws Exception { + Assert.assertEquals(0, JSON.parseObject("0", Float.class).intValue()); + Assert.assertEquals(0, JSON.parseObject("0.0", Float.class).intValue()); + Assert.assertEquals(0, JSON.parseObject("'0'", Float.class).intValue()); + + Assert.assertEquals(null, JSON.parseObject("null", Float.class)); + + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + Assert.assertEquals(null, FloatCodec.instance.deserialze(parser, null, null)); + Assert.assertEquals(JSONToken.LITERAL_INT, FloatCodec.instance.getFastMatchToken()); + } +} + diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/GetOnlyCollectionTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/GetOnlyCollectionTest.java new file mode 100755 index 0000000000..65eca0bbf7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/GetOnlyCollectionTest.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class GetOnlyCollectionTest extends TestCase { + + public void test_getOnly() throws Exception { + VO vo = JSON.parseObject("{\"items\":[\"a\",\"b\"]}", VO.class); + Assert.assertEquals(2, vo.getItems().size()); + Assert.assertEquals("a", vo.getItems().get(0)); + Assert.assertEquals("b", vo.getItems().get(1)); + } + + public static class VO { + private final List items = new ArrayList(); + + public List getItems() { + return items; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/HashtableFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/HashtableFieldTest.java new file mode 100644 index 0000000000..196d8d12dc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/HashtableFieldTest.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.Hashtable; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class HashtableFieldTest extends TestCase { + + public void test_null() throws Exception { + Entity value = JSON.parseObject("{value:null}", Entity.class); + Assert.assertNull(value.getValue()); + } + + public void test_empty() throws Exception { + Entity value = JSON.parseObject("{value:{}}", Entity.class); + Assert.assertEquals(0, value.getValue().size()); + } + + public void test_null_2() throws Exception { + Entity value = JSON.parseObject("{\"value\":null}", Entity.class); + Assert.assertNull(value.getValue()); + } + + public void test_empty_a() throws Exception { + A value = JSON.parseObject("{value:{\"@type\":\"java.util.Hashtable\"}}", A.class); + Assert.assertEquals(0, ((Hashtable)value.getValue()).size()); + } + + private static class Entity { + + private Hashtable value; + + public Hashtable getValue() { + return value; + } + + public void setValue(Hashtable value) { + this.value = value; + } + } + + private static class A { + + private Object value; + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/InetAddressDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/InetAddressDeserializerTest.java new file mode 100755 index 0000000000..8e973613d4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/InetAddressDeserializerTest.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.MiscCodec; +import com.alibaba.fastjson.serializer.StringCodec; + +import junit.framework.TestCase; + +public class InetAddressDeserializerTest extends TestCase { + + public void test_null() throws Exception { + String input = "null"; + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + + MiscCodec deser = new MiscCodec(); + + Assert.assertNull(deser.deserialze(parser, null, null)); + } + + public void test_string_null() throws Exception { + String input = "null"; + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + + StringCodec deser = new StringCodec(); + + Assert.assertNull(deser.deserialze(parser, null, null)); + } + + public void test_error_0() throws Exception { + String input = "'[&中国-^]'"; + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + + MiscCodec deser = new MiscCodec(); + + Throwable error = null; + + Object value = null; + try { + value = deser.deserialze(parser, null, null); + } catch (Throwable ex) { + error = ex; + } + + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser.java b/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser.java new file mode 100644 index 0000000000..6a1a0e41c2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 25/03/2017. + */ +public class InnerClassDeser extends TestCase { + public void test_for_inner_class() throws Exception { + Model model = JSON.parseObject("{\"item\":{\"id\":123}}", Model.class); + assertNotNull(model.item); + assertEquals(123, model.item.id); + } + + public static class Model { + public Item item; + + public class Item { + public int id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser2.java new file mode 100644 index 0000000000..3ff85f87d7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser2.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 25/03/2017. + */ +public class InnerClassDeser2 extends TestCase { + public void test_for_inner_class() throws Exception { + Model model = JSON.parseObject("{\"items\":[{\"id\":123}]}", Model.class); + assertNotNull(model.items); + assertEquals(123, model.items.get(0).id); + } + + public static class Model { + public List items; + + public class Item { + public int id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser3.java new file mode 100644 index 0000000000..23bf5fc661 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser3.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.List; +import java.util.Map; + +/** + * Created by wenshao on 25/03/2017. + */ +public class InnerClassDeser3 extends TestCase { + public void test_for_inner_class() throws Exception { + Model model = JSON.parseObject("{\"items\":{\"123\":{\"id\":123}}}", Model.class); + assertNotNull(model.items); + assertEquals(123, model.items.get("123").id); + } + + public static class Model { + public Map items; + + public class Item { + public int id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser4.java b/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser4.java new file mode 100644 index 0000000000..b3701fd255 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser4.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by wenshao on 25/03/2017. + */ +public class InnerClassDeser4 extends TestCase { + public void test_for_inner_class() throws Exception { + Model model = JSON.parseObject("{\"items\":{\"123\":{\"id\":123}}}", Model.class); + assertNotNull(model.items); + assertEquals(123, model.items.get("123").id); + } + + public static class Model { + public HashMap items; + + public class Item { + public int id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerDeserializerTest.java new file mode 100755 index 0000000000..5ff9f349a9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerDeserializerTest.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.IntegerCodec; + +public class IntegerDeserializerTest extends TestCase { + + public void test_bigdecimal() throws Exception { + Assert.assertEquals(0, JSON.parseObject("0", Integer.class).intValue()); + Assert.assertEquals(0, JSON.parseObject("0.0", Integer.class).intValue()); + Assert.assertEquals(0, JSON.parseObject("'0'", Integer.class).intValue()); + + Assert.assertEquals(null, JSON.parseObject("null", Integer.class)); + + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + Assert.assertEquals(null, IntegerCodec.instance.deserialze(parser, null, null)); + Assert.assertEquals(JSONToken.LITERAL_INT, IntegerCodec.instance.getFastMatchToken()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/IntegerFieldDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/IntegerFieldDeserializerTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest.java index 9ae932b0b0..16e94db729 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/IntegerFieldDeserializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest2.java new file mode 100644 index 0000000000..9f4c45ceb1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest2.java @@ -0,0 +1,73 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class IntegerFieldDeserializerTest2 extends TestCase { + + protected void setUp() throws Exception { +// ParserConfig.getGlobalInstance().setAsmEnable(false); + } + + public void test_integer() throws Exception { + String text = "{\"value\":{\"column1\":\"aa\"}}"; + Map map = JSON.parseObject(text, new TypeReference>(){}); + Assert.assertNotNull(map); + Assert.assertNotNull(map.get("value")); + Assert.assertNotNull("aa", map.get("value").getColumn1()); + } + + public void test_integer_2() throws Exception { + String text = "[{\"value\":{\"column1\":\"aa\"}}]"; + List> mapList = JSON.parseObject(text, new TypeReference>>(){}); + Map map = mapList.get(0); + Assert.assertNotNull(map); + Assert.assertNotNull(map.get("value")); + Assert.assertNotNull("aa", map.get("value").getColumn1()); + } + + public void test_integer_3() throws Exception { + String text = "{\"value\":{\"valueA\":{\"column1\":\"aa\"}, \"valueB\":{\"column1\":\"bb\"}}}"; + Map> mapmap = JSON.parseObject(text, new TypeReference>>(){}); + Map map = mapmap.get("value"); + Assert.assertNotNull(map); + Assert.assertNotNull(map.get("valueA")); + Assert.assertNotNull("aa", map.get("valueA").getColumn1()); + Assert.assertNotNull(map.get("valueB")); + Assert.assertNotNull("bb", map.get("valueB").getColumn1()); + } + + public static class Entity implements Serializable { + private static final long serialVersionUID = 1L; + private String column1; + private Integer column3; + + public String getColumn1() { + return column1; + } + + public void setColumn1(String column1) { + this.column1 = column1; + } + + public Integer getColumn3() { + return column3; + } + + public void setColumn3(Integer column3) { + this.column3 = column3; + } + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest3.java new file mode 100644 index 0000000000..47eb45a0dd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest3.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +public class IntegerFieldDeserializerTest3 extends TestCase { + + public void test_0() throws Exception { + Entity a = JSON.parseObject("{f1:123, f2:null}", Entity.class); + Assert.assertEquals(123, a.getF1()); + Assert.assertEquals(null, a.getF2()); + } + + public void test_1() throws Exception { + Entity a = JSON.parseObject("{f1:22, f2:'33'}", Entity.class); + Assert.assertEquals(22, a.getF1()); + Assert.assertEquals(33, a.getF2().intValue()); + } + + public void test_2() throws Exception { + Entity a = JSON.parseObject("{f1:'22', f2:33}", Entity.class); + Assert.assertEquals(22, a.getF1()); + Assert.assertEquals(33, a.getF2().intValue()); + } + + public static class Entity { + + private int f1 = 124; + private Integer f2 = 123; + + @JSONCreator + public Entity(@JSONField(name="f1") int f1, @JSONField(name="f2") Integer f2){ + this.f1 = f1; + this.f2 = f2; + } + + public int getF1() { + return f1; + } + + public Integer getF2() { + return f2; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerParseTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerParseTest.java new file mode 100755 index 0000000000..495d12bd87 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/IntegerParseTest.java @@ -0,0 +1,77 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class IntegerParseTest extends TestCase { + public void test_l () throws Exception { + Assert.assertEquals(Long.valueOf(12), JSON.parseObject("12L", long.class)); + Assert.assertEquals(Integer.valueOf(12), JSON.parseObject("12L", int.class)); + Assert.assertEquals(new Short((short) 12), JSON.parseObject("12L", short.class)); + Assert.assertEquals(new Byte((byte) 12), JSON.parseObject("12L", byte.class)); + Assert.assertEquals(new Float(12), JSON.parseObject("12L", float.class)); + Assert.assertEquals(new Double(12), JSON.parseObject("12L", double.class)); + Assert.assertEquals(new BigDecimal(12), JSON.parseObject("12L", BigDecimal.class)); + Assert.assertEquals(new BigInteger("12"), JSON.parseObject("12L", BigInteger.class)); + } + + public void test_s () throws Exception { + Assert.assertEquals(Long.valueOf(12), JSON.parseObject("12S", long.class)); + Assert.assertEquals(Integer.valueOf(12), JSON.parseObject("12S", int.class)); + Assert.assertEquals(new Short((short) 12), JSON.parseObject("12S", short.class)); + Assert.assertEquals(new Byte((byte) 12), JSON.parseObject("12S", byte.class)); + Assert.assertEquals(new Float(12), JSON.parseObject("12S", float.class)); + Assert.assertEquals(new Double(12), JSON.parseObject("12S", double.class)); + Assert.assertEquals(new BigDecimal(12), JSON.parseObject("12S", BigDecimal.class)); + Assert.assertEquals(new BigInteger("12"), JSON.parseObject("12S", BigInteger.class)); + } + + public void test_b () throws Exception { + Assert.assertEquals(Long.valueOf(12), JSON.parseObject("12B", long.class)); + Assert.assertEquals(Integer.valueOf(12), JSON.parseObject("12B", int.class)); + Assert.assertEquals(new Short((short) 12), JSON.parseObject("12B", short.class)); + Assert.assertEquals(new Byte((byte) 12), JSON.parseObject("12B", byte.class)); + Assert.assertEquals(new Float(12), JSON.parseObject("12B", float.class)); + Assert.assertEquals(new Double(12), JSON.parseObject("12B", double.class)); + Assert.assertEquals(new BigDecimal(12), JSON.parseObject("12B", BigDecimal.class)); + Assert.assertEquals(new BigInteger("12"), JSON.parseObject("12B", BigInteger.class)); + } + + public void test_f () throws Exception { + Assert.assertEquals(Long.valueOf(12), JSON.parseObject("12F", long.class)); + Assert.assertEquals(Integer.valueOf(12), JSON.parseObject("12F", int.class)); + Assert.assertEquals(new Short((short) 12), JSON.parseObject("12F", short.class)); + Assert.assertEquals(new Byte((byte) 12), JSON.parseObject("12F", byte.class)); + Assert.assertEquals(new Float(12), JSON.parseObject("12F", float.class)); + Assert.assertEquals(new Double(12), JSON.parseObject("12F", double.class)); + Assert.assertEquals(new BigDecimal(12), JSON.parseObject("12F", BigDecimal.class)); + Assert.assertEquals(new BigInteger("12"), JSON.parseObject("12F", BigInteger.class)); + } + + public void test_d () throws Exception { + Assert.assertEquals(Long.valueOf(12), JSON.parseObject("12D", long.class)); + Assert.assertEquals(Integer.valueOf(12), JSON.parseObject("12D", int.class)); + Assert.assertEquals(new Short((short) 12), JSON.parseObject("12D", short.class)); + Assert.assertEquals(new Byte((byte) 12), JSON.parseObject("12D", byte.class)); + Assert.assertEquals(new Float(12), JSON.parseObject("12D", float.class)); + Assert.assertEquals(new Double(12), JSON.parseObject("12D", double.class)); + Assert.assertEquals(new BigDecimal(12), JSON.parseObject("12D", BigDecimal.class)); + Assert.assertEquals(new BigInteger("12"), JSON.parseObject("12D", BigInteger.class)); + } + + public void test_m () throws Exception { + Assert.assertEquals(Long.valueOf(12), JSON.parseObject("12.", long.class)); + Assert.assertEquals(Integer.valueOf(12), JSON.parseObject("12.", int.class)); + Assert.assertEquals(new Short((short) 12), JSON.parseObject("12.", short.class)); + Assert.assertEquals(new Byte((byte) 12), JSON.parseObject("12.", byte.class)); + Assert.assertEquals(new Float(12), JSON.parseObject("12.", float.class)); + Assert.assertEquals(new Double(12), JSON.parseObject("12.", double.class)); + Assert.assertEquals(new BigDecimal(12), JSON.parseObject("12.", BigDecimal.class)); + Assert.assertEquals(new BigInteger("12"), JSON.parseObject("12.", BigInteger.class)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/InterfaceParseTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/InterfaceParseTest.java new file mode 100755 index 0000000000..235d3a415f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/InterfaceParseTest.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; + +import org.junit.Assert; +import junit.framework.TestCase; + + +public class InterfaceParseTest extends TestCase { + public void test_interface() throws Exception { + VO vo = JSON.parseObject("{\"text\":\"abc\",\"b\":true}", VO.class); + Assert.assertEquals("abc", vo.getText()); + Assert.assertEquals(Boolean.TRUE, vo.getB()); + } + + public static interface VO { + void setText(String val); + String getText(); + + void setB(Boolean val); + Boolean getB(); + + void setI(int value); + void setC(char value); + void setS(short value); + void setL(long value); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/JSONFieldSetterTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/JSONFieldSetterTest.java new file mode 100644 index 0000000000..69cd8b2195 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/JSONFieldSetterTest.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 05/04/2017. + */ +public class JSONFieldSetterTest extends TestCase { + public void test_for_setter() throws Exception { + Model model = JSON.parseObject("{\"id\":123}", Model.class); + assertEquals(123, model._id); + } + + public static class Model { + private int _id; + + @JSONField(name = "id") + public void id(int id) { + this._id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/LocaleFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/LocaleFieldTest.java new file mode 100644 index 0000000000..afa3c5287b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/LocaleFieldTest.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import junit.framework.TestCase; + +import java.util.Locale; + +/** + * Created by wenshao on 14/03/2017. + */ +public class LocaleFieldTest extends TestCase { + public void test_local_str() throws Exception { + Model model = new Model(); + model.locale = Locale.CHINA; + + String json = JSON.toJSONString(model); + + JSONObject jsonObject = JSON.parseObject(json); + jsonObject.toJavaObject(Model.class); + } + + public void test_local_obj() throws Exception { + String json = "{\"locale\":{\"displayCountry\":\"China\",\"displayVariant\":\"\",\"displayLanguage\":\"Chinese\",\"language\":\"zh\",\"displayName\":\"Chinese (China)\",\"variant\":\"\",\"ISO3Language\":\"zho\",\"ISO3Country\":\"CHN\",\"country\":\"CN\"}}"; + + JSONObject jsonObject = JSON.parseObject(json); + Model model2 = jsonObject.toJavaObject(Model.class); + assertEquals("CN", model2.locale.getCountry()); + assertEquals("zh", model2.locale.getLanguage()); + assertEquals(Locale.CHINA.getDisplayCountry(), model2.locale.getDisplayCountry()); + } + + public static class Model { + public Locale locale; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/LocaleTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/LocaleTest.java new file mode 100755 index 0000000000..c35c56e778 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/LocaleTest.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.Locale; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.MiscCodec; + +import junit.framework.TestCase; + +public class LocaleTest extends TestCase { + + public void test_0() throws Exception { + String input = JSON.toJSONString(Locale.US); + Assert.assertEquals(Locale.US, JSON.parseObject(input, Locale.class)); + } + + public void test_1() throws Exception { + Locale l1 = new Locale("l1"); + String input = JSON.toJSONString(l1); + Assert.assertEquals(l1, JSON.parseObject(input, Locale.class)); + } + + public void test_2() throws Exception { + Locale l1 = new Locale("l1", "l2", "l3"); + String input = JSON.toJSONString(l1); + Assert.assertEquals(l1, JSON.parseObject(input, Locale.class)); + } + + public void test_null() throws Exception { + String input = "null"; + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + + MiscCodec deser = new MiscCodec(); + + Assert.assertNull(deser.deserialze(parser, null, null)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/LongDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/LongDeserializerTest.java new file mode 100755 index 0000000000..96adb27a6d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/LongDeserializerTest.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.LongCodec; + +public class LongDeserializerTest extends TestCase { + + public void test_bigdecimal() throws Exception { + Assert.assertEquals(0, JSON.parseObject("0", Long.class).intValue()); + Assert.assertEquals(0, JSON.parseObject("0.0", Long.class).intValue()); + Assert.assertEquals(0, JSON.parseObject("'0'", Long.class).intValue()); + + Assert.assertEquals(null, JSON.parseObject("null", Long.class)); + + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + Assert.assertEquals(null, LongCodec.instance.deserialze(parser, null, null)); + Assert.assertEquals(JSONToken.LITERAL_INT, LongCodec.instance.getFastMatchToken()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/LongFieldDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/LongFieldDeserializerTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest.java index 277f92ffb5..1262b198b0 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/LongFieldDeserializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; import java.util.UUID; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest2.java new file mode 100644 index 0000000000..880a1ba4c7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest2.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class LongFieldDeserializerTest2 extends TestCase { + + protected void setUp() throws Exception { +// ParserConfig.getGlobalInstance().setAsmEnable(false); + } + + public void test_integer() throws Exception { + String text = "{\"value\":{\"column1\":\"aa\"}}"; + Map map = JSON.parseObject(text, new TypeReference>(){}); + Assert.assertNotNull(map); + Assert.assertNotNull(map.get("value")); + Assert.assertNotNull("aa", map.get("value").getColumn1()); + } + + public void test_integer_2() throws Exception { + String text = "[{\"value\":{\"column1\":\"aa\"}}]"; + List> mapList = JSON.parseObject(text, new TypeReference>>(){}); + Map map = mapList.get(0); + Assert.assertNotNull(map); + Assert.assertNotNull(map.get("value")); + Assert.assertNotNull("aa", map.get("value").getColumn1()); + } + + public static class Entity implements Serializable { + private static final long serialVersionUID = 1L; + private String column1; + private Long column3; + + public String getColumn1() { + return column1; + } + + public void setColumn1(String column1) { + this.column1 = column1; + } + + public Long getColumn3() { + return column3; + } + + public void setColumn3(Long column3) { + this.column3 = column3; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest3.java new file mode 100644 index 0000000000..74e7e116bd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest3.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; + +public class LongFieldDeserializerTest3 extends TestCase { + + public void test_0() throws Exception { + Entity a = JSON.parseObject("{f1:123, f2:null}", Entity.class); + Assert.assertEquals(123L, a.getF1()); + Assert.assertEquals(null, a.getF2()); + } + + public void test_1() throws Exception { + Entity a = JSON.parseObject("{f1:22, f2:'33'}", Entity.class); + Assert.assertEquals(22L, a.getF1()); + Assert.assertEquals(33L, a.getF2().intValue()); + } + + public void test_2() throws Exception { + Entity a = JSON.parseObject("{f1:'22', f2:33}", Entity.class); + Assert.assertEquals(22L, a.getF1()); + Assert.assertEquals(33L, a.getF2().intValue()); + } + + public static class Entity { + + private long f1 = 124; + private Long f2 = 123L; + + @JSONCreator + public Entity(@JSONField(name = "f1") long f1, @JSONField(name = "f2") Long f2){ + this.f1 = f1; + this.f2 = f2; + } + + public long getF1() { + return f1; + } + + public Long getF2() { + return f2; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/MapDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/MapDeserializerTest.java new file mode 100644 index 0000000000..79b5ca40ee --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/MapDeserializerTest.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class MapDeserializerTest extends TestCase { + protected void setUp() throws Exception { + com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.parser.deser.MapDeserializerTest."); + } + + public void test_0() throws Exception { + JSON.parseObject("{\"@type\":\"com.alibaba.json.bvt.parser.deser.MapDeserializerTest$MyMap\"}", Map.class); + } + + public static class MyMap extends HashMap { + public MyMap () { + + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/MapTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/MapTest.java new file mode 100755 index 0000000000..a0d7ec79f0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/MapTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.math.BigDecimal; +import java.util.Map; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class MapTest extends TestCase { + + public void test_0() throws Exception { + Map map = JSON.parseObject("{id:33}", new TypeReference>() { + }); + + Assert.assertEquals(1, map.size()); + Assert.assertEquals("33", map.get("id")); + } + + public void test_1() throws Exception { + Map map = JSON.parseObject("{id:33}", new TypeReference>() { + }); + + Assert.assertEquals(1, map.size()); + Assert.assertEquals(new BigDecimal("33"), map.get("id")); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/MultiArrayTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/MultiArrayTest.java old mode 100644 new mode 100755 similarity index 88% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/MultiArrayTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/MultiArrayTest.java index fd3ec2ec74..19f212394d --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/MultiArrayTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/MultiArrayTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/MyMapFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/MyMapFieldTest.java new file mode 100644 index 0000000000..198fc99234 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/MyMapFieldTest.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.HashMap; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class MyMapFieldTest extends TestCase { + + public void test_null() throws Exception { + Entity value = JSON.parseObject("{value:null}", Entity.class); + Assert.assertNull(value.getValue()); + } + + public void test_empty() throws Exception { + Exception error = null; + try { + JSON.parseObject("{value:{}}", Entity.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Entity { + + private MyMap value; + + public MyMap getValue() { + return value; + } + + public void setValue(MyMap value) { + this.value = value; + } + } + + public class MyMap extends HashMap { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/NumberDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/NumberDeserializerTest.java new file mode 100755 index 0000000000..516a5c5dad --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/NumberDeserializerTest.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class NumberDeserializerTest extends TestCase { + + public void test_byte() throws Exception { + Assert.assertEquals(Byte.valueOf((byte) 123), JSON.parseObject("\"123\"", byte.class)); + Assert.assertEquals(Byte.valueOf((byte) 123), JSON.parseObject("\"123\"", Byte.class)); + } + + public void test_byte1() throws Exception { + Assert.assertEquals(Byte.valueOf((byte) 123), JSON.parseObject("123.", byte.class)); + Assert.assertEquals(Byte.valueOf((byte) 123), JSON.parseObject("123.", Byte.class)); + } + + public void test_short() throws Exception { + Assert.assertEquals(Short.valueOf((short) 123), JSON.parseObject("\"123\"", short.class)); + Assert.assertEquals(Short.valueOf((short) 123), JSON.parseObject("\"123\"", Short.class)); + } + + public void test_short1() throws Exception { + Assert.assertEquals(Short.valueOf((short) 123), JSON.parseObject("123.", short.class)); + Assert.assertEquals(Short.valueOf((short) 123), JSON.parseObject("123.", Short.class)); + } + + public void test_double() throws Exception { + Assert.assertTrue(123.0D == JSON.parseObject("123.", double.class)); + Assert.assertTrue(123.0D == JSON.parseObject("123.", Double.class).doubleValue()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/NumberDeserializerTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/NumberDeserializerTest2.java new file mode 100644 index 0000000000..e67680c3a8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/NumberDeserializerTest2.java @@ -0,0 +1,15 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class NumberDeserializerTest2 extends TestCase { + + public void test_double2() throws Exception { + Assert.assertTrue(123.0D == JSON.parseObject("123B", double.class)); + Assert.assertTrue(123.0D == JSON.parseObject("123B", Double.class).doubleValue()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ParseNullTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ParseNullTest.java new file mode 100644 index 0000000000..0b578f010e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ParseNullTest.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class ParseNullTest extends TestCase { + public void test_parse_null() throws Exception { + JSON.parseObject("{\"value\":null}", Model.class); + } + + public static class Model { + public JSONObject value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/PatternDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/PatternDeserializerTest.java new file mode 100755 index 0000000000..9abc506e39 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/PatternDeserializerTest.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.regex.Pattern; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.MiscCodec; + +import junit.framework.TestCase; + +public class PatternDeserializerTest extends TestCase { + + public void test_pattern() throws Exception { + Assert.assertEquals(Pattern.compile("abc").pattern(), JSON.parseObject("'abc'", Pattern.class).pattern()); + + Assert.assertEquals(null, JSON.parseObject("null", Pattern.class)); + + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + Assert.assertEquals(null, MiscCodec.instance.deserialze(parser, null, null)); + Assert.assertEquals(JSONToken.LITERAL_STRING, MiscCodec.instance.getFastMatchToken()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/PropertyProcessableTest_0.java b/src/test/java/com/alibaba/json/bvt/parser/deser/PropertyProcessableTest_0.java new file mode 100644 index 0000000000..3fc6a4f321 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/PropertyProcessableTest_0.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.deserializer.PropertyProcessable; +import junit.framework.TestCase; + +import java.lang.reflect.Type; + +/** + * Created by wenshao on 15/07/2017. + */ +public class PropertyProcessableTest_0 extends TestCase { + public void test_processable() throws Exception { + VO vo = JSON.parseObject("{\"vo_id\":123,\"vo_name\":\"abc\",\"value\":{}}", VO.class); + assertEquals(123, vo.id); + assertEquals("abc", vo.name); + assertNotNull(vo.value); + } + + public static class VO implements PropertyProcessable { + public int id; + public String name; + public Value value; + + public Type getType(String name) { + if ("value".equals(name)) { + return Value.class; + } + return null; + } + + public void apply(String name, Object value) { + if ("vo_id".equals(name)) { + this.id = ((Integer) value).intValue(); + } else if ("vo_name".equals(name)) { + this.name = (String) value; + } else if ("value".equals(name)) { + this.value = (Value) value; + } + } + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ResolveFieldDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ResolveFieldDeserializerTest.java new file mode 100644 index 0000000000..ab40ed87a3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ResolveFieldDeserializerTest.java @@ -0,0 +1,13 @@ +package com.alibaba.json.bvt.parser.deser; + +import com.alibaba.fastjson.parser.deserializer.ResolveFieldDeserializer; + +import junit.framework.TestCase; + + +public class ResolveFieldDeserializerTest extends TestCase { + public void test_0 () throws Exception { + new ResolveFieldDeserializer(null, null).parseField(null, null, null, null); + new ResolveFieldDeserializer(null, null, 0).parseField(null, null, null, null); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ShortFieldDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ShortFieldDeserializerTest.java new file mode 100644 index 0000000000..c3e93e1f8f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ShortFieldDeserializerTest.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class ShortFieldDeserializerTest extends TestCase { + + protected void setUp() throws Exception { +// ParserConfig.getGlobalInstance().setAsmEnable(false); + } + + public void f_test_integer() throws Exception { + String text = "{\"value\":{\"column1\":\"aa\"}}"; + Map map = JSON.parseObject(text, new TypeReference>(){}); + Assert.assertNotNull(map); + Assert.assertNotNull(map.get("value")); + Assert.assertNotNull("aa", map.get("value").getColumn1()); + } + + public void test_integer_2() throws Exception { + String text = "[{\"value\":{\"column1\":\"aa\"}}]"; + List> mapList = JSON.parseObject(text, new TypeReference>>(){}); + Map map = mapList.get(0); + Assert.assertNotNull(map); + Assert.assertNotNull(map.get("value")); + Assert.assertNotNull("aa", map.get("value").getColumn1()); + } + + public static class Entity implements Serializable { + private static final long serialVersionUID = 1L; + private String column1; + private Short column3; + + public String getColumn1() { + return column1; + } + + public void setColumn1(String column1) { + this.column1 = column1; + } + + public Short getColumn3() { + return column3; + } + + public void setColumn3(Short column3) { + this.column3 = column3; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest.java new file mode 100644 index 0000000000..25efa47243 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class SmartMatchTest extends TestCase { + + public void f_test_0() throws Exception { + String text = "{\"message_id\":1001}"; + + VO vo = JSON.parseObject(text, VO.class); + Assert.assertEquals(1001, vo.getMessageId()); + } + + public void test_vo2() throws Exception { + String text = "{\"message_id\":1001}"; + + VO2 vo = JSON.parseObject(text, VO2.class); + Assert.assertEquals(1001, vo.getMessageId()); + } + + private static class VO { + + private int messageId; + + public int getMessageId() { + return messageId; + } + + public void setMessageId(int messageId) { + this.messageId = messageId; + } + + } + + public static class VO2 { + + private int messageId; + + public int getMessageId() { + return messageId; + } + + public void setMessageId(int messageId) { + this.messageId = messageId; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest2.java new file mode 100644 index 0000000000..b6519db7f2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest2.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + + +public class SmartMatchTest2 extends TestCase { + + public void f_test_0 () throws Exception { + String text = "{\"_id\":1001}"; + + VO vo = JSON.parseObject(text, VO.class); + Assert.assertEquals(1001, vo.getId()); + } + + public void test_vo2 () throws Exception { + String text = "{\"_id\":1001}"; + + VO2 vo = JSON.parseObject(text, VO2.class); + Assert.assertEquals(1001, vo.getId()); + } + + private static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } + + public static class VO2 { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_boolean_is.java b/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_boolean_is.java new file mode 100644 index 0000000000..ddce52fd84 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_boolean_is.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + + +public class SmartMatchTest_boolean_is extends TestCase { + + public void test_0() throws Exception { + String text = "{\"isVisible\":true}"; + + VO vo = JSON.parseObject(text, VO.class); + Assert.assertEquals(true, vo.isVisible()); + } + + public static class VO { + + private boolean visible; + + public boolean isVisible() { + return visible; + } + + public void setVisible(boolean visible) { + this.visible = visible; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_snake.java b/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_snake.java new file mode 100644 index 0000000000..134ed2f90a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_snake.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + + +public class SmartMatchTest_snake extends TestCase { + + public void test_0() throws Exception { + String text = "{\"person_id\":1001}"; + + VO vo = JSON.parseObject(text, VO.class); + Assert.assertEquals(1001, vo.personId); + } + + public static class VO { + public int personId; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_snake2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_snake2.java new file mode 100644 index 0000000000..7f6fa99525 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_snake2.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + + +public class SmartMatchTest_snake2 extends TestCase { + + public void test_0() throws Exception { + String text = "{\"_id\":1001}"; + + VO vo = JSON.parseObject(text, VO.class); + Assert.assertEquals(1001, vo.id); + } + + public static class VO { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/SortedSetFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/SortedSetFieldTest.java new file mode 100644 index 0000000000..9d3354c343 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/SortedSetFieldTest.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.SortedSet; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class SortedSetFieldTest extends TestCase { + + public void test_null() throws Exception { + Entity value = JSON.parseObject("{value:null}", Entity.class); + Assert.assertNull(value.getValue()); + } + + public void test_empty() throws Exception { + Entity value = JSON.parseObject("{value:[]}", Entity.class); + Assert.assertEquals(0, value.getValue().size()); + } + + private static class Entity { + + private SortedSet value; + + public SortedSet getValue() { + return value; + } + + public void setValue(SortedSet value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/SqlDateDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/SqlDateDeserializerTest.java old mode 100644 new mode 100755 similarity index 75% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/SqlDateDeserializerTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/SqlDateDeserializerTest.java index b40dea1331..7b3b50ca7c --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/SqlDateDeserializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/SqlDateDeserializerTest.java @@ -1,10 +1,10 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.SqlDateDeserializer; @@ -18,8 +18,8 @@ public void test_bigdecimal() throws Exception { Assert.assertEquals(null, JSON.parseObject("null", Integer.class)); - DefaultExtJSONParser parser = new DefaultExtJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); - Assert.assertEquals(null, SqlDateDeserializer.instance.deserialze(parser, null)); + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + Assert.assertEquals(null, SqlDateDeserializer.instance.deserialze(parser, null, null)); Assert.assertEquals(JSONToken.LITERAL_INT, SqlDateDeserializer.instance.getFastMatchToken()); } } diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/SqlDateDeserializerTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/SqlDateDeserializerTest2.java new file mode 100755 index 0000000000..52a50bdfdd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/SqlDateDeserializerTest2.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.sql.Date; +import java.text.SimpleDateFormat; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class SqlDateDeserializerTest2 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + + public void test_sqlDate() throws Exception { + java.util.Date date = new java.util.Date(); + long millis = date.getTime(); + long millis2 = (millis / 1000) * 1000; + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + String text = dateFormat.format(millis); + text = text.replace(' ', 'T'); + + SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", JSON.defaultLocale); + dateFormat2.setTimeZone(JSON.defaultTimeZone); + String text2 = dateFormat2.format(millis2); + + Assert.assertNull(JSON.parseObject("null", Date.class)); + Assert.assertNull(JSON.parseObject("\"\"", Date.class)); + Assert.assertNull(JSON.parseArray("null", Date.class)); + Assert.assertNull(JSON.parseArray("[null]", Date.class).get(0)); + Assert.assertNull(JSON.parseObject("{\"value\":null}", VO.class).getValue()); + + Assert.assertEquals(new Date(millis), JSON.parseObject("" + millis, Date.class)); + Assert.assertEquals(new Date(millis), JSON.parseObject("{\"@type\":\"java.sql.Date\",\"val\":" + millis + "}", Date.class)); + Assert.assertEquals(new Date(millis), JSON.parseObject("\"" + millis + "\"", Date.class)); + Assert.assertEquals(new Date(millis2), JSON.parseObject("\"" + text2 + "\"", Date.class)); + Assert.assertEquals(new Date(millis), JSON.parseObject("\"" + text + "\"", Date.class)); + + //System.out.println(JSON.toJSONString(new Time(millis), SerializerFeature.WriteClassName)); + + } + + public static class VO { + + private Date value; + + public Date getValue() { + return value; + } + + public void setValue(Date value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/StackTraceElementDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/StackTraceElementDeserializerTest.java new file mode 100755 index 0000000000..d4d1744bf4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/StackTraceElementDeserializerTest.java @@ -0,0 +1,145 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +public class StackTraceElementDeserializerTest extends TestCase { + + public void test_stack() throws Exception { + Assert.assertNull(JSON.parseObject("null", StackTraceElement.class)); + Assert.assertNull(JSON.parseArray("null", StackTraceElement.class)); + Assert.assertNull(JSON.parseArray("[null]", StackTraceElement.class).get(0)); + Assert.assertNull(JSON.parseObject("{\"value\":null}", VO.class).getValue()); + Assert.assertNull(JSON.parseObject("{\"className\":\"int\",\"methodName\":\"parseInt\"}", + StackTraceElement.class).getFileName()); + + Assert.assertEquals(StackTraceElement.class, ((StackTraceElement) JSON.parse("{\"@type\":\"java.lang.StackTraceElement\",\"className\":\"int\",\"methodName\":\"parseInt\",\"nativeMethod\":null}")).getClass()); + } + + public void test_stack_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{}", StackTraceElement.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("[]", StackTraceElement.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"className\":null,\"methodName\":null,\"fileName\":null,\"lineNumber\":null,\"@type\":\"xxx\"}", StackTraceElement.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"@type\":int}", StackTraceElement.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_4() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"xxx\":33}", StackTraceElement.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_5() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"nativeMethod\":33}", StackTraceElement.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_6() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"lineNumber\":33}", StackTraceElement.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_7() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"fileName\":33}", StackTraceElement.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_8() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"methodName\":33}", StackTraceElement.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_9() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"className\":33}", StackTraceElement.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_10() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"lineNumber\":true}", StackTraceElement.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private StackTraceElement value; + + public StackTraceElement getValue() { + return value; + } + + public void setValue(StackTraceElement value) { + this.value = value; + } + + } +} \ No newline at end of file diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestEnum.java b/src/test/java/com/alibaba/json/bvt/parser/deser/TestEnum.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestEnum.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/TestEnum.java index 03c830d0eb..a51123498a --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestEnum.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/TestEnum.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/TestNull.java b/src/test/java/com/alibaba/json/bvt/parser/deser/TestNull.java new file mode 100755 index 0000000000..d95bcad478 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/TestNull.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.NumberDeserializer; +import com.alibaba.fastjson.serializer.CharacterCodec; + +public class TestNull extends TestCase { + + public void test_byte() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + + Assert.assertNull(new NumberDeserializer().deserialze(parser, null, null)); + } + + public void test_char() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + + Assert.assertNull(new CharacterCodec().deserialze(parser, null, null)); + } + + public void test_short() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + + Assert.assertNull(new NumberDeserializer().deserialze(parser, null, null)); + } + + public void test_null() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + + Assert.assertNull(new NumberDeserializer().deserialze(parser, null, null)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ThrowableDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ThrowableDeserializerTest.java new file mode 100755 index 0000000000..09619b7c66 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ThrowableDeserializerTest.java @@ -0,0 +1,70 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + + +public class ThrowableDeserializerTest extends TestCase { + public void test_0 () throws Exception { + Assert.assertEquals(Throwable.class, JSON.parseObject("{}", Throwable.class).getClass()); + Assert.assertEquals(Throwable.class, JSON.parseObject("{,,,}", Throwable.class).getClass()); + Assert.assertEquals(java.lang.RuntimeException.class, JSON.parseObject("{\"@type\":\"java.lang.RuntimeException\"}", Throwable.class).getClass()); + Assert.assertEquals(null, JSON.parseObject("{\"message\":null}", Throwable.class).getMessage()); + Assert.assertEquals(Exception.class, JSON.parseObject("{\"cause\":{}}", Throwable.class).getCause().getClass()); + } + + public void test_error() throws Exception { + JSONException error = null; + try { + JSON.parseObject("{\"@type\":33}", Throwable.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error1() throws Exception { + JSONException error = null; + try { + Assert.assertEquals(null, JSON.parseObject("{\"message\":33}", Throwable.class).getMessage()); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error2() throws Exception { + Exception error = null; + try { + Assert.assertEquals(null, JSON.parseObject("{}", MyException.class).getMessage()); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error3() throws Exception { + Exception error = null; + try { + Assert.assertEquals(null, JSON.parseObject("{}", MyException2.class).getMessage()); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class MyException extends Exception { + private MyException() { + + } + } + + public static class MyException2 extends Exception { + public MyException2() { + throw new RuntimeException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/ThrowableDeserializerTest_2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/ThrowableDeserializerTest_2.java new file mode 100644 index 0000000000..09afe1ba90 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/ThrowableDeserializerTest_2.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.parser.deser; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ThrowableDeserializerTest_2 extends TestCase { + + public void test_0() throws Exception { + Assert.assertEquals("xxx", JSON.parseObject("{\"message\":\"xxx\",,,}", MyException.class).getMessage()); + } + + public void test_2() throws Exception { + Assert.assertEquals(null, JSON.parseObject("{\"message\":\"xxx\"}", MyException2.class).getMessage()); + } + + public void test_3() throws Exception { + Exception error = null; + try { + JSON.parseObject(",\"message\":\"xxx\"}", MyException.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class MyException extends Exception { + + public MyException(){ + + } + + public MyException(String message){ + super(message); + } + } + + public static class MyException2 extends Exception { + + public MyException2(){ + + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest.java new file mode 100755 index 0000000000..d678990614 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest.java @@ -0,0 +1,60 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.sql.Time; +import java.text.SimpleDateFormat; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class TimeDeserializerTest extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_time() throws Exception { + long millis = System.currentTimeMillis(); + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + format.setTimeZone(JSON.defaultTimeZone); + String text = format.format(new java.util.Date(millis)); + text += "T"; + + SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss.SSS", JSON.defaultLocale); + format2.setTimeZone(JSON.defaultTimeZone); + text += format2.format(new java.util.Date(millis)); + + Assert.assertNull(JSON.parseObject("null", Time.class)); + Assert.assertNull(JSON.parseObject("\"\"", Time.class)); + Assert.assertNull(JSON.parseArray("null", Time.class)); + Assert.assertNull(JSON.parseArray("[null]", Time.class).get(0)); + Assert.assertNull(JSON.parseObject("{\"value\":null}", VO.class).getValue()); + + Assert.assertEquals(new Time(millis), JSON.parseObject("" + millis, Time.class)); + Assert.assertEquals(new Time(millis), JSON.parseObject("{\"@type\":\"java.sql.Time\",\"val\":" + millis + "}", Time.class)); + Assert.assertEquals(new Time(millis), JSON.parseObject("\"" + millis + "\"", Time.class)); + Assert.assertEquals(new Time(millis), JSON.parseObject("\"" + text + "\"", Time.class)); + + //System.out.println(JSON.toJSONString(new Time(millis), SerializerFeature.WriteClassName)); + + } + + public static class VO { + + private Time value; + + public Time getValue() { + return value; + } + + public void setValue(Time value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest2.java new file mode 100755 index 0000000000..181add7ae6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest2.java @@ -0,0 +1,76 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.sql.Time; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +public class TimeDeserializerTest2 extends TestCase { + + public void test_0() throws Exception { + long millis = System.currentTimeMillis(); + JSON.parse("{\"@type\":\"java.sql.Time\",\"value\":" + millis + "}"); + } + + public void test_error() throws Exception { + long millis = System.currentTimeMillis(); + + Exception error = null; + try { + JSON.parse("{\"@type\":\"java.sql.Time\",33:" + millis + "}"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + Exception error = null; + try { + JSON.parse("{\"@type\":\"java.sql.Time\",\"value\":true}"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + long millis = System.currentTimeMillis(); + + Exception error = null; + try { + JSON.parse("{\"@type\":\"java.sql.Time\",\"value\":" + millis + ",}"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"time\":{}}", VO.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private Time time; + + public Time getTime() { + return time; + } + + public void setTime(Time time) { + this.time = time; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest3.java new file mode 100644 index 0000000000..bf8810969d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest3.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.sql.Time; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class TimeDeserializerTest3 extends TestCase { + public void test_time() throws Exception { + Assert.assertEquals(Time.valueOf("17:00:00"), JSON.parseObject("\"17:00:00\"", Time.class)); + } + + public void test_time_null() throws Exception { + Assert.assertEquals(null, JSON.parseObject("\"\"", Time.class)); + } + + public static class VO { + + private Time value; + + public Time getValue() { + return value; + } + + public void setValue(Time value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/TimeZoneDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/TimeZoneDeserializerTest.java new file mode 100755 index 0000000000..dc6f6e93c0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/TimeZoneDeserializerTest.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.MiscCodec; + +import junit.framework.TestCase; + +public class TimeZoneDeserializerTest extends TestCase { + public void test_timezone() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + Assert.assertEquals(null, MiscCodec.instance.deserialze(parser, null, null)); + Assert.assertEquals(JSONToken.LITERAL_STRING, MiscCodec.instance.getFastMatchToken()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TreeMapDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/TreeMapDeserializerTest.java old mode 100644 new mode 100755 similarity index 80% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TreeMapDeserializerTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/TreeMapDeserializerTest.java index 1990e3cf36..75255f92c6 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TreeMapDeserializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/TreeMapDeserializerTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser; import java.util.TreeMap; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/TreeSetFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/TreeSetFieldTest.java new file mode 100644 index 0000000000..b7be0de274 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/TreeSetFieldTest.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.TreeSet; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class TreeSetFieldTest extends TestCase { + + public void test_null() throws Exception { + Entity value = JSON.parseObject("{value:null}", Entity.class); + Assert.assertNull(value.getValue()); + } + + public void test_empty() throws Exception { + Entity value = JSON.parseObject("{value:[]}", Entity.class); + Assert.assertEquals(0, value.getValue().size()); + } + + private static class Entity { + + private TreeSet value; + + public TreeSet getValue() { + return value; + } + + public void setValue(TreeSet value) { + this.value = value; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/URIDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/URIDeserializerTest.java new file mode 100755 index 0000000000..cc72ec8b51 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/URIDeserializerTest.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser.deser; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.MiscCodec; + +import junit.framework.TestCase; + +public class URIDeserializerTest extends TestCase { + + public void test_null() throws Exception { + String input = "null"; + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + + MiscCodec deser = new MiscCodec(); + Assert.assertEquals(JSONToken.LITERAL_STRING, deser.getFastMatchToken()); + + Assert.assertNull(deser.deserialze(parser, null, null)); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/URLDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/URLDeserializerTest.java new file mode 100755 index 0000000000..a66b5fab08 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/URLDeserializerTest.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.net.URL; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.MiscCodec; + +public class URLDeserializerTest extends TestCase { + + public void test_url() throws Exception { + Assert.assertEquals(new URL("http://www.alibaba.com"), JSON.parseObject("'http://www.alibaba.com'", URL.class)); + + Assert.assertEquals(null, JSON.parseObject("null", URL.class)); + + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + Assert.assertEquals(null, MiscCodec.instance.deserialze(parser, null, null)); + Assert.assertEquals(JSONToken.LITERAL_STRING, MiscCodec.instance.getFastMatchToken()); + + } + + public void test_url_error() throws Exception { + JSONException ex = null; + try { + JSON.parseObject("'123'", URL.class); + } catch (JSONException e) { + ex = e; + } + Assert.assertNotNull(ex); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/UUIDDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/UUIDDeserializerTest.java new file mode 100755 index 0000000000..52e65273d8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/UUIDDeserializerTest.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.parser.deser; + +import java.util.UUID; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.MiscCodec; + +import junit.framework.TestCase; + +public class UUIDDeserializerTest extends TestCase { + + public void test_url() throws Exception { + UUID id = UUID.randomUUID(); + Assert.assertEquals(id, JSON.parseObject("'" + id.toString() + "'", UUID.class)); + + Assert.assertEquals(null, JSON.parseObject("null", UUID.class)); + + DefaultJSONParser parser = new DefaultJSONParser("null", ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); + Assert.assertEquals(null, MiscCodec.instance.deserialze(parser, null, null)); + Assert.assertEquals(JSONToken.LITERAL_STRING, MiscCodec.instance.getFastMatchToken()); + + } + + public void test_url_error() throws Exception { + JSONException ex = null; + try { + JSON.parseObject("'123'", UUID.class); + } catch (JSONException e) { + ex = e; + } + Assert.assertNotNull(ex); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldBoolArrayTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldBoolArrayTest.java new file mode 100644 index 0000000000..3173650b00 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldBoolArrayTest.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldBoolArrayTest extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[1,null,true,false,0]}", Model.class); + assertNotNull(model.value); + assertEquals(5, model.value.length); + assertEquals(true, model.value[0]); + assertEquals(false, model.value[1]); + assertEquals(true, model.value[2]); + assertEquals(false, model.value[3]); + assertEquals(false, model.value[4]); + } + + public static class Model { + public boolean[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldByteArrayTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldByteArrayTest.java new file mode 100644 index 0000000000..37bf17c1e3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldByteArrayTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldByteArrayTest extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[1,null,3]}", Model.class); + assertNotNull(model.value); + assertEquals(3, model.value.length); + assertEquals(1, model.value[0]); + assertEquals(0, model.value[1]); + assertEquals(3, model.value[2]); + } + + public static class Model { + public byte[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldDoubleArrayTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldDoubleArrayTest.java new file mode 100644 index 0000000000..1eecbb65d4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldDoubleArrayTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldDoubleArrayTest extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[1,null,3]}", Model.class); + assertNotNull(model.value); + assertEquals(3, model.value.length); + assertEquals(1.0D, model.value[0]); + assertEquals(0.0D, model.value[1]); + assertEquals(3.0D, model.value[2]); + } + + public static class Model { + public double[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArray2Test.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArray2Test.java new file mode 100644 index 0000000000..076d7dc36f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArray2Test.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldFloatArray2Test extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[[1,2.1,-0.3]]}", Model.class); + assertNotNull(model.value); + assertEquals(1, model.value.length); + assertEquals(3, model.value[0].length); + assertEquals(1f, model.value[0][0]); + assertEquals(2.1f, model.value[0][1]); + assertEquals(-0.3f, model.value[0][2]); + } + + public static class Model { + public float[][] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArray2Test_private.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArray2Test_private.java new file mode 100644 index 0000000000..2348f0ed00 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArray2Test_private.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldFloatArray2Test_private extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[[1,2.1,-0.3]]}", Model.class); + assertNotNull(model.value); + assertEquals(1, model.value.length); + assertEquals(3, model.value[0].length); + assertEquals(1f, model.value[0][0]); + assertEquals(2.1f, model.value[0][1]); + assertEquals(-0.3f, model.value[0][2]); + } + + private static class Model { + public float[][] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest.java new file mode 100644 index 0000000000..b9a7db70d7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldFloatArrayTest extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[1,2.1,-0.3]}", Model.class); + assertNotNull(model.value); + assertEquals(3, model.value.length); + assertEquals(1f, model.value[0]); + assertEquals(2.1f, model.value[1]); + assertEquals(-0.3f, model.value[2]); + } + + public static class Model { + public float[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest2.java new file mode 100644 index 0000000000..0405fd98d0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest2.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldFloatArrayTest2 extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[1,null,3]}", Model.class); + assertNotNull(model.value); + assertEquals(3, model.value.length); + assertEquals(1.0f, model.value[0]); + assertEquals(0.0f, model.value[1]); + assertEquals(3.0f, model.value[2]); + } + + public static class Model { + public float[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest_private.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest_private.java new file mode 100644 index 0000000000..4d3231e63d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest_private.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldFloatArrayTest_private extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[1,2.1,-0.3]}", Model.class); + assertNotNull(model.value); + assertEquals(3, model.value.length); + assertEquals(1f, model.value[0]); + assertEquals(2.1f, model.value[1]); + assertEquals(-0.3f, model.value[2]); + } + + private static class Model { + public float[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest.java new file mode 100644 index 0000000000..aa54e608be --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldIntArrayTest extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[1,2,3]}", Model.class); + assertNotNull(model.value); + assertEquals(3, model.value.length); + assertEquals(1, model.value[0]); + assertEquals(2, model.value[1]); + assertEquals(3, model.value[2]); + } + + public static class Model { + public int[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest2.java new file mode 100644 index 0000000000..f4aca6464c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest2.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldIntArrayTest2 extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[1,null,3]}", Model.class); + assertNotNull(model.value); + assertEquals(3, model.value.length); + assertEquals(1, model.value[0]); + assertEquals(0, model.value[1]); + assertEquals(3, model.value[2]); + } + + public static class Model { + public int[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest_private.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest_private.java new file mode 100644 index 0000000000..986322ff89 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest_private.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldIntArrayTest_private extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[1,2,3]}", Model.class); + assertNotNull(model.value); + assertEquals(3, model.value.length); + assertEquals(1, model.value[0]); + assertEquals(2, model.value[1]); + assertEquals(3, model.value[2]); + } + + private static class Model { + public int[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldLongArrayTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldLongArrayTest.java new file mode 100644 index 0000000000..0d64a26dd2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldLongArrayTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldLongArrayTest extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[1,null,3]}", Model.class); + assertNotNull(model.value); + assertEquals(3, model.value.length); + assertEquals(1, model.value[0]); + assertEquals(0, model.value[1]); + assertEquals(3, model.value[2]); + } + + public static class Model { + public long[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldShortArrayTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldShortArrayTest.java new file mode 100644 index 0000000000..e774c26e8f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldShortArrayTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.array; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 11/01/2017. + */ +public class FieldShortArrayTest extends TestCase { + public void test_intArray() throws Exception { + Model model = JSON.parseObject("{\"value\":[1,null,3]}", Model.class); + assertNotNull(model.value); + assertEquals(3, model.value.length); + assertEquals(1, model.value[0]); + assertEquals(0, model.value[1]); + assertEquals(3, model.value[2]); + } + + public static class Model { + public short[] value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest.java new file mode 100644 index 0000000000..e69199488b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.parser.deser.arraymapping; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ArrayMappingErrorTest extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[1001,2002]", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public int id; + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest2.java new file mode 100644 index 0000000000..d5e8b09d50 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest2.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.parser.deser.arraymapping; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ArrayMappingErrorTest2 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[1001,{}}", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public int id; + public JSONObject obj; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest3.java new file mode 100644 index 0000000000..69052f5c02 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest3.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.parser.deser.arraymapping; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ArrayMappingErrorTest3 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[1001,{}}", Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public int id; + public JSONObject obj; + public JSONObject obj2; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_bool.java b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_bool.java new file mode 100644 index 0000000000..7179870312 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_bool.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.parser.deser.arraymapping; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ArrayMapping_bool extends TestCase { + public void test_for_true() throws Exception { + Model model = JSON.parseObject("[true,\"wenshao\"]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(true, model.id); + Assert.assertEquals("wenshao", model.name); + } + + public void test_for_false() throws Exception { + Model model = JSON.parseObject("[false,\"wenshao\"]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(false, model.id); + Assert.assertEquals("wenshao", model.name); + } + + public static class Model { + public boolean id; + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_double.java b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_double.java new file mode 100644 index 0000000000..e265da98cb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_double.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.arraymapping; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ArrayMapping_double extends TestCase { + public void test_float() throws Exception { + Model model = JSON.parseObject("[123.45,\"wenshao\"]", Model.class, Feature.SupportArrayToBean); + Assert.assertTrue(123.45D == model.id); + Assert.assertEquals("wenshao", model.name); + } + + public static class Model { + public double id; + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_float.java b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_float.java new file mode 100644 index 0000000000..b471a13e75 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_float.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.arraymapping; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ArrayMapping_float extends TestCase { + public void test_float() throws Exception { + Model model = JSON.parseObject("[123.45,\"wenshao\"]", Model.class, Feature.SupportArrayToBean); + Assert.assertTrue(123.45F == model.id); + Assert.assertEquals("wenshao", model.name); + } + + public static class Model { + public float id; + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_long.java b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_long.java new file mode 100644 index 0000000000..44caa6ff71 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_long.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.deser.arraymapping; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ArrayMapping_long extends TestCase { + public void test_for_error() throws Exception { + Model model = JSON.parseObject("[1001,\"wenshao\"]", Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(1001, model.id); + Assert.assertEquals("wenshao", model.name); + } + + public static class Model { + public long id; + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_long_stream.java b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_long_stream.java new file mode 100644 index 0000000000..7ce2703784 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_long_stream.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.parser.deser.arraymapping; + +import java.io.StringReader; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ArrayMapping_long_stream extends TestCase { + public void test_for_error() throws Exception { + + JSONReader reader = new JSONReader(new StringReader("[1001,\"wenshao\"]"), Feature.SupportArrayToBean); + Model model = reader.readObject(Model.class); + Assert.assertEquals(1001, model.id); + Assert.assertEquals("wenshao", model.name); + } + + public static class Model { + public long id; + public String name; + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM.java old mode 100644 new mode 100755 similarity index 98% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM.java index d669bd9d83..f7c8a7980d --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; import java.math.BigDecimal; import java.util.ArrayList; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM2.java old mode 100644 new mode 100755 similarity index 97% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM2.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM2.java index 135e2033b7..97a19e794a --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM2.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM2.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; import java.util.ArrayList; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASMEishay.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASMEishay.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASMEishay.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASMEishay.java index 742262b021..ea188e3bbb --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASMEishay.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASMEishay.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_BigDecimal.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_BigDecimal.java old mode 100644 new mode 100755 similarity index 96% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_BigDecimal.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_BigDecimal.java index 905c2022ee..d2b829201f --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_BigDecimal.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_BigDecimal.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; import java.math.BigDecimal; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Byte_0.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Byte_0.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Byte_0.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Byte_0.java index 1e95234913..3ea2429d7a --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Byte_0.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Byte_0.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Date.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Date.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Date.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Date.java index 16d63024b6..5a937d49f7 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Date.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Date.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; import java.util.Date; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Integer.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Integer.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Integer.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Integer.java index b2f2641f1a..e5208a706b --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Integer.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Integer.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_List.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_List.java old mode 100644 new mode 100755 similarity index 96% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_List.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_List.java index 65d7888956..d5f7272036 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_List.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_List.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; import java.util.ArrayList; import java.util.List; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Long_0.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Long_0.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Long_0.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Long_0.java index 3ec4d5a95f..723ea3ff83 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Long_0.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Long_0.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Short_0.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Short_0.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Short_0.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Short_0.java index df2f665504..60da08a6a5 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_Short_0.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Short_0.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_boolean.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_boolean.java old mode 100644 new mode 100755 similarity index 88% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_boolean.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_boolean.java index f11ae10349..3e0d695493 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_boolean.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_boolean.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_byte.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_byte.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_byte.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_byte.java index 9f770701f2..2f7ee69042 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_byte.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_byte.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_char.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_char.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_char.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_char.java index b410237912..2d2dd1bd5c --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_char.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_char.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_double.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_double.java old mode 100644 new mode 100755 similarity index 79% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_double.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_double.java index 51ff958ba8..4e053a8dae --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_double.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_double.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -12,7 +12,7 @@ public void test_asm() throws Exception { String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); - Assert.assertEquals(v.getValue(), v1.getValue()); + Assert.assertTrue(v.getValue() == v1.getValue()); } public static class V0 { diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_float.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_float.java old mode 100644 new mode 100755 similarity index 79% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_float.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_float.java index 9dab4f1732..745b9344a9 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_float.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_float.java @@ -1,8 +1,9 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; import junit.framework.TestCase; +import org.junit.Assert; + import com.alibaba.fastjson.JSON; public class TestASM_float extends TestCase { @@ -12,7 +13,7 @@ public void test_asm() throws Exception { String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); - Assert.assertEquals(v.getValue(), v1.getValue()); + Assert.assertTrue(v.getValue() == v1.getValue()); } public static class V0 { diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_int.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_int.java old mode 100644 new mode 100755 similarity index 79% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_int.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_int.java index a26fe0f2d7..b6077ba270 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_int.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_int.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -23,8 +23,9 @@ public int getI() { return i; } - public void setI(int i) { + public V0 setI(int i) { this.i = i; + return this; } } diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_long.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_long.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_long.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_long.java index d18ccef2f4..7d34844581 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_long.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_long.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_null.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_null.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_null.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_null.java index 104233db82..4e3d848a06 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_null.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_null.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_object.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_object.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_object.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_object.java index 02ab35a94b..a0c5af0e78 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_object.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_object.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_primitive.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_primitive.java new file mode 100644 index 0000000000..d05e42355e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_primitive.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.parser.deser.asm; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ASMDeserializerFactory; +import com.alibaba.fastjson.util.ASMClassLoader; +import com.alibaba.fastjson.util.JavaBeanInfo; + +import junit.framework.TestCase; + +public class TestASM_primitive extends TestCase { + + public void test_asm() throws Exception { + + ASMDeserializerFactory factory = new ASMDeserializerFactory(new ASMClassLoader()); + Exception error = null; + try { + JavaBeanInfo beanInfo = JavaBeanInfo.build(int.class, int.class, null); + factory.createJavaBeanDeserializer(ParserConfig.getGlobalInstance(), beanInfo); + } catch (Exception ex) { + error = ex; + } + assertNotNull(error); + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_short.java b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_short.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_short.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_short.java index 24952854c9..02b85181b3 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/TestASM_short.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_short.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.asm; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/awt/ColorDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/awt/ColorDeserializerTest.java new file mode 100755 index 0000000000..16411f2649 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/awt/ColorDeserializerTest.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt.parser.deser.awt; + +import java.awt.Color; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.serializer.AwtCodec; + +import junit.framework.TestCase; + + +public class ColorDeserializerTest extends TestCase { + public void test_0 () throws Exception { + new AwtCodec().getFastMatchToken(); + } + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[]", Color.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{33:44}", Color.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"r\":44.}", Color.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"x\":44}", Color.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/awt/FontDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/awt/FontDeserializerTest.java new file mode 100755 index 0000000000..10ff32dfcc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/awt/FontDeserializerTest.java @@ -0,0 +1,97 @@ +package com.alibaba.json.bvt.parser.deser.awt; + +import java.awt.Font; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.serializer.AwtCodec; + +import junit.framework.TestCase; + + +public class FontDeserializerTest extends TestCase { + public void test_0 () throws Exception { + AwtCodec.instance.getFastMatchToken(); + + Assert.assertNull(JSON.parseObject("null", StackTraceElement.class)); + Assert.assertNull(JSON.parseArray("null", StackTraceElement.class)); + Assert.assertNull(JSON.parseArray("[null]", StackTraceElement.class).get(0)); + Assert.assertNull(JSON.parseObject("{\"value\":null}", VO.class).getValue()); + } + + public void test_stack_error_0() throws Exception { + Exception error = null; + try { + JSON.parseObject("[]", Font.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{33:22}", Font.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"name\":22}", Font.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"style\":true}", Font.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_4() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"size\":\"33\"}", Font.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_5() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"xxx\":22}", Font.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private Font value; + + public Font getValue() { + return value; + } + + public void setValue(Font value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/awt/PointDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/awt/PointDeserializerTest.java new file mode 100755 index 0000000000..98b4f20409 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/awt/PointDeserializerTest.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt.parser.deser.awt; + +import java.awt.Point; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.serializer.AwtCodec; + +import junit.framework.TestCase; + + +public class PointDeserializerTest extends TestCase { + public void test_0 () throws Exception { + new AwtCodec().getFastMatchToken(); + } + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("[]", Point.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{33:44}", Point.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"r\":44.}", Point.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"x\":\"aaa\"}", Point.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/awt/PointDeserializerTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/awt/PointDeserializerTest2.java new file mode 100644 index 0000000000..9eeb5fdcaf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/awt/PointDeserializerTest2.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.parser.deser.awt; + +import java.awt.Point; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + + +public class PointDeserializerTest2 extends TestCase { + public void test_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"z\":44}", Point.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/awt/RectangleDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/awt/RectangleDeserializerTest.java new file mode 100755 index 0000000000..26587c6b9d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/awt/RectangleDeserializerTest.java @@ -0,0 +1,98 @@ +package com.alibaba.json.bvt.parser.deser.awt; + +import java.awt.Font; +import java.awt.Rectangle; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.serializer.AwtCodec; + +import junit.framework.TestCase; + + +public class RectangleDeserializerTest extends TestCase { + public void test_0 () throws Exception { + AwtCodec.instance.getFastMatchToken(); + + Assert.assertNull(JSON.parseObject("null", Rectangle.class)); + Assert.assertNull(JSON.parseArray("null", Rectangle.class)); + Assert.assertNull(JSON.parseArray("[null]", Rectangle.class).get(0)); + Assert.assertNull(JSON.parseObject("{\"value\":null}", VO.class).getValue()); + } + + public void test_stack_error_0() throws Exception { + Exception error = null; + try { + JSON.parseObject("[]", Rectangle.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{33:22}", Rectangle.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"name\":22}", Rectangle.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"style\":true}", Rectangle.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_4() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"size\":\"33\"}", Rectangle.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_stack_error_5() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"xxx\":22}", Font.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private Rectangle value; + + public Rectangle getValue() { + return value; + } + + public void setValue(Rectangle value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/DateDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateDeserializerTest.java old mode 100644 new mode 100755 similarity index 81% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/DateDeserializerTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/date/DateDeserializerTest.java index cf9debcae5..f77ec5a0f7 --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/DateDeserializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateDeserializerTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.date; import java.util.Date; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateFormatDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateFormatDeserializerTest.java new file mode 100644 index 0000000000..6abfa49276 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateFormatDeserializerTest.java @@ -0,0 +1,79 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Locale; +import java.util.TimeZone; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class DateFormatDeserializerTest extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_dateFormat_empty() throws Exception { + VO vo = JSON.parseObject("{\"format\":\"\"}", VO.class); + Assert.assertEquals(null, vo.getFormat()); + } + + public void test_dateFormat_array() throws Exception { + List list = JSON.parseArray("[\"\",null,\"yyyy\"]", SimpleDateFormat.class); + Assert.assertEquals(null, list.get(0)); + Assert.assertEquals(null, list.get(1)); + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals(dateFormat, list.get(2)); + } + + public void test_dateFormat_null() throws Exception { + VO vo = JSON.parseObject("{\"format\":null}", VO.class); + Assert.assertEquals(null, vo.getFormat()); + } + + public void test_dateFormat_yyyy() throws Exception { + VO vo = JSON.parseObject("{\"format\":\"yyyy\"}", VO.class); + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals(dateFormat, vo.getFormat()); + } + + public void test_dateFormat_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"format\":123}", VO.class); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private SimpleDateFormat format; + + public VO(){ + + } + + public VO(SimpleDateFormat format){ + this.format = format; + } + + public SimpleDateFormat getFormat() { + return format; + } + + public void setFormat(SimpleDateFormat format) { + this.format = format; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest1.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest1.java new file mode 100644 index 0000000000..9c8750866b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest1.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class DateParseTest1 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + String text = "\"1979-07-14\""; + Date date = JSON.parseObject(text, Date.class); + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(date); + Assert.assertEquals(1979, calendar.get(Calendar.YEAR)); + Assert.assertEquals(6, calendar.get(Calendar.MONTH)); + Assert.assertEquals(14, calendar.get(Calendar.DAY_OF_MONTH)); + + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest10.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest10.java new file mode 100644 index 0000000000..98ef5215ac --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest10.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.text.SimpleDateFormat; +import java.util.Locale; +import java.util.TimeZone; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class DateParseTest10 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + String text = "{\"value\":\"1979-07-14\"}"; + VO vo = JSON.parseObject(text, VO.class); + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals(vo.getValue(), dateFormat.parse("1979-07-14").getTime()); + } + + public static class VO { + + private long value; + + public long getValue() { + return value; + } + + public VO setValue(long value) { + this.value = value; + return this; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest11.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest11.java new file mode 100644 index 0000000000..3dab6e5612 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest11.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.util.Date; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class DateParseTest11 extends TestCase { + + public void test() throws Exception { + VO vo = JSON.parseObject("{\"date\":\"2012-04-01T12:04:05.555\"}", VO.class); + } + + public static class VO { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest12.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest12.java new file mode 100644 index 0000000000..2a323ea8f2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest12.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.util.Date; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class DateParseTest12 extends TestCase { + + public void test() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"date\":\"20129401\"", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest13.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest13.java new file mode 100644 index 0000000000..1bcb36d047 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest13.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.util.Date; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class DateParseTest13 extends TestCase { + + public void test() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"date\":\"2012040125000a\"}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest14.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest14.java new file mode 100644 index 0000000000..ad6a0cd1f8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest14.java @@ -0,0 +1,86 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.util.Date; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class DateParseTest14 extends TestCase { + + public void test_0_lt() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"date\":\"19790714130723#56\"}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_0_gt() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"date\":\"19790714130723A56\"}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_1_lt() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"date\":\"197907141307231#6\"}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_1_gt() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"date\":\"197907141307231A6\"}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_2_lt() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"date\":\"1979071413072315#\"}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_2_gt() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"date\":\"1979071413072315A\"}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest2.java new file mode 100644 index 0000000000..3ec04cbc71 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest2.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class DateParseTest2 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + String text = "\"1979-07-14 13:07:23\""; + Date date = JSON.parseObject(text, Date.class); + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(date); + + Assert.assertEquals(1979, calendar.get(Calendar.YEAR)); + Assert.assertEquals(6, calendar.get(Calendar.MONTH)); + Assert.assertEquals(14, calendar.get(Calendar.DAY_OF_MONTH)); + + Assert.assertEquals(13, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(7, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(23, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest3.java new file mode 100644 index 0000000000..471844ad57 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest3.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class DateParseTest3 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + String text = "\"1979-07-14 13:07:23.456\""; + Date date = JSON.parseObject(text, Date.class); + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(date); + + Assert.assertEquals(1979, calendar.get(Calendar.YEAR)); + Assert.assertEquals(6, calendar.get(Calendar.MONTH)); + Assert.assertEquals(14, calendar.get(Calendar.DAY_OF_MONTH)); + + Assert.assertEquals(13, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(7, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(23, calendar.get(Calendar.SECOND)); + Assert.assertEquals(456, calendar.get(Calendar.MILLISECOND)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest4.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest4.java new file mode 100644 index 0000000000..c4d567231c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest4.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class DateParseTest4 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + String text = "\"1979-07-14T13:07:23\""; + Date date = JSON.parseObject(text, Date.class); + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(date); + + Assert.assertEquals(1979, calendar.get(Calendar.YEAR)); + Assert.assertEquals(6, calendar.get(Calendar.MONTH)); + Assert.assertEquals(14, calendar.get(Calendar.DAY_OF_MONTH)); + + Assert.assertEquals(13, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(7, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(23, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest5.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest5.java new file mode 100644 index 0000000000..fa9e42ac23 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest5.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class DateParseTest5 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + String text = "\"1979-07-14T13:07:23.456\""; + Date date = JSON.parseObject(text, Date.class); + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(date); + + Assert.assertEquals(1979, calendar.get(Calendar.YEAR)); + Assert.assertEquals(6, calendar.get(Calendar.MONTH)); + Assert.assertEquals(14, calendar.get(Calendar.DAY_OF_MONTH)); + + Assert.assertEquals(13, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(7, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(23, calendar.get(Calendar.SECOND)); + Assert.assertEquals(456, calendar.get(Calendar.MILLISECOND)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest6.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest6.java new file mode 100644 index 0000000000..74a64d978f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest6.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class DateParseTest6 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + String text = "\"19790714\""; + Date date = JSON.parseObject(text, Date.class); + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(date); + + Assert.assertEquals(1979, calendar.get(Calendar.YEAR)); + Assert.assertEquals(6, calendar.get(Calendar.MONTH)); + Assert.assertEquals(14, calendar.get(Calendar.DAY_OF_MONTH)); + + Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(0, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(0, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest7.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest7.java new file mode 100644 index 0000000000..8b430d71d7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest7.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class DateParseTest7 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + System.out.println(System.currentTimeMillis()); + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + + System.out.println(dateFormat.parse("1970-01-01 20:00:01").getTime()); + System.out.println(new Date().toString()); + + //1369273142603 + String text = "\"19790714130723\""; + Date date = JSON.parseObject(text, Date.class); + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(date); + + Assert.assertEquals(1979, calendar.get(Calendar.YEAR)); + Assert.assertEquals(6, calendar.get(Calendar.MONTH)); + Assert.assertEquals(14, calendar.get(Calendar.DAY_OF_MONTH)); + + Assert.assertEquals(13, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(7, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(23, calendar.get(Calendar.SECOND)); + Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest8.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest8.java new file mode 100644 index 0000000000..f23328762e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest8.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + + +public class DateParseTest8 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + System.out.println(System.currentTimeMillis()); + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + System.out.println(dateFormat.parse("1970-01-01 20:00:01").getTime()); + System.out.println(new Date().toString()); + + //1369273142603 + String text = "\"19790714130723456\""; + Date date = JSON.parseObject(text, Date.class); + Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); + calendar.setTime(date); + + Assert.assertEquals(1979, calendar.get(Calendar.YEAR)); + Assert.assertEquals(6, calendar.get(Calendar.MONTH)); + Assert.assertEquals(14, calendar.get(Calendar.DAY_OF_MONTH)); + + Assert.assertEquals(13, calendar.get(Calendar.HOUR_OF_DAY)); + Assert.assertEquals(7, calendar.get(Calendar.MINUTE)); + Assert.assertEquals(23, calendar.get(Calendar.SECOND)); + Assert.assertEquals(456, calendar.get(Calendar.MILLISECOND)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest9.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest9.java new file mode 100644 index 0000000000..804ad5889e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest9.java @@ -0,0 +1,43 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.util.Date; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.serializer.CalendarCodec; +import com.alibaba.json.bvt.parser.deser.date.DateParseTest14.VO; + + +public class DateParseTest9 extends TestCase { + public void test_date() throws Exception { + String text = "\"/Date(1242357713797+0800)/\""; + Date date = JSON.parseObject(text, Date.class); + Assert.assertEquals(date.getTime(), 1242357713797L); + + Assert.assertEquals(JSONToken.LITERAL_INT, CalendarCodec.instance.getFastMatchToken()); + } + + public void test_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"date\":\"/Date(1242357713797A0800)/\"}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"date\":\"/Date(1242357713797#0800)/\"}", VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateTest.java new file mode 100644 index 0000000000..417acdc43a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/date/DateTest.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.parser.deser.date; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import com.alibaba.fastjson.parser.JSONReaderScanner; +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; + +public class DateTest extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser("{\"date\":\"2012/04-01\"}", ParserConfig.getGlobalInstance(), + 0); + parser.setDateFormat("yyyy/MM-dd"); + VO vo = parser.parseObject(VO.class); + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM-dd", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals(dateFormat.parse("2012/04-01"), vo.getDate()); + + parser.close(); + } + + public void test_reader() throws Exception { + + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"date\":\"2012/04-01\"}", 0)); + parser.setDateFormat("yyyy/MM-dd"); + VO vo = parser.parseObject(VO.class); + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM-dd", JSON.defaultLocale); + dateFormat.setTimeZone(JSON.defaultTimeZone); + Assert.assertEquals(dateFormat.parse("2012/04-01"), vo.getDate()); + + parser.close(); + } + + public static class VO { + + private Date date; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest.java new file mode 100644 index 0000000000..f605f792db --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.json.bvtVO.deny.A; + +import junit.framework.TestCase; + +public class DenyTest extends TestCase { + + public void test_0() throws Exception { + String text = "{}"; + + ParserConfig config = new ParserConfig(); + + config.addDeny(null); + config.addDeny("com.alibaba.json.bvtVO.deny"); + + Exception error = null; + try { + JSON.parseObject("{\"@type\":\"com.alibaba.json.bvtVO.deny$A\"}", Object.class, config, JSON.DEFAULT_PARSER_FEATURE); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + + JSON.parseObject(text, B.class, config, JSON.DEFAULT_PARSER_FEATURE); + } + + public void test_1() throws Exception { + String text = "{}"; + + ParserConfig config = new ParserConfig(); + + config.addDeny(null); + config.addDeny("com.alibaba.json.bvt.parser.deser.deny.DenyTest.B"); + + Exception error = null; + try { + JSON.parseObject("{\"@type\":\"LLLcom.alibaba.json.bvt.parser.deser.deny.DenyTest$B;;;\"}", Object.class, config, JSON.DEFAULT_PARSER_FEATURE); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + + JSON.parseObject(text, B.class, config, JSON.DEFAULT_PARSER_FEATURE); + } + + + public static class B { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest10.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest10.java new file mode 100644 index 0000000000..4fe8bc8337 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest10.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Properties; +import java.util.UUID; +import java.util.WeakHashMap; +import java.util.concurrent.ConcurrentHashMap; + +public class DenyTest10 extends TestCase { + ParserConfig config = new ParserConfig(); + + protected void setUp() throws Exception { + assertFalse(config.isAutoTypeSupport()); + + Properties properties = new Properties(); + properties.put(ParserConfig.AUTOTYPE_SUPPORT_PROPERTY, "false"); + // -ea -Dfastjson.parser.autoTypeAccept=com.alibaba.json.bvt.parser.deser.DenyTest9 + config.configFromPropety(properties); + } + + public void test_hashMap() throws Exception { + Object obj = JSON.parseObject("{\"@type\":\"java.util.HashMap\"}", Object.class, config); + assertEquals(HashMap.class, obj.getClass()); + } + + public void test_hashMap_weekHashMap() throws Exception { + Object obj = JSON.parseObject("{\"@type\":\"java.util.WeakHashMap\"}", Object.class, config); + assertEquals(WeakHashMap.class, obj.getClass()); + } + + public void test_hashMap_concurrentHashMap() throws Exception { + Object obj = JSON.parseObject("{\"@type\":\"java.util.concurrent.ConcurrentHashMap\"}", Object.class, config); + assertEquals(ConcurrentHashMap.class, obj.getClass()); + } + + public void test_uuid() throws Exception { + System.out.println(UUID.randomUUID()); + Object obj = JSON.parseObject("{\"@type\":\"java.util.UUID\",\"val\":\"290c580d-efa3-432b-8475-2655e336232a\"}", Object.class, config); + assertEquals(UUID.class, obj.getClass()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest11.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest11.java new file mode 100644 index 0000000000..d77b5922c2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest11.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +import java.util.Properties; + +public class DenyTest11 extends TestCase { + ParserConfig config = new ParserConfig(); + + protected void setUp() throws Exception { + assertFalse(config.isAutoTypeSupport()); + + Properties properties = new Properties(); + properties.put(ParserConfig.AUTOTYPE_SUPPORT_PROPERTY, "false"); + config.addAccept("com.alibaba.json.bvt.parser.deser.deny.DenyTest11.Model"); + // -ea -Dfastjson.parser.autoTypeAccept=com.alibaba.json.bvt.parser.deser.deny.DenyTest9 + config.configFromPropety(properties); + + assertFalse(config.isAutoTypeSupport()); + + config.clearDeserializers(); + } + + public void test_autoTypeDeny() throws Exception { + Model model = new Model(); + model.a = new B(); + String text = JSON.toJSONString(model, SerializerFeature.WriteClassName); + System.out.println(text); + + Object obj = JSON.parseObject(text, Object.class, config); + assertEquals(Model.class, obj.getClass()); + } + + public static class Model { + public A a; + } + + public static class Model2 { + public A a; + } + + public static class A { + + } + + public static class B extends A { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest12.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest12.java new file mode 100644 index 0000000000..ed7809efc4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest12.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 29/01/2017. + */ +public class DenyTest12 extends TestCase { + public void test_deny() throws Exception { + String text = "{\"value\":{\"@type\":\"java.lang.Thread\"}}"; + + Exception error = null; + try { + JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public static class Model { + public Value value; + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest13.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest13.java new file mode 100644 index 0000000000..ee709e9eab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest13.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 29/01/2017. + */ +public class DenyTest13 extends TestCase { + public void test_deny() throws Exception { + String text = "{\"value\":{\"@type\":\"java.lang.Thread\"}}"; + Exception error = null; + try { + JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public static class Model { + public Object value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest14.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest14.java new file mode 100644 index 0000000000..a4bee0a272 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest14.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import junit.framework.TestCase; + +/** + * Created by wenshao on 29/01/2017. + */ +public class DenyTest14 extends TestCase { + public void test_deny() throws Exception { + String text = "{\"value\":{\"@type\":\"com.alibaba.json.bvt.parser.deser.deny.DenyTest14$MyException\"}}"; + Model model = JSON.parseObject(text, Model.class); + assertTrue(model.value instanceof MyException); + } + + public static class Model { + public Throwable value; + } + + public static class MyException extends Exception { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest15.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest15.java new file mode 100644 index 0000000000..0a53796460 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest15.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 29/01/2017. + */ +public class DenyTest15 extends TestCase { + public void test_deny() throws Exception { + String text = "{\"value\":{\"@type\":\"com.mchange.v2.c3p0.impl.PoolBackedDataSourceBase\"}}"; + Exception error = null; + try { + Model model = JSON.parseObject(text, Model.class); + } catch (Exception ex) { + error = ex; + } + assertNotNull(error); + } + + public static class Model { + public Throwable value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest16.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest16.java new file mode 100644 index 0000000000..7d45b385d3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest16.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.util.TypeUtils; +import junit.framework.TestCase; + +/** + * Created by wenshao on 29/01/2017. + */ +public class DenyTest16 extends TestCase { + public void test_deny() throws Exception { + JSONObject object = new JSONObject(); + object.put("@type", "com.mchange.v2.c3p0.impl.PoolBackedDataSourceBase"); + + Throwable error = null; + try { + TypeUtils.castToJavaBean(object, Object.class); + } catch (Exception ex) { + error = ex; + } + assertNotNull(error); + } + + public static class Model { + public Throwable value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest2.java new file mode 100644 index 0000000000..10de00adab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest2.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import java.util.Properties; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.json.bvtVO.deny.A; + +import junit.framework.TestCase; + +public class DenyTest2 extends TestCase { + + public void test_0() throws Exception { + String text = "{}"; + + ParserConfig config = new ParserConfig(); + + Properties properties = new Properties(); + properties.put(ParserConfig.DENY_PROPERTY, "com.alibaba.json.bvtVO.deny"); + config.configFromPropety(properties); + + Exception error = null; + try { + JSON.parseObject("{\"@type\":\"com.alibaba.json.bvtVO.deny$A\"}", Object.class, config, JSON.DEFAULT_PARSER_FEATURE); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + + JSON.parseObject(text, B.class, config, JSON.DEFAULT_PARSER_FEATURE); + } + + public static class B { + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest3.java new file mode 100644 index 0000000000..e190c99a5f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest3.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import java.util.Properties; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.json.bvtVO.deny.A; + +import junit.framework.TestCase; + +public class DenyTest3 extends TestCase { + + public void test_0() throws Exception { + String text = "{}"; + + ParserConfig config = new ParserConfig(); + + Properties properties = new Properties(); + properties.put(ParserConfig.DENY_PROPERTY, "com.alibaba.json.bvtVO.deny,,aa"); + config.configFromPropety(properties); + + Exception error = null; + try { + JSON.parseObject("{\"@type\":\"com.alibaba.json.bvtVO.deny$A\"}", Object.class, config, JSON.DEFAULT_PARSER_FEATURE); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + + JSON.parseObject(text, B.class, config, JSON.DEFAULT_PARSER_FEATURE); + } + + public static class B { + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest4.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest4.java new file mode 100644 index 0000000000..77ad671388 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest4.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.json.bvtVO.deny.A; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.Properties; + +public class DenyTest4 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"@type\":\"com.alibaba.json.bvt.parser.deser.deny.DenyTest4$MyClassLoader\"}", Object.class); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public static class MyClassLoader extends ClassLoader { + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest5.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest5.java new file mode 100644 index 0000000000..4a72976f05 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest5.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +public class DenyTest5 extends TestCase { + + public void test_c3p0() throws Exception { + ParserConfig config = new ParserConfig(); + config.setAutoTypeSupport(true); + + Object obj = null; + Exception error = null; + try { + obj = JSON.parseObject("{\"@type\":\"com.mchange.v2.c3p0.impl.PoolBackedDataSourceBase\"}", Object.class, config); + System.out.println(obj.getClass()); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest6.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest6.java new file mode 100644 index 0000000000..1c35e98664 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest6.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +public class DenyTest6 extends TestCase { + + public void test_autoTypeDeny() throws Exception { + ParserConfig config = new ParserConfig(); + assertFalse(config.isAutoTypeSupport()); + config.setAutoTypeSupport(true); + assertTrue(config.isAutoTypeSupport()); + config.addDeny("com.alibaba.json.bvt.parser.deser.deny.DenyTest6"); + config.setAutoTypeSupport(false); + + Exception error = null; + try { + Object obj = JSON.parseObject("{\"@type\":\"com.alibaba.json.bvt.parser.deser.deny.DenyTest6$Model\"}", Object.class, config); + System.out.println(obj.getClass()); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public static class Model { + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest7.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest7.java new file mode 100644 index 0000000000..7e0c548d7c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest7.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import java.util.Properties; + +public class DenyTest7 extends TestCase { + + public void test_autoTypeDeny() throws Exception { + ParserConfig config = new ParserConfig(); + + assertFalse(config.isAutoTypeSupport()); + config.setAutoTypeSupport(true); + assertTrue(config.isAutoTypeSupport()); + + Properties properties = new Properties(); + properties.put(ParserConfig.AUTOTYPE_SUPPORT_PROPERTY, "false"); + + config.configFromPropety(properties); + + assertFalse(config.isAutoTypeSupport()); + + Exception error = null; + try { + Object obj = JSON.parseObject("{\"@type\":\"com.alibaba.json.bvt.parser.deser.deny.DenyTest7$Model\"}", Object.class, config); + System.out.println(obj.getClass()); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + } + + public static class Model { + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest8.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest8.java new file mode 100644 index 0000000000..dd38408f7b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest8.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import java.util.Properties; + +public class DenyTest8 extends TestCase { + + public void test_autoTypeDeny() throws Exception { + ParserConfig config = new ParserConfig(); + + assertFalse(config.isAutoTypeSupport()); + config.setAutoTypeSupport(true); + assertTrue(config.isAutoTypeSupport()); + + Properties properties = new Properties(); + properties.put(ParserConfig.AUTOTYPE_SUPPORT_PROPERTY, "false"); + config.configFromPropety(properties); + + assertFalse(config.isAutoTypeSupport()); + + config.addAccept("com.alibaba.json.bvt.parser.deser.deny.DenyTest8"); + + + Object obj = JSON.parseObject("{\"@type\":\"com.alibaba.json.bvt.parser.deser.deny.DenyTest8$Model\"}", Object.class, config); + assertEquals(Model.class, obj.getClass()); + } + + public static class Model { + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest9.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest9.java new file mode 100644 index 0000000000..88a551c31b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest9.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import java.util.Properties; + +public class DenyTest9 extends TestCase { + + public void test_autoTypeDeny() throws Exception { + ParserConfig config = new ParserConfig(); + + assertFalse(config.isAutoTypeSupport()); + config.setAutoTypeSupport(true); + assertTrue(config.isAutoTypeSupport()); + + Properties properties = new Properties(); + properties.put(ParserConfig.AUTOTYPE_SUPPORT_PROPERTY, "false"); + properties.put(ParserConfig.AUTOTYPE_ACCEPT, "com.alibaba.json.bvt.parser.deser.deny.DenyTest9"); + // -ea -Dfastjson.parser.autoTypeAccept=com.alibaba.json.bvt.parser.deser.deny.DenyTest9 + config.configFromPropety(properties); + + assertFalse(config.isAutoTypeSupport()); + + + Object obj = JSON.parseObject("{\"@type\":\"com.alibaba.json.bvt.parser.deser.deny.DenyTest9$Model\"}", Object.class, config); + assertEquals(Model.class, obj.getClass()); + } + + public static class Model { + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/deny/InitJavaBeanDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/InitJavaBeanDeserializerTest.java new file mode 100644 index 0000000000..042186a398 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/deny/InitJavaBeanDeserializerTest.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.parser.deser.deny; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.ParserConfig; +import junit.framework.TestCase; + +import java.util.Properties; + +/** + * Created by wenshao on 28/01/2017. + */ +public class InitJavaBeanDeserializerTest extends TestCase { + ParserConfig config = new ParserConfig(); + + protected void setUp() throws Exception { + assertFalse(config.isAutoTypeSupport()); + + Properties properties = new Properties(); + properties.put(ParserConfig.AUTOTYPE_SUPPORT_PROPERTY, "false"); + // config.addAccept("com.alibaba.json.bvt.parser.deser.deny.DenyTest11.Model"); + // -ea -Dfastjson.parser.autoTypeAccept=com.alibaba.json.bvt.parser.deser.deny.DenyTest9 + config.configFromPropety(properties); + + assertFalse(config.isAutoTypeSupport()); + } + + public void test_desktop() throws Exception { + DenyTest11.Model model = new DenyTest11.Model(); + model.a = new DenyTest11.B(); + String text = "{\"@type\":\"com.alibaba.json.bvt.parser.deser.deny.InitJavaBeanDeserializerTest$Model\"}"; + + Exception error = null; + try { + Object obj = JSON.parseObject(text, Object.class, config); + System.out.println(obj.getClass()); + } catch (JSONException ex) { + error = ex; + } + assertNotNull(error); + + config.initJavaBeanDeserializers(Model.class); + + Object obj = JSON.parseObject(text, Object.class, config); + assertEquals(Model.class, obj.getClass()); + } + + public static class Model { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/extra/ExtraTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/extra/ExtraTest.java new file mode 100644 index 0000000000..ce1d9428f6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/extra/ExtraTest.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.parser.deser.extra; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 30/03/2017. + */ +public class ExtraTest extends TestCase { + public void test_0() throws Exception { + JSON.parseObject("{\"ID\":123}", Model.class); + } + + public static class Model { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/ByteListTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/ByteListTest.java new file mode 100644 index 0000000000..8ad4b25624 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/ByteListTest.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 20/01/2017. + */ +public class ByteListTest extends TestCase { + public void test_for_issue() throws Exception { + Model model = JSON.parseObject("{\"values\":[[1,2,3]]}", Model.class); + + assertNotNull(model.values); + assertEquals(3, model.values[0].size()); + assertEquals(Byte.class, model.values[0].get(0).getClass()); + assertEquals(Byte.class, model.values[0].get(1).getClass()); + assertEquals(Byte.class, model.values[0].get(2).getClass()); + } + + public void test_for_List() throws Exception { + Model2 model = JSON.parseObject("{\"values\":[1,2,3]}", Model2.class); + + assertNotNull(model.values); + assertEquals(3, model.values.size()); + assertEquals(Byte.class, model.values.get(0).getClass()); + assertEquals(Byte.class, model.values.get(1).getClass()); + assertEquals(Byte.class, model.values.get(2).getClass()); + } + + public static class Model { + public List[] values; + } + + public static class Model2 { + public List values; + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest.java new file mode 100644 index 0000000000..201d7bd66e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class GenericArrayTest extends TestCase { + + public void test_generic() throws Exception { + VO vo = new VO(); + vo.values = new Number[] {1, 1}; + + String text = JSON.toJSONString(vo); + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertNotNull(vo1.values); + Assert.assertEquals(2, vo1.values.length); +// Assert.assertEquals("a", vo1.values[0]); +// Assert.assertEquals("b", vo1.values[1]); + } + + public static class A { + public T[] values; + } + + public static class VO extends A { + + } +} + diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest2.java new file mode 100644 index 0000000000..0849bed919 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest2.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class GenericArrayTest2 extends TestCase { + + public void test_generic() throws Exception { + VO vo = new VO(); + vo.values = new String[] {"a", "b"}; + + String text = JSON.toJSONString(vo); + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertNotNull(vo1.values); + Assert.assertEquals(2, vo1.values.length); + Assert.assertEquals("a", vo1.values[0]); + Assert.assertEquals("b", vo1.values[1]); + } + + public static class A { + public T[] values; + } + + public static class VO extends A { + + } +} + diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest3.java new file mode 100644 index 0000000000..9a650dbbc6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest3.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class GenericArrayTest3 extends TestCase { + + public void test_generic() throws Exception { + VO vo = new VO(); + vo.values = new Pair[] {null, null}; + + String text = JSON.toJSONString(vo); +// VO vo1 = JSON.parseObject(text, new TypeReference>(){} ); + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertNotNull(vo1.values); + Assert.assertEquals(2, vo1.values.length); +// Assert.assertEquals("a", vo1.values[0]); +// Assert.assertEquals("b", vo1.values[1]); + } + + public static class A { + public Pair[] values; + } + + public static class VO extends A { + + } + + public static class Pair { + public A a; + public B b; + } +} + diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest4.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest4.java new file mode 100644 index 0000000000..f42bd209c7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest4.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class GenericArrayTest4 extends TestCase { + + public void test_generic() throws Exception { + VO vo = new VO(); + vo.values = new Pair[] {null, null}; + + String text = JSON.toJSONString(vo); +// VO vo1 = JSON.parseObject(text, new TypeReference>(){} ); + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertNotNull(vo1.values); + Assert.assertEquals(2, vo1.values.length); +// Assert.assertEquals("a", vo1.values[0]); +// Assert.assertEquals("b", vo1.values[1]); + } + + public static class A { + public Pair[] values; + } + + public static class VO extends A { + + } + + public static class Pair { + public A a; + public B b; + } +} + diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest5.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest5.java new file mode 100644 index 0000000000..8679c51685 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest5.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class GenericArrayTest5 extends TestCase { + + public void test_generic() throws Exception { + VO vo = new VO(); + vo.values = new Number[] {1, 1}; + + String text = JSON.toJSONString(vo); + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertNotNull(vo1.values); + Assert.assertEquals(2, vo1.values.length); +// Assert.assertEquals("a", vo1.values[0]); +// Assert.assertEquals("b", vo1.values[1]); + } + + public static class A { + public T[] values; + } + + public static class VO extends A { + + } +} + diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericMap.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericMap.java new file mode 100644 index 0000000000..ce46061a07 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericMap.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +import java.util.Map; + +/** + * Created by wenshao on 20/01/2017. + */ +public class GenericMap extends TestCase { + public void test_generic() throws Exception { + Model model = JSON.parseObject("{\"values\":{\"1001\":{\"id\":1001}}}", new TypeReference>() {}); + User user = model.values.get("1001"); + assertNotNull(user); + assertEquals(1001, user.id); + } + + public static class Model { + public Map values; + } + + public static class User { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest.java new file mode 100644 index 0000000000..788ba7033b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + + +public class GenericTest extends TestCase { + + public void test_0 () throws Exception { + B b = JSON.parseObject("{\"data\":[1,2,3]}", B.class); + b.get(0); + } + + public static abstract class A { + T[] data; + + public A() { + + } + + + + public T[] getData() { + return data; + } + + + + public void setData(T[] data) { + this.data = data; + } + } + + public static class B extends A { + public B() { + } + + public Long get(int index) { + Long l = data[index]; + return l; + } + } + + public static class C { + private T[] data; + + public C(T[] data) { + this.data = data; + } + + + public T[] getData() { + return data; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest2.java new file mode 100755 index 0000000000..3397d4bc9d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest2.java @@ -0,0 +1,86 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class GenericTest2 extends TestCase { + public void test_for_bingyang() throws Exception { + String text = "{\"count\":123,\"index\":7,\"items\":[{\"id\":234,\"latitude\":2.5,\"longtitude\":3.7}]}"; + PageBean pageBean = JSON.parseObject(text, new TypeReference>() {}); + Assert.assertNotNull(pageBean); + Assert.assertEquals(123, pageBean.getCount()); + Assert.assertEquals(7, pageBean.getIndex()); + Assert.assertNotNull(pageBean.getItems()); + Assert.assertEquals(1, pageBean.getItems().size()); + ActiveBase active = pageBean.getItems().get(0); + Assert.assertEquals(new Integer(234), active.getId()); + Assert.assertTrue(3.7D == active.getLongtitude()); + Assert.assertTrue(2.5D == active.getLatitude()); + } + + public static class ActiveBase extends BaseModel { + private double latitude; + private double longtitude; + public double getLatitude() { + return latitude; + } + public void setLatitude(double latitude) { + this.latitude = latitude; + } + public double getLongtitude() { + return longtitude; + } + public void setLongtitude(double longtitude) { + this.longtitude = longtitude; + } + } + + public static class BaseModel { + private Integer id; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + } + + public static class PageBean { + private int count; + private int index; + private List items; + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = index; + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest3.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest3.java new file mode 100755 index 0000000000..7048beebd0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest3.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class GenericTest3 extends TestCase { + public static class A { + public B b; + } + + public static class B { + public T value; + } + + public static class ValueObject { + public String property1; + public int property2; + } + + public void test_generic() throws Exception { + A object = JSON.parseObject( + "{b:{value:{property1:'string',property2:123}}}", + new TypeReference>() { + }); + + Assert.assertEquals(ValueObject.class, object.b.value.getClass()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest4.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest4.java new file mode 100755 index 0000000000..6e8b6b5c48 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest4.java @@ -0,0 +1,83 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class GenericTest4 extends TestCase { + + public void test_0() throws Exception { + String text; + { + User user = new User("Z友群"); + user.getAddresses().add(new Address("滨江")); + text = JSON.toJSONString(user); + } + + System.out.println(text); + + User user = JSON.parseObject(text, User.class); + + Assert.assertEquals("Z友群", user.getName()); + Assert.assertEquals(1, user.getAddresses().size()); + Assert.assertEquals(Address.class, user.getAddresses().get(0).getClass()); + Assert.assertEquals("滨江", user.getAddresses().get(0).getValue()); + } + + public static class User { + + private String name; + + public User(){ + + } + + public User(String name){ + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + private List
addresses = new ArrayList
(); + + public List
getAddresses() { + return addresses; + } + + public void setAddresses(List
addresses) { + this.addresses = addresses; + } + + } + + public static class Address { + + private String value; + + public Address(){ + } + + public Address(String value){ + this.value = value; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest5.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest5.java new file mode 100644 index 0000000000..6f3eff6dc4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest5.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import junit.framework.TestCase; + +public class GenericTest5 extends TestCase { + public void test_generic() { + Pair p1 = new Pair(); + p1.label = "p1"; + p1.value = 3L; + String p1Json = JSON.toJSONString(p1); + + JSON.parseObject(p1Json, LongPair.class); + JSON.parseObject(p1Json, StringPair.class); + + JSONObject p1Jobj = JSON.parseObject(p1Json); + + TypeReference> tr = new TypeReference>() {}; + Pair p2 = null; + p2 = JSON.parseObject(p1Json, tr); + assertNotNull(p2); // 基于JSON字符串的转化正常 + + p2 = p1Jobj.toJavaObject(tr); + assertNotNull(p2); + assertEquals(Long.valueOf(3), p2.value); + + + } + + public static class Pair { + private T value; + public String label; + + public T getValue() { + return value; + } + + public void setValue(T value) { + this.value = value; + } + } + + public static class LongPair extends Pair { + + } + + public static class StringPair extends Pair { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/generic/ListStrFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/ListStrFieldTest.java new file mode 100644 index 0000000000..626ac8f291 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/generic/ListStrFieldTest.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.parser.deser.generic; + +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ListStrFieldTest extends TestCase { + public void test_0() throws Exception { + Model model = JSON.parseObject("{\"values\":null}", Model.class); + Assert.assertNull(model.values); + } + + public static class Model { + public List values; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayDeserializerTest.java new file mode 100755 index 0000000000..0b9a67ef01 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayDeserializerTest.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class ArrayDeserializerTest extends TestCase { + + public void test_null() throws Exception { + Assert.assertNull(JSON.parseObject("null", Object[].class)); + Assert.assertNull(JSON.parseObject("null", String[].class)); + Assert.assertNull(JSON.parseObject("null", VO[].class)); + Assert.assertNull(JSON.parseObject("null", VO[][].class)); + } + + public void test_0() throws Exception { + Assert.assertEquals(0, JSON.parseObject("[]", Object[].class).length); + Assert.assertEquals(0, JSON.parseObject("[]", Object[][].class).length); + Assert.assertEquals(0, JSON.parseObject("[]", Object[][][].class).length); + Assert.assertEquals(1, JSON.parseObject("[null]", Object[].class).length); + Assert.assertEquals(1, JSON.parseObject("[null]", Object[][].class).length); + Assert.assertEquals(1, JSON.parseObject("[[[[[[]]]]]]", Object[][].class).length); + Assert.assertEquals(1, JSON.parseObject("[null]", Object[][][].class).length); + Assert.assertEquals(null, JSON.parseObject("{\"value\":null}", VO.class).getValue()); + } + + public static class VO { + + private Object[] value; + + public Object[] getValue() { + return value; + } + + public void setValue(Object[] value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/ArrayLisMapDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayLisMapDeserializerTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/ArrayLisMapDeserializerTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayLisMapDeserializerTest.java index c345d8c8d5..6bcc31830d --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/ArrayLisMapDeserializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayLisMapDeserializerTest.java @@ -1,10 +1,10 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.list; import java.util.ArrayList; import java.util.List; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/ArrayListEnumFieldDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListEnumFieldDeserializerTest.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/ArrayListEnumFieldDeserializerTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListEnumFieldDeserializerTest.java index 87348a5407..8fa0d2f0cb --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/ArrayListEnumFieldDeserializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListEnumFieldDeserializerTest.java @@ -1,10 +1,10 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.list; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/parser/deser/ArrayListStringDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListStringDeserializerTest.java old mode 100644 new mode 100755 similarity index 75% rename from src/test/java/com/alibaba/json/test/bvt/parser/deser/ArrayListStringDeserializerTest.java rename to src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListStringDeserializerTest.java index dae6cc94f8..6bced9827a --- a/src/test/java/com/alibaba/json/test/bvt/parser/deser/ArrayListStringDeserializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListStringDeserializerTest.java @@ -1,21 +1,38 @@ -package com.alibaba.json.test.bvt.parser.deser; +package com.alibaba.json.bvt.parser.deser.list; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.TypeReference; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; public class ArrayListStringDeserializerTest extends TestCase { + public void test_null() throws Exception { + Assert.assertNull(JSON.parseObject("null", new TypeReference>() { + })); + + Assert.assertNull(JSON.parseArray("null", new Type[] {new TypeReference>() { + }.getType()})); + + Assert.assertNull(JSON.parseArray("null", Entity.class)); + Assert.assertNull(JSON.parseArray("null", Entity[].class)); + Assert.assertNull(JSON.parseArray("null")); + Assert.assertNull(JSON.parseObject("null")); + Assert.assertNull(JSON.parseObject("null", Object[].class)); + Assert.assertNull(JSON.parseObject("null", Entity[].class)); + + Assert.assertNull(JSON.parseArray("[null]", new Type[] {new TypeReference>() { + }.getType()}).get(0)); + } public void test_strings() throws Exception { Entity a = JSON.parseObject("{units:['NANOSECONDS', 'SECONDS', 3, null]}", Entity.class); @@ -91,11 +108,11 @@ public static final T parseObject(String input, Type clazz, Feature... featu } int featureValues = 0; - for (Feature featrue : features) { - featureValues = Feature.config(featureValues, featrue, true); + for (Feature feature : features) { + featureValues = Feature.config(featureValues, feature, true); } - DefaultExtJSONParser parser = new DefaultExtJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); + DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); T value = (T) parser.parseObject(clazz); if (clazz != JSONArray.class) { diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListTypeDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListTypeDeserializerTest.java new file mode 100755 index 0000000000..0c00ef5746 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListTypeDeserializerTest.java @@ -0,0 +1,75 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class ArrayListTypeDeserializerTest extends TestCase { + + public void test_null_0() throws Exception { + Assert.assertNull(JSON.parseObject("null", new TypeReference>() { + })); + } + + public void test_null_1() throws Exception { + Assert.assertNull(JSON.parseObject("null", new TypeReference>() { + })); + } + + public void test_null_2() throws Exception { + Assert.assertNull(JSON.parseObject("{\"value\":null}", VO.class).getValue()); + } + + public void test_null_3() throws Exception { + Assert.assertNull(JSON.parseObject("{\"value\":null}", V1.class).getValue()); + } + + public void test_empty() throws Exception { + Assert.assertEquals(0, JSON.parseObject("[]", new TypeReference>() { + }).size()); + Assert.assertEquals(0, JSON.parseObject("[]", new TypeReference>() { + }).size()); + + Assert.assertEquals(0, JSON.parseObject("[]", new TypeReference>() { + }).size()); + + Assert.assertEquals(0, JSON.parseObject("{\"value\":[]}", VO.class).getValue().size()); + } + + public static class VO { + + private ArrayList value; + + public ArrayList getValue() { + return value; + } + + public void setValue(ArrayList value) { + this.value = value; + } + + } + + private static class V1 { + + private ArrayList value; + + public ArrayList getValue() { + return value; + } + + @SuppressWarnings("unused") + public void setValue(ArrayList value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListTypeFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListTypeFieldTest.java new file mode 100755 index 0000000000..99681c9f02 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListTypeFieldTest.java @@ -0,0 +1,70 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.util.ArrayList; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.Feature; + +public class ArrayListTypeFieldTest extends TestCase { + + public void test_0() throws Exception { + Entity entity = JSON.parseObject("{,,,list:[,,,{value:3}]}", Entity.class); + Assert.assertEquals(3, entity.getList().get(0).getValue()); + } + + public void test_1() throws Exception { + Entity entity = JSON.parseObject("{list:[{value:3}]}", Entity.class, 0, Feature.AllowUnQuotedFieldNames); + Assert.assertEquals(3, entity.getList().get(0).getValue()); + } + + public void test_null() throws Exception { + Entity entity = JSON.parseObject("{list:null}", Entity.class, 0, Feature.AllowUnQuotedFieldNames); + Assert.assertEquals(null, entity.getList()); + } + public void test_null2() throws Exception { + Entity entity = JSON.parseObject("{list:[null]}", Entity.class, 0, Feature.AllowUnQuotedFieldNames); + Assert.assertEquals(null, entity.getList().get(0)); + } + + public void test_error_0() throws Exception { + Exception error = null; + try { + JSON.parseObject("{list:{{value:3}]}", Entity.class, 0, Feature.AllowUnQuotedFieldNames); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Entity { + + private ArrayList list; + + public ArrayList getList() { + return list; + } + + public void setList(ArrayList list) { + this.list = list; + } + + } + + public static class VO { + + private int value; + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest.java new file mode 100644 index 0000000000..1ce972bca5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ListStringFieldTest extends TestCase { + + public void test_list() throws Exception { + String text = "[[\"a\",null,\"b\"]]"; + Model model = JSON.parseObject(text, Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(3, model.values.size()); + Assert.assertEquals("a", model.values.get(0)); + Assert.assertEquals(null, model.values.get(1)); + Assert.assertEquals("b", model.values.get(2)); + } + + public void test_null() throws Exception { + String text = "[null]"; + Model model = JSON.parseObject(text, Model.class, Feature.SupportArrayToBean); + Assert.assertNull(model.values); + } + + public static class Model { + + private List values; + + public List getValues() { + return values; + } + + public void setValues(List values) { + this.values = values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_array_big.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_array_big.java new file mode 100644 index 0000000000..d289858055 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_array_big.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class ListStringFieldTest_array_big extends TestCase { + public void test_list() throws Exception { + Model model = new Model(); + model.values = new ArrayList(); + for (int i = 0; i < 1000; ++i) { + char[] chars = new char[512]; + Arrays.fill(chars, (char) ('0' + (i % 10))); + model.values.add(new String(chars)); + } + + String text = JSON.toJSONString(model, SerializerFeature.BeanToArray); + + Model model2 = JSON.parseObject(text, Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(model.values.size(), model2.values.size()); + for (int i = 0; i < model.values.size(); ++i) { + Assert.assertEquals(model.values.get(i), model2.values.get(i)); + } + } + + public void test_list_empty() throws Exception { + Model model = new Model(); + model.values = new ArrayList(); + + String text = JSON.toJSONString(model, SerializerFeature.BeanToArray); + + Model model2 = JSON.parseObject(text, Model.class, Feature.SupportArrayToBean); + Assert.assertEquals(model.values.size(), model2.values.size()); + for (int i = 0; i < model.values.size(); ++i) { + Assert.assertEquals(model.values.get(i), model2.values.get(i)); + } + } + + public static class Model { + public List values; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_createError.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_createError.java new file mode 100644 index 0000000000..1b14f26197 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_createError.java @@ -0,0 +1,60 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.io.StringReader; +import java.util.ArrayList; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ListStringFieldTest_createError extends TestCase { + + public void test_null() throws Exception { + Exception error = null; + try { + String text = "{\"values\":[]}"; + JSON.parseObject(text, Model.class, Feature.SupportArrayToBean); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_reader() throws Exception { + Exception error = null; + try { + String text = "{\"values\":[]}"; + JSONReader reader = new JSONReader(new StringReader(text)); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + private MyErrorList values; + + public MyErrorList getValues() { + return values; + } + + public void setValues(MyErrorList values) { + this.values = values; + } + + } + + public static class MyErrorList extends ArrayList { + + public MyErrorList(){ + throw new IllegalStateException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom.java new file mode 100644 index 0000000000..712c3378bd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom.java @@ -0,0 +1,202 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.io.StringReader; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.json.bvt.parser.deser.list.ListStringFieldTest_stream.Model; + +import junit.framework.TestCase; + +public class ListStringFieldTest_dom extends TestCase { + + public void test_list() throws Exception { + String text = "{\"values\":[\"a\",null,\"b\",\"ab\\\\c\"]}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(4, model.values.size()); + Assert.assertEquals("a", model.values.get(0)); + Assert.assertEquals(null, model.values.get(1)); + Assert.assertEquals("b", model.values.get(2)); + Assert.assertEquals("ab\\c", model.values.get(3)); + } + + public void test_null() throws Exception { + String text = "{\"values\":null}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertNull(model.values); + } + + public void test_empty() throws Exception { + String text = "{\"values\":[]}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(0, model.values.size()); + } + + public void test_null_element() throws Exception { + String text = "{\"values\":[\"abc\",null]}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(2, model.values.size()); + Assert.assertEquals("abc", model.values.get(0)); + Assert.assertEquals(null, model.values.get(1)); + } + + public void test_map_empty() throws Exception { + String text = "{\"model\":{\"values\":[]}}"; + Map map = JSON.parseObject(text, new TypeReference>() { + }); + Model model = (Model) map.get("model"); + Assert.assertEquals(0, model.values.size()); + } + + public void test_notMatch() throws Exception { + String text = "{\"value\":[]}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertNull(model.values); + } + + public void test_error() throws Exception { + String text = "{\"values\":[1"; + + Exception error = null; + try { + JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + String text = "{\"values\":[\"b\"["; + + Exception error = null; + try { + JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + String text = "{\"model\":{\"values\":[]["; + + + Exception error = null; + try { + JSON.parseObject(text, new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + String text = "{\"model\":{\"values\":[]}["; + + Exception error = null; + try { + JSON.parseObject(text, new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_4() throws Exception { + String text = "{\"model\":{\"values\":[\"aaa]}["; + + + Exception error = null; + try { + JSON.parseObject(text, new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_n() throws Exception { + String text = "{\"values\":[n"; + + Exception error = null; + try { + JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_nu() throws Exception { + String text = "{\"values\":[nu"; + + Exception error = null; + try { + JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_nul() throws Exception { + String text = "{\"values\":[nul"; + + Exception error = null; + try { + JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_null() throws Exception { + String text = "{\"values\":[null"; + + Exception error = null; + try { + JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_rbacket() throws Exception { + String text = "{\"values\":[null,]"; + + Exception error = null; + try { + JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + private List values; + + public List getValues() { + return values; + } + + public void setValues(List values) { + this.values = values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_array.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_array.java new file mode 100644 index 0000000000..2e057ed9e0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_array.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ListStringFieldTest_dom_array extends TestCase { + + public void test_list() throws Exception { + String text = "[[\"a\",null,\"b\",\"ab\\\\c\"],[]]"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(4, model.values.size()); + Assert.assertEquals("a", model.values.get(0)); + Assert.assertEquals(null, model.values.get(1)); + Assert.assertEquals("b", model.values.get(2)); + Assert.assertEquals("ab\\c", model.values.get(3)); + + Assert.assertEquals(0, model.values2.size()); + } + + public void test_list2() throws Exception { + String text = "{\"values\":[\"a\",null,\"b\",\"ab\\\\c\"],\"values2\":[]}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(4, model.values.size()); + Assert.assertEquals("a", model.values.get(0)); + Assert.assertEquals(null, model.values.get(1)); + Assert.assertEquals("b", model.values.get(2)); + Assert.assertEquals("ab\\c", model.values.get(3)); + + Assert.assertEquals(0, model.values2.size()); + } + + @JSONType(parseFeatures = Feature.SupportArrayToBean) + public static class Model { + + public List values; + public List values2; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_array_2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_array_2.java new file mode 100644 index 0000000000..a3c8d38704 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_array_2.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.io.StringReader; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.json.bvt.parser.deser.list.ListStringFieldTest_dom_array.Model; + +import junit.framework.TestCase; + +public class ListStringFieldTest_dom_array_2 extends TestCase { + + public void test_list() throws Exception { + String text = "[[\"a\",null,\"b\",\"ab\\\\c\"],[]]"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(4, model.values.size()); + Assert.assertEquals("a", model.values.get(0)); + Assert.assertEquals(null, model.values.get(1)); + Assert.assertEquals("b", model.values.get(2)); + Assert.assertEquals("ab\\c", model.values.get(3)); + + Assert.assertEquals(0, model.values2.size()); + } + + public void test_list2() throws Exception { + String text = "{\"values\":[\"a\",null,\"b\",\"ab\\\\c\"],\"values2\":[]}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(4, model.values.size()); + Assert.assertEquals("a", model.values.get(0)); + Assert.assertEquals(null, model.values.get(1)); + Assert.assertEquals("b", model.values.get(2)); + Assert.assertEquals("ab\\c", model.values.get(3)); + + Assert.assertEquals(0, model.values2.size()); + } + + @JSONType(parseFeatures = Feature.SupportArrayToBean) + public static class Model { + + public List values; + public List values2; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_hashSet.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_hashSet.java new file mode 100644 index 0000000000..fee062ffe3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_hashSet.java @@ -0,0 +1,118 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.io.StringReader; +import java.util.Map; +import java.util.Set; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.json.bvt.parser.deser.list.ListStringFieldTest_dom_array.Model; + +import junit.framework.TestCase; + +public class ListStringFieldTest_dom_hashSet extends TestCase { + + public void test_list() throws Exception { + String text = "{\"values\":[\"a\",null,\"b\",\"ab\\\\c\"]}"; + + Model model = JSON.parseObject(text, Model.class); + + Assert.assertEquals(4, model.values.size()); + Assert.assertTrue(model.values.contains("a")); + Assert.assertTrue(model.values.contains("b")); + Assert.assertTrue(model.values.contains(null)); + Assert.assertTrue(model.values.contains("ab\\c")); + } + + public void test_null() throws Exception { + String text = "{\"values\":null}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertNull(model.values); + } + + public void test_empty() throws Exception { + String text = "{\"values\":[]}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(0, model.values.size()); + } + + public void test_map_empty() throws Exception { + String text = "{\"model\":{\"values\":[]}}"; + Map map = JSON.parseObject(text, new TypeReference>() { + }); + Model model = (Model) map.get("model"); + Assert.assertEquals(0, model.values.size()); + } + + public void test_notMatch() throws Exception { + String text = "{\"value\":[]}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertNull(model.values); + } + + public void test_error() throws Exception { + String text = "{\"values\":[1"; + Exception error = null; + try { + Model model = JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + String text = "{\"values\":[\"b\"["; + Exception error = null; + try { + Model model = JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + String text = "{\"model\":{\"values\":[]["; + + Exception error = null; + try { + JSON.parseObject(text, new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + String text = "{\"model\":{\"values\":[]}["; + + Exception error = null; + try { + JSON.parseObject(text, new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + private Set values; + + public Set getValues() { + return values; + } + + public void setValues(Set values) { + this.values = values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_treeSet.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_treeSet.java new file mode 100644 index 0000000000..31d56176b9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_treeSet.java @@ -0,0 +1,114 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.util.Map; +import java.util.TreeSet; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class ListStringFieldTest_dom_treeSet extends TestCase { + + public void test_list() throws Exception { + String text = "{\"values\":[\"a\",\"b\",\"ab\\\\c\"]}"; + + Model model = JSON.parseObject(text, Model.class); + + Assert.assertEquals(3, model.values.size()); + Assert.assertTrue(model.values.contains("a")); + Assert.assertTrue(model.values.contains("b")); + Assert.assertTrue(model.values.contains("ab\\c")); + } + + public void test_null() throws Exception { + String text = "{\"values\":null}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertNull(model.values); + } + + public void test_empty() throws Exception { + String text = "{\"values\":[]}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertEquals(0, model.values.size()); + } + + public void test_map_empty() throws Exception { + String text = "{\"model\":{\"values\":[]}}"; + Map map = JSON.parseObject(text, new TypeReference>() { + }); + Model model = (Model) map.get("model"); + Assert.assertEquals(0, model.values.size()); + } + + public void test_notMatch() throws Exception { + String text = "{\"value\":[]}"; + Model model = JSON.parseObject(text, Model.class); + Assert.assertNull(model.values); + } + + public void test_error() throws Exception { + String text = "{\"values\":[1"; + Exception error = null; + try { + Model model = JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + String text = "{\"values\":[\"b\"["; + Exception error = null; + try { + Model model = JSON.parseObject(text, Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + String text = "{\"model\":{\"values\":[]["; + + Exception error = null; + try { + JSON.parseObject(text, new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + String text = "{\"model\":{\"values\":[]}["; + + Exception error = null; + try { + JSON.parseObject(text, new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + private TreeSet values; + + public TreeSet getValues() { + return values; + } + + public void setValues(TreeSet values) { + this.values = values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream.java new file mode 100644 index 0000000000..5e3614fb12 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream.java @@ -0,0 +1,208 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.io.StringReader; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class ListStringFieldTest_stream extends TestCase { + + public void test_list() throws Exception { + String text = "{\"values\":[\"a\",null,\"b\",\"ab\\\\c\\\"\"]}"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertEquals(4, model.values.size()); + Assert.assertEquals("a", model.values.get(0)); + Assert.assertEquals(null, model.values.get(1)); + Assert.assertEquals("b", model.values.get(2)); + Assert.assertEquals("ab\\c\"", model.values.get(3)); + } + + public void test_null() throws Exception { + String text = "{\"values\":null}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertNull(model.values); + } + + public void test_empty() throws Exception { + String text = "{\"values\":[]}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertEquals(0, model.values.size()); + } + + public void test_map_empty() throws Exception { + String text = "{\"model\":{\"values\":[]}}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Map map = reader.readObject(new TypeReference>() { + }); + Model model = (Model) map.get("model"); + Assert.assertEquals(0, model.values.size()); + } + + public void test_notMatch() throws Exception { + String text = "{\"value\":[]}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertNull(model.values); + } + + public void test_error() throws Exception { + String text = "{\"values\":[1"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + String text = "{\"values\":[\"b\"["; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + String text = "{\"model\":{\"values\":[]["; + JSONReader reader = new JSONReader(new StringReader(text)); + + + Exception error = null; + try { + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + String text = "{\"model\":{\"values\":[]}["; + JSONReader reader = new JSONReader(new StringReader(text)); + + + Exception error = null; + try { + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_4() throws Exception { + String text = "{\"model\":{\"values\":[\"aaa]}["; + JSONReader reader = new JSONReader(new StringReader(text)); + + + Exception error = null; + try { + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_n() throws Exception { + String text = "{\"values\":[n"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_nu() throws Exception { + String text = "{\"values\":[nu"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_nul() throws Exception { + String text = "{\"values\":[nul"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_null() throws Exception { + String text = "{\"values\":[null"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_rbacket() throws Exception { + String text = "{\"values\":[null,]"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + private List values; + + public List getValues() { + return values; + } + + public void setValues(List values) { + this.values = values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_TreeSet.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_TreeSet.java new file mode 100644 index 0000000000..79cf5468aa --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_TreeSet.java @@ -0,0 +1,128 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.io.StringReader; +import java.util.Map; +import java.util.TreeSet; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class ListStringFieldTest_stream_TreeSet extends TestCase { + + public void test_list() throws Exception { + String text = "{\"values\":[\"a\",\"b\",\"ab\\\\c\"]}"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + + Assert.assertEquals(3, model.values.size()); + Assert.assertTrue(model.values.contains("a")); + Assert.assertTrue(model.values.contains("b")); + } + + public void test_null() throws Exception { + String text = "{\"values\":null}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertNull(model.values); + } + + public void test_empty() throws Exception { + String text = "{\"values\":[]}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertEquals(0, model.values.size()); + } + + public void test_map_empty() throws Exception { + String text = "{\"model\":{\"values\":[]}}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Map map = reader.readObject(new TypeReference>() { + }); + Model model = (Model) map.get("model"); + Assert.assertEquals(0, model.values.size()); + } + + public void test_notMatch() throws Exception { + String text = "{\"value\":[]}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertNull(model.values); + } + + public void test_error() throws Exception { + String text = "{\"values\":[1"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + String text = "{\"values\":[\"b\"["; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + String text = "{\"model\":{\"values\":[]["; + JSONReader reader = new JSONReader(new StringReader(text)); + + + Exception error = null; + try { + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + String text = "{\"model\":{\"values\":[]}["; + JSONReader reader = new JSONReader(new StringReader(text)); + + + Exception error = null; + try { + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + + public static class Model { + + private TreeSet values; + + public TreeSet getValues() { + return values; + } + + public void setValues(TreeSet values) { + this.values = values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_array.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_array.java new file mode 100644 index 0000000000..65e2f4177b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_array.java @@ -0,0 +1,280 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.io.StringReader; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ListStringFieldTest_stream_array extends TestCase { + + public void test_list() throws Exception { + String text = "[[\"a\",null,\"b\",\"ab\\\\c\\\"a\"]]"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertEquals(4, model.values.size()); + Assert.assertEquals("a", model.values.get(0)); + Assert.assertEquals(null, model.values.get(1)); + Assert.assertEquals("b", model.values.get(2)); + Assert.assertEquals("ab\\c\"a", model.values.get(3)); + } + + public void test_null() throws Exception { + String text = "[null]"; + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertNull(model.values); + } + + public void test_empty() throws Exception { + String text = "[[]]}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertEquals(0, model.values.size()); + } + + public void test_map_empty() throws Exception { + String text = "{\"model\":[[]]}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Map map = reader.readObject(new TypeReference>() { + }); + Model model = (Model) map.get("model"); + Assert.assertEquals(0, model.values.size()); + } + + public void test_map_empty_2() throws Exception { + String text = "{\"model\":[[]],\"model2\":[[]]}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Map map = reader.readObject(new TypeReference>() { + }); + Model model = (Model) map.get("model"); + Assert.assertEquals(0, model.values.size()); + + Model model2 = (Model) map.get("model2"); + Assert.assertEquals(0, model2.values.size()); + } + + public void test_error() throws Exception { + String text = "[[1{1,}"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_0() throws Exception { + String text = "[{"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_n() throws Exception { + String text = "[n"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_nu() throws Exception { + String text = "[nu"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_nul() throws Exception { + String text = "[nul"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + + public void test_error_null() throws Exception { + String text = "[null"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_fn() throws Exception { + String text = "[[n"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_fnu() throws Exception { + String text = "[[nu"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_fnul() throws Exception { + String text = "[[nul"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + + public void test_error_fnull() throws Exception { + String text = "[[null"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_notclose() throws Exception { + String text = "[[\"aaa"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + String text = "[[\"b\"[[{"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + reader.close(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + String text = "{\"model\":[[]["; + JSONReader reader = new JSONReader(new StringReader(text)); + + + Exception error = null; + try { + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + String text = "{\"model\":[[]}["; + JSONReader reader = new JSONReader(new StringReader(text)); + + + Exception error = null; + try { + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + @JSONType(parseFeatures = Feature.SupportArrayToBean) + public static class Model { + + private List values; + + public List getValues() { + return values; + } + + public void setValues(List values) { + this.values = values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_array_2.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_array_2.java new file mode 100644 index 0000000000..0223b6293c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_array_2.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.io.StringReader; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; + +import junit.framework.TestCase; + +public class ListStringFieldTest_stream_array_2 extends TestCase { + + public void test_list() throws Exception { + String text = "[[\"a\",null,\"b\",\"ab\\\\c\"],[]]"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertEquals(4, model.values.size()); + Assert.assertEquals("a", model.values.get(0)); + Assert.assertEquals(null, model.values.get(1)); + Assert.assertEquals("b", model.values.get(2)); + Assert.assertEquals("ab\\c", model.values.get(3)); + + Assert.assertEquals(0, model.values2.size()); + } + + public void test_list2() throws Exception { + String text = "{\"values\":[\"a\",null,\"b\",\"ab\\\\c\"],\"values2\":[]}"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertEquals(4, model.values.size()); + Assert.assertEquals("a", model.values.get(0)); + Assert.assertEquals(null, model.values.get(1)); + Assert.assertEquals("b", model.values.get(2)); + Assert.assertEquals("ab\\c", model.values.get(3)); + + Assert.assertEquals(0, model.values2.size()); + } + + + @JSONType(parseFeatures = Feature.SupportArrayToBean) + public static class Model { + + public List values; + public List values2; + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_hashSet.java b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_hashSet.java new file mode 100644 index 0000000000..1d5d027776 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_hashSet.java @@ -0,0 +1,130 @@ +package com.alibaba.json.bvt.parser.deser.list; + +import java.io.StringReader; +import java.util.Map; +import java.util.Set; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class ListStringFieldTest_stream_hashSet extends TestCase { + + public void test_list() throws Exception { + String text = "{\"values\":[\"a\",null,\"b\",\"ab\\\\c\"]}"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + + Assert.assertEquals(4, model.values.size()); + Assert.assertTrue(model.values.contains("a")); + Assert.assertTrue(model.values.contains("b")); + Assert.assertTrue(model.values.contains(null)); + Assert.assertTrue(model.values.contains("ab\\c")); + } + + public void test_null() throws Exception { + String text = "{\"values\":null}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertNull(model.values); + } + + public void test_empty() throws Exception { + String text = "{\"values\":[]}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertEquals(0, model.values.size()); + } + + public void test_map_empty() throws Exception { + String text = "{\"model\":{\"values\":[]}}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Map map = reader.readObject(new TypeReference>() { + }); + Model model = (Model) map.get("model"); + Assert.assertEquals(0, model.values.size()); + } + + public void test_notMatch() throws Exception { + String text = "{\"value\":[]}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertNull(model.values); + } + + public void test_error() throws Exception { + String text = "{\"values\":[1"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_1() throws Exception { + String text = "{\"values\":[\"b\"["; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + String text = "{\"model\":{\"values\":[]["; + JSONReader reader = new JSONReader(new StringReader(text)); + + + Exception error = null; + try { + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + String text = "{\"model\":{\"values\":[]}["; + JSONReader reader = new JSONReader(new StringReader(text)); + + + Exception error = null; + try { + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + + public static class Model { + + private Set values; + + public Set getValues() { + return values; + } + + public void setValues(Set values) { + this.values = values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/nonctor/NonDefaultConstructorTest0.java b/src/test/java/com/alibaba/json/bvt/parser/deser/nonctor/NonDefaultConstructorTest0.java new file mode 100644 index 0000000000..0ce0ecc725 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/nonctor/NonDefaultConstructorTest0.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.parser.deser.nonctor; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 06/08/2017. + */ +public class NonDefaultConstructorTest0 extends TestCase { + public void test_non_default_constructor() throws Exception { + Model model = JSON.parseObject("{\"id\":1001,\"value\":{\"id\":2001}}", Model.class); + assertNotNull(model); + assertEquals(1001, model.id); + assertNotNull(model.value); + assertEquals(2001, model.value.id); + } + + + public static class Model { + private final int id; + private final Value value; + + public Model(int id, Value value) { + this.id = id; + this.value = value; + } + } + + public static class Value { + private final int id; + + public Value(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderBooleanFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderBooleanFieldTest.java new file mode 100644 index 0000000000..016f676cf3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderBooleanFieldTest.java @@ -0,0 +1,126 @@ +package com.alibaba.json.bvt.parser.deser.stream; + +import java.io.StringReader; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class ReaderBooleanFieldTest extends TestCase { + + public void test_bool_error_0() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":t}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_bool_error_1() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":tr}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_bool_error_2() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":tru}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_bool_error_f0() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":f}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_bool_error_f1() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":fa}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_bool_error_f2() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":fal}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_bool_error_f3() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":fals}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_bool_normal() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"value\":false,\"value2\":true}")); + Model model = reader.readObject(Model.class); + Assert.assertFalse(model.value); + Assert.assertTrue(model.value2); + reader.close(); + } + + public void test_bool_normal_2() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"model\":{\"value\":false,\"value2\":true}}")); + Map map = reader.readObject(new TypeReference>() {}); + Model model = map.get("model"); + Assert.assertFalse(model.value); + Assert.assertTrue(model.value2); + reader.close(); + } + + public void test_bool_error_map() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"model\":{\"value\":false,\"value2\":true}[")); + reader.readObject(new TypeReference>() {}); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Model { + + public boolean value; + public boolean value2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderIntFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderIntFieldTest.java new file mode 100644 index 0000000000..78c9c553e0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderIntFieldTest.java @@ -0,0 +1,117 @@ +package com.alibaba.json.bvt.parser.deser.stream; + +import java.io.StringReader; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class ReaderIntFieldTest extends TestCase { + + public void test_int_error_0() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":1.A}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_int_error_1() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":2147483648}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_int_error_1_x() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":9223372036854775808}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_int_error_1_x1() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":-2147483649}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_int_error_2() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":AA}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_int_normal() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"value\":1001,\"value2\":-2001}")); + Model model = reader.readObject(Model.class); + Assert.assertEquals(1001, model.value); + Assert.assertEquals(-2001, model.value2); + reader.close(); + } + + public void test_int_normal_2() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"model\":{\"value\":3001,\"value2\":-4001}}")); + Map map = reader.readObject(new TypeReference>() { + }); + Model model = map.get("model"); + Assert.assertEquals(3001, model.value); + Assert.assertEquals(-4001, model.value2); + reader.close(); + } + + public void test_int_error_map() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"model\":{\"value\":3001,\"value2\":-4001}[")); + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_int_error_end() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":1001,\"value2\":-2001[")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Model { + + public int value; + public int value2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderLongFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderLongFieldTest.java new file mode 100644 index 0000000000..ca3db64b08 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderLongFieldTest.java @@ -0,0 +1,106 @@ +package com.alibaba.json.bvt.parser.deser.stream; + +import java.io.StringReader; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class ReaderLongFieldTest extends TestCase { + + public void test_long_error_0() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":1.A}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_long_error_1() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":9223372036854775808}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_long_error_1_x() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":922337203685477580892233720368547758088}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_long_error_2() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":AA}")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_long_normal() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"value\":1001,\"value2\":-2001}")); + Model model = reader.readObject(Model.class); + Assert.assertEquals(1001L, model.value); + Assert.assertEquals(-2001L, model.value2); + reader.close(); + } + + public void test_long_normal_2() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"model\":{\"value\":3001,\"value2\":-4001}}")); + Map map = reader.readObject(new TypeReference>() { + }); + Model model = map.get("model"); + Assert.assertEquals(3001L, model.value); + Assert.assertEquals(-4001L, model.value2); + reader.close(); + } + + public void test_long_error_map() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"model\":{\"value\":3001,\"value2\":-4001}[")); + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_long_error_end() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"value\":1001,\"value2\":-2001[")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Model { + + public long value; + public long value2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/deser/var/TwoTypeTest.java b/src/test/java/com/alibaba/json/bvt/parser/deser/var/TwoTypeTest.java new file mode 100644 index 0000000000..5df77b141a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/deser/var/TwoTypeTest.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.parser.deser.var; + +import junit.framework.TestCase; + +/** + * Created by wenshao on 23/01/2017. + */ +public class TwoTypeTest extends TestCase { + public void test_two() throws Exception { + + } + + public static class ModelA { + public int id; + } + + public static class ModelB { + public int value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/JSONReaderError.java b/src/test/java/com/alibaba/json/bvt/parser/error/JSONReaderError.java new file mode 100644 index 0000000000..56ce07f88f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/JSONReaderError.java @@ -0,0 +1,88 @@ +package com.alibaba.json.bvt.parser.error; + +import java.io.StringReader; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class JSONReaderError extends TestCase { + + public void test_reader_error() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"id\":")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_reader_error_1() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"id\":\"aa")); + reader.readObject(Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_reader_no_error() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"id\":\"aa\",\"name\":\"wenshao\"}")); + Model model = reader.readObject(Model.class); + Assert.assertEquals("aa", model.id); + Assert.assertEquals("wenshao", model.name); + reader.close(); + } + + public void test_reader_no_error_1() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"model\":{\"id\":\"aa\",\"name\":\"wenshao\"}}")); + Map map = reader.readObject(new TypeReference>() {}); + Model model = map.get("model"); + Assert.assertEquals("aa", model.id); + Assert.assertEquals("wenshao", model.name); + reader.close(); + } + + public void test_reader_no_error_2() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"model\":{\"id\":\"aa\",\"name\":\"wenshao\"},\"model2\":{\"id\":\"bb\",\"name\":\"ljw\"}}")); + Map map = reader.readObject(new TypeReference>() {}); + + { + Model model = map.get("model"); + Assert.assertEquals("aa", model.id); + Assert.assertEquals("wenshao", model.name); + } + { + Model model = map.get("model2"); + Assert.assertEquals("bb", model.id); + Assert.assertEquals("ljw", model.name); + } + reader.close(); + } + + public void test_reader_error_3() throws Exception { + Exception error = null; + try { + JSONReader reader = new JSONReader(new StringReader("{\"model\":{\"id\":\"aa\",\"name\":\"wenshao\"}[")); + Map map = reader.readObject(new TypeReference>() {}); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public String id; + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_10.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_10.java new file mode 100644 index 0000000000..5f45dcfbfb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_10.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_10 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{123,"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_11.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_11.java new file mode 100644 index 0000000000..e7c1118b5e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_11.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_11 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parse("[123,"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_12.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_12.java new file mode 100644 index 0000000000..e9293307cb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_12.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_12 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parse("new \"Date\""); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_13.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_13.java new file mode 100644 index 0000000000..9736ae2729 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_13.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_13 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":Set[]:"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_14.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_14.java new file mode 100644 index 0000000000..5e0e7aaf60 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_14.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_14 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":true,"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_15.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_15.java new file mode 100644 index 0000000000..17493bb68f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_15.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_15 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":trm"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_16.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_16.java new file mode 100644 index 0000000000..2974098692 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_16.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_16 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":fale"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_17.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_17.java new file mode 100644 index 0000000000..0cea9b23b2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_17.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_17 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parse("[{\"$ref\":\"$\"]"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_18.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_18.java new file mode 100644 index 0000000000..893fefec6f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_18.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_18 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parse("[{\"$ref\":123}]"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_19.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_19.java new file mode 100644 index 0000000000..b3153305f9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_19.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_19 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parse("[\"wenshao\""); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_20.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_20.java new file mode 100644 index 0000000000..b6d0c51944 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_20.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_20 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parse("[\"wenshao\":"); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_21.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_21.java new file mode 100644 index 0000000000..09c18be027 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_21.java @@ -0,0 +1,83 @@ +package com.alibaba.json.bvt.parser.error; + +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.parser.ParserConfig; + +import junit.framework.TestCase; + +public class ParseErrorTest_21 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":123}", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{,,,\"id\",}}", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{'child1':{\"id\":123}}}", Model.class, ParserConfig.getGlobalInstance(), 0); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{'child1',{\"id\":123}}}", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_4() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{child1:{\"id\":123}}}", Model.class, ParserConfig.getGlobalInstance(), 0); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_5() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":{child1,{\"id\":123}}}", Model.class, ParserConfig.getGlobalInstance(), 0, Feature.AllowUnQuotedFieldNames); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + public Map value; + } + + public static class Child { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_8.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_8.java new file mode 100644 index 0000000000..7060f38e21 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_8.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_8 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":33\"}", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"33\"", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"33\",", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_4() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"33\"},", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + public int value; + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_9.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_9.java new file mode 100644 index 0000000000..fbaaad87a2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_9.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_9 extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":33\"}", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_2() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"33\"", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_3() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"33\",", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_4() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"33\"},", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + public long value; + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_date.java b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_date.java new file mode 100644 index 0000000000..405d578065 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_date.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt.parser.error; + +import java.util.Date; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class ParseErrorTest_date extends TestCase { + + public void test_for_error() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"2011-01-09M\"}", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_for_error_1() throws Exception { + Exception error = null; + try { + JSON.parseObject("{\"value\":\"2011-01-09", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + +// public void test_for_error_2() throws Exception { +// Exception error = null; +// try { +// JSON.parseObject("{\"value\":\"2011-01-09 00:00:00.000+.M\"}", Model.class); +// } catch (JSONException ex) { +// error = ex; +// } +// Assert.assertNotNull(error); +// } +// +// public void test_for_error_3() throws Exception { +// Exception error = null; +// try { +// JSON.parseObject("{\"value\":\"2011-01-09 00:00:00.000+2M\"}", Model.class); +// } catch (JSONException ex) { +// error = ex; +// } +// Assert.assertNotNull(error); +// } + + public static class Model { + public Date value; + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/error/TypeNotMatchError.java b/src/test/java/com/alibaba/json/bvt/parser/error/TypeNotMatchError.java new file mode 100644 index 0000000000..5db33d4a88 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/error/TypeNotMatchError.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser.error; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class TypeNotMatchError extends TestCase { + + public void test_0() throws Exception { + JSON.parseObject("{\"value\":{\"@type\":\"com.alibaba.json.bvt.parser.error.TypeNotMatchError$AA\"}}", Model.class); + + Exception error = null; + try { + JSON.parseObject("{\"value\":{\"@type\":\"com.alibaba.json.bvt.parser.error.TypeNotMatchError$B\"}}", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + private static class Model { + + public A value; + } + + private static class A { + + } + + private static class AA extends A { + + } + + private static class B { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/fieldTypeResolver/FieldTypeResolverTest.java b/src/test/java/com/alibaba/json/bvt/parser/fieldTypeResolver/FieldTypeResolverTest.java new file mode 100644 index 0000000000..8b68745030 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/fieldTypeResolver/FieldTypeResolverTest.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.parser.fieldTypeResolver; + +import java.lang.reflect.Type; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.deserializer.FieldTypeResolver; + +import junit.framework.TestCase; + +public class FieldTypeResolverTest extends TestCase { + + public void test_0() throws Exception { + String text = "{\"item_0\":{},\"item_1\":{}}"; + + FieldTypeResolver fieldResolver = new FieldTypeResolver() { + + public Type resolve(Object object, String fieldName) { + if (fieldName.startsWith("item_")) { + return Item.class; + } + + return null; + } + }; + + JSONObject jsonObject = JSON.parseObject(text, JSONObject.class, fieldResolver); + Assert.assertTrue(jsonObject.get("item_0") instanceof Item); + } + + public static class Item { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberEmtpyObjectTest.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberEmtpyObjectTest.java new file mode 100644 index 0000000000..f8595dd11f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberEmtpyObjectTest.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.parser.number; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 24/04/2017. + */ +public class NumberEmtpyObjectTest extends TestCase { + public void test_for_emptyObj() throws Exception { + Model model = JSON.parseObject("{\"val\":{}}", Model.class); + assertNull(model.val); + } + + public static class Model { + public Number val; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest.java new file mode 100644 index 0000000000..c5b840dabc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class NumberValueTest extends TestCase { + + public void test_0() throws Exception { + String text = "{\"value\":3D}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertTrue(3D == ((Double)obj.get("value")).doubleValue()); + + } + + public void test_1() throws Exception { + String text = "{\"value\":3.e3D}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertTrue(3.e3D == ((Double)obj.get("value")).doubleValue()); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest2.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest2.java new file mode 100644 index 0000000000..4038323d98 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest2.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class NumberValueTest2 extends TestCase { + + public void test_0() throws Exception { + String text = "{\"value\":3F}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertTrue(3F == ((Float)obj.get("value")).floatValue()); + + } + + public void test_1() throws Exception { + String text = "{\"value\":3.e3F}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertTrue(3.e3F == ((Float)obj.get("value")).floatValue()); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest3.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest3.java new file mode 100644 index 0000000000..356fe0fccc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest3.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class NumberValueTest3 extends TestCase { + + public void test_0() throws Exception { + String text = "{\"value\":-21474836481}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(Long.valueOf(-21474836481L), obj.get("value")); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest4.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest4.java new file mode 100644 index 0000000000..3ed3cb2424 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest4.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class NumberValueTest4 extends TestCase { + + public void test_0() throws Exception { + String text = "{\"value\":21474836481}"; + JSONObject obj = (JSONObject) JSON.parse(text); + Assert.assertEquals(Long.valueOf(21474836481L), obj.get("value")); + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_0.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_0.java new file mode 100644 index 0000000000..c91a03421b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_0.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_0 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{\"value\":33e}"; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_1.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_1.java new file mode 100644 index 0000000000..24b442ad2d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_1.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_1 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "33e"; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_10.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_10.java new file mode 100644 index 0000000000..b41003dfb1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_10.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_10 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{\"value\":3e-"; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_11.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_11.java new file mode 100644 index 0000000000..4c4489af09 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_11.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_11 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{\"value\":3e-1"; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_12.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_12.java new file mode 100644 index 0000000000..b288372fb4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_12.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_12 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{\"value\":33.33"; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_2.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_2.java new file mode 100644 index 0000000000..8274382109 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_2.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_2 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{\"value\":33e"; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_3.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_3.java new file mode 100644 index 0000000000..14f2f1f2b4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_3.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_3 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{\"value\":33e+}"; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_4.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_4.java new file mode 100644 index 0000000000..43581fa4b0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_4.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_4 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{\"value\":33e-}"; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_5.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_5.java new file mode 100644 index 0000000000..7207b84758 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_5.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_5 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{-"; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_6.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_6.java new file mode 100644 index 0000000000..62778270fc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_6.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_6 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{3e+"; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_7.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_7.java new file mode 100644 index 0000000000..3be9678039 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_7.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_7 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{\"value\":-"; + JSON.parse(text); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_8.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_8.java new file mode 100644 index 0000000000..ae35894c70 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_8.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_8 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{\"value\":3"; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_9.java b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_9.java new file mode 100644 index 0000000000..758e9bbc08 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_9.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.number; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; + +import junit.framework.TestCase; + +public class NumberValueTest_error_9 extends TestCase { + + public void test_0() throws Exception { + Exception error = null; + try { + String text = "{\"value\":3."; + JSON.parse(text); + } catch (JSONException e) { + error = e; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/str/EmptyStringTest.java b/src/test/java/com/alibaba/json/bvt/parser/str/EmptyStringTest.java new file mode 100644 index 0000000000..4be7919289 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/str/EmptyStringTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.parser.str; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 13/03/2017. + */ +public class EmptyStringTest extends TestCase { + public void test_for_emptyString() throws Exception { + SolutionIdentifier solutionIdentifier = JSON.parseObject("{\"id\":\"\"}", SolutionIdentifier.class); + assertNull(solutionIdentifier.id); + } + + public static class SolutionIdentifier { + public Id id; + } + + public static class Id { + public String id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/str/StringTest_00.java b/src/test/java/com/alibaba/json/bvt/parser/str/StringTest_00.java new file mode 100644 index 0000000000..d7825f6ada --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/str/StringTest_00.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.parser.str; + +import java.util.Arrays; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; + +import junit.framework.TestCase; + +public class StringTest_00 extends TestCase { + + public void test_string() throws Exception { + char[] chars = new char[1024]; + Arrays.fill(chars, '0'); + StringBuilder buf = new StringBuilder(); + buf.append("[\""); + for (int i = 0; i < 16; ++i) { + buf.append("\\\\"); + buf.append(new String(chars)); + } + buf.append("\"]"); + + String text = buf.toString(); + JSONArray array = (JSONArray) JSON.parse(text); + Assert.assertEquals(1, array.size()); + + String item = (String) array.get(0); + Assert.assertEquals(16 * 1024 + 16, item.length()); + + for (int i = 0; i < 16; ++i) { + Assert.assertTrue(item.charAt(i * 1025) == '\\'); + for (int j = 0; j < 1024; ++j) { + Assert.assertTrue(item.charAt(i * 1025 + j + 1) == '0'); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/str/StringTest_01.java b/src/test/java/com/alibaba/json/bvt/parser/str/StringTest_01.java new file mode 100644 index 0000000000..a0a0a5d4cc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/str/StringTest_01.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.parser.str; + +import java.util.Arrays; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; + +import junit.framework.TestCase; + +public class StringTest_01 extends TestCase { + + public void test_string() throws Exception { + char[] chars = new char[1024]; + Arrays.fill(chars, '0'); + StringBuilder buf = new StringBuilder(); + buf.append("[\""); + for (int i = 0; i < 16; ++i) { + buf.append("\\\\"); + buf.append("\\\""); + buf.append(new String(chars)); + } + buf.append("\"]"); + + String text = buf.toString(); + JSONArray array = (JSONArray) JSON.parse(text); + Assert.assertEquals(1, array.size()); + + String item = (String) array.get(0); + Assert.assertEquals(16 * 1024 + 32, item.length()); + + for (int i = 0; i < 16; ++i) { + Assert.assertTrue(item.charAt(i * 1026) == '\\'); + Assert.assertTrue(item.charAt(i * 1026 + 1) == '\"'); + for (int j = 0; j < 1024; ++j) { + Assert.assertTrue(item.charAt(i * 1026 + j + 2) == '0'); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/str/StringTest_02.java b/src/test/java/com/alibaba/json/bvt/parser/str/StringTest_02.java new file mode 100644 index 0000000000..fd07cab5f7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/str/StringTest_02.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.parser.str; + +import java.util.Arrays; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; + +import junit.framework.TestCase; + +public class StringTest_02 extends TestCase { + + public void test_string() throws Exception { + char[] chars = new char[1024]; + Arrays.fill(chars, '0'); + StringBuilder buf = new StringBuilder(); + buf.append("[\""); + for (int i = 0; i < 16; ++i) { + buf.append("\\\""); + buf.append(new String(chars)); + } + buf.append("\"]"); + + String text = buf.toString(); + JSONArray array = (JSONArray) JSON.parse(text); + Assert.assertEquals(1, array.size()); + + String item = (String) array.get(0); + Assert.assertEquals(16 * 1024 + 16, item.length()); + + for (int i = 0; i < 16; ++i) { + Assert.assertTrue(item.charAt(i * 1025) == '\"'); + for (int j = 0; j < 1024; ++j) { + Assert.assertTrue(item.charAt(i * 1025 + j + 1) == '0'); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest.java new file mode 100644 index 0000000000..cc7b9e013e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.parser.stream; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest extends TestCase { + public void test_singleQuote() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{'name':'张三\\'\\n\\r\\\"'}")); + JSONObject json = parser.parseObject(); + Assert.assertEquals("张三\'\n\r\"", json.get("name")); + parser.close(); + } + + public void test_doubleQuote() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"name\":\"张三\\'\\n\\r\\\"\"}")); + JSONObject json = parser.parseObject(); + Assert.assertEquals("张三\'\n\r\"", json.get("name")); + parser.close(); + } + + public void test_doubleQuote_2() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{name:\"张三\\'\\n\\r\\\"\"}")); + JSONObject json = parser.parseObject(); + Assert.assertEquals("张三\'\n\r\"", json.get("name")); + parser.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_boolean.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_boolean.java new file mode 100644 index 0000000000..af20356911 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_boolean.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser.stream; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest_boolean extends TestCase { + public void test_true() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"name\":true}")); + JSONObject json = parser.parseObject(); + Assert.assertEquals(Boolean.TRUE, json.get("name")); + parser.close(); + } + + public void test_false() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"name\":false}")); + JSONObject json = parser.parseObject(); + Assert.assertEquals(Boolean.FALSE, json.get("name")); + parser.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_chars.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_chars.java new file mode 100644 index 0000000000..ae271c78aa --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_chars.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.math.BigDecimal; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest_chars extends TestCase { + + public void test_double() throws Exception { + char[] chars = "{\"value\":3.5D}".toCharArray(); + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner(chars, chars.length)); + JSONObject json = parser.parseObject(); + Assert.assertTrue(3.5D == ((Double) json.get("value")).doubleValue()); + parser.close(); + } + + public void test_float() throws Exception { + char[] chars = "{\"value\":3.5F}".toCharArray(); + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner(chars, chars.length)); + JSONObject json = parser.parseObject(); + Assert.assertTrue(3.5F == ((Float) json.get("value")).doubleValue()); + parser.close(); + } + + public void test_decimal() throws Exception { + char[] chars = "{\"value\":3.5}".toCharArray(); + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner(chars, chars.length)); + JSONObject json = parser.parseObject(); + Assert.assertEquals(new BigDecimal("3.5"), json.get("value")); + parser.close(); + } + + public void test_long() throws Exception { + char[] chars = "{\"value\":3L}".toCharArray(); + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner(chars, chars.length)); + JSONObject json = parser.parseObject(); + Assert.assertTrue(3L == ((Long) json.get("value")).longValue()); + parser.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_enum.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_enum.java new file mode 100644 index 0000000000..02217a7190 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_enum.java @@ -0,0 +1,57 @@ +package com.alibaba.json.bvt.parser.stream; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest_enum extends TestCase { + + public void test_a() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"type\":\"A\"}")); + VO vo = parser.parseObject(VO.class); + Assert.assertEquals(Type.A, vo.getType()); + parser.close(); + } + + public void test_b() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"type\":\"B\"}")); + VO vo = parser.parseObject(VO.class); + Assert.assertEquals(Type.B, vo.getType()); + parser.close(); + } + + public void test_c() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"type\":\"C\"}")); + VO vo = parser.parseObject(VO.class); + Assert.assertEquals(Type.C, vo.getType()); + parser.close(); + } + + public void test_x() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"type\":\"XXXXXXXXXXXXXXXXXXXXXXXX\"}")); + VO vo = parser.parseObject(VO.class); + Assert.assertEquals(Type.XXXXXXXXXXXXXXXXXXXXXXXX, vo.getType()); + parser.close(); + } + + public static class VO { + + private Type type; + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } + + } + + public static enum Type { + A, B, C, D, XXXXXXXXXXXXXXXXXXXXXXXX + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_matchField.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_matchField.java new file mode 100644 index 0000000000..fe6c67846f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_matchField.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest_matchField extends TestCase { + + public void test_true() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"items\":[{}],\"value\":{}}")); + VO vo = parser.parseObject(VO.class); + Assert.assertNotNull(vo.getValue()); + Assert.assertNotNull(vo.getItems()); + Assert.assertEquals(1, vo.getItems().size()); + Assert.assertNotNull(vo.getItems().get(0)); + parser.close(); + } + + public static class VO { + + private List items; + private Entity value; + + public Entity getValue() { + return value; + } + + public void setValue(Entity value) { + this.value = value; + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } + + } + + public static class Entity { + + } + + public static class Item { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_negative.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_negative.java new file mode 100644 index 0000000000..f0443e5dd2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_negative.java @@ -0,0 +1,46 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.math.BigDecimal; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest_negative extends TestCase { + + public void test_double() throws Exception { + char[] chars = "{\"value\":-3.5D}".toCharArray(); + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner(chars, chars.length)); + JSONObject json = parser.parseObject(); + Assert.assertTrue(-3.5D == ((Double) json.get("value")).doubleValue()); + parser.close(); + } + + public void test_float() throws Exception { + char[] chars = "{\"value\":-3.5F}".toCharArray(); + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner(chars, chars.length)); + JSONObject json = parser.parseObject(); + Assert.assertTrue(-3.5F == ((Float) json.get("value")).doubleValue()); + parser.close(); + } + + public void test_decimal() throws Exception { + char[] chars = "{\"value\":-3.5}".toCharArray(); + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner(chars, chars.length)); + JSONObject json = parser.parseObject(); + Assert.assertEquals(new BigDecimal("-3.5"), json.get("value")); + parser.close(); + } + + public void test_long() throws Exception { + char[] chars = "{\"value\":-3L}".toCharArray(); + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner(chars, chars.length)); + JSONObject json = parser.parseObject(); + Assert.assertTrue(-3L == ((Long) json.get("value")).longValue()); + parser.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_type.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_type.java new file mode 100644 index 0000000000..37c2d907ef --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_type.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.util.LinkedHashMap; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONReaderScanner; + +public class JSONReaderScannerTest_type extends TestCase { + @SuppressWarnings("rawtypes") + public void test_true() throws Exception { + DefaultJSONParser parser = new DefaultJSONParser(new JSONReaderScanner("{\"@type\":\"java.util.LinkedHashMap\",\"name\":\"张三\"}")); + LinkedHashMap json = (LinkedHashMap) parser.parse(); + Assert.assertEquals("张三", json.get("name")); + parser.close(); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest.java new file mode 100644 index 0000000000..efa9be9aa9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.InputStream; +import java.io.InputStreamReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONReader; + +public class JSONReaderTest extends TestCase { + public void test_read() throws Exception { + String resource = "2.json"; + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); + + JSONReader reader = new JSONReader(new InputStreamReader(is, "UTF-8")); + + reader.startObject(); + + Assert.assertEquals("company", reader.readString()); + Assert.assertTrue(reader.readObject() instanceof JSONObject); + + Assert.assertEquals("count", reader.readString()); + Assert.assertEquals(5, reader.readObject()); + + Assert.assertEquals("pagecount", reader.readString()); + Assert.assertEquals(0, reader.readObject()); + + Assert.assertEquals("pageindex", reader.readString()); + Assert.assertEquals(0, reader.readObject()); + + Assert.assertEquals("resultList", reader.readString()); + Assert.assertTrue(reader.readObject() instanceof JSONArray); + + Assert.assertEquals("totalCount", reader.readString()); + Assert.assertEquals(0, reader.readObject()); + + reader.endObject(); + + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_0.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_0.java new file mode 100644 index 0000000000..6455ab5cff --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_0.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; + +public class JSONReaderTest_0 extends TestCase { + public void test_read() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{}")); + reader.config(Feature.AllowArbitraryCommas, true); + + JSONObject object = (JSONObject) reader.readObject(); + Assert.assertNotNull(object); + + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_1.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_1.java new file mode 100644 index 0000000000..d9981b65fb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_1.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.JSONToken; + +import junit.framework.TestCase; + +public class JSONReaderTest_1 extends TestCase { + public void test_read() throws Exception { + String text = "{\"id\":1001}"; + JSONReader reader = new JSONReader(new StringReader(text)); + Assert.assertEquals(JSONToken.LBRACE, reader.peek()); + reader.startObject(); + Assert.assertEquals(JSONToken.LITERAL_STRING, reader.peek()); + Assert.assertEquals("id", reader.readString()); + Assert.assertEquals(JSONToken.COLON, reader.peek()); + Assert.assertEquals(Integer.valueOf(1001), reader.readInteger()); + reader.endObject(); + + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_2.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_2.java new file mode 100644 index 0000000000..ac0a9d7674 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_2.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +import junit.framework.TestCase; + +public class JSONReaderTest_2 extends TestCase { + public void test_read_integer() throws Exception { + String text = "1001"; + JSONReader reader = new JSONReader(new StringReader(text)); + Assert.assertEquals(Integer.valueOf(1001), reader.readInteger()); + reader.close(); + } + + public void test_read_Long() throws Exception { + String text = "1001"; + JSONReader reader = new JSONReader(new StringReader(text)); + Assert.assertEquals(Long.valueOf(1001), reader.readLong()); + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_3.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_3.java new file mode 100644 index 0000000000..5252dee98d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_3.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; + +import junit.framework.TestCase; + +public class JSONReaderTest_3 extends TestCase { + + public void test_read_Long() throws Exception { + String text = "1001"; + JSONReader reader = new JSONReader(new StringReader(text)); + + Exception error = null; + try { + reader.hasNext(); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_4.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_4.java new file mode 100644 index 0000000000..9de072cf5d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_4.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; + +import com.alibaba.fastjson.JSONReader; + +import junit.framework.TestCase; + +public class JSONReaderTest_4 extends TestCase { + + public void test_read_Long() throws Exception { + String text = "1001"; + JSONReader reader = new JSONReader(new MyReader(text)); + + } + + public static class MyReader extends BufferedReader { + + public MyReader(String s){ + super(new StringReader(s)); + } + + public void close() throws IOException { + throw new IOException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_error.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_error.java new file mode 100644 index 0000000000..a03363289c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_error.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; +import java.lang.reflect.Field; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; + +public class JSONReaderTest_error extends TestCase { + + public void test_read() throws Exception { + Field field = JSONReader.class.getDeclaredField("context"); + field.setAccessible(true); + ; + + JSONReader reader = new JSONReader(new StringReader("[{}]")); + reader.config(Feature.AllowArbitraryCommas, true); + + reader.startArray(); + + Object context = field.get(reader); + Field stateField = context.getClass().getDeclaredField("state"); + stateField.setAccessible(true); + stateField.set(context, -1); + + { + Exception error = null; + try { + reader.startObject(); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + { + Exception error = null; + try { + reader.readInteger(); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_error2.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_error2.java new file mode 100644 index 0000000000..b843a89fe0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_error2.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; +import java.lang.reflect.Field; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.parser.Feature; + +public class JSONReaderTest_error2 extends TestCase { + private static Object context; + private static Field stateField; + + public void test_read() throws Exception { + Field field = JSONReader.class.getDeclaredField("context"); + field.setAccessible(true); + ; + + JSONReader reader = new JSONReader(new StringReader("[{}]")); + reader.config(Feature.AllowArbitraryCommas, true); + + reader.startArray(); + + context = field.get(reader); + stateField = context.getClass().getDeclaredField("state"); + stateField.setAccessible(true); + + + { + Exception error = null; + try { + reader.readObject(VO.class); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + } + + public static class VO { + public VO() { + try { + stateField.set(context, -1); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_array.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_array.java new file mode 100644 index 0000000000..8a2c4f7f5f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_array.java @@ -0,0 +1,61 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONReader; + +public class JSONReader_array extends TestCase { + + public void test_array() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[[],[],3,null,{\"name\":\"jobs\"},{\"id\":123},{\"id\":1},{\"id\":2}]")); + reader.startArray(); + + JSONArray first = (JSONArray) reader.readObject(); + JSONArray second = (JSONArray) reader.readObject(); + + Assert.assertNotNull(first); + Assert.assertNotNull(second); + + Assert.assertEquals(new Integer(3), reader.readInteger()); + Assert.assertNull(reader.readString()); + + { + Map map = new HashMap(); + reader.readObject(map); + Assert.assertEquals("jobs", map.get("name")); + } + + { + VO vo = new VO(); + reader.readObject(vo); + Assert.assertEquals(123, vo.getId()); + } + + while (reader.hasNext()) { + VO vo = reader.readObject(VO.class); + Assert.assertNotNull(vo); + } + reader.endArray(); + reader.close(); + } + + public static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_map.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_map.java new file mode 100644 index 0000000000..797d2970d5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_map.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReader_map extends TestCase { + + public void test_array() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[{\"id\":123}]")); + + reader.startArray(); + + Map map = new HashMap(); + reader.readObject(map); + + Assert.assertEquals(123, map.get("id")); + + reader.endArray(); + + reader.close(); + } + + public void test_map() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"id\":123}")); + + Map map = new HashMap(); + reader.readObject(map); + + Assert.assertEquals(123, map.get("id")); + + reader.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj.java new file mode 100644 index 0000000000..c9f8ba5471 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReader_obj extends TestCase { + + public void test_array() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[{\"id\":123}]")); + + reader.startArray(); + + VO vo = new VO(); + reader.readObject(vo); + + Assert.assertEquals(123, vo.getId()); + + reader.endArray(); + + reader.close(); + } + + public void test_obj() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"id\":123}")); + + VO vo = new VO(); + reader.readObject(vo); + + Assert.assertEquals(123, vo.getId()); + + reader.close(); + } + + public static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj_2.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj_2.java new file mode 100644 index 0000000000..d6585f874b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj_2.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReader_obj_2 extends TestCase { + + public void test_array() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[{\"id\":123}]")); + + reader.startArray(); + + VO vo = reader.readObject(VO.class); + + Assert.assertEquals(123, vo.getId()); + + reader.endArray(); + + reader.close(); + } + + public void test_obj() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"id\":123}")); + + VO vo = reader.readObject(VO.class); + + Assert.assertEquals(123, vo.getId()); + + reader.close(); + } + + public static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj_3.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj_3.java new file mode 100644 index 0000000000..e50a7e727b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj_3.java @@ -0,0 +1,61 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReader_obj_3 extends TestCase { + + public void test_obj() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"id\":123}")); + + reader.startObject(); + Assert.assertEquals("id", reader.readString()); + Assert.assertEquals(Integer.valueOf(123), reader.readInteger()); + reader.endObject(); + + reader.close(); + } + + public void test_obj_2() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"val\":{\"id\":123}}")); + + reader.startObject(); + + Assert.assertEquals("val", reader.readString()); + + reader.startObject(); + Assert.assertEquals("id", reader.readString()); + Assert.assertEquals(Integer.valueOf(123), reader.readInteger()); + reader.endObject(); + + reader.endObject(); + + reader.close(); + } + + public void test_obj_3() throws Exception { + JSONReader reader = new JSONReader(new StringReader("{\"val\":{\"val\":{\"id\":123}}}")); + + reader.startObject(); + Assert.assertEquals("val", reader.readString()); + + reader.startObject(); + Assert.assertEquals("val", reader.readString()); + + reader.startObject(); + Assert.assertEquals("id", reader.readString()); + Assert.assertEquals(Long.valueOf(123), reader.readLong()); + reader.endObject(); + + reader.endObject(); + reader.endObject(); + + reader.close(); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_string.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_string.java new file mode 100644 index 0000000000..04ca62c304 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_string.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReader_string extends TestCase { + + public void test_array() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[\"abc\"]")); + + reader.startArray(); + + Assert.assertEquals("abc", reader.readString()); + + reader.endArray(); + + reader.close(); + } + + public void test_array_2() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[[\"abc\"]]")); + + reader.startArray(); + reader.startArray(); + + Assert.assertEquals("abc", reader.readString()); + + reader.endArray(); + reader.endArray(); + + reader.close(); + } + + public void test_array_3() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[[[\"abc\"]]]")); + + reader.startArray(); + reader.startArray(); + reader.startArray(); + + Assert.assertEquals("abc", reader.readString()); + + reader.endArray(); + reader.endArray(); + reader.endArray(); + + reader.close(); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_string_1.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_string_1.java new file mode 100644 index 0000000000..dfe75b1ed7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_string_1.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; + +public class JSONReader_string_1 extends TestCase { + public void test_obj() throws Exception { + JSONReader reader = new JSONReader(new StringReader("\"abc\"")); + + Assert.assertEquals("abc", reader.readString()); + + reader.close(); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_typeRef.java b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_typeRef.java new file mode 100644 index 0000000000..b16b8dcae6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_typeRef.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.parser.stream; + +import java.io.StringReader; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; + +public class JSONReader_typeRef extends TestCase { + public void test_array() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[{\"id\":123}]")); + + List list = reader.readObject(new TypeReference>() {}.getType()); + + Assert.assertEquals(123, list.get(0).getId()); + + reader.close(); + } + + public void test_array_1() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[[{\"id\":123}]]")); + + reader.startArray(); + List list = reader.readObject(new TypeReference>() {}.getType()); + + Assert.assertEquals(123, list.get(0).getId()); + + reader.endArray(); + + reader.close(); + } + + public void test_array_2() throws Exception { + JSONReader reader = new JSONReader(new StringReader("[[{\"id\":123}]]")); + + reader.startArray(); + List list = reader.readObject(new TypeReference>() {}); + + Assert.assertEquals(123, list.get(0).getId()); + + reader.endArray(); + + reader.close(); + } + + public static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/taobao/BooleanObjectFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/taobao/BooleanObjectFieldTest.java new file mode 100644 index 0000000000..e1ae55bda3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/taobao/BooleanObjectFieldTest.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.parser.taobao; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class BooleanObjectFieldTest extends TestCase { + public void test_0 () throws Exception { + VO vo = JSON.parseObject("{\"value\":true}", VO.class); + Assert.assertTrue(vo.value); + } + + public static class VO { + public Boolean value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/taobao/DoubleObjectFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/taobao/DoubleObjectFieldTest.java new file mode 100644 index 0000000000..2be165e82e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/taobao/DoubleObjectFieldTest.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.parser.taobao; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class DoubleObjectFieldTest extends TestCase { + public void test_0 () throws Exception { + VO vo = JSON.parseObject("{\"value\":1001}", VO.class); + Assert.assertTrue(1001D == vo.value); + } + + public static class VO { + public Double value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/taobao/FloatObjectFieldTest.java b/src/test/java/com/alibaba/json/bvt/parser/taobao/FloatObjectFieldTest.java new file mode 100644 index 0000000000..3b82062330 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/taobao/FloatObjectFieldTest.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.parser.taobao; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class FloatObjectFieldTest extends TestCase { + public void test_0 () throws Exception { + VO vo = JSON.parseObject("{\"value\":1001}", VO.class); + Assert.assertTrue(1001F == vo.value); + } + + public static class VO { + public Float value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/taobao/IntAsStringTest.java b/src/test/java/com/alibaba/json/bvt/parser/taobao/IntAsStringTest.java new file mode 100644 index 0000000000..63f30a6851 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/taobao/IntAsStringTest.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.parser.taobao; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class IntAsStringTest extends TestCase { + public void test_0 () throws Exception { + VO vo = JSON.parseObject("{\"value\":\"1001\"}", VO.class); + Assert.assertEquals(1001, vo.value); + } + + public static class VO { + public int value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/taobao/IntegerAsStringTest.java b/src/test/java/com/alibaba/json/bvt/parser/taobao/IntegerAsStringTest.java new file mode 100644 index 0000000000..c99be27ec0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/taobao/IntegerAsStringTest.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.parser.taobao; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class IntegerAsStringTest extends TestCase { + public void test_0 () throws Exception { + VO vo = JSON.parseObject("{\"value\":\"1001\"}", VO.class); + Assert.assertEquals(1001, vo.value.intValue()); + } + + public static class VO { + public Integer value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/taobao/LongAsStringTest.java b/src/test/java/com/alibaba/json/bvt/parser/taobao/LongAsStringTest.java new file mode 100644 index 0000000000..30527f9db6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/taobao/LongAsStringTest.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.parser.taobao; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class LongAsStringTest extends TestCase { + public void test_0 () throws Exception { + VO vo = JSON.parseObject("{\"value\":\"1001\"}", VO.class); + Assert.assertEquals(1001L, vo.value); + } + + public static class VO { + public long value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/taobao/LongObjectAsStringTest.java b/src/test/java/com/alibaba/json/bvt/parser/taobao/LongObjectAsStringTest.java new file mode 100644 index 0000000000..1c37e132ea --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/taobao/LongObjectAsStringTest.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.parser.taobao; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class LongObjectAsStringTest extends TestCase { + public void test_0 () throws Exception { + VO vo = JSON.parseObject("{\"value\":\"1001\"}", VO.class); + Assert.assertEquals(1001, vo.value.intValue()); + } + + public static class VO { + public Long value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/parser/taobao/SpecialStringTest.java b/src/test/java/com/alibaba/json/bvt/parser/taobao/SpecialStringTest.java new file mode 100644 index 0000000000..06f5d1c238 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/parser/taobao/SpecialStringTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.parser.taobao; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class SpecialStringTest extends TestCase { + public void test_for_special() throws Exception { + VO vo = new VO(); + vo.value = "{\"aurl\""; + String text = JSON.toJSONString(vo); + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertEquals(vo1.value, vo.value); + } + + public void test_for_special_1() throws Exception { + VO vo = new VO(); + vo.value = "{\"aurl\":\"http://a.m.taobao.com/i529666038203.htm\",\"eurl\":\"http://click.mz.simba.taobao.com/ecpm?e=FKzStLpktUcmgME64bmjnBsQmLP5zomMI9WwdvViswDtdMUS1TLPryFiqQmsaUcblU3hrUulblXi4Nf5jVnFI3mESrWAJFi8UK7RDtIZydUyXElRAMLwo3HZWQvTKXBpyitB%2BgALy7j45JkIPnsiapEFjIWbdXJAnae9i5WIlhTnQ%2FthEaQ9IuT5J4gzB5T%2FcKP7YijzmvIZWnX1fL8Wv2yOkjnv1RfOuAwHNITyYhs0036Nbzw1rue9DcuU1VaInAsdAQs%2BcFbs41NPY6%2FbqjqRHfjhCyty&u=http%3A%2F%2Fa.m.taobao.com%2Fi529666038203.htm&k=289\",\"tbgoodslink\":\"http://i.mmcdn.cn/simba/img/TB120WTMpXXXXazXXXXSutbFXXX.jpg\",\"tmpl\":\"\"}"; + String text = JSON.toJSONString(vo); + VO vo1 = JSON.parseObject(text, VO.class); + Assert.assertEquals(vo1.value, vo.value); + } + + public static class VO { + public String value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/DeepScanTest.java b/src/test/java/com/alibaba/json/bvt/path/DeepScanTest.java new file mode 100644 index 0000000000..000c7262bb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/DeepScanTest.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.path; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +import java.util.List; + +/** + * Created by wenshao on 30/07/2017. + */ +public class DeepScanTest extends TestCase { + public void test_when_deep_scanning_illegal_property_access_is_ignored() { + Object result = JSONPath.eval( + JSON.parseObject("{\"x\": {\"foo\": {\"bar\": 4}}, \"y\": {\"foo\": 1}}") + , "$..foo"); + assertEquals(2, ((List) result).size()); + + result = JSONPath.eval( + JSON.parseObject("{\"x\": {\"foo\": {\"bar\": 4}}, \"y\": {\"foo\": 1}}") + , "$..foo.bar"); + assertEquals(1, ((List) result).size()); + assertEquals(4, ((List) result).get(0)); + + result = JSONPath.eval( + JSON.parseObject("{\"x\": {\"foo\": {\"bar\": 4}}, \"y\": {\"foo\": 1}}") + , "$..[*].foo.bar"); + assertEquals(1, ((List) result).size()); + assertEquals(4, ((List) result).get(0)); + + result = JSONPath.eval( + JSON.parseObject("{\"x\": {\"foo\": {\"baz\": 4}}, \"y\": {\"foo\": 1}}") + , "$..[*].foo.bar"); + assertTrue(((List) result).isEmpty()); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_0.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_0.java new file mode 100644 index 0000000000..6c8d39fef9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_0.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.path; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_0 extends TestCase { + + public void test_root() throws Exception { + Object obj = new Object(); + Assert.assertSame(obj, new JSONPath("$").eval(obj)); + } + + public void test_null() throws Exception { + Assert.assertNull(new JSONPath("$").eval(null)); + } + + public void test_map() throws Exception { + Map map = new HashMap(); + map.put("val", new Object()); + Assert.assertSame(map.get("val"), new JSONPath("$.val").eval(map)); + } + + public void test_entity() throws Exception { + Entity entity = new Entity(); + entity.setValue(new Object()); + Assert.assertSame(entity.getValue(), new JSONPath("$.value").eval(entity)); + } + + public static class Entity { + + private Object value; + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_1.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_1.java new file mode 100644 index 0000000000..4c21e428f1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_1.java @@ -0,0 +1,41 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; +import com.alibaba.fastjson.JSONPathException; + +import junit.framework.TestCase; + +public class JSONPath_1 extends TestCase { + + public void test_path_empty() throws Exception { + Throwable error = null; + try { + JSONPath.compile(""); + } catch (JSONPathException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_path_null() throws Exception { + Throwable error = null; + try { + JSONPath.compile(null); + } catch (JSONPathException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_path_null_1() throws Exception { + Throwable error = null; + try { + new JSONPath(null); + } catch (JSONPathException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_2.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_2.java new file mode 100644 index 0000000000..9a21632b70 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_2.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_2 extends TestCase { + public void test_path() throws Exception { + String json ="{\"user\":[{\"amount\":1.11,\"isadmin\":true,\"age\":18},{\"amount\":0.22,\"isadmin\":false,\"age\":28}]}"; + + + { + JSONArray array = (JSONArray) JSONPath.read(json, "$.user"); + Assert.assertEquals(2, array.size()); + + Assert.assertTrue(1.11D == array.getJSONObject(0).getDoubleValue("amount")); + Assert.assertTrue(array.getJSONObject(0).getBoolean("isadmin")); + Assert.assertTrue(18 == array.getJSONObject(0).getIntValue("age")); + + Assert.assertTrue(0.22D == array.getJSONObject(1).getDoubleValue("amount")); + Assert.assertFalse(array.getJSONObject(1).getBoolean("isadmin")); + Assert.assertTrue(28 == array.getJSONObject(1).getIntValue("age")); + } + + { + JSONArray array = (JSONArray) JSONPath.read(json, "$.user[age = 18]"); + Assert.assertEquals(1, array.size()); + + Assert.assertTrue(1.11D == array.getJSONObject(0).getDoubleValue("amount")); + Assert.assertTrue(array.getJSONObject(0).getBoolean("isadmin")); + Assert.assertTrue(18 == array.getJSONObject(0).getIntValue("age")); + } + + { + JSONArray array = (JSONArray) JSONPath.read(json, "$.user[isadmin = true]"); + Assert.assertEquals(1, array.size()); + + Assert.assertTrue(1.11D == array.getJSONObject(0).getDoubleValue("amount")); + Assert.assertTrue(array.getJSONObject(0).getBoolean("isadmin")); + Assert.assertTrue(18 == array.getJSONObject(0).getIntValue("age")); + } + + { + JSONArray array = (JSONArray) JSONPath.read(json, "$.user[isadmin = false]"); + Assert.assertEquals(1, array.size()); + + Assert.assertTrue(0.22D == array.getJSONObject(0).getDoubleValue("amount")); + Assert.assertFalse(array.getJSONObject(0).getBoolean("isadmin")); + Assert.assertTrue(28 == array.getJSONObject(0).getIntValue("age")); + } + + { + JSONArray array = (JSONArray) JSONPath.read(json, "$.user[amount = 0.22]"); + Assert.assertEquals(1, array.size()); + + Assert.assertTrue(0.22D == array.getJSONObject(0).getDoubleValue("amount")); + Assert.assertFalse(array.getJSONObject(0).getBoolean("isadmin")); + Assert.assertTrue(28 == array.getJSONObject(0).getIntValue("age")); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_3.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_3.java new file mode 100644 index 0000000000..b0b93dbcab --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_3.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_3 extends TestCase { + public void test_path() throws Exception { + String a = "{\"a\":{\"b\":{\"c\":{\"d\":{\"e\":{\"f\":{\"g\":{\"h\":{\"i\":{\"j\":{\"k\":{\"l\":\"\"}}}}}}}}}}}}"; + Object x = JSON.parse(a); + Assert.assertTrue(JSONPath.contains(x, "$.a.b.c.d.e.f.g.h.i")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_4.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_4.java new file mode 100644 index 0000000000..7186b71713 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_4.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_4 extends TestCase { + + public void test_path() throws Exception { + String a = "{\"key\":\"value\",\"10.0.1.1\":\"haha\"}"; + Object x = JSON.parse(a); + JSONPath.set(x, "$.test", "abc"); + Object o = JSONPath.eval(x, "$.10\\.0\\.1\\.1"); + Assert.assertEquals("haha", o); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_5.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_5.java new file mode 100644 index 0000000000..5f86f701f4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_5.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.path; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.ArrayList; +import java.util.List; + +public class JSONPath_5 extends TestCase { + + public void test_path() throws Exception { + Model m = new Model(); + Value v = new Value(m); + m.values.add(v); + m.values.add(m.values); + m.values.add(m); + + String json = JSON.toJSONString(m); + System.out.println(json); + } + + public static class Model { + public List values = new ArrayList(); + } + + public static class Value { + public Model model = new Model(); + + public Value() { + + } + + public Value(Model model) { + this.model = model; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_length.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_length.java new file mode 100644 index 0000000000..a383f1bc2f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_length.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.path; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.Collections; + +public class JSONPath_array_length extends TestCase { + public void test_list_size() throws Exception { + Assert.assertEquals(0, JSONPath.eval(new JSONArray(), "$.length")); + } + + public void test_list_size1() throws Exception { + Assert.assertEquals(0, JSONPath.eval(new Object[0], "$.length()")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_multi.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_multi.java new file mode 100644 index 0000000000..3cffeb6b47 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_multi.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_array_multi extends TestCase { + + Object[] list = new Object[10]; + + public JSONPath_array_multi(){ + for (int i = 0; i < list.length; ++i) { + list[i] = new Object(); + } + } + + public void test_list_multi() throws Exception { + List result = (List) new JSONPath("$[2,4,5,8,100]").eval(list); + Assert.assertEquals(5, result.size()); + Assert.assertSame(list[2], result.get(0)); + Assert.assertSame(list[4], result.get(1)); + Assert.assertSame(list[5], result.get(2)); + Assert.assertSame(list[8], result.get(3)); + Assert.assertNull(result.get(4)); + } + + public void test_list_multi_negative() throws Exception { + List result = (List) new JSONPath("$[-1,-2,-100]").eval(list); + Assert.assertEquals(3, result.size()); + Assert.assertSame(list[9], result.get(0)); + Assert.assertSame(list[8], result.get(1)); + Assert.assertNull(result.get(2)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_put.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_put.java new file mode 100644 index 0000000000..0b527fd609 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_put.java @@ -0,0 +1,102 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_array_put extends TestCase { + + public void test_put() throws Exception { + Map root = new HashMap(); + List list = new ArrayList(); + root.put("values", list); + + JSONPath path = new JSONPath("$.values"); + path.arrayAdd(root, 123); + path.arrayAdd(root, (Object[]) null); + path.arrayAdd(root, new Object[0]); + path.arrayAdd(null, new Object[] { 1 }); + + Assert.assertEquals(1, list.size()); + Assert.assertEquals(123, ((Integer) list.get(0)).intValue()); + } + + public void test_set() throws Exception { + List list = new ArrayList(); + list.add(new int[0]); + list.add(new int[0]); + + JSONPath path = new JSONPath("$[0]"); + path.arrayAdd(list, 123); + + Assert.assertEquals(1, list.get(0).length); + Assert.assertEquals(123, ((int[]) list.get(0))[0]); + } + + public void test_set_2() throws Exception { + Object[] list = new Object[2]; + list[0] = new int[0]; + list[0] = new int[0]; + + JSONPath path = new JSONPath("$[0]"); + path.arrayAdd(list, 123); + + Assert.assertEquals(1, ((int[]) list[0]).length); + Assert.assertEquals(123, ((int[]) list[0])[0]); + } + + public void test_put_array_int() throws Exception { + Map root = new HashMap(); + root.put("values", new int[0]); + + JSONPath path = new JSONPath("$.values"); + path.arrayAdd(root, 123); + + int[] array = (int[]) root.get("values"); + Assert.assertEquals(1, array.length); + Assert.assertEquals(123, array[0]); + } + + public void test_put_array_long() throws Exception { + Map root = new HashMap(); + root.put("values", new long[0]); + + JSONPath path = new JSONPath("$.values"); + path.arrayAdd(root, 123); + + long[] array = (long[]) root.get("values"); + Assert.assertEquals(1, array.length); + Assert.assertEquals(123, array[0]); + } + + public void test_put_array_error_0() throws Exception { + Exception error = null; + try { + JSONPath path = new JSONPath("$.values"); + path.arrayAdd(new Object(), 123); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_put_array_error_1() throws Exception { + Exception error = null; + try { + JSONPath path = new JSONPath("$.values"); + path.arrayAdd(Collections.singletonMap("values", new Object()), 123); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_put_2.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_put_2.java new file mode 100644 index 0000000000..e866241d68 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_put_2.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_array_put_2 extends TestCase { + + public void test_put() throws Exception { + Map root = new HashMap(); + List list = new ArrayList(); + root.put("values", list); + + JSONPath.arrayAdd(root, "$.values", 1, 2,3 ); + + Assert.assertEquals(3, list.size()); + Assert.assertEquals(1, ((Integer) list.get(0)).intValue()); + Assert.assertEquals(2, ((Integer) list.get(1)).intValue()); + Assert.assertEquals(3, ((Integer) list.get(2)).intValue()); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_remove_0.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_remove_0.java new file mode 100644 index 0000000000..3303b24154 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_array_remove_0.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.path; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; + +/** + * Created by wenshao on 09/03/2017. + */ +public class JSONPath_array_remove_0 extends TestCase { + public void test_remove() throws Exception { + JSONObject jsonObject = new JSONObject(); + + JSONArray array = new JSONArray(); + for (int i = 0; i < 10; ++i) { + JSONObject item = new JSONObject(); + item.put("age", i); + array.add(item); + } + jsonObject.put("aaa", array); + + JSONPath.remove(jsonObject, "$.aaa[0:1].age"); //解析出错 + JSONPath.remove(jsonObject, "$.aaa[0,1].age"); //解析出错 + JSONPath.remove(jsonObject, "$.aaa[0].age"); //解析正确 + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_between_int.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_between_int.java new file mode 100644 index 0000000000..3b9aa207a1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_between_int.java @@ -0,0 +1,71 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_between_int extends TestCase { + public void test_between() throws Exception { + List list = new ArrayList(); + list.add(new Entity(101, "kiki")); + list.add(new Entity(102, "ljw2083")); + list.add(new Entity(103, "ljw2083")); + List result = (List) JSONPath.eval(list, "$[id between 101 and 101]"); + Assert.assertEquals(1, result.size()); + Assert.assertSame(list.get(0), result.get(0)); + } + + public void test_between_2() throws Exception { + List list = new ArrayList(); + list.add(new Entity(101, "kiki")); + list.add(new Entity(102, "ljw2083")); + list.add(new Entity(103, "ljw2083")); + List result = (List) JSONPath.eval(list, "$[id between 101 and 102]"); + Assert.assertEquals(2, result.size()); + Assert.assertSame(list.get(0), result.get(0)); + Assert.assertSame(list.get(1), result.get(1)); + } + + public void test_between_not() throws Exception { + List list = new ArrayList(); + list.add(new Entity(101, "kiki")); + list.add(new Entity(102, "ljw2083")); + list.add(new Entity(103, "ljw2083")); + List result = (List) JSONPath.eval(list, "$[id not between 101 and 102]"); + Assert.assertEquals(1, result.size()); + Assert.assertSame(list.get(2), result.get(0)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_calenar_test.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_calenar_test.java new file mode 100644 index 0000000000..f9d0a5e568 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_calenar_test.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.path; + +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; + +public class JSONPath_calenar_test extends TestCase { + public void test_map() throws Exception { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.YEAR, 2017); + calendar.set(Calendar.MONTH, 6); + calendar.set(Calendar.DAY_OF_MONTH, 30); + + calendar.set(Calendar.HOUR_OF_DAY, 16); + calendar.set(Calendar.MINUTE, 8); + calendar.set(Calendar.SECOND, 43); + + assertEquals(2017, JSONPath.eval(calendar, "/year")); + assertEquals(6, JSONPath.eval(calendar, "/month")); + assertEquals(30, JSONPath.eval(calendar, "/day")); + + assertEquals(16, JSONPath.eval(calendar, "/hour")); + assertEquals(8, JSONPath.eval(calendar, "/minute")); + assertEquals(43, JSONPath.eval(calendar, "/second")); + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_conatinas_null.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_conatinas_null.java new file mode 100644 index 0000000000..65ce145473 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_conatinas_null.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.path; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class JSONPath_conatinas_null extends TestCase { + public void test_null() throws Exception { + Map map = new HashMap(); + map.put("a", null); + map.put("b", "1"); + + String x = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue); + System.out.println(x); + + JSONObject jsonObject = JSON.parseObject(x); + System.out.println(JSONPath.contains(jsonObject, "$.a") + "\t" + jsonObject.containsKey("a")); + System.out.println(JSONPath.contains(jsonObject, "$.b") + "\t" + jsonObject.containsKey("b")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue.java new file mode 100644 index 0000000000..d1c8fe9af8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue.java @@ -0,0 +1,36 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_containsValue extends TestCase { + public void test_root() throws Exception { + List list = new ArrayList(); + list.add("kiki"); + list.add("ljw2083"); + list.add("wenshao"); + + Assert.assertTrue(JSONPath.containsValue(list, "/0", "kiki")); + Assert.assertFalse(JSONPath.containsValue(list, "/0", "kiki_")); + + Assert.assertTrue(JSONPath.containsValue(list, "/", "kiki")); + Assert.assertFalse(JSONPath.containsValue(list, "/", "kiki_")); + + + Assert.assertTrue(JSONPath.contains(list, "/")); + Assert.assertTrue(JSONPath.contains(list, "/0")); + Assert.assertTrue(JSONPath.contains(list, "/1")); + Assert.assertTrue(JSONPath.contains(list, "/2")); + Assert.assertFalse(JSONPath.contains(list, "/3")); + Assert.assertFalse(JSONPath.contains(null, "$")); + Assert.assertFalse(JSONPath.compile("$").contains(null)); + Assert.assertFalse(JSONPath.containsValue(null, "$", "kiki")); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_2.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_2.java new file mode 100644 index 0000000000..923d44a235 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_2.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_containsValue_2 extends TestCase { + public void test_root() throws Exception { + Model model = new Model(); + model.value = 1001; + + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001L)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", (short) 1001)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001F)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001D)); + + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002L)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", (short) 1002)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002F)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002D)); + } + + public static class Model { + public int value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_bigdecimal.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_bigdecimal.java new file mode 100644 index 0000000000..141dc7ca55 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_bigdecimal.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.path; + +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_containsValue_bigdecimal extends TestCase { + public void test_root() throws Exception { + Model model = new Model(); + model.value = new BigDecimal("1001"); + + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001L)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", (short) 1001)); + + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002L)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", (short) 1002)); + } + + public static class Model { + public BigDecimal value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_biginteger.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_biginteger.java new file mode 100644 index 0000000000..c0e7609579 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_biginteger.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.path; + +import java.math.BigInteger; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_containsValue_biginteger extends TestCase { + public void test_root() throws Exception { + Model model = new Model(); + model.value = new BigInteger("1001"); + + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001L)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", (short) 1001)); + + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002L)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", (short) 1002)); + } + + public static class Model { + public BigInteger value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_double.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_double.java new file mode 100644 index 0000000000..4e6d0fa2ca --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_double.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_containsValue_double extends TestCase { + public void test_root() throws Exception { + Model model = new Model(); + model.value = 1001D; + + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001L)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", (short) 1001)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001F)); + Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001D)); + + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002L)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", (short) 1002)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002F)); + Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002D)); + } + + public static class Model { + public double value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_deepScan_test.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_deepScan_test.java new file mode 100644 index 0000000000..d8e67d2e8d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_deepScan_test.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.path; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_deepScan_test extends TestCase { + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void test_0() throws Exception { + Map root = Collections.singletonMap("company", // + Collections.singletonMap("departs", // + Arrays.asList( // + Collections.singletonMap("id", + 1001), // + Collections.singletonMap("id", + 1002), // + Collections.singletonMap("id", 1003) // + ) // + )); + + List ids = (List) JSONPath.eval(root, "$..id"); + Assert.assertEquals(3, ids.size()); + Assert.assertEquals(1001, ids.get(0)); + Assert.assertEquals(1002, ids.get(1)); + Assert.assertEquals(1003, ids.get(2)); + } + + public static class Root { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_deepScan_test2.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_deepScan_test2.java new file mode 100644 index 0000000000..59d073e075 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_deepScan_test2.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_deepScan_test2 extends TestCase { + + @SuppressWarnings({"unchecked" }) + public void test_0() throws Exception { + + Root root = new Root(); + root.company = new Company(); + root.company.departs.add(new Department(1001)); + root.company.departs.add(new Department(1002)); + root.company.departs.add(new Department(1003)); + + + List ids = (List) JSONPath.eval(root, "$..id"); + Assert.assertEquals(3, ids.size()); + Assert.assertEquals(1001, ids.get(0)); + Assert.assertEquals(1002, ids.get(1)); + Assert.assertEquals(1003, ids.get(2)); + } + + public static class Root { + public Company company; + } + + public static class Company { + public List departs = new ArrayList(); + } + + public static class Department { + public int id; + + public Department() { + + } + + public Department(int id) { + this.id = id; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_enum.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_enum.java new file mode 100644 index 0000000000..4694a95539 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_enum.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_enum extends TestCase { + + public void test_name() throws Exception { + Model model = new Model(); + model.size = Size.Small; + + Assert.assertEquals(Size.Small.name(), JSONPath.eval(model, "$.size.name")); + } + + public void test_orginal() throws Exception { + Model model = new Model(); + model.size = Size.Small; + + Assert.assertEquals(Size.Small.ordinal(), JSONPath.eval(model, "$.size.ordinal")); + } + + public static class Model { + public Size size; + } + + public static enum Size { + Big, Median, Small + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access.java new file mode 100644 index 0000000000..ac68514210 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.path; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access extends TestCase { + + public void test_list_map() throws Exception { + Entity entity = new Entity(123, "wenshao"); + JSONPath path = new JSONPath("$['id']"); + + Assert.assertSame(entity.getId(), path.eval(entity)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_int.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_int.java new file mode 100644 index 0000000000..68e8a03a83 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_int.java @@ -0,0 +1,84 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access_filter_compare_int extends TestCase { + + List entities = new ArrayList(); + + public JSONPath_field_access_filter_compare_int(){ + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + } + + public void test_list_map_le() throws Exception { + JSONPath path = new JSONPath("$[?(@.id <= 1002)]"); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + } + + public void test_list_map_lt() throws Exception { + JSONPath path = new JSONPath("$[?(@.id < 1002)]"); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_map_ge() throws Exception { + JSONPath path = new JSONPath("$[?(@.id >= 1002)]"); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + } + + public void test_list_map_gt() throws Exception { + JSONPath path = new JSONPath("$[?(@.id > 1002)]"); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(2), result.get(0)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_int_simple.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_int_simple.java new file mode 100644 index 0000000000..0ba094c666 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_int_simple.java @@ -0,0 +1,71 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access_filter_compare_int_simple extends TestCase { + + public void test_list() throws Exception { + JSONPath path = new JSONPath("$[id <= 1002]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + } + + public void test_list_2() throws Exception { + JSONPath path = new JSONPath("[id <= 1002]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_string.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_string.java new file mode 100644 index 0000000000..75d98aca97 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_string.java @@ -0,0 +1,157 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access_filter_compare_string extends TestCase { + + public void test_list_eq() throws Exception { + JSONPath path = new JSONPath("$[?(@.name = 'ljw2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_eq_x() throws Exception { + JSONPath path = new JSONPath("$[?(name = 'ljw2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_eq_null() throws Exception { + JSONPath path = new JSONPath("$[?(@.name = null)]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(2), result.get(0)); + Assert.assertSame(entities.get(3), result.get(1)); + } + + public void test_list_not_null() throws Exception { + JSONPath path = new JSONPath("$[?(@.name != null)]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + } + + public void test_list_gt() throws Exception { + JSONPath path = new JSONPath("$[?(@.name > 'ljw2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + } + + public void test_list_ge() throws Exception { + JSONPath path = new JSONPath("$[?(@.name >= 'ljw2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + } + + public void test_list_lt() throws Exception { + JSONPath path = new JSONPath("$[?(@.name < 'wenshao')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_le() throws Exception { + JSONPath path = new JSONPath("$[?(@.name <= 'wenshao')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_string_simple.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_string_simple.java new file mode 100644 index 0000000000..a8f5e9be1e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_string_simple.java @@ -0,0 +1,157 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access_filter_compare_string_simple extends TestCase { + + public void test_list_eq() throws Exception { + JSONPath path = new JSONPath("[name = 'ljw2083']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_eq_x() throws Exception { + JSONPath path = new JSONPath("[name = 'ljw2083']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_eq_null() throws Exception { + JSONPath path = new JSONPath("$[name = null]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(2), result.get(0)); + Assert.assertSame(entities.get(3), result.get(1)); + } + + public void test_list_not_null() throws Exception { + JSONPath path = new JSONPath("$[name != null]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + } + + public void test_list_gt() throws Exception { + JSONPath path = new JSONPath("$[name > 'ljw2083']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + } + + public void test_list_ge() throws Exception { + JSONPath path = new JSONPath("$[name >= 'ljw2083']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + } + + public void test_list_lt() throws Exception { + JSONPath path = new JSONPath("$[?(@.name < 'wenshao')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_le() throws Exception { + JSONPath path = new JSONPath("$[name <= 'wenshao']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_in_int.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_in_int.java new file mode 100644 index 0000000000..75c8c85a6e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_in_int.java @@ -0,0 +1,135 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access_filter_in_int extends TestCase { + + public void test_list_in() throws Exception { + JSONPath path = new JSONPath("[id in (1001)]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(1004, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_not_in() throws Exception { + JSONPath path = new JSONPath("[id not in (1001)]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(1004, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(3, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + Assert.assertSame(entities.get(3), result.get(2)); + } + + public void test_list_not_in_null() throws Exception { + JSONPath path = new JSONPath("[id not in (null)]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(1004, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(4, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + Assert.assertSame(entities.get(2), result.get(2)); + Assert.assertSame(entities.get(3), result.get(3)); + } + + public void test_list_in_2() throws Exception { + JSONPath path = new JSONPath("[id in (1001, 1003)]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(1004, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + } + + public void test_list_in_3() throws Exception { + JSONPath path = new JSONPath("[id in (1001, 1003, 1004)]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(1004, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(3, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + Assert.assertSame(entities.get(3), result.get(2)); + } + + public void test_list_in_3_null() throws Exception { + JSONPath path = new JSONPath("[id in (1001, 1003, null)]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(3, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + Assert.assertSame(entities.get(3), result.get(2)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_in_string.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_in_string.java new file mode 100644 index 0000000000..70cc50c1ad --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_in_string.java @@ -0,0 +1,102 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access_filter_in_string extends TestCase { + + public void test_list_in() throws Exception { + JSONPath path = new JSONPath("[name in ('ljw2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(1004, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_not_in() throws Exception { + JSONPath path = new JSONPath("[name not in ('ljw2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(1004, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(3, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + Assert.assertSame(entities.get(3), result.get(2)); + } + + public void test_list_in_2() throws Exception { + JSONPath path = new JSONPath("[name in ('ljw2083', 'yakolee')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(1004, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + } + + public void test_list_in_3() throws Exception { + JSONPath path = new JSONPath("[name in ('ljw2083', 'yakolee',null)]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(1004, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(3, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + Assert.assertSame(entities.get(3), result.get(2)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_like.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_like.java new file mode 100644 index 0000000000..271173575f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_like.java @@ -0,0 +1,154 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access_filter_like extends TestCase { + + public void test_list_like_extract() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like 'ljw2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_not_like_extract() throws Exception { + JSONPath path = new JSONPath("$[?(@.name not like 'ljw2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(3, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + Assert.assertSame(entities.get(3), result.get(2)); + } + + public void test_list_like_left_match() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like 'ljw%')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_right_match() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like '%2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_contains() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like '%208%')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_match_two_segement() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like 'ljw%83')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_match_two_segement_2() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like 'ljw%w2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(0, result.size()); + } + + public void test_list_like_match_two_segement_3() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like 'ljw%2%0%83')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_like_simple.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_like_simple.java new file mode 100644 index 0000000000..46936f9901 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_like_simple.java @@ -0,0 +1,245 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access_filter_like_simple extends TestCase { + + public void test_list_like_extract() throws Exception { + JSONPath path = new JSONPath("$[name like 'ljw2083']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_not_like_extract() throws Exception { + JSONPath path = new JSONPath("$[name not like 'ljw2083']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(3, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + Assert.assertSame(entities.get(3), result.get(2)); + } + + public void test_list_like_left_match() throws Exception { + JSONPath path = new JSONPath("$[name like 'ljw%']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_left_not_match() throws Exception { + JSONPath path = new JSONPath("$[name not like 'ljw%']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + } + + public void test_list_like_right_match() throws Exception { + JSONPath path = new JSONPath("$[name like '%2083']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_right_not_match() throws Exception { + JSONPath path = new JSONPath("$[name not like '%2083']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + } + + public void test_list_like_contains() throws Exception { + JSONPath path = new JSONPath("$[name like '%208%']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_not_contains() throws Exception { + JSONPath path = new JSONPath("$[name not like '%208%']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + } + + public void test_list_like_match_two_segement() throws Exception { + JSONPath path = new JSONPath("$[name like 'ljw%83']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_match_two_segement_not() throws Exception { + JSONPath path = new JSONPath("$[name not like 'ljw%83']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + } + + public void test_list_like_match_two_segement_2() throws Exception { + JSONPath path = new JSONPath("$[name like 'ljw%w2083']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(0, result.size()); + } + + public void test_list_like_match_two_segement_2_not() throws Exception { + JSONPath path = new JSONPath("$[name not like 'ljw%w2083']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(3, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + Assert.assertSame(entities.get(2), result.get(2)); + } + + public void test_list_like_match_two_segement_3() throws Exception { + JSONPath path = new JSONPath("$[name like 'ljw%2%0%83']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_match_two_segement_3_not() throws Exception { + JSONPath path = new JSONPath("$[name not like 'ljw%2%0%83']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(1), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_notNull.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_notNull.java new file mode 100644 index 0000000000..34b0ff5a9e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_notNull.java @@ -0,0 +1,55 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access_filter_notNull extends TestCase { + + public void test_list_map() throws Exception { + JSONPath path = new JSONPath("$[?(@.name)]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(1), result.get(1)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_rlike.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_rlike.java new file mode 100644 index 0000000000..1a7d75c380 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_rlike.java @@ -0,0 +1,153 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access_filter_rlike extends TestCase { + + public void test_list_like_extract() throws Exception { + JSONPath path = new JSONPath("$[name rlike 'ljw2083']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, null)); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_not_like_extract() throws Exception { + JSONPath path = new JSONPath("$[name not rlike 'wenshao']"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(2, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + Assert.assertSame(entities.get(2), result.get(1)); + } + + public void test_list_like_left_match() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like 'ljw%')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_right_match() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like '%2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_contains() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like '%208%')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_match_two_segement() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like 'ljw%83')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public void test_list_like_match_two_segement_2() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like 'ljw%w2083')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(0, result.size()); + } + + public void test_list_like_match_two_segement_3() throws Exception { + JSONPath path = new JSONPath("$[?(@.name like 'ljw%2%0%83')]"); + + List entities = new ArrayList(); + entities.add(new Entity(1001, "ljw2083")); + entities.add(new Entity(1002, "wenshao")); + entities.add(new Entity(1003, "yakolee")); + entities.add(new Entity(null, null)); + + List result = (List) path.eval(entities); + Assert.assertEquals(1, result.size()); + Assert.assertSame(entities.get(0), result.get(0)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_multi.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_multi.java new file mode 100644 index 0000000000..af7cc2d717 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_multi.java @@ -0,0 +1,49 @@ +package com.alibaba.json.bvt.path; + +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_field_access_multi extends TestCase { + + public void test_list_map() throws Exception { + Entity entity = new Entity(123, "wenshao"); + JSONPath path = new JSONPath("$['id','name']"); + + List result = (List) path.eval(entity); + Assert.assertSame(entity.getId(), result.get(0)); + Assert.assertSame(entity.getName(), result.get(1)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_wildcard.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_wildcard.java new file mode 100644 index 0000000000..498a5935d3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_field_wildcard.java @@ -0,0 +1,65 @@ +package com.alibaba.json.bvt.path; + +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_field_wildcard extends TestCase { + + public void test_list_map() throws Exception { + JSONPath path = new JSONPath("$.*"); + Map map = new LinkedHashMap(); + map.put("id", 123); + map.put("name", "wenshao"); + + Collection fieldValues = (Collection) path.eval(map); + Iterator it = fieldValues.iterator(); + Assert.assertSame(map.get("id"), it.next()); + Assert.assertSame(map.get("name"), it.next()); + } + + public void test_list_map_none_root() throws Exception { + JSONPath path = new JSONPath("*"); + Entity entity = new Entity(123, "wenshao"); + + List fieldValues = (List) path.eval(entity); + Assert.assertSame(entity.getId(), fieldValues.get(0)); + Assert.assertSame(entity.getName(), fieldValues.get(1)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_issue1208.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_issue1208.java new file mode 100644 index 0000000000..8dc00563f4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_issue1208.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.path; + +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; +import org.junit.Assert; + +public class JSONPath_issue1208 extends TestCase { + + public void test_largeNumberProperty() throws Exception { + String json1 = "{\"articles\":{\"2147483647\":{\"XXX\":\"xiu\"}}}"; + String path1 = "$.articles.2147483647.XXX"; + Object read = JSONPath.read(json1, path1); + Assert.assertEquals("xiu", read); + + String json2 = "{\"articles\":{\"2147483648\":{\"XXX\":\"xiu\"}}}"; + String path2 = "$.articles.2147483648.XXX"; + Object read2 = JSONPath.read(json2, path2); + + Assert.assertEquals("xiu", read2); + } + + +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_list.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list.java new file mode 100644 index 0000000000..db8f33f875 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_list extends TestCase { + public void test_list_map() throws Exception { + Map map = new HashMap(); + map.put("val", new Object()); + List list = new ArrayList(); + list.add(map); + Assert.assertSame(map.get("val"), new JSONPath("$[0].val").eval(list)); + Assert.assertSame(map.get("val"), new JSONPath("$[-1].val").eval(list)); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_field.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_field.java new file mode 100644 index 0000000000..c307ed1d10 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_field.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_list_field extends TestCase { + + public void test_list_field() throws Exception { + JSONPath path = new JSONPath("$.name"); + List entities = new ArrayList(); + entities.add(new Entity("wenshao")); + entities.add(new Entity("ljw2083")); + + List names = (List)path.eval(entities); + Assert.assertSame(entities.get(0).getName(), names.get(0)); + Assert.assertSame(entities.get(1).getName(), names.get(1)); + } + + public void test_list_field_simple() throws Exception { + JSONPath path = new JSONPath("name"); + + List entities = new ArrayList(); + entities.add(new Entity("wenshao")); + entities.add(new Entity("ljw2083")); + + List names = (List) path.eval(entities); + Assert.assertSame(entities.get(0).getName(), names.get(0)); + Assert.assertSame(entities.get(1).getName(), names.get(1)); + } + + public static class Entity { + + private String name; + + public Entity(String name){ + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_multi.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_multi.java new file mode 100644 index 0000000000..62c78c73b9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_multi.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_list_multi extends TestCase { + + List list = new ArrayList(); + + public JSONPath_list_multi(){ + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + } + + public void test_list_multi() throws Exception { + List result = (List) new JSONPath("$[2,4,5,8,100]").eval(list); + Assert.assertEquals(5, result.size()); + Assert.assertSame(list.get(2), result.get(0)); + Assert.assertSame(list.get(4), result.get(1)); + Assert.assertSame(list.get(5), result.get(2)); + Assert.assertSame(list.get(8), result.get(3)); + Assert.assertNull(result.get(4)); + } + + public void test_list_multi_negative() throws Exception { + List result = (List) new JSONPath("$[-1,-2,-100]").eval(list); + Assert.assertEquals(3, result.size()); + Assert.assertSame(list.get(9), result.get(0)); + Assert.assertSame(list.get(8), result.get(1)); + Assert.assertNull(result.get(2)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_range.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_range.java new file mode 100644 index 0000000000..25d29c9687 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_range.java @@ -0,0 +1,85 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_list_range extends TestCase { + public void test_range() throws Exception { + List list = new ArrayList(); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + JSONPath path = new JSONPath("$[2:4]"); + List result = (List) path.eval(list); + Assert.assertEquals(3, result.size()); + Assert.assertSame(list.get(2), result.get(0)); + Assert.assertSame(list.get(3), result.get(1)); + Assert.assertSame(list.get(4), result.get(2)); + } + + public void test_range_1() throws Exception { + List list = new ArrayList(); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + JSONPath path = new JSONPath("$[:4]"); + List result = (List) path.eval(list); + Assert.assertEquals(5, result.size()); + Assert.assertSame(list.get(0), result.get(0)); + Assert.assertSame(list.get(1), result.get(1)); + Assert.assertSame(list.get(2), result.get(2)); + Assert.assertSame(list.get(3), result.get(3)); + Assert.assertSame(list.get(4), result.get(4)); + } + + public void test_range_2() throws Exception { + List list = new ArrayList(); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + + JSONPath path = new JSONPath("$[4:]"); + List result = (List) path.eval(list); + Assert.assertEquals(2, result.size()); + Assert.assertSame(list.get(4), result.get(0)); + Assert.assertSame(list.get(5), result.get(1)); + } + + + public void test_range_step() throws Exception { + List list = new ArrayList(); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + JSONPath path = new JSONPath("$[2:8:2]"); + List result = (List) path.eval(list); + Assert.assertEquals(2, result.size()); + Assert.assertSame(list.get(2), result.get(0)); + Assert.assertSame(list.get(4), result.get(1)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size.java new file mode 100644 index 0000000000..57d0047b57 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_list_size extends TestCase { + public void test_list_size() throws Exception { + List list = new ArrayList(); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + JSONPath path = new JSONPath("$.size()"); + Integer result = (Integer) path.eval(list); + Assert.assertEquals(list.size(), result.intValue()); + } + + public void test_list_size2() throws Exception { + List list = new ArrayList(); + list.add(new Object()); + list.add(new Object()); + list.add(new Object()); + JSONPath path = new JSONPath("$.size"); + Integer result = (Integer) path.eval(list); + Assert.assertEquals(list.size(), result.intValue()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_1.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_1.java new file mode 100644 index 0000000000..367eafc554 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_1.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_list_size_1 extends TestCase { + public void test_obj_array() throws Exception { + Object[] array = new Object[] {1, 2, 3}; + JSONPath path = new JSONPath("$.size()"); + Integer result = (Integer) path.eval(array); + Assert.assertEquals(array.length, result.intValue()); + } + + public void test_int_array() throws Exception { + int[] array = new int[] {1, 2, 3}; + JSONPath path = new JSONPath("$.size()"); + Integer result = (Integer) path.eval(array); + Assert.assertEquals(array.length, result.intValue()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_2.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_2.java new file mode 100644 index 0000000000..66badda3eb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_2.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.path; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_list_size_2 extends TestCase { + public void test_map() throws Exception { + Map map = new HashMap(); + map.put("1001", 1001); + map.put("1002", 1002); + JSONPath path = new JSONPath("$.size()"); + Integer result = (Integer) path.eval(map); + Assert.assertEquals(map.size(), result.intValue()); + } + + public void test_map_null() throws Exception { + Map map = new HashMap(); + map.put("1001", 1001); + map.put("1002", 1002); + map.put("1003", null); + JSONPath path = new JSONPath("$.size()"); + Integer result = (Integer) path.eval(map); + Assert.assertEquals(2, result.intValue()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_3.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_3.java new file mode 100644 index 0000000000..063e924986 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_3.java @@ -0,0 +1,32 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_list_size_3 extends TestCase { + public void test_java_bean() throws Exception { + Model model = new Model(); + model.id = 1001; + model.name = "wenshao"; + JSONPath path = new JSONPath("$.size()"); + Integer result = (Integer) path.eval(model); + Assert.assertEquals(2, result.intValue()); + } + + public void test_java_bean_field_null() throws Exception { + Model model = new Model(); + model.id = 1001; + model.name = null; + JSONPath path = new JSONPath("$.size()"); + Integer result = (Integer) path.eval(model); + Assert.assertEquals(1, result.intValue()); + } + + public static class Model { + public int id; + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_map_size.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_map_size.java new file mode 100644 index 0000000000..73bbf6ca7f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_map_size.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.path; + +import java.util.Collections; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_map_size extends TestCase { + public void test_list_size() throws Exception { + Assert.assertEquals(0, JSONPath.eval(Collections.emptyMap(), "$.size")); + } + + public void test_list_size1() throws Exception { + Assert.assertEquals(0, JSONPath.eval(Collections.emptyMap(), "$.size()")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_none_root.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_none_root.java new file mode 100644 index 0000000000..de1cc39643 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_none_root.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +public class JSONPath_none_root extends TestCase { + + public void test_root() throws Exception { + List list = new ArrayList(); + list.add(new Object()); + Assert.assertSame(list.get(0), new JSONPath("[0]").eval(list)); + } + + public void test_null() throws Exception { + Assert.assertNull(new JSONPath("name").eval(null)); + } + + public void test_map() throws Exception { + Map map = new HashMap(); + map.put("val", new Object()); + Assert.assertSame(map.get("val"), new JSONPath("val").eval(map)); + } + + public void test_entity() throws Exception { + Entity entity = new Entity(); + entity.setValue(new Object()); + Assert.assertSame(entity.getValue(), new JSONPath("value").eval(entity)); + } + + public static class Entity { + + private Object value; + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_object_filter.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_object_filter.java new file mode 100644 index 0000000000..c67ddc4ebf --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_object_filter.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSONPath; + + +public class JSONPath_object_filter extends TestCase { + public void test_object_filter() throws Exception { + JSONPath path = new JSONPath("[id=123]"); + + Entity entity = new Entity(123, "ljw2083"); + Assert.assertSame(entity, path.eval(entity)); + } + + + public void test_object_filter_not_match() throws Exception { + JSONPath path = new JSONPath("[id=124]"); + + Entity entity = new Entity(123, "ljw2083"); + Assert.assertNull(path.eval(entity)); + } + + public static class Entity { + + private Integer id; + private String name; + + public Entity(Integer id, String name){ + this.id = id; + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test.java new file mode 100644 index 0000000000..5de8940675 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.path; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_paths_test extends TestCase { + public void test_map() throws Exception { + Map map = new HashMap(); + map.put("id", 1001); + map.put("name", "wenshao"); + + Map paths = JSONPath.paths(map); + + Assert.assertEquals(3, paths.size()); + Assert.assertSame(map, paths.get("/")); + Assert.assertEquals(1001, paths.get("/id")); + Assert.assertEquals("wenshao", paths.get("/name")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test1.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test1.java new file mode 100644 index 0000000000..870b221fd8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test1.java @@ -0,0 +1,27 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_paths_test1 extends TestCase { + public void test_map() throws Exception { + List list = new ArrayList(); + list.add(1001); + list.add("wenshao"); + + + Map paths = JSONPath.paths(list); + + Assert.assertEquals(3, paths.size()); + Assert.assertSame(list, paths.get("/")); + Assert.assertEquals(1001, paths.get("/0")); + Assert.assertEquals("wenshao", paths.get("/1")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test2.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test2.java new file mode 100644 index 0000000000..6619733580 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test2.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.path; + +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_paths_test2 extends TestCase { + public void test_map() throws Exception { + Model model = new Model(); + model.id = 1001; + model.name = "wenshao"; + + + Map paths = JSONPath.paths(model); + + Assert.assertEquals(3, paths.size()); + Assert.assertSame(model, paths.get("/")); + Assert.assertEquals(1001, paths.get("/id")); + Assert.assertEquals("wenshao", paths.get("/name")); + } + + public static class Model { + public int id; + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test3.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test3.java new file mode 100644 index 0000000000..270fc1aab1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test3.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.path; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_paths_test3 extends TestCase { + public void test_map() throws Exception { + Model model = new Model(); + model.id = 1001; + model.name = "wenshao"; + model.attributes.put("type", "employee"); + + Map paths = JSONPath.paths(model); + + Assert.assertEquals(5, paths.size()); + Assert.assertSame(model, paths.get("/")); + Assert.assertEquals(1001, paths.get("/id")); + Assert.assertEquals("wenshao", paths.get("/name")); + Assert.assertSame(model.attributes, paths.get("/attributes")); + Assert.assertEquals("employee", paths.get("/attributes/type")); + } + + public static class Model { + public int id; + public String name; + + public Map attributes = new HashMap(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test4.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test4.java new file mode 100644 index 0000000000..0a9e76c1c1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test4.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_paths_test4 extends TestCase { + public void test_map() throws Exception { + List list = new ArrayList(); + list.add(1001); + list.add("wenshao"); + + list.add(Collections.singletonMap("type", "emp")); + + Map paths = JSONPath.paths(list); + + Assert.assertEquals(5, paths.size()); + Assert.assertSame(list, paths.get("/")); + Assert.assertEquals(1001, paths.get("/0")); + Assert.assertEquals("wenshao", paths.get("/1")); + Assert.assertSame(list.get(2), paths.get("/2")); + Assert.assertSame(((Map)list.get(2)).get("type"), paths.get("/2/type")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test5.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test5.java new file mode 100644 index 0000000000..246e3a15f8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test5.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.path; + +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.Map; + +/** + * Created by wuwen on 2016/12/27. + */ +public class JSONPath_paths_test5 extends TestCase { + + public void test_array() throws Exception { + String[] array = new String[]{"1001", "wenshao"}; + + Map paths = JSONPath.paths(array); + + Assert.assertEquals(3, paths.size()); + Assert.assertSame(array, paths.get("/")); + Assert.assertEquals("1001", paths.get("/0")); + Assert.assertEquals("wenshao", paths.get("/1")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_remove_test.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_remove_test.java new file mode 100644 index 0000000000..2ee1c82c73 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_remove_test.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_remove_test extends TestCase { + + public void test_remove() throws Exception { + Map root = new HashMap(); + root.put("name", "wenshao"); + root.put("salary", 1234567890); + Assert.assertTrue(JSONPath.remove(root, "/name")); + Assert.assertEquals(1, root.size()); + Assert.assertFalse(root.containsKey("name")); + Assert.assertTrue(root.containsKey("salary")); + Assert.assertFalse(JSONPath.remove(root, "/name")); + } + + public void test_remove_list() throws Exception { + List root = new ArrayList(); + root.add("wenshao"); + root.add(1234567890); + + Assert.assertTrue(JSONPath.remove(root, "/0")); + Assert.assertEquals(1, root.size()); + + Assert.assertEquals(1234567890, root.get(0)); + + Assert.assertFalse(JSONPath.remove(root, "/1")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_set.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set.java new file mode 100644 index 0000000000..c1143cbc77 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; +import com.alibaba.fastjson.JSONPathException; + +import junit.framework.TestCase; + +public class JSONPath_set extends TestCase { + + public void test_set() throws Exception { + Entity entity = new Entity(); + + JSONPath.set(entity, "$.name", "abc"); + + Assert.assertEquals("abc", entity.getName()); + } + + public void test_set_array() throws Exception { + Object[] array = new Object[1]; + + JSONPath.set(array, "[0]", "abc"); + + Assert.assertEquals("abc", array[0]); + } + + public void test_set_list() throws Exception { + List array = new ArrayList(); + array.add(null); + array.add(null); + + JSONPath.set(array, "[0]", "abc"); + + Assert.assertEquals("abc", array.get(0)); + } + + public void test_root_null() throws Exception { + Assert.assertFalse(JSONPath.set(null, "[0]", "abc")); + } + + public void test_object_not_exits() throws Exception { + Map root = new HashMap(); + root.put("values", null); + Assert.assertTrue(JSONPath.set(root, "$.values[0]", "abc")); + } + + public void test_error() throws Exception { + Map root = new HashMap(); + root.put("values", null); + JSONPath.set(root, "$.values[0]", "abc"); + } + + static class Entity { + + private Integer id; + private String name; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test2.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test2.java new file mode 100644 index 0000000000..dda8a9762d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test2.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_set_test2 extends TestCase { + + public void test_jsonpath() throws Exception { + JSONObject rootObject = JSON.parseObject("{\"array\":[{},{},{},{}]}"); + JSONPath.set(rootObject, "$.array[0:].key", "123"); + + JSONArray array = rootObject.getJSONArray("array"); + for (int i = 0; i < array.size(); ++i) { + Assert.assertEquals("123", array.getJSONObject(i).get("key")); + } + System.out.println(rootObject); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test3.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test3.java new file mode 100644 index 0000000000..30679f1e93 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test3.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.path; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_set_test3 extends TestCase { + + public void test_jsonpath_leve_1() throws Exception { + Map root = new HashMap(); + + JSONPath.set(root, "/id", 1001); + + Assert.assertEquals(1001, JSONPath.eval(root, "/id")); + } + + public void test_jsonpath() throws Exception { + Map root = new HashMap(); + + JSONPath.set(root, "/a/b/id", 1001); + + Assert.assertEquals(1001, JSONPath.eval(root, "a/b/id")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test4.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test4.java new file mode 100644 index 0000000000..9039ef53c8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test4.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.path; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_set_test4 extends TestCase { + public void test_jsonpath_1() throws Exception { + Map root = new HashMap(); + + JSONPath.set(root, "/a[0]/b", 1001); + + Assert.assertEquals("{\"a\":[{\"b\":1001}]}", JSON.toJSONString(root)); + + Assert.assertEquals(1001, JSONPath.eval(root, "/a[0]/b")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test5.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test5.java new file mode 100644 index 0000000000..184fb00266 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test5.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.path; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_set_test5 extends TestCase { + public void test_jsonpath_1() throws Exception { + Map root = new HashMap(); + + JSONPath.set(root, "/a[0]/b[0]", 1001); + + String json = JSON.toJSONString(root); + Assert.assertEquals("{\"a\":[{\"b\":[1001]}]}", json); + Assert.assertEquals(1001, JSONPath.eval(root, "/a[0]/b[0]")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test6.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test6.java new file mode 100644 index 0000000000..4585b2754c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test6.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.path; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.HashMap; +import java.util.Map; + +public class JSONPath_set_test6 extends TestCase { + public void test_jsonpath_1() throws Exception { + JSONObject aa= new JSONObject(); + aa.put("app-a", "haj "); + JSONPath.set(aa, "$.app\\-a\\.x", "123"); + assertEquals("haj ", aa.getString("app-a")); + assertEquals("123", aa.getString("app-a.x")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_size.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_size.java new file mode 100644 index 0000000000..614ce4965b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_size.java @@ -0,0 +1,88 @@ +package com.alibaba.json.bvt.path; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; +import com.alibaba.fastjson.JSONPathException; +import com.alibaba.json.bvt.path.JSONPath_between_int.Entity; + +import junit.framework.TestCase; + +public class JSONPath_size extends TestCase { + + public void test_root() throws Exception { + List list = new ArrayList(); + list.add(new Entity(101, "kiki")); + list.add(new Entity(102, "ljw2083")); + list.add(new Entity(103, "ljw2083")); + + Assert.assertEquals(3, JSONPath.size(list, "$")); + } + + public void test_path() throws Exception { + List list = new ArrayList(); + list.add(new Entity(101, "kiki")); + list.add(new Entity(102, "ljw2083")); + list.add(new Entity(103, "ljw2083")); + + JSONObject root = new JSONObject(); + root.put("values", list); + + Assert.assertEquals(3, JSONPath.size(root, "$.values")); + } + + public void test_path_size() throws Exception { + JSONPath path = JSONPath.compile("$"); + + Assert.assertEquals(-1, path.size(null)); + } + + public void test_path_size_1() throws Exception { + List list = new ArrayList(); + list.add(new Entity(101, "kiki")); + list.add(new Entity(102, "ljw2083")); + list.add(new Entity(103, "ljw2083")); + + JSONPath path = JSONPath.compile("$"); + + Assert.assertEquals(3, path.size(list)); + } + + public void test_path_size_2() throws Exception { + List list = new ArrayList(); + list.add(new Entity(101, "kiki")); + list.add(new Entity(102, "ljw2083")); + list.add(new Entity(103, "ljw2083")); + + JSONObject root = new JSONObject(); + root.put("values", list); + + JSONPath path = JSONPath.compile("$.values"); + + Assert.assertEquals(3, path.size(root)); + } + + public void test_error() throws Exception { + ErrorSizeBean obj = new ErrorSizeBean(); + + Exception error = null; + try { + JSONPath.eval(obj, "$.size()"); + } catch (JSONPathException ex) { + error = ex; + } + Assert.assertNotNull(error); + Assert.assertNotNull(error.getCause()); + } + + public static class ErrorSizeBean { + + public int getId() { + throw new IllegalStateException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPath_toString.java b/src/test/java/com/alibaba/json/bvt/path/JSONPath_toString.java new file mode 100644 index 0000000000..3dbeb11f75 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPath_toString.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPath_toString extends TestCase { + public void test_toJSONString() throws Exception { + Model model = new Model(); + model.path = new JSONPath("$"); + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"path\":\"$\"}", text); + + JSON.parseObject(text, Model.class); + } + + public static class Model { + public JSONPath path; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPointTest_0.java b/src/test/java/com/alibaba/json/bvt/path/JSONPointTest_0.java new file mode 100644 index 0000000000..8d488789d8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPointTest_0.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.path; + +import java.math.BigDecimal; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +@SuppressWarnings("unchecked") +public class JSONPointTest_0 extends TestCase { + + private JSONObject json; + + protected void setUp() throws Exception { + String text = "{\"foo\":[\"bar\",\"baz\"],\"pi\":3.1416,\"ext\":{\"ex1\":1,\"ex2\":\"abc\"}}"; + json = JSON.parseObject(text); + } + + public void test_list() throws Exception { + List list = (List) JSONPath.eval(json, "/foo"); + Assert.assertEquals(2, list.size()); + Assert.assertEquals("bar", list.get(0)); + Assert.assertEquals("baz", list.get(1)); + } + + public void test_list_0() throws Exception { + Object val = JSONPath.eval(json, "/foo/0"); + Assert.assertEquals("bar", val); + } + + public void test_list_1() throws Exception { + Object val = JSONPath.eval(json, "/foo/1"); + Assert.assertEquals("baz", val); + } + + public void test_key() throws Exception { + Object val = JSONPath.eval(json, "/pi"); + Assert.assertEquals(new BigDecimal("3.1416"), val); + } + + public void test_key_1() throws Exception { + Object val = JSONPath.eval(json, "/ext/ex1"); + Assert.assertEquals(1, val); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/JSONPointTest_1.java b/src/test/java/com/alibaba/json/bvt/path/JSONPointTest_1.java new file mode 100644 index 0000000000..3a2936b8b1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/JSONPointTest_1.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class JSONPointTest_1 extends TestCase { + + private Object json; + + protected void setUp() throws Exception { + String text = "[{\"name\":\"ljw\",\"age\":123}]"; + json = JSON.parse(text); + } + + + public void test_key_1() throws Exception { + Object val = JSONPath.eval(json, "/0/name"); + Assert.assertEquals("ljw", val); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/path/TestSpecial_0.java b/src/test/java/com/alibaba/json/bvt/path/TestSpecial_0.java new file mode 100644 index 0000000000..aa0e01c5e1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/TestSpecial_0.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.path; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONPath; + + +public class TestSpecial_0 extends TestCase { + public void test_special() throws Exception { + Map vo = new HashMap(); + + vo.put("a.b", 123); + + Assert.assertEquals((Integer) vo.get("a.b"), (Integer) JSONPath.eval(vo, "a\\.b")); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/path/TestSpecial_1.java b/src/test/java/com/alibaba/json/bvt/path/TestSpecial_1.java new file mode 100644 index 0000000000..ef45a821f8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/TestSpecial_1.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.path; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; + +import junit.framework.TestCase; + +public class TestSpecial_1 extends TestCase { + + public void test_special() throws Exception { + String x = "{\"10.0.0.1\":{\"region\":\"xxx\"}}"; + Object o = JSON.parse(x); + Assert.assertTrue(JSONPath.contains(o, "$.10\\.0\\.0\\.1")); + Assert.assertEquals("{\"region\":\"xxx\"}", JSONPath.eval(o, "$.10\\.0\\.0\\.1").toString()); + Assert.assertTrue(JSONPath.contains(o, "$.10\\.0\\.0\\.1.region")); + Assert.assertEquals("xxx", JSONPath.eval(o, "$.10\\.0\\.0\\.1.region")); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/path/TestSpecial_2.java b/src/test/java/com/alibaba/json/bvt/path/TestSpecial_2.java new file mode 100644 index 0000000000..8412e67f83 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/path/TestSpecial_2.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.path; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONPath; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.HashMap; +import java.util.Map; + +public class TestSpecial_2 extends TestCase { + + public void test_special() throws Exception { + Model model = new Model(); + Value value = new Value(); + model.values.put("com.ibatis.sqlmap.client.SqlMapExecutor@queryForObject(String,Object)", value); + model.subInvokes.put("com.ibatis.sqlmap.client.SqlMapExecutor@queryForObject(String,Object)", value); + + String json = JSON.toJSONString(model); + System.out.println(json); + + Model m2 = JSON.parseObject(json, Model.class); + assertEquals(1, m2.values.size()); + assertEquals(1, m2.subInvokes.size()); + + assertSame(m2.values.values().iterator().next(), m2.subInvokes.values().iterator().next()); + } + + public static class Model { + public Map values = new HashMap(); + public Map subInvokes = new HashMap(); + } + + public static class Value { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/proxy/TestProxy.java b/src/test/java/com/alibaba/json/bvt/proxy/TestProxy.java new file mode 100755 index 0000000000..98f8bf8c2a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/proxy/TestProxy.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.proxy; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class TestProxy extends TestCase { + + public void test_0() throws Exception { + Object vo = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {I.class}, new VO()); + + String text = JSON.toJSONString(vo); + + System.out.println(text); + } + + public static interface I { + + } + + + public static class VO implements InvocationHandler { + + private int id; + private String name; + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return null; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest.java new file mode 100644 index 0000000000..7be07a0bb1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.ref; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class RefTest extends TestCase { + + public void test_ref() throws Exception { + JSONSerializer ser = new JSONSerializer(); + Assert.assertFalse(ser.containsReference(null)); + } + + public void test_array_ref() throws Exception { + JSON.toJSONString(new A[] {new A()}, SerializerFeature.DisableCircularReferenceDetect); + } + + public class A { + + private A a; + + public A getA() { + return a; + } + + public void setA(A a) { + this.a = a; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest10.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest10.java new file mode 100644 index 0000000000..b1e73fbe32 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest10.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.ref; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class RefTest10 extends TestCase { + + public void test_bug_for_wanglin() throws Exception { + String text = "{ \"schedulerCluster\": \"xyQuestionImport\", \"log\": { \"abilityServiceId\": \"-1\", \"abilityServiceVersionId\": \"-1\", \"createTime\": 1456832040060, \"ip\": \"192.168.1.71\", \"jobDataMap\": { \"com.fjhb.context.v1.Context\": { \"domain\": \"dev.medical.com\", \"gUID\": \"25c5e12ec19946e8a6850237cd8182de\", \"ip\": \"127.0.0.1\", \"organizationId\": \"-1\", \"platformId\": \"2c9180e5520a5e70015214fb2849000a\", \"platformVersionId\": \"2c9180e5520a6063015214fc062d0006\", \"projectId\": \"2c9180e5520a60630152150b0b4a000e\", \"recordChain\": true, \"requestUrl\": \"http://dev.medical.com:9009/gateway/web/admin/questionIE/questionImport\", \"subProjectId\": \"2c9180e5520a606301521596e7070018\", \"test\": false, \"unitId\": \"2c9180e54e7580cd014e801793720010\", \"userId\": \"4028823c4e850e60014e853115dc00sa\" }, \"questionImportDto\": { \"filePath\": \"/work/A4Mode2.xls\", \"organizationId\": \"-1\", \"platformId\": \"2c9180e5520a5e70015214fb2849000a\", \"platformVersionId\": \"2c9180e5520a6063015214fc062d0006\", \"projectId\": \"2c9180e5520a60630152150b0b4a000e\", \"subProjectId\": \"2c9180e5520a606301521596e7070018\", \"unitId\": \"-1\" }, \"questionExcelModeType\": 2, \"user.job.current.execute.key\": \"402881c75331cc62015331e732ce0002\" }, \"jobGroup\": \"xyQuestionImport\", \"jobName\": \"questionImport\", \"key\": \"402881c75331cc62015331e732ce0002\", \"organizationId\": \"-1\", \"platformId\": \"-1\", \"platformVersionId\": \"-1\", \"projectId\": \"-1\", \"remark\": \"\\\"xyQuestionImport\\\"集群中名为:\\\"402881c75331cc62015331ccecbc0000\\\"的调度器开始运行此任务\", \"status\": \"toExecuted\", \"subProjectId\": \"-1\", \"unitId\": \"-1\", \"userId\": \"4028823c4e850e60014e853115dc00sa\" }, \"context\": { \"$ref\": \"$.log.jobDataMap.com.fjhb.context.v1.Context\" }, \"schedulerName\": \"402881c75331cc62015331ccecbc0000\" }";; + JSONObject jsonObj = JSON.parseObject(text); + + Assert.assertSame(jsonObj.getJSONObject("log").getJSONObject("jobDataMap").get("com.fjhb.context.v1.Context"), jsonObj.get("context")); + } + + public static class VO { + + private A a; + private Set values = new HashSet(); + + public A getA() { + return a; + } + + public void setA(A a) { + this.a = a; + } + + public Set getValues() { + return values; + } + + public void setValues(Set values) { + this.values = values; + } + + } + + public static class A { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest11.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest11.java new file mode 100755 index 0000000000..051c188187 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest11.java @@ -0,0 +1,117 @@ +package com.alibaba.json.bvt.ref; + +import java.util.ArrayList; +import java.util.Collection; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class RefTest11 extends TestCase { + + public void test_ref() throws Exception { + Department tech = new Department(1, "技术部"); + tech.setRoot(tech); + + { + Department pt = new Department(2, "平台技术部"); + pt.setParent(tech); + pt.setRoot(tech); + tech.getChildren().add(pt); + { + Department sysbase = new Department(3, "系统基础"); + sysbase.setParent(pt); + sysbase.setRoot(tech); + pt.getChildren().add(sysbase); + } + } + { + Department cn = new Department(4, "中文站技术部"); + cn.setParent(tech); + cn.setRoot(tech); + tech.getChildren().add(cn); + } + + { + //JSON.toJSONString(tech); + } + + { + String prettyText = JSON.toJSONString(tech, SerializerFeature.PrettyFormat); + System.out.println(prettyText); + + String text = JSON.toJSONString(tech); + Department dept = JSON.parseObject(text, Department.class); + Assert.assertTrue(dept == dept.getRoot()); + + System.out.println(JSON.toJSONString(dept, SerializerFeature.PrettyFormat)); + } + } + + public static class Department { + + private int id; + private String name; + + private Department parent; + private Department root; + + private Collection children = new ArrayList(); + + public Department(){ + + } + + public Department getRoot() { + return root; + } + + public void setRoot(Department root) { + this.root = root; + } + + public Department(int id, String name){ + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getParent() { + return parent; + } + + public void setParent(Department parent) { + this.parent = parent; + } + + public Collection getChildren() { + return children; + } + + public void setChildren(Collection children) { + this.children = children; + } + + public String toString() { + return "{id:" + id + ",name:" + name + "}"; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest12.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest12.java new file mode 100755 index 0000000000..6ef8ab482b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest12.java @@ -0,0 +1,64 @@ +package com.alibaba.json.bvt.ref; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; + +public class RefTest12 extends TestCase { + + public void test_0() throws Exception { + Entity entity = new Entity(123, new Child()); + entity.getChild().setParent(entity); + + String text = JSON.toJSONString(entity); + System.out.println(text); + + ParserConfig config = new ParserConfig(); + config.setAsmEnable(false); + Entity entity2 = JSON.parseObject(text, Entity.class, config, 0); + + Assert.assertEquals(entity2, entity2.getChild().getParent()); + + System.out.println(JSON.toJSONString(entity2)); + } + + public static class Entity { + + private final int id; + private final Child child; + + @JSONCreator + public Entity(@JSONField(name = "id") int id, @JSONField(name = "child") Child child){ + super(); + this.id = id; + this.child = child; + } + + public int getId() { + return id; + } + + public Child getChild() { + return child; + } + + } + + public static class Child { + + private Entity parent; + + public Entity getParent() { + return parent; + } + + public void setParent(Entity parent) { + this.parent = parent; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest13.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest13.java new file mode 100755 index 0000000000..b8f16f0b2c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest13.java @@ -0,0 +1,72 @@ +package com.alibaba.json.bvt.ref; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONCreator; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.parser.ParserConfig; + +public class RefTest13 extends TestCase { + + public void test_0() throws Exception { + Entity entity = new Entity(123, new Child()); + entity.getChild().setParent(entity); + + String text = JSON.toJSONString(entity); + System.out.println(text); + + Entity entity2 = JSON.parseObject(text, Entity.class); + + Assert.assertEquals(entity2, entity2.getChild().getParent()); + + System.out.println(JSON.toJSONString(entity2)); + } + + public static class Entity { + + private final int id; + private final Child child; + + @JSONCreator + public Entity(@JSONField(name = "id") int id, @JSONField(name = "child") Child child){ + super(); + this.id = id; + this.child = child; + } + + public int getId() { + return id; + } + + public Child getChild() { + return child; + } + + public String toString() { + return "Model-" + id; + } + } + + public static class Child { + + private Entity parent; + + public Child(){ + + } + + public Entity getParent() { + return parent; + } + + public void setParent(Entity parent) { + this.parent = parent; + } + + public String toString() { + return "Child"; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest14.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest14.java new file mode 100755 index 0000000000..45bc70a10a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest14.java @@ -0,0 +1,124 @@ +package com.alibaba.json.bvt.ref; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class RefTest14 extends TestCase { + + public void test_0() throws Exception { + Group admin = new Group("admin"); + + User jobs = new User("jobs"); + User sager = new User("sager"); + User sdh5724 = new User("sdh5724"); + + admin.getMembers().add(jobs); + jobs.getGroups().add(admin); + + admin.getMembers().add(sager); + sager.getGroups().add(admin); + + admin.getMembers().add(sdh5724); + sdh5724.getGroups().add(admin); + + sager.setReportTo(sdh5724); + jobs.setReportTo(sdh5724); + + SerializeConfig serializeConfig = new SerializeConfig(); + serializeConfig.setAsmEnable(false); + String text = JSON.toJSONString(admin, serializeConfig, SerializerFeature.PrettyFormat); + System.out.println(text); + + ParserConfig config = new ParserConfig(); + config.setAsmEnable(false); + + JSON.parseObject(text, Group.class, config, 0); + } + + public static class Group { + + private String name; + + private List members = new ArrayList(); + + public Group(){ + + } + + public Group(String name){ + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getMembers() { + return members; + } + + public void setMembers(List members) { + this.members = members; + } + + public String toString() { + return this.name; + } + } + + public static class User { + + private String name; + + private List groups = new ArrayList(); + + private User reportTo; + + public User(){ + + } + + public User getReportTo() { + return reportTo; + } + + public void setReportTo(User reportTo) { + this.reportTo = reportTo; + } + + public User(String name){ + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getGroups() { + return groups; + } + + public void setGroups(List groups) { + this.groups = groups; + } + + public String toString() { + return this.name; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest15.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest15.java new file mode 100755 index 0000000000..bd4c8f3ff5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest15.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.ref; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + + +public class RefTest15 extends TestCase { + public void test_0 () throws Exception { + List a = new ArrayList(); + List b = new ArrayList(); + List c = new ArrayList(); + List d = new ArrayList(); + + a.add(b); + a.add(c); + a.add(d); + + b.add(a); + b.add(c); + b.add(d); + + c.add(a); + c.add(b); + c.add(d); + + d.add(a); + d.add(b); + d.add(c); + + String text = JSON.toJSONString(a); + System.out.println(text); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest16.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest16.java new file mode 100755 index 0000000000..87a3ea6b9a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest16.java @@ -0,0 +1,81 @@ +package com.alibaba.json.bvt.ref; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class RefTest16 extends TestCase { + + public void test_0() throws Exception { + + Person pA = new Person("a"); + Person pB = new Person("b"); + + Family fA = new Family(); + fA.setMembers(new Person[] { pA, pB }); + fA.setMaster(pA); + + Person pC = new Person("c"); + Person pD = new Person("d"); + + Family fB = new Family(); + fB.setMembers(new Person[] { pC, pD }); + fB.setMaster(pC); + + Family[] familyArray = new Family[] { fA, fB }; + String text = JSON.toJSONString(familyArray); + System.out.println(text); + + Family[] result = JSON.parseObject(text, Family[].class); + + Assert.assertSame(result[0].getMaster(), result[0].getMembers()[0]); + Assert.assertSame(result[1].getMaster(), result[1].getMembers()[0]); + + } + + public static class Family { + + private Person master; + private Person[] members; + + public Person getMaster() { + return master; + } + + public void setMaster(Person master) { + this.master = master; + } + + public Person[] getMembers() { + return members; + } + + public void setMembers(Person[] members) { + this.members = members; + } + + } + + public static class Person { + + private String name; + + public Person(){ + + } + + public Person(String name){ + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest17.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest17.java new file mode 100755 index 0000000000..7fcae16d41 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest17.java @@ -0,0 +1,84 @@ +package com.alibaba.json.bvt.ref; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; + +public class RefTest17 extends TestCase { + + public void test_0() throws Exception { + + Person pA = new Person("a"); + Person pB = new Person("b"); + + Family fA = new Family(); + fA.setMembers(new Person[] { pA, pB }); + fA.setMaster(pA); + + Person pC = new Person("c"); + Person pD = new Person("d"); + + Family fB = new Family(); + fB.setMembers(new Person[] { pC, pD }); + fB.setMaster(pC); + + Family[] familyArray = new Family[] { fA, fB }; + String text = JSON.toJSONString(familyArray, true); + System.out.println(text); + + JSONArray array = JSON.parseArray(text); + + Assert.assertSame(array.getJSONObject(0).get("master"), array.getJSONObject(0).getJSONArray("members").get(0)); + + Family family = array.getObject(0, Family.class); + Assert.assertNotNull(family.getMembers()[0]); + Assert.assertNotNull(family.getMembers()[1]); + } + + public static class Family { + + private Person master; + private Person[] members; + + public Person getMaster() { + return master; + } + + public void setMaster(Person master) { + this.master = master; + } + + public Person[] getMembers() { + return members; + } + + public void setMembers(Person[] members) { + this.members = members; + } + + } + + public static class Person { + + private String name; + + public Person(){ + + } + + public Person(String name){ + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest18.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest18.java new file mode 100644 index 0000000000..7c3cb8df95 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest18.java @@ -0,0 +1,20 @@ +package com.alibaba.json.bvt.ref; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class RefTest18 extends TestCase { + public void test_array() throws Exception { + String text = "{\"b\":{},\"a\":[{\"$ref\":\"$.b\"}]}"; + + JSONObject obj = JSON.parseObject(text); + JSONArray array = obj.getJSONArray("a"); + Assert.assertEquals(1, array.size()); + Assert.assertNotNull(array.get(0)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest19.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest19.java new file mode 100644 index 0000000000..36c1ebd242 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest19.java @@ -0,0 +1,19 @@ +package com.alibaba.json.bvt.ref; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class RefTest19 extends TestCase { + public void test_array() throws Exception { + String text = "{\"b\":{},\"a\":{\"$ref\":\"$.b\"}}"; + + JSONObject obj = JSON.parseObject(text); + JSONObject a = obj.getJSONObject("a"); + JSONObject b = obj.getJSONObject("b"); + Assert.assertSame(a, b); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest2.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest2.java new file mode 100644 index 0000000000..fab492e841 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest2.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.ref; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class RefTest2 extends TestCase { + + public void test_ref() throws Exception { + Object[] array = new Object[1]; + array[0] = array; + Assert.assertEquals("[{\"$ref\":\"@\"}]", JSON.toJSONString(array)); + } + + public void test_ref_1() throws Exception { + Object[] array = new Object[3]; + array[0] = array; + array[1] = new Object(); + array[2] = new Object(); + Assert.assertEquals("[{\"$ref\":\"@\"},{},{}]", JSON.toJSONString(array)); + } + + public void test_ref_2() throws Exception { + Object[] array = new Object[3]; + array[0] = new Object(); + array[1] = array; + array[2] = new Object(); + Assert.assertEquals("[{},{\"$ref\":\"@\"},{}]", JSON.toJSONString(array)); + } + + public void test_ref_3() throws Exception { + Object[] array = new Object[3]; + array[0] = new Object(); + array[1] = new Object(); + array[2] = array; + Assert.assertEquals("[{},{},{\"$ref\":\"@\"}]", JSON.toJSONString(array)); + } + + public void test_parse() throws Exception { + Object[] array2 = JSON.parseObject("[{\"$ref\":\"$\"}]", Object[].class); + Assert.assertSame(array2, array2[0]); + } + + public void test_parse_1() throws Exception { + Object[] array2 = JSON.parseObject("[{\"$ref\":\"@\"}]", Object[].class); + Assert.assertSame(array2, array2[0]); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest20.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest20.java new file mode 100644 index 0000000000..36aa4884c1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest20.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.ref; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class RefTest20 extends TestCase { + public void test_array() throws Exception { + String text = "{\"resultObj\":{\"appId\":1161605300000000588,\"inputParamList\":[],\"obj\":{\"$ref\":\"$.resultObj\"}}}"; + + JSONObject obj = JSON.parseObject(text); + JSONObject resultObj = obj.getJSONObject("resultObj"); + Assert.assertSame(resultObj, resultObj.get("obj")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest21.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest21.java new file mode 100644 index 0000000000..421a8a8b7e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest21.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.ref; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/8/23. + */ +public class RefTest21 extends TestCase { + public void test_ref() throws Exception { + String jsonTest = "{\"details\":{\"type\":{\"items\":{\"allOf\":[{\"$ref\":\"title\",\"required\":[\"iconImg\"]}]}}}}"; + JSONObject object = JSON.parseObject(jsonTest, Feature.DisableSpecialKeyDetect); + System.out.println( object.get( "details")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest22.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest22.java new file mode 100644 index 0000000000..dc349298d3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest22.java @@ -0,0 +1,17 @@ +package com.alibaba.json.bvt.ref; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.Feature; +import junit.framework.TestCase; + +/** + * Created by wenshao on 16/8/23. + */ +public class RefTest22 extends TestCase { + public void test_ref() throws Exception { + String json = "{\"name\":\"123\",\"assetSize\":{},\"items\":[{\"id\":123}],\"refItems\":{\"$ref\":\"$.items[0]\"}}"; + JSONObject root = JSON.parseObject(json); + assertSame(root.getJSONArray("items").get(0), root.getJSONObject("refItems")); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest3.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest3.java new file mode 100644 index 0000000000..a4ce06f653 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest3.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.ref; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class RefTest3 extends TestCase { + + public void test_ref() throws Exception { + Object[] array = new Object[1]; + array[0] = array; + Assert.assertEquals("[{\"$ref\":\"@\"}]", JSON.toJSONString(array)); + } + + public void test_parse() throws Exception { + Object[] array2 = JSON.parseObject("[{\"$ref\":\"$\"}]", Object[].class); + Assert.assertSame(array2, array2[0]); + } + + public void test_parse_1() throws Exception { + Object[] array2 = JSON.parseObject("[{\"$ref\":\"@\"}]", Object[].class); + Assert.assertSame(array2, array2[0]); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest4.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest4.java new file mode 100644 index 0000000000..71a255e534 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest4.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.ref; + +import java.math.BigDecimal; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class RefTest4 extends TestCase { + + public void test_str() throws Exception { + Object[] array = new Object[2]; + array[0] = "abc"; + array[1] = array[0]; + Assert.assertEquals("[\"abc\",\"abc\"]", JSON.toJSONString(array)); + } + + public void test_decimal() throws Exception { + Object[] array = new Object[2]; + array[0] = new BigDecimal("123"); + array[1] = array[0]; + Assert.assertEquals("[123,123]", JSON.toJSONString(array)); + } + + public void test_integer() throws Exception { + Object[] array = new Object[2]; + array[0] = Integer.valueOf(123); + array[1] = array[0]; + Assert.assertEquals("[123,123]", JSON.toJSONString(array)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest5.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest5.java new file mode 100644 index 0000000000..69a8983f0b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest5.java @@ -0,0 +1,24 @@ +package com.alibaba.json.bvt.ref; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; + +public class RefTest5 extends TestCase { + + public void test_ref() throws Exception { + Object[] array = new Object[1]; + array[0] = new Object[] { array }; + Assert.assertEquals("[[{\"$ref\":\"..\"}]]", JSON.toJSONString(array)); + } + + public void test_parse() throws Exception { + Object[] array2 = JSON.parseObject("[[{\"$ref\":\"..\"}]]", Object[].class); + JSONArray item = (JSONArray) array2[0]; + Assert.assertSame(item, item.get(0)); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest6.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest6.java new file mode 100644 index 0000000000..ca829228d0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest6.java @@ -0,0 +1,80 @@ +package com.alibaba.json.bvt.ref; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class RefTest6 extends TestCase { + + /** + * A -> B -> C -> B -> A + * + * @throws Exception + */ + public void test_0() throws Exception { + A a = new A(); + B b = new B(); + C c = new C(); + a.setB(b); + b.setC(c); + c.setB(b); + b.setA(a); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("a", a); + jsonObject.put("c", c); + + String text = JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat); + System.out.println(text); + } + + private class A { + + private B b; + + public B getB() { + return b; + } + + public void setB(B b) { + this.b = b; + } + } + + private class B { + + private C c; + private A a; + + public C getC() { + return c; + } + + public void setC(C c) { + this.c = c; + } + + public A getA() { + return a; + } + + public void setA(A a) { + this.a = a; + } + } + + private class C { + + private B b; + + public B getB() { + return b; + } + + public void setB(B b) { + this.b = b; + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest7.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest7.java new file mode 100644 index 0000000000..020501d7f8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest7.java @@ -0,0 +1,105 @@ +package com.alibaba.json.bvt.ref; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class RefTest7 extends TestCase { + + public void test_bug_for_juqkai() throws Exception { + + VO vo = new VO(); + C c = new C(); + vo.setA(new A(c)); + vo.setB(new B(c)); + + VO[] root = new VO[] { vo }; + + String text = JSON.toJSONString(root); + System.out.println(text); + + VO[] array2 = JSON.parseObject(text, VO[].class); + Assert.assertEquals(1, array2.length); + Assert.assertNotNull(array2[0].getA()); + Assert.assertNotNull(array2[0].getB()); + Assert.assertNotNull(array2[0].getA().getC()); + Assert.assertNotNull(array2[0].getB().getC()); + Assert.assertSame(array2[0].getA().getC(), array2[0].getB().getC()); + } + + public static class VO { + + private A a; + private B b; + + public A getA() { + return a; + } + + public void setA(A a) { + this.a = a; + } + + public B getB() { + return b; + } + + public void setB(B b) { + this.b = b; + } + + } + + public static class A { + + private C c; + + public A(){ + + } + + public A(C c){ + this.c = c; + } + + public C getC() { + return c; + } + + public void setC(C c) { + this.c = c; + } + + } + + public static class B { + + private C c; + + public B(){ + + } + + public B(C c){ + this.c = c; + } + + public C getC() { + return c; + } + + public void setC(C c) { + this.c = c; + } + } + + public static class C { + + public C(){ + + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest8.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest8.java new file mode 100644 index 0000000000..15fb2a7019 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest8.java @@ -0,0 +1,112 @@ +package com.alibaba.json.bvt.ref; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class RefTest8 extends TestCase { + + public void test_bug_for_juqkai() throws Exception { + + C c = new C(); + + Map a = Collections.singletonMap("c", c); + Map b = Collections.singletonMap("c", c); + Map vo = new HashMap(); + vo.put("a", a); + vo.put("b", b); + + Object[] root = new Object[] { vo }; + + String text = JSON.toJSONString(root); + System.out.println(text); + + VO[] array2 = JSON.parseObject(text, VO[].class); + Assert.assertEquals(1, array2.length); + Assert.assertNotNull(array2[0].getA()); + Assert.assertNotNull(array2[0].getB()); + Assert.assertNotNull(array2[0].getA().getC()); + Assert.assertNotNull(array2[0].getB().getC()); + Assert.assertSame(array2[0].getA().getC(), array2[0].getB().getC()); + } + + private static class VO { + + private A a; + private B b; + + public A getA() { + return a; + } + + public void setA(A a) { + this.a = a; + } + + public B getB() { + return b; + } + + public void setB(B b) { + this.b = b; + } + + } + + private static class A { + + private C c; + + public A(){ + + } + + public A(C c){ + this.c = c; + } + + public C getC() { + return c; + } + + public void setC(C c) { + this.c = c; + } + + } + + private static class B { + + private C c; + + public B(){ + + } + + public B(C c){ + this.c = c; + } + + public C getC() { + return c; + } + + public void setC(C c) { + this.c = c; + } + } + + private static class C { + + public C(){ + + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest9.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest9.java new file mode 100644 index 0000000000..1eb2574008 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest9.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.ref; + +import java.util.HashSet; +import java.util.Set; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class RefTest9 extends TestCase { + + public void test_bug_for_wanglin() throws Exception { + VO vo = new VO(); + A a = new A(); + vo.setA(a); + vo.getValues().add(a); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"a\":{},\"values\":[{\"$ref\":\"$.a\"}]}", text); + + VO vo2 = JSON.parseObject(text, VO.class); + } + + public static class VO { + + private A a; + private Set values = new HashSet(); + + public A getA() { + return a; + } + + public void setA(A a) { + this.a = a; + } + + public Set getValues() { + return values; + } + + public void setValues(Set values) { + this.values = values; + } + + } + + public static class A { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/ref/RefTest_for_huanxige.java b/src/test/java/com/alibaba/json/bvt/ref/RefTest_for_huanxige.java new file mode 100644 index 0000000000..a7caf02179 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/ref/RefTest_for_huanxige.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt.ref; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.io.Serializable; + +/** + * Created by wenshao on 08/02/2017. + */ +public class RefTest_for_huanxige extends TestCase { + public void test_for_ref() throws Exception { +//字符串通过其它对象序列化而来,当中涉及循环引用,因此存在$ref + String jsonStr="{\"displayName\":\"灰度发布\",\"id\":221," + + "\"name\":\"灰度\",\"processInsId\":48,\"processInstance\":{\"$ref\":\"$" + + ".lastSubProcessInstence.parentProcess\"},\"status\":1,\"success\":true," + + "\"tail\":true,\"type\":\"gray\"}"; + ProcessNodeInstanceDto a = JSON.parseObject(jsonStr, ProcessNodeInstanceDto.class);//status为空!!! + assertNotNull(a.status); + assertEquals(1, a.status.intValue()); + } + + public static class ProcessNodeInstanceDto implements Serializable { + private Long id; + private Long processInsId; + private String name; + private String displayName; + private Integer status; + private String type; + private Boolean success; + private Boolean tail; + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + public Long getProcessInsId() { + return processInsId; + } + public void setProcessInsId(Long processInsId) { + this.processInsId = processInsId; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getDisplayName() { + return displayName; + } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + public Integer getStatus() { + return status; + } + public void setStatus(Integer status) { + this.status = status; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public Boolean getSuccess() { + return success; + } + public void setSuccess(Boolean success) { + this.success = success; + } + public Boolean getTail() { + return tail; + } + public void setTail(Boolean tail) { + this.tail = tail; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/AbstractTest.java b/src/test/java/com/alibaba/json/bvt/serializer/AbstractTest.java new file mode 100644 index 0000000000..8fc7d2b8f5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/AbstractTest.java @@ -0,0 +1,106 @@ +package com.alibaba.json.bvt.serializer; + +import java.lang.reflect.Type; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.JSONToken; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; + +public class AbstractTest extends TestCase { + + public void test_0() throws Exception { + ParserConfig.getGlobalInstance().putDeserializer(A.class, new ADeserializer()); + VO vo = JSON.parseObject("{\"a\":{\"num\":1,\"name\":\"bb\"}}", VO.class); + Assert.assertTrue(vo.getA() instanceof B); + } + + public void test_1() throws Exception { + ParserConfig.getGlobalInstance().putDeserializer(A.class, new ADeserializer()); + VO vo = JSON.parseObject("{\"a\":{\"num\":2,\"name\":\"bb\"}}", VO.class); + Assert.assertTrue(vo.getA() instanceof C); + } + + + public static class ADeserializer implements ObjectDeserializer { + + @SuppressWarnings("unchecked") + public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { + JSONObject json = parser.parseObject(); + int num = json.getInteger("num"); + if (num == 1) { + return (T) JSON.toJavaObject(json, B.class); + } else if (num == 2) { + return (T) JSON.toJavaObject(json, C.class); + } else { + return (T) JSON.toJavaObject(json, A.class); + } + } + + public int getFastMatchToken() { + return JSONToken.LBRACE; + } + + } + + public static class VO { + + private A a; + + public A getA() { + return a; + } + + public void setA(A a) { + this.a = a; + } + + } + + public static class A { + + private int num; + + public int getNum() { + return num; + } + + public void setNum(int num) { + this.num = num; + } + } + + public static class B extends A { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + + public static class C extends A { + + public String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/BooleanArraySerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/BooleanArraySerializerTest.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/serializer/BooleanArraySerializerTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/BooleanArraySerializerTest.java index a324f53293..a09042e24a --- a/src/test/java/com/alibaba/json/test/bvt/serializer/BooleanArraySerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/BooleanArraySerializerTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/BooleanFieldSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldSerializerTest.java old mode 100644 new mode 100755 similarity index 89% rename from src/test/java/com/alibaba/json/test/bvt/serializer/BooleanFieldSerializerTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldSerializerTest.java index 376449ee86..ec7e27e8a3 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/BooleanFieldSerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldSerializerTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.lang.reflect.Type; @@ -8,7 +8,7 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializeConfig; @@ -59,14 +59,14 @@ public static final T parseObjectNoAsm(String input, Type clazz, int feature return null; } - for (Feature featrue : features) { - featureValues = Feature.config(featureValues, featrue, true); + for (Feature feature : features) { + featureValues = Feature.config(featureValues, feature, true); } ParserConfig config = new ParserConfig(); config.setAsmEnable(false); - DefaultExtJSONParser parser = new DefaultExtJSONParser(input, config, featureValues); + DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues); T value = (T) parser.parseObject(clazz); if (clazz != JSONArray.class) { diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/BooleanFieldSerializerTest_primitive.java b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldSerializerTest_primitive.java old mode 100644 new mode 100755 similarity index 88% rename from src/test/java/com/alibaba/json/test/bvt/serializer/BooleanFieldSerializerTest_primitive.java rename to src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldSerializerTest_primitive.java index 6ce00f6ae6..be020ebfdc --- a/src/test/java/com/alibaba/json/test/bvt/serializer/BooleanFieldSerializerTest_primitive.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldSerializerTest_primitive.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.lang.reflect.Type; @@ -8,12 +8,12 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.parser.DefaultExtJSONParser; +import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; -import com.alibaba.json.test.bvt.serializer.BooleanFieldSerializerTest.Entity; +import com.alibaba.json.bvt.serializer.BooleanFieldSerializerTest.Entity; public class BooleanFieldSerializerTest_primitive extends TestCase { @@ -71,14 +71,14 @@ public static final T parseObjectNoAsm(String input, Type clazz, int feature return null; } - for (Feature featrue : features) { - featureValues = Feature.config(featureValues, featrue, true); + for (Feature feature : features) { + featureValues = Feature.config(featureValues, feature, true); } ParserConfig config = new ParserConfig(); config.setAsmEnable(false); - DefaultExtJSONParser parser = new DefaultExtJSONParser(input, config, featureValues); + DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues); T value = (T) parser.parseObject(clazz); if (clazz != JSONArray.class) { diff --git a/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest.java b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest.java new file mode 100644 index 0000000000..c0278224b2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class BooleanFieldTest extends TestCase { + + public void test_model() throws Exception { + Model model = new Model(); + model.value = true; + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"value\":true}", text); + } + + public void test_model_max() throws Exception { + Model model = new Model(); + model.value = false; + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"value\":false}", text); + } + + public static class Model { + + public boolean value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest2.java new file mode 100644 index 0000000000..92ab504312 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest2.java @@ -0,0 +1,82 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringReader; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONReader; + +import junit.framework.TestCase; + +public class BooleanFieldTest2 extends TestCase { + + public void test_true() throws Exception { + String text = "{\"f001\":1001,\"value\":true}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertTrue(model.value); + } + + public void test_false() throws Exception { + String text = "{\"f001\":1001,\"value\":false}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertFalse(model.value); + } + + public void test_true_reader() throws Exception { + String text = "{\"f001\":1001,\"value\":true}"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertTrue(model.value); + reader.close(); + } + + public void test_false_reader() throws Exception { + String text = "{\"f001\":1001,\"value\":false}"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertFalse(model.value); + reader.close(); + } + + public void test_1() throws Exception { + String text = "{\"value\":1}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertTrue(model.value); + } + + public void test_0() throws Exception { + String text = "{\"value\":0}"; + + Model model = JSON.parseObject(text, Model.class); + Assert.assertFalse(model.value); + } + + public void test_1_reader() throws Exception { + String text = "{\"value\":1}"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertTrue(model.value); + reader.close(); + } + + public void test_0_reader() throws Exception { + String text = "{\"value\":0}"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Model model = reader.readObject(Model.class); + Assert.assertFalse(model.value); + reader.close(); + } + + public static class Model { + + public boolean value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest3.java b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest3.java new file mode 100644 index 0000000000..41cd69171f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest3.java @@ -0,0 +1,54 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; +import org.junit.Assert; + +/** + * Created by wuwen on 2016/11/3. + */ +public class BooleanFieldTest3 extends TestCase { + + public void test_model() throws Exception { + Model model = new Model(); + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"ok\":true,\"ok2\":true,\"ok3\":true}", text); + } + + public static class Model { + + private Long fail; + + private boolean ok; + + private Boolean ok2; + + private boolean ok3; + + public Long isFail() { + return 1L; + } + + public boolean getOk() { + return true; + } + + public boolean isOk() { + return false; + } + + public Boolean getOk2() { + return true; + } + + public Boolean isOk2() { + return false; + } + + public boolean isOk3() { + return true; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest_array.java b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest_array.java new file mode 100644 index 0000000000..a423199456 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest_array.java @@ -0,0 +1,113 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.annotation.JSONType; +import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class BooleanFieldTest_array extends TestCase { + + public void test_model_error_t() throws Exception { + Exception error = null; + try { + JSON.parseObject("[t", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_model_error_tr() throws Exception { + Exception error = null; + try { + JSON.parseObject("[tr", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_model_error_tru() throws Exception { + Exception error = null; + try { + JSON.parseObject("[tru", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + + public void test_model_error_true_notclose() throws Exception { + Exception error = null; + try { + JSON.parseObject("[true", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_model_error_false_notclose() throws Exception { + Exception error = null; + try { + JSON.parseObject("[false", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_model_error_f() throws Exception { + Exception error = null; + try { + JSON.parseObject("[f", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_model_error_fa() throws Exception { + Exception error = null; + try { + JSON.parseObject("[fa", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_model_error_fal() throws Exception { + Exception error = null; + try { + JSON.parseObject("[fal", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + + public void test_model_error_fals() throws Exception { + Exception error = null; + try { + JSON.parseObject("[fals", Model.class); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + @JSONType(serialzeFeatures = SerializerFeature.BeanToArray, parseFeatures = Feature.SupportArrayToBean) + public static class Model { + + public boolean value; + public boolean value1; + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/BugTest0.java b/src/test/java/com/alibaba/json/bvt/serializer/BugTest0.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/serializer/BugTest0.java rename to src/test/java/com/alibaba/json/bvt/serializer/BugTest0.java index c22afe5707..e9abec33c4 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/BugTest0.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/BugTest0.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.sql.Date; import java.sql.Timestamp; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/BugTest1.java b/src/test/java/com/alibaba/json/bvt/serializer/BugTest1.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/serializer/BugTest1.java rename to src/test/java/com/alibaba/json/bvt/serializer/BugTest1.java index bcc4b4f555..96c2cb3144 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/BugTest1.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/BugTest1.java @@ -1,11 +1,11 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/BugTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/BugTest2.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/serializer/BugTest2.java rename to src/test/java/com/alibaba/json/bvt/serializer/BugTest2.java index ce6ca69f32..9290dff191 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/BugTest2.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/BugTest2.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import junit.framework.TestCase; import net.sf.json.JSONObject; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/ByteArrayFieldSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ByteArrayFieldSerializerTest.java old mode 100644 new mode 100755 similarity index 79% rename from src/test/java/com/alibaba/json/test/bvt/serializer/ByteArrayFieldSerializerTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/ByteArrayFieldSerializerTest.java index 78bba6256f..51b569dba9 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/ByteArrayFieldSerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/ByteArrayFieldSerializerTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -12,7 +12,7 @@ public void test_0() throws Exception { A a1 = new A(); a1.setBytes(new byte[] { 1, 2 }); - Assert.assertEquals("{\"bytes\":[1,2]}", JSON.toJSONString(a1)); + Assert.assertEquals("{\"bytes\":\"AQI=\"}", JSON.toJSONString(a1)); } public void test_1() throws Exception { diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ByteArraySerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ByteArraySerializerTest.java new file mode 100755 index 0000000000..3f93af6cf5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ByteArraySerializerTest.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.serializer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.util.IOUtils; + +public class ByteArraySerializerTest extends TestCase { + + public void test_b_0() { + char[] buf = new char[4]; + IOUtils.getChars((byte) -127, 4, buf); + } + + public void test_0() { + Assert.assertEquals("\"\"", JSON.toJSONString(new byte[0])); + Assert.assertEquals("\"AQI=\"", JSON.toJSONString(new byte[] { 1, 2 })); + Assert.assertEquals("\"AQID\"", JSON.toJSONString(new byte[] { 1, 2, 3 })); + + Assert.assertEquals("1", JSON.toJSONString((byte) 1)); + Assert.assertEquals("1", JSON.toJSONString((short) 1)); + Assert.assertEquals("true", JSON.toJSONString(true)); + } + + public void test_1() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.writeByteArray(new byte[] { 1, 2, 3 }); + Assert.assertEquals("\"AQID\"", out.toString()); + } + + public void test_2() throws Exception { + SerializeWriter out = new SerializeWriter(100); + out.writeByteArray(new byte[] { 1, 2, 3 }); + Assert.assertEquals("\"AQID\"", out.toString()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/ByteArrayTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ByteArrayTest.java old mode 100644 new mode 100755 similarity index 88% rename from src/test/java/com/alibaba/json/test/bvt/serializer/ByteArrayTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/ByteArrayTest.java index 7d008eff3a..ece915c441 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/ByteArrayTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/ByteArrayTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; @@ -32,10 +32,10 @@ public void test_bytes_1() throws Exception { SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty }; String text1 = JSON.toJSONString(vo, mapping, features); - Assert.assertEquals("{\"value\":[1,2,3]}", text1); + Assert.assertEquals("{\"value\":\"AQID\"}", text1); String text2 = JSON.toJSONString(vo, features); - Assert.assertEquals("{\"value\":[1,2,3]}", text2); + Assert.assertEquals("{\"value\":\"AQID\"}", text2); } public static class VO { diff --git a/src/test/java/com/alibaba/json/bvt/serializer/CharArraySerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/CharArraySerializerTest.java new file mode 100755 index 0000000000..8b1e9d875d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/CharArraySerializerTest.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import org.junit.Assert; +import junit.framework.TestCase; + +public class CharArraySerializerTest extends TestCase { + + public void test_null() throws Exception { + VO vo = new VO(); + + Assert.assertEquals("{\"value\":[]}", JSON.toJSONString(vo, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); + Assert.assertEquals("{\"value\":null}", JSON.toJSONString(vo, SerializerFeature.WriteMapNullValue)); + } + + private static class VO { + + private char[] value; + + public char[] getValue() { + return value; + } + + public void setValue(char[] value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/CharTest.java b/src/test/java/com/alibaba/json/bvt/serializer/CharTest.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/serializer/CharTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/CharTest.java index 429ac8e807..4692aa09c1 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/CharTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/CharTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/CharsetSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/CharsetSerializerTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/serializer/CharsetSerializerTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/CharsetSerializerTest.java index b9fda8eb87..676a957291 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/CharsetSerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/CharsetSerializerTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.nio.charset.Charset; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/CharsetTest.java b/src/test/java/com/alibaba/json/bvt/serializer/CharsetTest.java old mode 100644 new mode 100755 similarity index 86% rename from src/test/java/com/alibaba/json/test/bvt/serializer/CharsetTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/CharsetTest.java index 9f8f7e2e7a..d3accfc07f --- a/src/test/java/com/alibaba/json/test/bvt/serializer/CharsetTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/CharsetTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.nio.charset.Charset; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/CircularReferencesTest.java b/src/test/java/com/alibaba/json/bvt/serializer/CircularReferencesTest.java new file mode 100755 index 0000000000..62c721db76 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/CircularReferencesTest.java @@ -0,0 +1,83 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class CircularReferencesTest extends TestCase { + + public void test_0() throws Exception { + A a = new A(); + B b = new B(a); + a.setB(b); + + String text = JSON.toJSONString(a); + A a1 = JSON.parseObject(text, A.class); + Assert.assertTrue(a1 == a1.getB().getA()); + } + + public void test_1() throws Exception { + A a = new A(); + B b = new B(a); + a.setB(b); + + String text = JSON.toJSONString(a, SerializerFeature.UseISO8601DateFormat); + A a1 = JSON.parseObject(text, A.class); + Assert.assertTrue(a1 == a1.getB().getA()); + } + + public void test_2() throws Exception { + A a = new A(); + B b = new B(a); + a.setB(b); + + String text = JSON.toJSONString(a, true); + A a1 = JSON.parseObject(text, A.class); + Assert.assertTrue(a1 == a1.getB().getA()); + } + + public static class A { + + private B b; + + public A(){ + } + + public A(B b){ + this.b = b; + } + + public B getB() { + return b; + } + + public void setB(B b) { + this.b = b; + } + + } + + public static class B { + + private A a; + + public B(){ + + } + + public B(A a){ + this.a = a; + } + + public A getA() { + return a; + } + + public void setA(A a) { + this.a = a; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ClassFieldTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ClassFieldTest.java new file mode 100644 index 0000000000..aeecfc25f9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ClassFieldTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.serializer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ClassFieldTest extends TestCase { + + public void test_writer_1() throws Exception { + VO vo = JSON.parseObject("{\"value\":\"int\"}", VO.class); + Assert.assertEquals(int.class, vo.getValue()); + } + + public static class VO { + + private Class value; + + public Class getValue() { + return value; + } + + public void setValue(Class value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ClassLoaderTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ClassLoaderTest.java new file mode 100644 index 0000000000..04e5f325ac --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ClassLoaderTest.java @@ -0,0 +1,108 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.URL; +import java.util.Enumeration; +import java.util.Set; +import java.util.Vector; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.util.ServiceLoader; +import com.alibaba.json.demo.X; + +public class ClassLoaderTest extends TestCase { + + private ClassLoader ctxLoader; + + protected void setUp() throws Exception { + ctxLoader = Thread.currentThread().getContextClassLoader(); + } + + protected void tearDown() throws Exception { + Thread.currentThread().setContextClassLoader(ctxLoader); + } + + public void test_error() throws Exception { + Field field = ServiceLoader.class.getDeclaredField("loadedUrls"); + field.setAccessible(true); + Set loadedUrls = (Set) field.get(null); + + Thread.currentThread().setContextClassLoader(new MyClassLoader(new ClassCastException())); + JSON.toJSONString(new A()); + + loadedUrls.clear(); + + Thread.currentThread().setContextClassLoader(new MyClassLoader(new IOException())); + JSON.toJSONString(new B()); + + loadedUrls.clear(); + + Thread.currentThread().setContextClassLoader(new EmptyClassLoader()); + JSON.toJSONString(new C()); + + loadedUrls.clear(); + + Thread.currentThread().setContextClassLoader(new ErrorClassLoader()); + JSON.toJSONString(new D()); + + loadedUrls.clear(); + + Thread.currentThread().setContextClassLoader(ctxLoader); + JSON.toJSONString(new E()); + } + + public static class EmptyClassLoader extends ClassLoader { + + public Enumeration getResources(String name) throws IOException { + return new Vector().elements(); + } + } + + public static class ErrorClassLoader extends ClassLoader { + + public Class loadClass(String name) throws ClassNotFoundException { + return Object.class; + } + } + + public static class MyClassLoader extends ClassLoader { + + private final Exception error; + + public MyClassLoader(Exception error){ + super(); + this.error = error; + } + + public Enumeration getResources(String name) throws IOException { + if (error instanceof IOException) { + throw (IOException) error; + } + throw (RuntimeException) error; + } + } + + public class A { + + } + + public class B { + + } + + public class C { + + } + + public class D { + + } + + public class E { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ClobSeriliazerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ClobSeriliazerTest.java new file mode 100644 index 0000000000..1faf861033 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ClobSeriliazerTest.java @@ -0,0 +1,144 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.Writer; +import java.sql.Clob; +import java.sql.SQLException; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class ClobSeriliazerTest extends TestCase { + public void test_clob() throws Exception { + Assert.assertEquals("\"abcdefg中国\"", + JSON.toJSONString(new MockClob("abcdefg中国"))); + } + + public void test_clob_null() throws Exception { + Assert.assertEquals("{\"value\":null}", JSON.toJSONString(new VO(), + SerializerFeature.WriteMapNullValue)); + } + + public void test_clob_error() throws Exception { + Exception error = null; + try { + JSON.toJSONString(new MockClob(new SQLException())); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + @SuppressWarnings("unused") + private static class VO { + private Clob value; + + public Clob getValue() { + return value; + } + + public void setValue(Clob value) { + this.value = value; + } + } + + public static class MockClob implements Clob { + private final String text; + + private SQLException error; + + public MockClob(String text) { + this.text = text; + } + + public MockClob(SQLException error) { + this.text = null; + this.error = error; + } + + public SQLException getError() { + return error; + } + + public void setError(SQLException error) { + this.error = error; + } + + public long length() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + public String getSubString(long pos, int length) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + public Reader getCharacterStream() throws SQLException { + if (error != null) { + throw error; + } + return new StringReader(text); + } + + public InputStream getAsciiStream() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + public long position(String searchstr, long start) throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + public long position(Clob searchstr, long start) throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + public int setString(long pos, String str) throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + public int setString(long pos, String str, int offset, int len) + throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + public OutputStream setAsciiStream(long pos) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + public Writer setCharacterStream(long pos) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + public void truncate(long len) throws SQLException { + // TODO Auto-generated method stub + + } + + public void free() throws SQLException { + // TODO Auto-generated method stub + + } + + public Reader getCharacterStream(long pos, long length) + throws SQLException { + // TODO Auto-generated method stub + return null; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/CollectionSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/CollectionSerializerTest.java new file mode 100755 index 0000000000..5dc4b5b047 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/CollectionSerializerTest.java @@ -0,0 +1,87 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.serializer.CollectionCodec; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; + +public class CollectionSerializerTest extends TestCase { + + public void test_0() throws Exception { + SerializeWriter out = new SerializeWriter(); + + CollectionCodec listSerializer = new CollectionCodec(); + listSerializer.write(new JSONSerializer(out), Collections.EMPTY_LIST, null, null, 0); + + Assert.assertEquals("[]", out.toString()); + } + + public void test_1() throws Exception { + SerializeWriter out = new SerializeWriter(); + + CollectionCodec listSerializer = new CollectionCodec(); + listSerializer.write(new JSONSerializer(out), Collections.singletonList(1), null, null, 0); + + Assert.assertEquals("[1]", out.toString()); + } + + public void test_2_s() throws Exception { + SerializeWriter out = new SerializeWriter(); + + CollectionCodec listSerializer = new CollectionCodec(); + List list = new ArrayList(); + list.add(1); + list.add(2); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + + Assert.assertEquals("[1,2]", out.toString()); + } + + public void test_3_s() throws Exception { + SerializeWriter out = new SerializeWriter(); + + CollectionCodec listSerializer = new CollectionCodec(); + List list = new ArrayList(); + list.add(1); + list.add(2); + list.add(3); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + + Assert.assertEquals("[1,2,3]", out.toString()); + } + + public void test_4_s() throws Exception { + SerializeWriter out = new SerializeWriter(); + + CollectionCodec listSerializer = new CollectionCodec(); + List list = new ArrayList(); + list.add(1L); + list.add(2L); + list.add(3L); + list.add(Collections.emptyMap()); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + + Assert.assertEquals("[1,2,3,{}]", out.toString()); + } + + public void test_5_s() throws Exception { + SerializeWriter out = new SerializeWriter(); + + CollectionCodec listSerializer = new CollectionCodec(); + List list = new ArrayList(); + list.add(1L); + list.add(21474836480L); + list.add(null); + list.add(Collections.emptyMap()); + list.add(21474836480L); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + + Assert.assertEquals("[1,21474836480,null,{},21474836480]", out.toString()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ColorSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ColorSerializerTest.java new file mode 100755 index 0000000000..255391bc66 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ColorSerializerTest.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.serializer; + +import java.awt.Color; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.AwtCodec; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class ColorSerializerTest extends TestCase { + + public void test_null() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Color.class).getClass()); + + VO vo = new VO(); + + Assert.assertEquals("{\"value\":null}", JSON.toJSONString(vo, SerializerFeature.WriteMapNullValue)); + } + + public void test_rgb() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Color.class).getClass()); + + VO vo = new VO(); + vo.setValue(new Color(1,1,1,0)); + + Assert.assertEquals("{\"value\":{\"r\":1,\"g\":1,\"b\":1}}", JSON.toJSONString(vo, SerializerFeature.WriteMapNullValue)); + } + + public void test_rgb_getAutowiredFor() throws Exception { + + } + + private static class VO { + + private Color value; + + public Color getValue() { + return value; + } + + public void setValue(Color value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest.java new file mode 100644 index 0000000000..0e4fb72a18 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ConcurrentHashMapTest extends TestCase { + + public void test_concurrentHashmap() throws Exception { + OffsetSerializeWrapper wrapper = new OffsetSerializeWrapper(); + wrapper.getOffsetTable().put(new MessageQueue(), new AtomicLong(123)); + String text = JSON.toJSONString(wrapper); + Assert.assertEquals("{\"offsetTable\":{{\"items\":[]}:123}}", text); + + OffsetSerializeWrapper wrapper2 = JSON.parseObject(text, OffsetSerializeWrapper.class); + Assert.assertEquals(1, wrapper2.getOffsetTable().size()); + + Iterator> iter = wrapper2.getOffsetTable().entrySet().iterator(); + Map.Entry entry = iter.next(); + Assert.assertEquals(0, entry.getKey().getItems().size()); + Assert.assertEquals(123L, entry.getValue().longValue()); + } + + public static class OffsetSerializeWrapper { + + private ConcurrentHashMap offsetTable = new ConcurrentHashMap(); + + public ConcurrentHashMap getOffsetTable() { + return offsetTable; + } + + public void setOffsetTable(ConcurrentHashMap offsetTable) { + this.offsetTable = offsetTable; + } + + } + + public static class MessageQueue { + + private List items = new LinkedList(); + + public List getItems() { + return items; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest2.java new file mode 100644 index 0000000000..0c309baee1 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest2.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ConcurrentHashMapTest2 extends TestCase { + + public void test_concurrentHashmap() throws Exception { + OffsetSerializeWrapper wrapper = new OffsetSerializeWrapper(); + wrapper.getOffsetTable().put(new MessageQueue(), new AtomicInteger(123)); + String text = JSON.toJSONString(wrapper); + Assert.assertEquals("{\"offsetTable\":{{\"items\":[]}:123}}", text); + + OffsetSerializeWrapper wrapper2 = JSON.parseObject(text, OffsetSerializeWrapper.class); + Assert.assertEquals(1, wrapper2.getOffsetTable().size()); + + Iterator> iter = wrapper2.getOffsetTable().entrySet().iterator(); + Map.Entry entry = iter.next(); + Assert.assertEquals(0, entry.getKey().getItems().size()); + Assert.assertEquals(123, entry.getValue().intValue()); + } + + public static class OffsetSerializeWrapper { + + private ConcurrentHashMap offsetTable = new ConcurrentHashMap(); + + public ConcurrentHashMap getOffsetTable() { + return offsetTable; + } + + public void setOffsetTable(ConcurrentHashMap offsetTable) { + this.offsetTable = offsetTable; + } + + } + + public static class MessageQueue { + + private List items = new LinkedList(); + + public List getItems() { + return items; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest3.java b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest3.java new file mode 100644 index 0000000000..b3a3c02c1d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest3.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ConcurrentHashMapTest3 extends TestCase { + + public void test_concurrentHashmap() throws Exception { + OffsetSerializeWrapper wrapper = new OffsetSerializeWrapper(); + wrapper.getOffsetTable().put(new MessageQueue(), new AtomicBoolean(true)); + String text = JSON.toJSONString(wrapper); + Assert.assertEquals("{\"offsetTable\":{{\"items\":[]}:true}}", text); + + OffsetSerializeWrapper wrapper2 = JSON.parseObject(text, OffsetSerializeWrapper.class); + Assert.assertEquals(1, wrapper2.getOffsetTable().size()); + + Iterator> iter = wrapper2.getOffsetTable().entrySet().iterator(); + Map.Entry entry = iter.next(); + Assert.assertEquals(0, entry.getKey().getItems().size()); + Assert.assertEquals(true, entry.getValue().get()); + } + + public static class OffsetSerializeWrapper { + + private ConcurrentHashMap offsetTable = new ConcurrentHashMap(); + + public ConcurrentHashMap getOffsetTable() { + return offsetTable; + } + + public void setOffsetTable(ConcurrentHashMap offsetTable) { + this.offsetTable = offsetTable; + } + + } + + public static class MessageQueue { + + private List items = new LinkedList(); + + public List getItems() { + return items; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest4.java b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest4.java new file mode 100644 index 0000000000..2497498a0a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest4.java @@ -0,0 +1,79 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicReference; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ConcurrentHashMapTest4 extends TestCase { + + public void test_concurrentHashmap() throws Exception { + OffsetSerializeWrapper wrapper = new OffsetSerializeWrapper(); + wrapper.getOffsetTable().put(new MessageQueue(), new AtomicReference(new A(true))); + String text = JSON.toJSONString(wrapper); + Assert.assertEquals("{\"offsetTable\":{{\"items\":[]}:{\"value\":true}}}", text); + + OffsetSerializeWrapper wrapper2 = JSON.parseObject(text, OffsetSerializeWrapper.class); + Assert.assertEquals(1, wrapper2.getOffsetTable().size()); + + Iterator>> iter = wrapper2.getOffsetTable().entrySet().iterator(); + Map.Entry> entry = iter.next(); + Assert.assertEquals(0, entry.getKey().getItems().size()); + Assert.assertEquals(true, entry.getValue().get().isValue()); + } + + public static class OffsetSerializeWrapper { + + private ConcurrentHashMap> offsetTable = new ConcurrentHashMap>(); + + public ConcurrentHashMap> getOffsetTable() { + return offsetTable; + } + + public void setOffsetTable(ConcurrentHashMap> offsetTable) { + this.offsetTable = offsetTable; + } + + } + + public static class MessageQueue { + + private List items = new LinkedList(); + + public List getItems() { + return items; + } + + } + + public static class A { + + private boolean value; + + public A(){ + + } + + public A(boolean value){ + super(); + this.value = value; + } + + public boolean isValue() { + return value; + } + + public void setValue(boolean value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest5.java b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest5.java new file mode 100644 index 0000000000..99a532d4ba --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest5.java @@ -0,0 +1,79 @@ +package com.alibaba.json.bvt.serializer; + +import java.lang.ref.WeakReference; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ConcurrentHashMapTest5 extends TestCase { + + public void test_concurrentHashmap() throws Exception { + OffsetSerializeWrapper wrapper = new OffsetSerializeWrapper(); + wrapper.offsetTable.put(new MessageQueue(), new WeakReference(new A(true))); + String text = JSON.toJSONString(wrapper); + Assert.assertEquals("{\"offsetTable\":{{\"items\":[]}:{\"value\":true}}}", text); + + OffsetSerializeWrapper wrapper2 = JSON.parseObject(text, OffsetSerializeWrapper.class); + Assert.assertEquals(1, wrapper2.getOffsetTable().size()); + + Iterator>> iter = wrapper2.getOffsetTable().entrySet().iterator(); + Map.Entry> entry = iter.next(); + Assert.assertEquals(0, entry.getKey().getItems().size()); + Assert.assertEquals(true, entry.getValue().get().isValue()); + } + + public static class OffsetSerializeWrapper { + + private ConcurrentHashMap> offsetTable = new ConcurrentHashMap>(); + + public ConcurrentHashMap> getOffsetTable() { + return offsetTable; + } + + public void setOffsetTable(ConcurrentHashMap> offsetTable) { + this.offsetTable = offsetTable; + } + + } + + public static class MessageQueue { + + private List items = new LinkedList(); + + public List getItems() { + return items; + } + + } + + public static class A { + + private boolean value; + + public A(){ + + } + + public A(boolean value){ + super(); + this.value = value; + } + + public boolean isValue() { + return value; + } + + public void setValue(boolean value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest6.java b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest6.java new file mode 100644 index 0000000000..024b2a24d5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest6.java @@ -0,0 +1,80 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.Serializable; +import java.lang.ref.WeakReference; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ConcurrentHashMapTest6 extends TestCase { + + public void test_concurrentHashmap() throws Exception { + OffsetSerializeWrapper wrapper = new OffsetSerializeWrapper(); + wrapper.offsetTable.put(new MessageQueue(), new WeakReference(new A(true))); + String text = JSON.toJSONString(wrapper); + Assert.assertEquals("{\"offsetTable\":{{\"items\":[]}:{\"value\":true}}}", text); + + OffsetSerializeWrapper wrapper2 = JSON.parseObject(text, OffsetSerializeWrapper.class); + Assert.assertEquals(1, wrapper2.getOffsetTable().size()); + + Iterator>> iter = wrapper2.getOffsetTable().entrySet().iterator(); + Map.Entry> entry = iter.next(); + Assert.assertEquals(0, entry.getKey().getItems().size()); + Assert.assertEquals(true, entry.getValue().get().isValue()); + } + + public static class OffsetSerializeWrapper { + + private ConcurrentHashMap> offsetTable = new ConcurrentHashMap>(); + + public ConcurrentHashMap> getOffsetTable() { + return offsetTable; + } + + public void setOffsetTable(ConcurrentHashMap> offsetTable) { + this.offsetTable = offsetTable; + } + + } + + public static class MessageQueue { + + private List items = new LinkedList(); + + public List getItems() { + return items; + } + + } + + public static class A implements Serializable { + + private boolean value; + + public A(){ + + } + + public A(boolean value){ + super(); + this.value = value; + } + + public boolean isValue() { + return value; + } + + public void setValue(boolean value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest7.java b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest7.java new file mode 100644 index 0000000000..c05c2d85f6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest7.java @@ -0,0 +1,79 @@ +package com.alibaba.json.bvt.serializer; + +import java.lang.ref.SoftReference; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ConcurrentHashMapTest7 extends TestCase { + + public void test_concurrentHashmap() throws Exception { + OffsetSerializeWrapper wrapper = new OffsetSerializeWrapper(); + wrapper.getOffsetTable().put(new MessageQueue(), new SoftReference(new A(true))); + String text = JSON.toJSONString(wrapper); + Assert.assertEquals("{\"offsetTable\":{{\"items\":[]}:{\"value\":true}}}", text); + + OffsetSerializeWrapper wrapper2 = JSON.parseObject(text, OffsetSerializeWrapper.class); + Assert.assertEquals(1, wrapper2.getOffsetTable().size()); + + Iterator>> iter = wrapper2.getOffsetTable().entrySet().iterator(); + Map.Entry> entry = iter.next(); + Assert.assertEquals(0, entry.getKey().getItems().size()); + Assert.assertEquals(true, entry.getValue().get().isValue()); + } + + public static class OffsetSerializeWrapper { + + private ConcurrentHashMap> offsetTable = new ConcurrentHashMap>(); + + public ConcurrentHashMap> getOffsetTable() { + return offsetTable; + } + + public void setOffsetTable(ConcurrentHashMap> offsetTable) { + this.offsetTable = offsetTable; + } + + } + + public static class MessageQueue { + + private List items = new LinkedList(); + + public List getItems() { + return items; + } + + } + + public static class A { + + private boolean value; + + public A(){ + + } + + public A(boolean value){ + super(); + this.value = value; + } + + public boolean isValue() { + return value; + } + + public void setValue(boolean value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DateFormatSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/DateFormatSerializerTest.java new file mode 100644 index 0000000000..d39e05f22b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DateFormatSerializerTest.java @@ -0,0 +1,85 @@ +package com.alibaba.json.bvt.serializer; + +import java.text.SimpleDateFormat; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class DateFormatSerializerTest extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_date() throws Exception { + Assert.assertEquals("{\"format\":null}", JSON.toJSONString(new VO(), SerializerFeature.WriteMapNullValue)); + } + + public void test_date_2() throws Exception { + SerializeWriter out = new SerializeWriter(); + SerializeConfig config = new SerializeConfig(); + JSONSerializer serializer = new JSONSerializer(out, config); + + serializer.config(SerializerFeature.WriteMapNullValue, true); + serializer.write(new VO()); + + Assert.assertEquals("{\"format\":null}", out.toString()); + } + + public void test_date_3() throws Exception { + SerializeWriter out = new SerializeWriter(); + SerializeConfig config = new SerializeConfig(); + JSONSerializer serializer = new JSONSerializer(out, config); + + serializer.config(SerializerFeature.WriteClassName, true); + serializer.write(new VO()); + + Assert.assertEquals("{\"@type\":\"com.alibaba.json.bvt.serializer.DateFormatSerializerTest$VO\"}", + out.toString()); + } + + public void test_date_4() throws Exception { + SerializeWriter out = new SerializeWriter(); + SerializeConfig config = new SerializeConfig(); + JSONSerializer serializer = new JSONSerializer(out, config); + + SimpleDateFormat format = new SimpleDateFormat("yyyy"); + format.setTimeZone(JSON.defaultTimeZone); + serializer.write(new VO(format)); + + Assert.assertEquals("{\"format\":\"yyyy\"}", out.toString()); + + JSON.parseObject(out.toString(), VO.class); + } + + private static class VO { + + private SimpleDateFormat format; + + public VO(){ + + } + + public VO(SimpleDateFormat format){ + this.format = format; + } + + public SimpleDateFormat getFormat() { + return format; + } + + public void setFormat(SimpleDateFormat format) { + this.format = format; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/DoubleArraySerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/DoubleArraySerializerTest.java old mode 100644 new mode 100755 similarity index 90% rename from src/test/java/com/alibaba/json/test/bvt/serializer/DoubleArraySerializerTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/DoubleArraySerializerTest.java index 405aa2a687..c5133c86e5 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/DoubleArraySerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/DoubleArraySerializerTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DoubleFormatTest.java b/src/test/java/com/alibaba/json/bvt/serializer/DoubleFormatTest.java new file mode 100644 index 0000000000..c2a55247e0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DoubleFormatTest.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 09/01/2017. + */ +public class DoubleFormatTest extends TestCase { + public void test_format() throws Exception { + Model model = new Model(); + model.value = 123.45678D; + + String str = JSON.toJSONString(model); + assertEquals("{\"value\":123.46}", str); + } + + public static class Model { + @JSONField(format = "0.00") + public double value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DoubleFormatTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/DoubleFormatTest2.java new file mode 100644 index 0000000000..3835ea654f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DoubleFormatTest2.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 09/01/2017. + */ +public class DoubleFormatTest2 extends TestCase { + public void test_format() throws Exception { + Model model = new Model(); + model.value = 123.45678D; + + String str = JSON.toJSONString(model); + assertEquals("{\"value\":123.46}", str); + } + + public static class Model { + @JSONField(format = "0.00") + public Double value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DoubleTest.java b/src/test/java/com/alibaba/json/bvt/serializer/DoubleTest.java new file mode 100755 index 0000000000..e859b3517a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DoubleTest.java @@ -0,0 +1,58 @@ +package com.alibaba.json.bvt.serializer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class DoubleTest extends TestCase { + + public void test_double() throws Exception { + VO vo = new VO(); + vo.setF1(Integer.MAX_VALUE); + vo.setF2(Double.MAX_VALUE); + vo.setF3(Integer.MAX_VALUE); + + String text = JSON.toJSONString(vo); + System.out.println(text); + + VO vo1 = JSON.parseObject(text, VO.class); + + Assert.assertEquals(vo.getF1(), vo1.getF1()); + Assert.assertTrue(vo.getF2() == vo1.getF2()); + Assert.assertEquals(vo.getF3(), vo1.getF3()); + } + + public static class VO { + + private int f1; + private double f2; + private int f3; + + public int getF1() { + return f1; + } + + public void setF1(int f1) { + this.f1 = f1; + } + + public double getF2() { + return f2; + } + + public void setF2(double f2) { + this.f2 = f2; + } + + public int getF3() { + return f3; + } + + public void setF3(int f3) { + this.f3 = f3; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DoubleTest_custom.java b/src/test/java/com/alibaba/json/bvt/serializer/DoubleTest_custom.java new file mode 100644 index 0000000000..6927186a49 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DoubleTest_custom.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.serializer; + +import java.text.DecimalFormat; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.DoubleSerializer; +import com.alibaba.fastjson.serializer.SerializeConfig; + +public class DoubleTest_custom extends TestCase { + + public void test_0() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.put(Double.class, new DoubleSerializer(new DecimalFormat("###.##"))); + Assert.assertEquals("1.12", JSON.toJSONString(1.123456789D, config)); + } + + public void test_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.put(Double.class, new DoubleSerializer("###.###")); + Assert.assertEquals("1.123", JSON.toJSONString(1.123456789D, config)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DoubleTest_custom2.java b/src/test/java/com/alibaba/json/bvt/serializer/DoubleTest_custom2.java new file mode 100644 index 0000000000..41e5efcdd5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DoubleTest_custom2.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.serializer; + +import java.text.DecimalFormat; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.DoubleSerializer; +import com.alibaba.fastjson.serializer.SerializeConfig; + +public class DoubleTest_custom2 extends TestCase { + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void test_0() throws Exception { + Map values = new HashMap(); + Double v = 9.00; + values.put("double", v); + + SerializeConfig config = new SerializeConfig(); + config.put(Double.class, new DoubleSerializer(new DecimalFormat("###.00"))); + Assert.assertEquals("{\"double\":9.00}", JSON.toJSONString(values, config)); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest.java b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest.java new file mode 100644 index 0000000000..35c50d3218 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest.java @@ -0,0 +1,52 @@ +/* + * www.yiji.com Inc. + * Copyright (c) 2014 All Rights Reserved + */ + +/* + * 修订记录: + * qzhanbo@yiji.com 2015-03-01 00:55 创建 + * + */ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class DupSetterTest extends TestCase { + + public void testEnum() { + VO enumTest = new VO(); + enumTest.setStatus(3); + String json = JSONObject.toJSONString(enumTest); + JSONObject.parseObject(json, VO.class); + } + + public static class VO { + + private Integer status; + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public void setStatus(Status status) { + throw new IllegalStateException(); + } + } + + public static enum Status { + ENABLE(1); + + private Integer code; + + Status(Integer code){ + this.code = code; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest2.java new file mode 100644 index 0000000000..3097cf9397 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest2.java @@ -0,0 +1,42 @@ +/* + * www.yiji.com Inc. + * Copyright (c) 2014 All Rights Reserved + */ + +/* + * 修订记录: + * qzhanbo@yiji.com 2015-03-01 00:55 创建 + * + */ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class DupSetterTest2 extends TestCase { + + public void testEnum() { + VO enumTest = new VO(); + enumTest.setStatus(3); + String json = JSONObject.toJSONString(enumTest); + JSONObject.parseObject(json, VO.class); + } + + public static class VO { + + private Integer status; + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public void setStatus(String status) { + throw new IllegalStateException(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest3.java b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest3.java new file mode 100644 index 0000000000..4f4fd9222c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest3.java @@ -0,0 +1,34 @@ +/* + * www.yiji.com Inc. + * Copyright (c) 2014 All Rights Reserved + */ + +/* + * 修订记录: + * qzhanbo@yiji.com 2015-03-01 00:55 创建 + * + */ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class DupSetterTest3 extends TestCase { + + public void testEnum() { + VO enumTest = new VO(); + enumTest.status = 3; + String json = JSONObject.toJSONString(enumTest); + JSONObject.parseObject(json, VO.class); + } + + public static class VO { + + public Integer status; + + @JSONField(name = "status") + public Integer status2; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest4.java b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest4.java new file mode 100644 index 0000000000..49149e94c4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest4.java @@ -0,0 +1,46 @@ +/* + * www.yiji.com Inc. + * Copyright (c) 2014 All Rights Reserved + */ + +/* + * 修订记录: + * qzhanbo@yiji.com 2015-03-01 00:55 创建 + * + */ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class DupSetterTest4 extends TestCase { + + public void testDup() { + V1 vo = new V1(); + vo.status = 3; + String json = JSONObject.toJSONString(vo); + JSONObject.parseObject(json, V1.class); + } + + public static class V0 { + + @JSONField(name="status") + public Long status2; + } + + public static class V1 extends V0 { + + private Integer status; + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest5.java b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest5.java new file mode 100644 index 0000000000..d6fb49b0ec --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest5.java @@ -0,0 +1,46 @@ +/* + * www.yiji.com Inc. + * Copyright (c) 2014 All Rights Reserved + */ + +/* + * 修订记录: + * qzhanbo@yiji.com 2015-03-01 00:55 创建 + * + */ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; + +import junit.framework.TestCase; + +public class DupSetterTest5 extends TestCase { + + public void testDup() { + V1 vo = new V1(); + vo.status = 3; + String json = JSONObject.toJSONString(vo); + JSONObject.parseObject(json, V1.class); + } + + public static class V0 { + + @JSONField(name="status") + public long status2; + } + + public static class V1 extends V0 { + + private Integer status; + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest6.java b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest6.java new file mode 100644 index 0000000000..cf18242739 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest6.java @@ -0,0 +1,47 @@ +/* + * www.yiji.com Inc. + * Copyright (c) 2014 All Rights Reserved + */ + +/* + * 修订记录: + * qzhanbo@yiji.com 2015-03-01 00:55 创建 + * + */ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONObject; + +import junit.framework.TestCase; + +public class DupSetterTest6 extends TestCase { + + public void testDupSetter() { + VO vo = new VO(); + vo.status = 3; + String json = JSONObject.toJSONString(vo); + VO vo2 = JSONObject.parseObject(json, VO.class); + Assert.assertEquals(3, vo2.status3); + } + + public static class VO { + + public int status; + private int status2; + private int status3; + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status2 = status; + } + + public void setStatus(String status) { + this.status3 = Integer.parseInt(status); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/EnumerationSeriliazerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/EnumerationSeriliazerTest.java new file mode 100644 index 0000000000..4657964549 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/EnumerationSeriliazerTest.java @@ -0,0 +1,132 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.Enumeration; +import java.util.Vector; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class EnumerationSeriliazerTest extends TestCase { + + public void test_nullAsEmtpyList() throws Exception { + VO e = new VO(); + Assert.assertEquals("{\"elements\":[]}", JSON.toJSONString(e, SerializerFeature.WriteMapNullValue, + SerializerFeature.WriteNullListAsEmpty)); + } + + public void test_null() throws Exception { + VO e = new VO(); + Assert.assertEquals("{\"elements\":null}", JSON.toJSONString(e, SerializerFeature.WriteMapNullValue)); + } + + public void test_1() throws Exception { + VO e = new VO(new Entity(), new Entity()); + Assert.assertEquals("{\"elements\":[{},{}]}", JSON.toJSONString(e, SerializerFeature.WriteMapNullValue)); + } + + public void test_2() throws Exception { + VO e = new VO(new Entity(), new Entity2()); + Assert.assertEquals("{\"elements\":[{},{\"@type\":\"com.alibaba.json.bvt.serializer.EnumerationSeriliazerTest$Entity2\"}]}", + JSON.toJSONString(e, SerializerFeature.WriteClassName, + SerializerFeature.NotWriteRootClassName)); + } + + public void test_3() throws Exception { + VO2 e = new VO2(new Entity(), new Entity()); + Assert.assertEquals("{\"elements\":[{},{}]}", JSON.toJSONString(e, SerializerFeature.WriteClassName, + SerializerFeature.NotWriteRootClassName)); + } + + public void test_4() throws Exception { + VO3 e = new VO3(new Entity(), new Entity2()); + Assert.assertEquals("{\"elements\":[{\"@type\":\"com.alibaba.json.bvt.serializer.EnumerationSeriliazerTest$Entity\"},{\"@type\":\"com.alibaba.json.bvt.serializer.EnumerationSeriliazerTest$Entity2\"}]}", JSON.toJSONString(e, SerializerFeature.WriteClassName, + SerializerFeature.NotWriteRootClassName)); + } + + private static class VO { + + private Enumeration elements; + + public VO(Entity... array){ + if (array.length > 0) { + Vector vector = new Vector(); + for (Entity item : array) { + vector.add(item); + } + this.elements = vector.elements(); + } + } + + public Enumeration getElements() { + return elements; + } + + public void setElements(Enumeration elements) { + this.elements = elements; + } + + } + + private static class VO2 extends IVO2 { + + public VO2(Entity... array){ + if (array.length > 0) { + Vector vector = new Vector(); + for (Entity item : array) { + vector.add(item); + } + this.elements = vector.elements(); + } + } + + } + + private static class VO3 { + + private Enumeration elements; + + public VO3(Entity... array){ + if (array.length > 0) { + Vector vector = new Vector(); + for (Entity item : array) { + vector.add(item); + } + this.elements = vector.elements(); + } + } + + public Enumeration getElements() { + return elements; + } + + public void setElements(Enumeration elements) { + this.elements = elements; + } + + } + + private static abstract class IVO2 { + + protected Enumeration elements; + + public Enumeration getElements() { + return elements; + } + + public void setElements(Enumeration elements) { + this.elements = elements; + } + } + + public static class Entity { + + } + + public static class Entity2 extends Entity { + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ErrorTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ErrorTest.java new file mode 100644 index 0000000000..989e55aef6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ErrorTest.java @@ -0,0 +1,78 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import com.alibaba.fastjson.serializer.SerializeConfig; + +public class ErrorTest extends TestCase { + + public void test_error() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.put(A.class, new ObjectSerializer() { + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) + throws IOException { + throw new IOException(); + } + }); + JSONSerializer ser = new JSONSerializer(config); + + { + Exception error = null; + try { + ser.write(new A()); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + { + Exception error = null; + try { + B b = new B(); + b.setId(new A()); + ser.write(b); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + } + + public class A { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } + + public class B { + + private A id; + + public A getId() { + return id; + } + + public void setId(A id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/ExtendsTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ExtendsTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/serializer/ExtendsTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/ExtendsTest.java index a9c58c78a7..a27018dce0 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/ExtendsTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/ExtendsTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/FieldOrderTest.java b/src/test/java/com/alibaba/json/bvt/serializer/FieldOrderTest.java new file mode 100644 index 0000000000..2d94e16fa2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/FieldOrderTest.java @@ -0,0 +1,57 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +/** + * Created by wenshao on 2016/11/2. + */ +public class FieldOrderTest extends TestCase { + public void test_field_order() throws Exception { + Person p = new Person(); + p.setName("njb"); + School s = new School(); + s.setName("llyz"); + p.setSchool(s); + String json = JSON.toJSONString(p); + assertEquals("{\"name\":\"njb\",\"school\":{\"name\":\"llyz\"}}", json); + } + + public static class Person { + private String name; + private School school; + + public boolean isSchool() { + return false; + } + + public School getSchool() { + return school; + } + + public void setSchool(School school) { + this.school = school; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + + public static class School { + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/FileTest.java b/src/test/java/com/alibaba/json/bvt/serializer/FileTest.java old mode 100644 new mode 100755 similarity index 86% rename from src/test/java/com/alibaba/json/test/bvt/serializer/FileTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/FileTest.java index 944b9a5eb1..1a2e0efa04 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/FileTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/FileTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.io.File; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/FloatArraySerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/FloatArraySerializerTest.java old mode 100644 new mode 100755 similarity index 93% rename from src/test/java/com/alibaba/json/test/bvt/serializer/FloatArraySerializerTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/FloatArraySerializerTest.java index 67d99f6348..a1c192cf7c --- a/src/test/java/com/alibaba/json/test/bvt/serializer/FloatArraySerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/FloatArraySerializerTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/FloatFormatTest.java b/src/test/java/com/alibaba/json/bvt/serializer/FloatFormatTest.java new file mode 100644 index 0000000000..59b3259ecd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/FloatFormatTest.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 09/01/2017. + */ +public class FloatFormatTest extends TestCase { + public void test_format() throws Exception { + Model model = new Model(); + model.value = 123.45678F; + + String str = JSON.toJSONString(model); + assertEquals("{\"value\":123.46}", str); + } + + public static class Model { + @JSONField(format = "0.00") + public float value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/FloatFormatTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/FloatFormatTest2.java new file mode 100644 index 0000000000..e9b0a9a6f8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/FloatFormatTest2.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; + +/** + * Created by wenshao on 09/01/2017. + */ +public class FloatFormatTest2 extends TestCase { + public void test_format() throws Exception { + Model model = new Model(); + model.value = 123.45678F; + + String str = JSON.toJSONString(model); + assertEquals("{\"value\":123.46}", str); + } + + public static class Model { + @JSONField(format = "0.00") + public Float value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/FloatTest.java b/src/test/java/com/alibaba/json/bvt/serializer/FloatTest.java new file mode 100755 index 0000000000..c32ca31031 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/FloatTest.java @@ -0,0 +1,65 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class FloatTest extends TestCase { + + public void test_0() throws Exception { + Assert.assertEquals("null", JSON.toJSONString(Float.NaN)); + Assert.assertEquals("null", JSON.toJSONString(Double.NaN)); + Assert.assertEquals("null", JSON.toJSONString(Float.POSITIVE_INFINITY)); + Assert.assertEquals("null", JSON.toJSONString(Float.NEGATIVE_INFINITY)); + Assert.assertEquals("null", JSON.toJSONString(Double.NaN)); + Assert.assertEquals("null", JSON.toJSONString(Double.POSITIVE_INFINITY)); + Assert.assertEquals("null", JSON.toJSONString(Double.NEGATIVE_INFINITY)); + Assert.assertEquals("null", JSON.toJSONString(new Float(Float.NaN))); + Assert.assertEquals("null", JSON.toJSONString(new Double(Double.NaN))); + + //Assert.assertEquals("{\"f1\":null,\"f2\":null}", JSON.toJSONString(new Bean())); + //Assert.assertEquals("{\"f1\":null,\"f2\":null}", JSON.toJSONString(new Bean(Float.POSITIVE_INFINITY, Double.POSITIVE_INFINITY))); + //Assert.assertEquals("{\"f1\":null,\"f2\":null}", JSON.toJSONString(new Bean(Float.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY))); + Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean())).get("f1")); + Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean())).get("f2")); + + Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean(Float.POSITIVE_INFINITY, Double.POSITIVE_INFINITY))).get("f1")); + Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean(Float.POSITIVE_INFINITY, Double.POSITIVE_INFINITY))).get("f2")); + + Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean(Float.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY))).get("f1")); + Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean(Float.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY))).get("f2")); + } + + public static class Bean { + + private float f1 = Float.NaN; + private double f2 = Double.NaN; + + public Bean() { + + } + + public Bean(float f1, double f2) { + this.f1 = f1; + this.f2 = f2; + } + + public float getF1() { + return f1; + } + + public void setF1(float f1) { + this.f1 = f1; + } + + public double getF2() { + return f2; + } + + public void setF2(double f2) { + this.f2 = f2; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/FontSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/FontSerializerTest.java new file mode 100755 index 0000000000..f1d0dd37e4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/FontSerializerTest.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.serializer; + +import java.awt.Font; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.AwtCodec; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + + +public class FontSerializerTest extends TestCase { + + public void test_null() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Font.class).getClass()); + + VO vo = new VO(); + + Assert.assertEquals("{\"value\":null}", JSON.toJSONString(vo, SerializerFeature.WriteMapNullValue)); + } + + private static class VO { + + private Font value; + + public Font getValue() { + return value; + } + + public void setValue(Font value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeNotMatchTest.java b/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeNotMatchTest.java new file mode 100644 index 0000000000..23c2971db7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeNotMatchTest.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.math.BigInteger; + +/** + * Created by wenshao on 10/02/2017. + */ +public class GenericTypeNotMatchTest extends TestCase { + public void test_for_notMatch() throws Exception { + Model model = new Model(); + Base base = model; + base.id = BigInteger.valueOf(3); + JSON.toJSONString(base); + } + + + public static class Model extends Base { + } + + public static class Base { + public T id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeNotMatchTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeNotMatchTest2.java new file mode 100644 index 0000000000..b9637fc13c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeNotMatchTest2.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.math.BigInteger; + +/** + * Created by wenshao on 10/02/2017. + */ +public class GenericTypeNotMatchTest2 extends TestCase { + public void test_for_notMatch() throws Exception { + Model model = new Model(); + + Base base = model; + base.setId(BigInteger.valueOf(3)); + + JSON.toJSONString(base); + } + + + public static class Model extends Base { + + } + + public static class Base { + private T xid; + + public void setId(T id) { + this.xid = id; + } + + public T getId() { + return xid; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeTest.java b/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeTest.java new file mode 100644 index 0000000000..ef601b0437 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.Serializable; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class GenericTypeTest extends TestCase { + + public void test_gerneric() throws Exception { + MyResultResult result = new MyResultResult(); + JSON.toJSONString(result); + } + + public static class MyResultResult extends BaseResult { + } + + public static class BaseResult implements Serializable { + public T data; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeTest2.java new file mode 100644 index 0000000000..867235fa9a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/GenericTypeTest2.java @@ -0,0 +1,25 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.Serializable; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class GenericTypeTest2 extends TestCase { + + public void test_gerneric() throws Exception { + MyResultResult result = new MyResultResult(); + JSON.toJSONString(result); + } + + public static class MyResultResult extends BaseResult { + } + + public static class BaseResult { + private T data; + public T getData() { + return data; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/IgnoreGetMethodTest.java b/src/test/java/com/alibaba/json/bvt/serializer/IgnoreGetMethodTest.java new file mode 100644 index 0000000000..b7bebf384b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/IgnoreGetMethodTest.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class IgnoreGetMethodTest extends TestCase { +// public void test_nested_object() { +// QueryResult result = new QueryResult(); +// result.setPay(new PayDO()); +// String json = JSON.toJSONString(result, SerializerFeature.IgnoreNonFieldGetter); +// System.out.println(json); +// } + + public void test() { + PayDO result = new PayDO(); + String json = JSON.toJSONString(result, SerializerFeature.IgnoreNonFieldGetter); + System.out.println(json); + } + + public static class PayDO { + + public Integer getCurrentSubPayOrder() { + throw new RuntimeException("non getter getXXX method should not be called"); + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/IgnoreNonFieldGetterTest.java b/src/test/java/com/alibaba/json/bvt/serializer/IgnoreNonFieldGetterTest.java new file mode 100644 index 0000000000..08ff17312e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/IgnoreNonFieldGetterTest.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class IgnoreNonFieldGetterTest extends TestCase { + + public void test_int() throws Exception { + VO vo = new VO(); + vo.setId(123); + + String text = JSON.toJSONString(vo, SerializerFeature.IgnoreNonFieldGetter); + Assert.assertEquals("{\"id\":123}", text); + + } + + public static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getNextId() { + return id + 1; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/IgnoreNonFieldGetterTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/IgnoreNonFieldGetterTest2.java new file mode 100644 index 0000000000..5ce188f6f3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/IgnoreNonFieldGetterTest2.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class IgnoreNonFieldGetterTest2 extends TestCase { + + public void test_int() throws Exception { + VO vo = new VO(); + vo.setId(123); + + String text = JSON.toJSONString(vo, SerializerFeature.IgnoreNonFieldGetter); + Assert.assertEquals("{\"id\":123}", text); + + } + + private static class VO { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getNextId() { + return id + 1; + } + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/InetAddressTest.java b/src/test/java/com/alibaba/json/bvt/serializer/InetAddressTest.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/serializer/InetAddressTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/InetAddressTest.java index 7ab0aaab7a..c39f686745 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/InetAddressTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/InetAddressTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.net.InetAddress; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/InetSocketAddressTest.java b/src/test/java/com/alibaba/json/bvt/serializer/InetSocketAddressTest.java new file mode 100755 index 0000000000..d2b334dd73 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/InetSocketAddressTest.java @@ -0,0 +1,21 @@ +package com.alibaba.json.bvt.serializer; + +import java.net.InetAddress; +import java.net.InetSocketAddress; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; + +public class InetSocketAddressTest extends TestCase { + + public void test_timezone() throws Exception { + InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 80); + + String text = JSON.toJSONString(address); + + InetSocketAddress address2 = JSON.parseObject(text, InetSocketAddress.class); + Assert.assertEquals(address, address2); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/IntArrayEncodeTest.java b/src/test/java/com/alibaba/json/bvt/serializer/IntArrayEncodeTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/serializer/IntArrayEncodeTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/IntArrayEncodeTest.java index 5a4747553e..c9d7866be4 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/IntArrayEncodeTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/IntArrayEncodeTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/IntFieldTest.java b/src/test/java/com/alibaba/json/bvt/serializer/IntFieldTest.java new file mode 100644 index 0000000000..d2423ae3d8 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/IntFieldTest.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class IntFieldTest extends TestCase { + + public void test_model() throws Exception { + Model model = new Model(); + model.id = -1001; + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"id\":-1001}", text); + } + + public void test_model_max() throws Exception { + Model model = new Model(); + model.id = Integer.MIN_VALUE; + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"id\":-2147483648}", text); + } + + public static class Model { + + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/IntFieldTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/IntFieldTest2.java new file mode 100644 index 0000000000..c7d4924263 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/IntFieldTest2.java @@ -0,0 +1,87 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringReader; +import java.util.Map; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONReader; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class IntFieldTest2 extends TestCase { + + public void test_model() throws Exception { + Model model = new Model(); + model.id = -1001; + model.id2 = -1002; + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"id\":-1001,\"id2\":-1002}", text); + } + + public void test_model_max() throws Exception { + Model model = new Model(); + model.id = Integer.MIN_VALUE; + model.id2 = Integer.MAX_VALUE; + + String text = JSON.toJSONString(model); + Assert.assertEquals("{\"id\":-2147483648,\"id2\":2147483647}", text); + { + JSONReader reader = new JSONReader(new StringReader(text)); + Model model2 = reader.readObject(Model.class); + Assert.assertEquals(model.id, model2.id); + Assert.assertEquals(model.id2, model2.id2); + reader.close(); + } + } + + public void test_model_map() throws Exception { + String text = "{\"model\":{\"id\":-1001,\"id2\":-1002}}"; + + JSONReader reader = new JSONReader(new StringReader(text)); + Map map = reader.readObject(new TypeReference>() { + }); + Model model2 = map.get("model"); + Assert.assertEquals(-1001, model2.id); + Assert.assertEquals(-1002, model2.id2); + reader.close(); + } + + public void test_model_map_error() throws Exception { + String text = "{\"model\":{\"id\":-1001,\"id2\":-1002["; + + Exception error = null; + JSONReader reader = new JSONReader(new StringReader(text)); + try { + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_model_map_error_2() throws Exception { + String text = "{\"model\":{\"id\":-1001,\"id2\":-1002}["; + + Exception error = null; + JSONReader reader = new JSONReader(new StringReader(text)); + try { + reader.readObject(new TypeReference>() { + }); + } catch (JSONException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class Model { + + public int id; + public int id2; + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/IntegerArrayEncodeTest.java b/src/test/java/com/alibaba/json/bvt/serializer/IntegerArrayEncodeTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/serializer/IntegerArrayEncodeTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/IntegerArrayEncodeTest.java index ba68b1ff5c..a5fcba460f --- a/src/test/java/com/alibaba/json/test/bvt/serializer/IntegerArrayEncodeTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/IntegerArrayEncodeTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/IntegerArrayFieldSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/IntegerArrayFieldSerializerTest.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/serializer/IntegerArrayFieldSerializerTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/IntegerArrayFieldSerializerTest.java index fa0fa3b07b..a97e1272cb --- a/src/test/java/com/alibaba/json/test/bvt/serializer/IntegerArrayFieldSerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/IntegerArrayFieldSerializerTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/IntegerSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/IntegerSerializerTest.java new file mode 100755 index 0000000000..c77f890e86 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/IntegerSerializerTest.java @@ -0,0 +1,31 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + + +public class IntegerSerializerTest extends TestCase { + + public void test_null() throws Exception { + VO vo = new VO(); + + Assert.assertEquals("{\"value\":null}", JSON.toJSONString(vo, SerializerFeature.WriteMapNullValue)); + } + + private static class VO { + + private Integer value; + + public Integer getValue() { + return value; + } + + public void setValue(Integer value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/InterfaceTest.java b/src/test/java/com/alibaba/json/bvt/serializer/InterfaceTest.java new file mode 100755 index 0000000000..62511d1b98 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/InterfaceTest.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class InterfaceTest extends TestCase { + public void test_interface() throws Exception { + A a = new A(); + a.setId(123); + a.setName("xasdf"); + + String text = JSON.toJSONString(a); + Assert.assertEquals("{\"ID\":123,\"Name\":\"xasdf\"}", text); + } + + public static class A implements IA, IB { + private int id; + private String name; + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + } + + public static interface IA { + @JSONField(name="ID") + int getId(); + } + + public static interface IB { + @JSONField(name="Name") + String getName(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest.java new file mode 100644 index 0000000000..3c52d28734 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest.java @@ -0,0 +1,43 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class JSONFieldTest extends TestCase { + public void test_jsonField() throws Exception { + VO vo = new VO(); + + vo.setId(123); + vo.setName("xx"); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123}", text); + } + + public static class VO { + private int id; + + @JSONField(serialize=false) + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest2.java new file mode 100644 index 0000000000..b9f0731c77 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest2.java @@ -0,0 +1,42 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class JSONFieldTest2 extends TestCase { + public void test_jsonField() throws Exception { + VO vo = new VO(); + + vo.setId(123); + vo.setFlag(true); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123}", text); + } + + public static class VO { + private int id; + + @JSONField(serialize = false) + private boolean flag; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public boolean isFlag() { + return flag; + } + + public void setFlag(boolean flag) { + this.flag = flag; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest3.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest3.java new file mode 100644 index 0000000000..0d427f2a3e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest3.java @@ -0,0 +1,57 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class JSONFieldTest3 extends TestCase { + public void test_jsonField() throws Exception { + VO vo = new VO(); + + vo.setId(123); + vo.setFlag(true); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123}", text); + } + + public static class VO { + private int id; + + @JSONField(serialize = false) + private boolean _flag; + + @JSONField(serialize = false) + private int _id2; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public boolean isFlag() { + return _flag; + } + + public void setFlag(boolean flag) { + this._flag = flag; + } + + + public int getId2() { + return _id2; + } + + + public void setId2(int id2) { + this._id2 = id2; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest4.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest4.java new file mode 100644 index 0000000000..896bcafa30 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest4.java @@ -0,0 +1,57 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; + +public class JSONFieldTest4 extends TestCase { + public void test_jsonField() throws Exception { + VO vo = new VO(); + + vo.setId(123); + vo.setFlag(true); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123}", text); + } + + public static class VO { + private int id; + + @JSONField(serialize = false) + private boolean m_flag; + + @JSONField(serialize = false) + private int m_id2; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public boolean isFlag() { + return m_flag; + } + + public void setFlag(boolean flag) { + this.m_flag = flag; + } + + + public int getId2() { + return m_id2; + } + + + public void setId2(int id2) { + this.m_id2 = id2; + } + + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest5.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest5.java new file mode 100644 index 0000000000..c04911b09d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest5.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.serializer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class JSONFieldTest5 extends TestCase { + + public void test_jsonField() throws Exception { + VO vo = new VO(); + + vo.setID(123); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"iD\":123}", text); + + Assert.assertEquals(123, JSON.parseObject(text, VO.class).getID()); + } + + public static class VO { + + private int id; + + public int getID() { + return id; + } + + public void setID(int id) { + this.id = id; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_0.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_0.java new file mode 100644 index 0000000000..4aaab9e4cc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_0.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +public class JSONFieldTest_unwrapped_0 extends TestCase { + + public void test_jsonField() throws Exception { + VO vo = new VO(); + vo.id = 123; + vo.localtion = new Localtion(127, 37); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123,\"latitude\":37,\"longitude\":127}", text); + + VO vo2 = JSON.parseObject(text, VO.class); + assertNotNull(vo2.localtion); + assertEquals(vo.localtion.latitude, vo2.localtion.latitude); + assertEquals(vo.localtion.longitude, vo2.localtion.longitude); + } + + public static class VO { + public int id; + + @JSONField(unwrapped = true) + public Localtion localtion; + } + + public static class Localtion { + public int longitude; + public int latitude; + + public Localtion() { + + } + + public Localtion(int longitude, int latitude) { + this.longitude = longitude; + this.latitude = latitude; + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_1.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_1.java new file mode 100644 index 0000000000..4059c6c7d4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_1.java @@ -0,0 +1,37 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; + +public class JSONFieldTest_unwrapped_1 extends TestCase { + + public void test_jsonField() throws Exception { + VO vo = new VO(); + vo.id = 123; + vo.properties.put("latitude", 37); + vo.properties.put("longitude", 127); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123,\"latitude\":37,\"longitude\":127}", text); + + VO vo2 = JSON.parseObject(text, VO.class); + assertNotNull(vo2.properties); + assertEquals(37, vo2.properties.get("latitude")); + assertEquals(127, vo2.properties.get("longitude")); + + } + + public static class VO { + public int id; + + @JSONField(unwrapped = true) + public Map properties = new LinkedHashMap(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_2.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_2.java new file mode 100644 index 0000000000..2a414ddd49 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_2.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class JSONFieldTest_unwrapped_2 extends TestCase { + + public void test_jsonField() throws Exception { + String text = "{\"id\":123,\"latitude\":37,\"longitude\":127}"; + Assert.assertEquals("{\"id\":123,\"latitude\":37,\"longitude\":127}", text); + + VO vo2 = JSON.parseObject(text, VO.class); + assertNotNull(vo2.properties); + assertEquals(37, vo2.properties.get("latitude")); + assertEquals(127, vo2.properties.get("longitude")); + + } + + public static class VO { + public int id; + + private Map properties = new LinkedHashMap(); + + @JSONField(unwrapped = true) + public void setProperty(String key, Object value) { + properties.put(key, value); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_3.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_3.java new file mode 100644 index 0000000000..89e590a668 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_3.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class JSONFieldTest_unwrapped_3 extends TestCase { + + public void test_jsonField() throws Exception { + Health vo = new Health(); + vo.id = 123; + vo.details.put("latitude", 37); + vo.details.put("longitude", 127); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"latitude\":37,\"longitude\":127,\"id\":123}", text); + + Health vo2 = JSON.parseObject(text, Health.class); + assertNotNull(vo2.details); + assertEquals(37, vo2.details.get("latitude")); + assertEquals(127, vo2.details.get("longitude")); + + } + + public void test_null() throws Exception { + Health vo = new Health(); + vo.id = 123; + vo.details = null; + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123}", text); + } + + public void test_empty() throws Exception { + Health vo = new Health(); + vo.id = 123; + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123}", text); + } + + public static class Health { + public int id; + + @JSONField(unwrapped = true) + public Map details = new LinkedHashMap(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_4.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_4.java new file mode 100644 index 0000000000..916093c1ba --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_4.java @@ -0,0 +1,56 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class JSONFieldTest_unwrapped_4 extends TestCase { + + public void test_jsonField() throws Exception { + Health vo = new Health(); + vo.id = 123; + vo.border = 234; + vo.details.put("latitude", 37); + vo.details.put("longitude", 127); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"border\":234,\"latitude\":37,\"longitude\":127,\"id\":123}", text); + + Health vo2 = JSON.parseObject(text, Health.class); + assertNotNull(vo2.details); + assertEquals(37, vo2.details.get("latitude")); + assertEquals(127, vo2.details.get("longitude")); + + } + + public void test_null() throws Exception { + Health vo = new Health(); + vo.id = 123; + vo.border = 234; + vo.details = null; + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"border\":234,\"id\":123}", text); + } + + public void test_empty() throws Exception { + Health vo = new Health(); + vo.id = 123; + vo.border = 234; + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"border\":234,\"id\":123}", text); + } + + public static class Health { + public int id; + public int border; + + @JSONField(unwrapped = true) + public Map details = new LinkedHashMap(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_5.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_5.java new file mode 100644 index 0000000000..91f6709eb9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_5.java @@ -0,0 +1,53 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class JSONFieldTest_unwrapped_5 extends TestCase { + + public void test_jsonField() throws Exception { + Health vo = new Health(); + vo.id = 123; + vo.details.put("latitude", 37); + vo.details.put("longitude", 127); + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123,\"latitude\":37,\"longitude\":127}", text); + + Health vo2 = JSON.parseObject(text, Health.class); + assertNotNull(vo2.details); + assertEquals(37, vo2.details.get("latitude")); + assertEquals(127, vo2.details.get("longitude")); + + } + + public void test_null() throws Exception { + Health vo = new Health(); + vo.id = 123; + vo.details = null; + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123}", text); + } + + public void test_empty() throws Exception { + Health vo = new Health(); + vo.id = 123; + + String text = JSON.toJSONString(vo); + Assert.assertEquals("{\"id\":123}", text); + } + + public static class Health { + @JSONField(ordinal = 1) + public int id; + + @JSONField(unwrapped = true, ordinal = 2) + public Map details = new LinkedHashMap(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONObjectOrderTest.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONObjectOrderTest.java new file mode 100644 index 0000000000..d0288ffc40 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONObjectOrderTest.java @@ -0,0 +1,18 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + +public class JSONObjectOrderTest extends TestCase { + public void test_for_order() throws Exception { + System.out.println(JSON.VERSION); + JSONObject jsonObj = new JSONObject(true); + jsonObj.put("code","code"); + jsonObj.put("msg","msg"); + jsonObj.put("data", "data"); + String jsonStr = JSON.toJSONString(jsonObj, SerializerFeature.MapSortField); + assertEquals("{\"code\":\"code\",\"msg\":\"msg\",\"data\":\"data\"}", jsonStr); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerDeprecatedTest.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerDeprecatedTest.java new file mode 100644 index 0000000000..c91aa95e15 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerDeprecatedTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; + +import junit.framework.TestCase; + +@SuppressWarnings("deprecation") +public class JSONSerializerDeprecatedTest extends TestCase { + + public void test_() throws Exception { + JSONSerializer ser = new JSONSerializer(new SerializeConfig()); + + ser.setDateFormat(new ISO8601DateFormat()); + Assert.assertEquals(null, ser.getDateFormatPattern()); + + ser.close(); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerFeatureTest.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerFeatureTest.java old mode 100644 new mode 100755 similarity index 96% rename from src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerFeatureTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerFeatureTest.java index f9c12b3026..a6253882e5 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerFeatureTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerFeatureTest.java @@ -1,11 +1,11 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.io.StringWriter; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerMapTest.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerMapTest.java new file mode 100755 index 0000000000..c750a887d4 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerMapTest.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.serializer; + +import java.lang.reflect.Field; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.IntegerCodec; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.util.IdentityHashMap; + +import junit.framework.TestCase; + +@SuppressWarnings("deprecation") +public class JSONSerializerMapTest extends TestCase { + + public void test_0() throws Exception { + SerializeConfig map = new SerializeConfig(); + + Assert.assertFalse(0 == size(map)); + Assert.assertEquals(true, map.get(Integer.class) == IntegerCodec.instance); + + Assert.assertEquals(true, map.put(Integer.class, IntegerCodec.instance)); + Assert.assertEquals(true, map.put(Integer.class, IntegerCodec.instance)); + Assert.assertEquals(true, map.put(Integer.class, IntegerCodec.instance)); + + Assert.assertEquals(true, map.get(Integer.class) == IntegerCodec.instance); + + Assert.assertFalse(0 == size(map)); + } + + public static int size(SerializeConfig config) throws Exception { + Field serializersField = SerializeConfig.class.getDeclaredField("serializers"); + serializersField.setAccessible(true); + Object map = serializersField.get(config); + + Field bucketsField = IdentityHashMap.class.getDeclaredField("buckets"); + bucketsField.setAccessible(true); + Object[] buckets = (Object[]) bucketsField.get(map); + + Field nextField = Class.forName("com.alibaba.fastjson.util.IdentityHashMap$Entry").getDeclaredField("next"); + + int size = 0; + for (int i = 0; i < buckets.length; ++i) { + for (Object entry = buckets[i]; entry != null; entry = nextField.get(entry)) { + size++; + } + } + return size; + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest.java index 0aa6bf44b3..8eee92f854 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.io.IOException; import java.io.StringWriter; @@ -7,7 +7,7 @@ import java.util.Date; import java.util.Iterator; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONAware; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerTest1.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest1.java old mode 100644 new mode 100755 similarity index 91% rename from src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerTest1.java rename to src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest1.java index c8a21b9314..9a8ecc38a6 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerTest1.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest1.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest2.java old mode 100644 new mode 100755 similarity index 81% rename from src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerTest2.java rename to src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest2.java index 0d1b823313..c32529640f --- a/src/test/java/com/alibaba/json/test/bvt/serializer/JSONSerializerTest2.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest2.java @@ -1,30 +1,35 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.io.IOException; import java.io.Writer; -import junit.framework.Assert; -import junit.framework.TestCase; +import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; + public class JSONSerializerTest2 extends TestCase { public void test_0() throws Exception { JSONSerializer serializer = new JSONSerializer(); - int size = serializer.getMapping().size(); + int size = JSONSerializerMapTest.size(serializer.getMapping()); + serializer.config(SerializerFeature.WriteEnumUsingToString, false); + serializer.config(SerializerFeature.WriteEnumUsingName, false); serializer.write(Type.A); - Assert.assertEquals(size + 1, serializer.getMapping().size()); + Assert.assertTrue(size < JSONSerializerMapTest.size(serializer.getMapping())); Assert.assertEquals(Integer.toString(Type.A.ordinal()), serializer.getWriter().toString()); } public void test_1() throws Exception { JSONSerializer serializer = new JSONSerializer(); + serializer.config(SerializerFeature.WriteEnumUsingToString, false); + serializer.config(SerializerFeature.WriteEnumUsingName, false); serializer.write(new A(Type.B)); Assert.assertEquals("{\"type\":" + Integer.toString(Type.B.ordinal()) + "}", serializer.getWriter().toString()); diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest3.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest3.java new file mode 100644 index 0000000000..707173b990 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest3.java @@ -0,0 +1,38 @@ +package com.alibaba.json.bvt.serializer; + +import java.text.SimpleDateFormat; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; + +import junit.framework.TestCase; + +public class JSONSerializerTest3 extends TestCase { + protected void setUp() throws Exception { + JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); + JSON.defaultLocale = Locale.CHINA; + } + + public void test_0() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + + serializer.setDateFormat("yyyy"); + Assert.assertEquals("yyyy", ((SimpleDateFormat) serializer.getDateFormat()).toPattern()); + Assert.assertEquals("yyyy", serializer.getDateFormatPattern()); + + serializer.setDateFormat("yyyy-MM"); + Assert.assertEquals("yyyy-MM", ((SimpleDateFormat) serializer.getDateFormat()).toPattern()); + + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + format.setTimeZone(JSON.defaultTimeZone); + serializer.setDateFormat(format); + Assert.assertEquals("yyyy-MM-dd", serializer.getDateFormatPattern()); + + serializer.close(); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/JSONTypeIncludesTest.java b/src/test/java/com/alibaba/json/bvt/serializer/JSONTypeIncludesTest.java new file mode 100644 index 0000000000..e659ce2d4b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/JSONTypeIncludesTest.java @@ -0,0 +1,23 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONType; + +import junit.framework.TestCase; + +public class JSONTypeIncludesTest extends TestCase { + public void test_includes() throws Exception { + Model model = new Model(); + model.id = 1001; + model.name = "wenshao"; + + String text = JSON.toJSONString(model); + System.out.println(text); + } + + @JSONType(includes="name") + public static class Model { + public int id; + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/JavaBeanSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/JavaBeanSerializerTest.java old mode 100644 new mode 100755 similarity index 85% rename from src/test/java/com/alibaba/json/test/bvt/serializer/JavaBeanSerializerTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/JavaBeanSerializerTest.java index dbc7ad6852..348fcef494 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/JavaBeanSerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/JavaBeanSerializerTest.java @@ -1,10 +1,10 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; @@ -23,7 +23,7 @@ public void test_0_s() throws Exception { a.getL0().add("B"); JavaBeanSerializer serializer = new JavaBeanSerializer(A.class); - serializer.write(new JSONSerializer(out), a); + serializer.write(new JSONSerializer(out), a, null, null, 0); Assert.assertEquals("{\"l0\":[\"A\",\"B\"]}", out.toString()); } @@ -36,7 +36,7 @@ public void test_1_s() throws Exception { a.getL0().add("B"); JavaBeanSerializer serializer = new JavaBeanSerializer(B.class); - serializer.write(new JSONSerializer(out), a); + serializer.write(new JSONSerializer(out), a, null, null, 0); Assert.assertEquals("{\"l0\":[\"A\",\"B\"],\"l1\":[]}", out.toString()); } @@ -45,7 +45,7 @@ public void test_2_s() throws Exception { SerializeWriter out = new SerializeWriter(); JavaBeanSerializer serializer = new JavaBeanSerializer(F.class); - serializer.write(new JSONSerializer(out), new F(new E(123))); + serializer.write(new JSONSerializer(out), new F(new E(123)), null, null, 0); Assert.assertEquals("{\"e\":{\"id\":123}}", out.toString()); } @@ -54,12 +54,7 @@ public void test_3_s() throws Exception { SerializeWriter out = new SerializeWriter(); JavaBeanSerializer serializer = new JavaBeanSerializer(F.class); - serializer.write(new JSONSerializer(out), new F(null)); - - for (FieldSerializer getter : serializer.getGetters()) { - getter.getName(); - getter.getMethod(); - } + serializer.write(new JSONSerializer(out), new F(null), null, null, 0); Assert.assertEquals("{}", out.toString()); } @@ -69,7 +64,7 @@ public void test_error_s() throws Exception { try { SerializeWriter out = new SerializeWriter(); JavaBeanSerializer serializer = new JavaBeanSerializer(C.class); - serializer.write(new JSONSerializer(out), new C()); + serializer.write(new JSONSerializer(out), new C(), null, null, 0); } catch (JSONException e) { error = e; } @@ -81,7 +76,7 @@ public void test_error_1_s() throws Exception { try { SerializeWriter out = new SerializeWriter(); JavaBeanSerializer serializer = new JavaBeanSerializer(D.class); - serializer.write(new JSONSerializer(out), new D()); + serializer.write(new JSONSerializer(out), new D(), null, null, 0); } catch (JSONException e) { error = e; } diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/JavaBeanSerializerTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/JavaBeanSerializerTest2.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/serializer/JavaBeanSerializerTest2.java rename to src/test/java/com/alibaba/json/bvt/serializer/JavaBeanSerializerTest2.java index f1fcb8253f..754df55d2c --- a/src/test/java/com/alibaba/json/test/bvt/serializer/JavaBeanSerializerTest2.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/JavaBeanSerializerTest2.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.util.Collections; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ListFieldTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ListFieldTest.java new file mode 100644 index 0000000000..74f2c4cfe5 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ListFieldTest.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +import junit.framework.TestCase; + +public class ListFieldTest extends TestCase { + + public void test_for_list() throws Exception { + Model model = new Model(); + model.id = 1000; + Assert.assertEquals("{\"id\":1000,\"values\":[]}", JSON.toJSONString(model)); + + model.values.add("1001"); + Assert.assertEquals("{\"id\":1000,\"values\":[\"1001\"]}", JSON.toJSONString(model)); + + model.values.add("1002"); + Assert.assertEquals("{\"id\":1000,\"values\":[\"1001\",\"1002\"]}", JSON.toJSONString(model)); + + model.values.add("1003"); + Assert.assertEquals("{\"id\":1000,\"values\":[\"1001\",\"1002\",\"1003\"]}", JSON.toJSONString(model)); + } + + public static class Model { + + private int id; + private List values = new ArrayList(); + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public List getValues() { + return values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest.java new file mode 100755 index 0000000000..0c225cce4a --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest.java @@ -0,0 +1,116 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ListSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; +import org.junit.Assert; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class ListSerializerTest extends TestCase { + + public void test_0_s() throws Exception { + SerializeWriter out = new SerializeWriter(); + + ListSerializer listSerializer = new ListSerializer(); + listSerializer.write(new JSONSerializer(out), Collections.EMPTY_LIST, null, null, 0); + + Assert.assertEquals("[]", out.toString()); + } + + public void test_2_s() throws Exception { + SerializeWriter out = new SerializeWriter(); + + ListSerializer listSerializer = new ListSerializer(); + List list = new ArrayList(); + list.add(1); + list.add(2); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + + Assert.assertEquals("[1,2]", out.toString()); + } + + public void test_3_s() throws Exception { + SerializeWriter out = new SerializeWriter(); + + ListSerializer listSerializer = new ListSerializer(); + List list = new ArrayList(); + list.add(1); + list.add(2); + list.add(3); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + + Assert.assertEquals("[1,2,3]", out.toString()); + } + + public void test_4_s() throws Exception { + SerializeWriter out = new SerializeWriter(); + + ListSerializer listSerializer = new ListSerializer(); + List list = new ArrayList(); + list.add(1L); + list.add(2L); + list.add(3L); + list.add(Collections.emptyMap()); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + + Assert.assertEquals("[1,2,3,{}]", out.toString()); + } + + public void test_5_s() throws Exception { + SerializeWriter out = new SerializeWriter(); + + ListSerializer listSerializer = new ListSerializer(); + List list = new ArrayList(); + list.add(1L); + list.add(21474836480L); + list.add(null); + list.add(Collections.emptyMap()); + list.add(21474836480L); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + + Assert.assertEquals("[1,21474836480,null,{},21474836480]", out.toString()); + } + + public void test_6_s() throws Exception { + SerializeWriter out = new SerializeWriter(SerializerFeature.BrowserCompatible); + + ListSerializer listSerializer = new ListSerializer(); + List list = new ArrayList(); + list.add(1L); + list.add(1453964515792017682L); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + + Assert.assertEquals("[1,\"1453964515792017682\"]", out.toString()); + } + + public void test_7_s() throws Exception { + SerializeWriter out = new SerializeWriter( + SerializerFeature.BrowserCompatible, SerializerFeature.WriteClassName + ); + + ListSerializer listSerializer = new ListSerializer(); + List list = new ArrayList(); + list.add(1L); + list.add(1453964515792017682L); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + + Assert.assertEquals("[1L,1453964515792017682L]", out.toString()); + } + + public void test_8_s() throws Exception { + SerializeWriter out = new SerializeWriter(SerializerFeature.WriteClassName); + + ListSerializer listSerializer = new ListSerializer(); + List list = new ArrayList(); + list.add(1L); + list.add(1453964515792017682L); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + + Assert.assertEquals("[1L,1453964515792017682L]", out.toString()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/ListSerializerTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest2.java old mode 100644 new mode 100755 similarity index 80% rename from src/test/java/com/alibaba/json/test/bvt/serializer/ListSerializerTest2.java rename to src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest2.java index 74dd9606fa..67914bbc8c --- a/src/test/java/com/alibaba/json/test/bvt/serializer/ListSerializerTest2.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest2.java @@ -1,9 +1,9 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.util.Arrays; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; @@ -21,7 +21,7 @@ public void test_0() throws Exception { List list = Arrays.asList(array); - listSerializer.write(new JSONSerializer(out), list); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); // System.out.println(out.toString()); Assert.assertEquals("[1,2,3,4,5,6,\"a\"]", out.toString()); diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest3.java b/src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest3.java new file mode 100644 index 0000000000..1fb11fec1f --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest3.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.ArrayList; +import java.util.LinkedList; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ListSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; + +public class ListSerializerTest3 extends TestCase { + + public void test_1() throws Exception { + SerializeWriter out = new SerializeWriter(); + ListSerializer listSerializer = new ListSerializer(); + + ArrayList list = new ArrayList(); + for (int i = 0; i < 100000; i++) { + list.add(i); + } + + long start = System.currentTimeMillis(); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + long end = System.currentTimeMillis(); + + System.out.println("arrayList time: " + (end - start)); + } + + public void test_2() throws Exception { + SerializeWriter out = new SerializeWriter(); + + ListSerializer listSerializer = new ListSerializer(); + + LinkedList list = new LinkedList(); + for (int i = 0; i < 100000; i++) { + list.add(i); + } + + long start = System.currentTimeMillis(); + listSerializer.write(new JSONSerializer(out), list, null, null, 0); + long end = System.currentTimeMillis(); + + System.out.println("linkedList time: " + (end - start)); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ListTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ListTest.java new file mode 100755 index 0000000000..94f1c128ca --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ListTest.java @@ -0,0 +1,35 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.LinkedList; +import java.util.List; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class ListTest extends TestCase { + + public void test_null() throws Exception { + List list = new LinkedList(); + list.add(23L); + list.add(45L); + + Assert.assertEquals("[23L,45L]", JSON.toJSONString(list, SerializerFeature.WriteClassName)); + } + + public static class VO { + + private Object value; + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/LocalTest.java b/src/test/java/com/alibaba/json/bvt/serializer/LocalTest.java old mode 100644 new mode 100755 similarity index 85% rename from src/test/java/com/alibaba/json/test/bvt/serializer/LocalTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/LocalTest.java index a8c492a314..eb234ce0c1 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/LocalTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/LocalTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.util.Locale; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/LongArraySerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/LongArraySerializerTest.java new file mode 100755 index 0000000000..393b1087a9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/LongArraySerializerTest.java @@ -0,0 +1,34 @@ +package com.alibaba.json.bvt.serializer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class LongArraySerializerTest extends TestCase { + + public void test_0() { + Assert.assertEquals("[]", JSON.toJSONString(new long[0])); + Assert.assertEquals("[1,2]", JSON.toJSONString(new long[] { 1, 2 })); + Assert.assertEquals("[1,2,3,-4]", JSON.toJSONString(new long[] { 1, 2, 3, -4 })); + Assert.assertEquals("{\"value\":null}", JSON.toJSONString(new Entity(), SerializerFeature.WriteMapNullValue)); + Assert.assertEquals("{\"value\":[]}", JSON.toJSONString(new Entity(), SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); + } + + public static class Entity { + + private long[] value; + + public long[] getValue() { + return value; + } + + public void setValue(long[] value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/MapSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/MapSerializerTest.java old mode 100644 new mode 100755 similarity index 75% rename from src/test/java/com/alibaba/json/test/bvt/serializer/MapSerializerTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/MapSerializerTest.java index 4ec73e0ff0..02b3f837c4 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/MapSerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/MapSerializerTest.java @@ -1,12 +1,14 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.MapSerializer; import com.alibaba.fastjson.serializer.SerializeWriter; @@ -18,7 +20,7 @@ public void test_empty_1() throws Exception { SerializeWriter out = new SerializeWriter(); MapSerializer mapSerializer = new MapSerializer(); - mapSerializer.write(new JSONSerializer(out), Collections.EMPTY_MAP); + mapSerializer.write(new JSONSerializer(out), Collections.EMPTY_MAP, null, null, 0); Assert.assertEquals("{}", out.toString()); } @@ -27,7 +29,7 @@ public void test_singleton_1() throws Exception { SerializeWriter out = new SerializeWriter(); MapSerializer mapSerializer = new MapSerializer(); - mapSerializer.write(new JSONSerializer(out), Collections.singletonMap("A", 1)); + mapSerializer.write(new JSONSerializer(out), Collections.singletonMap("A", 1), null, null, 0); Assert.assertEquals("{\"A\":1}", out.toString()); } @@ -39,7 +41,7 @@ public void test_int2_s() throws Exception { Map map = new LinkedHashMap(); map.put("A", 1); map.put("B", 2); - mapSerializer.write(new JSONSerializer(out), map); + mapSerializer.write(new JSONSerializer(out), map, null, null, 0); Assert.assertEquals("{\"A\":1,\"B\":2}", out.toString()); } @@ -51,7 +53,7 @@ public void test_long2_s() throws Exception { Map map = new LinkedHashMap(); map.put("A", 1L); map.put("B", 2L); - mapSerializer.write(new JSONSerializer(out), map); + mapSerializer.write(new JSONSerializer(out), map, null, null, 0); Assert.assertEquals("{\"A\":1,\"B\":2}", out.toString()); } @@ -63,7 +65,7 @@ public void test_string2_s() throws Exception { Map map = new LinkedHashMap(); map.put("A", "1"); map.put("B", "2"); - mapSerializer.write(new JSONSerializer(out), map); + mapSerializer.write(new JSONSerializer(out), map, null, null, 0); Assert.assertEquals("{\"A\":\"1\",\"B\":\"2\"}", out.toString()); } @@ -78,7 +80,7 @@ public void test_string3_s() throws Exception { Map map = new LinkedHashMap(); map.put("A", "1"); map.put("B", "2"); - mapSerializer.write(serializer, map); + mapSerializer.write(serializer, map, null, null, 0); Assert.assertEquals("{'A':'1','B':'2'}", out.toString()); } @@ -87,7 +89,7 @@ public void test_special_s() throws Exception { SerializeWriter out = new SerializeWriter(); MapSerializer mapSerializer = new MapSerializer(); - mapSerializer.write(new JSONSerializer(out), Collections.singletonMap("A\nB", 1)); + mapSerializer.write(new JSONSerializer(out), Collections.singletonMap("A\nB", 1), null, null, 0); Assert.assertEquals("{\"A\\nB\":1}", out.toString()); } @@ -96,7 +98,7 @@ public void test_special2_s() throws Exception { SerializeWriter out = new SerializeWriter(); MapSerializer mapSerializer = new MapSerializer(); - mapSerializer.write(new JSONSerializer(out), Collections.singletonMap("A\nB", 1)); + mapSerializer.write(new JSONSerializer(out), Collections.singletonMap("A\nB", 1), null, null, 0); Assert.assertEquals("{\"A\\nB\":1}", out.toString()); } @@ -105,7 +107,7 @@ public void test_special3_s() throws Exception { SerializeWriter out = new SerializeWriter(); MapSerializer mapSerializer = new MapSerializer(); - mapSerializer.write(new JSONSerializer(out), Collections.singletonMap("A\nB", Collections.EMPTY_MAP)); + mapSerializer.write(new JSONSerializer(out), Collections.singletonMap("A\nB", Collections.EMPTY_MAP), null, null, 0); Assert.assertEquals("{\"A\\nB\":{}}", out.toString()); } @@ -117,8 +119,15 @@ public void test_4() throws Exception { map.put("bytes", new byte[] { 1, 2 }); MapSerializer mapSerializer = new MapSerializer(); - mapSerializer.write(new JSONSerializer(out), map); - - Assert.assertEquals("{\"TOP\":\"value\",\"bytes\":[1,2]}", out.toString()); + mapSerializer.write(new JSONSerializer(out), map, null, null, 0); + + String text = out.toString(); + Assert.assertEquals("{\"TOP\":\"value\",\"bytes\":\"AQI=\"}", text); + + JSONObject json = JSON.parseObject(text); + byte[] bytes = json.getBytes("bytes"); + Assert.assertEquals(1, bytes[0]); + Assert.assertEquals(2, bytes[1]); + Assert.assertEquals(2, bytes.length); } } diff --git a/src/test/java/com/alibaba/json/bvt/serializer/MapTest.java b/src/test/java/com/alibaba/json/bvt/serializer/MapTest.java new file mode 100755 index 0000000000..37a070ff6b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/MapTest.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class MapTest extends TestCase { + + public void test_no_sort() throws Exception { + JSONObject obj = new JSONObject(true); + obj.put("name", "jobs"); + obj.put("id", 33); + String text = toJSONString(obj); + Assert.assertEquals("{'name':'jobs','id':33}", text); + } + + public void test_null() throws Exception { + JSONObject obj = new JSONObject(true); + obj.put("name", null); + String text = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue); + Assert.assertEquals("{\"name\":null}", text); + } + + public static final String toJSONString(Object object) { + SerializeWriter out = new SerializeWriter(); + + try { + JSONSerializer serializer = new JSONSerializer(out); + serializer.config(SerializerFeature.SortField, false); + serializer.config(SerializerFeature.UseSingleQuotes, true); + + serializer.write(object); + + return out.toString(); + } catch (StackOverflowError e) { + throw new JSONException("maybe circular references", e); + } finally { + out.close(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/MaxBufSizeTest.java b/src/test/java/com/alibaba/json/bvt/serializer/MaxBufSizeTest.java new file mode 100644 index 0000000000..22c2673103 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/MaxBufSizeTest.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.serializer.SerializeWriter; +import junit.framework.TestCase; + +/** + * Created by wenshao on 01/04/2017. + */ +public class MaxBufSizeTest extends TestCase { + public void test_max_buf() throws Exception { + SerializeWriter writer = new SerializeWriter(); + + Throwable error = null; + try { + writer.setMaxBufSize(1); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/MaxBufSizeTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/MaxBufSizeTest2.java new file mode 100644 index 0000000000..7e31c4567c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/MaxBufSizeTest2.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import junit.framework.TestCase; + +import java.util.Arrays; + +/** + * Created by wenshao on 01/04/2017. + */ +public class MaxBufSizeTest2 extends TestCase { + public void test_max_buf() throws Exception { + char[] chars = new char[4096]; + Arrays.fill(chars, '0'); + + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("val", new String(chars)); + + Throwable error = null; + try { + toJSONString(jsonObject); + } catch (JSONException e) { + error = e; + } + assertNotNull(error); + } + + public String toJSONString(Object obj) { + + SerializeWriter out = new SerializeWriter(); + out.setMaxBufSize(4096); + try { + new JSONSerializer(out).write(obj); + return out.toString(); + } finally { + out.close(); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/MultiFieldIntTest_writer.java b/src/test/java/com/alibaba/json/bvt/serializer/MultiFieldIntTest_writer.java new file mode 100644 index 0000000000..f4d969e1d6 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/MultiFieldIntTest_writer.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONWriter; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class MultiFieldIntTest_writer extends TestCase { + + public void test_for_big_writer() throws Exception { + List list = new ArrayList(); + + for (int i = 0; i < 1024 * 10; ++i) { + Model model = new Model(); + model.id = 10000000 + i; + list.add(model); + } + + StringWriter out = new StringWriter(); + JSONWriter writer = new JSONWriter(out); + writer.writeObject(list); + writer.close(); + + String text = out.toString(); + System.out.println(text); + List results = JSON.parseObject(text, new TypeReference>() {}); + + Assert.assertEquals(list.size(), results.size()); + for (int i = 0; i < results.size(); ++i) { + Assert.assertEquals(list.get(i).id, results.get(i).id); + } + } + + public static class Model { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/MultiFieldIntTest_writer2.java b/src/test/java/com/alibaba/json/bvt/serializer/MultiFieldIntTest_writer2.java new file mode 100644 index 0000000000..003f5f947c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/MultiFieldIntTest_writer2.java @@ -0,0 +1,62 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONWriter; +import com.alibaba.fastjson.TypeReference; + +import junit.framework.TestCase; + +public class MultiFieldIntTest_writer2 extends TestCase { + + public void test_for_big_writer() throws Exception { + List list = new ArrayList(); + + for (int i = 0; i < 1024 * 10; ++i) { + Model model = new Model(); + model.i = 0; + model.j = 1; + model.k = 2; + model.v = 3; + model.l = 4; + model.m = 5; + model.n = 6; + list.add(model); + } + + StringWriter out = new StringWriter(); + JSONWriter writer = new JSONWriter(out); + writer.writeObject(list); + writer.close(); + + String text = out.toString(); + System.out.println(text); + List results = JSON.parseObject(text, new TypeReference>() {}); + + Assert.assertEquals(list.size(), results.size()); + for (int i = 0; i < results.size(); ++i) { + Assert.assertEquals(list.get(i).i, results.get(i).i); + Assert.assertEquals(list.get(i).j, results.get(i).j); + Assert.assertEquals(list.get(i).k, results.get(i).k); + Assert.assertEquals(list.get(i).v, results.get(i).v); + Assert.assertEquals(list.get(i).l, results.get(i).l); + Assert.assertEquals(list.get(i).m, results.get(i).m); + Assert.assertEquals(list.get(i).n, results.get(i).n); + } + } + + public static class Model { + public int i; + public int j; + public int k; + public int l; + public int m; + public int n; + public int v; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/NoneStringKeyTest.java b/src/test/java/com/alibaba/json/bvt/serializer/NoneStringKeyTest.java new file mode 100644 index 0000000000..2f12959bb2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/NoneStringKeyTest.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class NoneStringKeyTest extends TestCase { + + public void test_0() throws Exception { + Map map = new HashMap(); + map.put(1, 101); + + Assert.assertEquals("{1:101}", JSON.toJSONString(map)); + } + + public void test_1() throws Exception { + Map map = new HashMap(); + map.put(1, 101); + + Assert.assertEquals("{\"1\":101}", JSON.toJSONString(map, SerializerFeature.BrowserCompatible)); + } + + public void test_2() throws Exception { + Map map = new HashMap(); + map.put(1, 101); + + Assert.assertEquals("{\"1\":101}", JSON.toJSONString(map, SerializerFeature.WriteNonStringKeyAsString)); + } + + public void test_null_0() throws Exception { + Map map = new HashMap(); + map.put(null, 101); + + Assert.assertEquals("{null:101}", JSON.toJSONString(map)); + } + + public void test_3() throws Exception { + Map map = new HashMap(); + map.put(null, 101); + + Assert.assertEquals("{\"null\":101}", JSON.toJSONString(map, SerializerFeature.WriteNonStringKeyAsString)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/NotWriteDefaultValueTest.java b/src/test/java/com/alibaba/json/bvt/serializer/NotWriteDefaultValueTest.java new file mode 100644 index 0000000000..293df7e5a3 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/NotWriteDefaultValueTest.java @@ -0,0 +1,214 @@ +package com.alibaba.json.bvt.serializer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class NotWriteDefaultValueTest extends TestCase { + + public void test_for_byte() throws Exception { + VO_Byte vo = new VO_Byte(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_short() throws Exception { + VO_Short vo = new VO_Short(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_int() throws Exception { + VO_Int vo = new VO_Int(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_long() throws Exception { + VO_Long vo = new VO_Long(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_float() throws Exception { + VO_Float vo = new VO_Float(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_double() throws Exception { + VO_Double vo = new VO_Double(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_boolean() throws Exception { + VO_Boolean vo = new VO_Boolean(); + vo.f1 = true; + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{\"f1\":true}", text); + } + + public static class VO_Byte { + + private byte f0; + private byte f1; + + public byte getF0() { + return f0; + } + + public void setF0(byte f0) { + this.f0 = f0; + } + + public byte getF1() { + return f1; + } + + public void setF1(byte f1) { + this.f1 = f1; + } + + } + + public static class VO_Short { + + private short f0; + private short f1; + + public short getF0() { + return f0; + } + + public void setF0(short f0) { + this.f0 = f0; + } + + public short getF1() { + return f1; + } + + public void setF1(short f1) { + this.f1 = f1; + } + + } + + public static class VO_Int { + + private int f0; + private int f1; + + public int getF0() { + return f0; + } + + public void setF0(int f0) { + this.f0 = f0; + } + + public int getF1() { + return f1; + } + + public void setF1(int f1) { + this.f1 = f1; + } + } + + public static class VO_Long { + + private long f0; + private long f1; + + public long getF0() { + return f0; + } + + public void setF0(long f0) { + this.f0 = f0; + } + + public long getF1() { + return f1; + } + + public void setF1(long f1) { + this.f1 = f1; + } + + } + + public static class VO_Float { + + private float f0; + private float f1; + + public float getF0() { + return f0; + } + + public void setF0(float f0) { + this.f0 = f0; + } + + public float getF1() { + return f1; + } + + public void setF1(float f1) { + this.f1 = f1; + } + + } + + public static class VO_Double { + + private double f0; + private double f1; + + public double getF0() { + return f0; + } + + public void setF0(double f0) { + this.f0 = f0; + } + + public double getF1() { + return f1; + } + + public void setF1(double f1) { + this.f1 = f1; + } + + } + + public static class VO_Boolean { + + private boolean f0; + private boolean f1; + + public boolean isF0() { + return f0; + } + + public void setF0(boolean f0) { + this.f0 = f0; + } + + public boolean isF1() { + return f1; + } + + public void setF1(boolean f1) { + this.f1 = f1; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/NotWriteDefaultValueTest_NoneASM.java b/src/test/java/com/alibaba/json/bvt/serializer/NotWriteDefaultValueTest_NoneASM.java new file mode 100644 index 0000000000..0a01028595 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/NotWriteDefaultValueTest_NoneASM.java @@ -0,0 +1,214 @@ +package com.alibaba.json.bvt.serializer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class NotWriteDefaultValueTest_NoneASM extends TestCase { + + public void test_for_byte() throws Exception { + VO_Byte vo = new VO_Byte(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_short() throws Exception { + VO_Short vo = new VO_Short(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_int() throws Exception { + VO_Int vo = new VO_Int(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_long() throws Exception { + VO_Long vo = new VO_Long(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_float() throws Exception { + VO_Float vo = new VO_Float(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_double() throws Exception { + VO_Double vo = new VO_Double(); + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{}", text); + } + + public void test_for_boolean() throws Exception { + VO_Boolean vo = new VO_Boolean(); + vo.f1 = true; + String text = JSON.toJSONString(vo, SerializerFeature.NotWriteDefaultValue); + Assert.assertEquals("{\"f1\":true}", text); + } + + private static class VO_Byte { + + private byte f0; + private byte f1; + + public byte getF0() { + return f0; + } + + public void setF0(byte f0) { + this.f0 = f0; + } + + public byte getF1() { + return f1; + } + + public void setF1(byte f1) { + this.f1 = f1; + } + + } + + private static class VO_Short { + + private short f0; + private short f1; + + public short getF0() { + return f0; + } + + public void setF0(short f0) { + this.f0 = f0; + } + + public short getF1() { + return f1; + } + + public void setF1(short f1) { + this.f1 = f1; + } + + } + + private static class VO_Int { + + private int f0; + private int f1; + + public int getF0() { + return f0; + } + + public void setF0(int f0) { + this.f0 = f0; + } + + public int getF1() { + return f1; + } + + public void setF1(int f1) { + this.f1 = f1; + } + } + + private static class VO_Long { + + private long f0; + private long f1; + + public long getF0() { + return f0; + } + + public void setF0(long f0) { + this.f0 = f0; + } + + public long getF1() { + return f1; + } + + public void setF1(long f1) { + this.f1 = f1; + } + + } + + private static class VO_Float { + + private float f0; + private float f1; + + public float getF0() { + return f0; + } + + public void setF0(float f0) { + this.f0 = f0; + } + + public float getF1() { + return f1; + } + + public void setF1(float f1) { + this.f1 = f1; + } + + } + + private static class VO_Double { + + private double f0; + private double f1; + + public double getF0() { + return f0; + } + + public void setF0(double f0) { + this.f0 = f0; + } + + public double getF1() { + return f1; + } + + public void setF1(double f1) { + this.f1 = f1; + } + + } + + private static class VO_Boolean { + + private boolean f0; + private boolean f1; + + public boolean isF0() { + return f0; + } + + public void setF0(boolean f0) { + this.f0 = f0; + } + + public boolean isF1() { + return f1; + } + + public void setF1(boolean f1) { + this.f1 = f1; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/ObjectArraySerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ObjectArraySerializerTest.java old mode 100644 new mode 100755 similarity index 92% rename from src/test/java/com/alibaba/json/test/bvt/serializer/ObjectArraySerializerTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/ObjectArraySerializerTest.java index 7c20dea52f..deb87c541c --- a/src/test/java/com/alibaba/json/test/bvt/serializer/ObjectArraySerializerTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/ObjectArraySerializerTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ObjectSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ObjectSerializerTest.java new file mode 100644 index 0000000000..9c251d00b0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ObjectSerializerTest.java @@ -0,0 +1,50 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.IOException; +import java.lang.reflect.Type; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import com.alibaba.fastjson.serializer.SerializeConfig; + +import junit.framework.TestCase; + +public class ObjectSerializerTest extends TestCase { + + public void test_serialize() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.put(ResultCode.class, new ResultCodeSerilaizer()); + + Result result = new Result(); + result.code = ResultCode.SIGN_ERROR; + String json = JSON.toJSONString(result, config); + Assert.assertEquals("{\"code\":17}", json); + } + + public static class Result { + + public ResultCode code; + } + + public static enum ResultCode { + SUCCESS(1), ERROR(-1), UNKOWN_ERROR(999), LOGIN_FAILURE(8), INVALID_ARGUMENT(0), + SIGN_ERROR(17); + + public final int value; + + ResultCode(int value){ + this.value = value; + } + } + + public static class ResultCodeSerilaizer implements ObjectSerializer { + + public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, + int features) throws IOException { + serializer.write(((ResultCode) object).value); + } + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ObjectWriteTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ObjectWriteTest.java new file mode 100644 index 0000000000..34a1115193 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ObjectWriteTest.java @@ -0,0 +1,26 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.ObjectSerializer; +import com.alibaba.fastjson.serializer.SerializeConfig; +import junit.framework.TestCase; + +/** + * Created by wenshao on 15/03/2017. + */ +public class ObjectWriteTest extends TestCase { + public void test_objectWriteTest() throws Exception { + ObjectSerializer serializer = SerializeConfig.getGlobalInstance().getObjectWriter(Model.class); + + JSONSerializer jsonSerializer = new JSONSerializer(); + serializer.write(jsonSerializer, null, "a", Model.class, 0); + + String text = jsonSerializer.out.toString(); + assertEquals("null", text); + } + + public static class Model { + public int id; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ParserConfigTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ParserConfigTest.java new file mode 100755 index 0000000000..f9b472e97d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ParserConfigTest.java @@ -0,0 +1,28 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; + +import junit.framework.TestCase; + +public class ParserConfigTest extends TestCase { + + public void test_0() throws Exception { + ParserConfig config = new ParserConfig(); + config.getDeserializers(); + } + + + public void test_1() throws Exception { + ParserConfig config = new ParserConfig(Thread.currentThread().getContextClassLoader()); + + Model model = JSON.parseObject("{\"value\":123}", Model.class, config); + Assert.assertEquals(123, model.value); + } + + public static class Model { + public int value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/PascalNameFilterTest.java b/src/test/java/com/alibaba/json/bvt/serializer/PascalNameFilterTest.java new file mode 100755 index 0000000000..187a4b9df0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/PascalNameFilterTest.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.PascalNameFilter; + +public class PascalNameFilterTest extends TestCase { + + public void test_0() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + serializer.getNameFilters().add(new PascalNameFilter()); + + VO vo = new VO(); + vo.setId(123); + vo.setName("wenshao"); + + serializer.write(vo); + + Assert.assertEquals("{\"Id\":123,\"Name\":\"wenshao\"}", serializer.toString()); + + serializer.close(); + } + + public static class VO { + + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/PascalNameFilterTest_1.java b/src/test/java/com/alibaba/json/bvt/serializer/PascalNameFilterTest_1.java new file mode 100644 index 0000000000..1d442ae057 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/PascalNameFilterTest_1.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.LinkedHashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.PascalNameFilter; + +public class PascalNameFilterTest_1 extends TestCase { + + public void test_0() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + serializer.getNameFilters().add(new PascalNameFilter()); + + Map vo = new LinkedHashMap(); + vo.put("", 123); + vo.put(null, "wenshao"); + + serializer.write(vo); + + Assert.assertEquals("{\"\":123,null:\"wenshao\"}", serializer.toString()); + + serializer.close(); + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/PatternTest.java b/src/test/java/com/alibaba/json/bvt/serializer/PatternTest.java old mode 100644 new mode 100755 similarity index 86% rename from src/test/java/com/alibaba/json/test/bvt/serializer/PatternTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/PatternTest.java index 1aa6ce872e..bde1f14f38 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/PatternTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/PatternTest.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.util.regex.Pattern; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/PointSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/PointSerializerTest.java new file mode 100755 index 0000000000..f600c7598e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/PointSerializerTest.java @@ -0,0 +1,33 @@ +package com.alibaba.json.bvt.serializer; + +import java.awt.Point; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + + +public class PointSerializerTest extends TestCase { + + public void test_null() throws Exception { + VO vo = new VO(); + + Assert.assertEquals("{\"value\":null}", JSON.toJSONString(vo, SerializerFeature.WriteMapNullValue)); + } + + private static class VO { + + private Point value; + + public Point getValue() { + return value; + } + + public void setValue(Point value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/PrePropertyFilterTest.java b/src/test/java/com/alibaba/json/bvt/serializer/PrePropertyFilterTest.java new file mode 100644 index 0000000000..0e919414c9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/PrePropertyFilterTest.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.serializer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.PropertyPreFilter; + +public class PrePropertyFilterTest extends TestCase { + + public void test_0() throws Exception { + class VO { + public int getId() { throw new RuntimeException(); } + } + + PropertyPreFilter filter = new PropertyPreFilter () { + public boolean apply(JSONSerializer serializer, Object source, String name) { + return false; + } + }; + + VO vo = new VO(); + + String text = JSON.toJSONString(vo, filter); + Assert.assertEquals("{}", text); + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/indent/PrettyFormatTest.java b/src/test/java/com/alibaba/json/bvt/serializer/PrettyFormatTest.java old mode 100644 new mode 100755 similarity index 85% rename from src/test/java/com/alibaba/json/test/bvt/serializer/indent/PrettyFormatTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/PrettyFormatTest.java index 2f5a66bcc9..11efc72692 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/indent/PrettyFormatTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/PrettyFormatTest.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.serializer.indent; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/PrettyFormatTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/PrettyFormatTest2.java new file mode 100755 index 0000000000..ce1f4811be --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/PrettyFormatTest2.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializerFeature; +import junit.framework.TestCase; +import org.junit.Assert; + +public class PrettyFormatTest2 extends TestCase { + + public void test_0() throws Exception { + Model model = new Model(); + model.id = 123; + model.name = "wenshao"; + String text = JSON.toJSONString(model, SerializerFeature.PrettyFormat); + assertEquals("{\n" + + "\t\"id\":123,\n" + + "\t\"name\":\"wenshao\"\n" + + "}", text); + + Assert.assertEquals("[\n\t{},\n\t{}\n]", JSON.toJSONString(new Object[] { new Object(), new Object() }, SerializerFeature.PrettyFormat)); + } + + public static class Model { + public int id; + public String name; + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/PrimitiveTest.java b/src/test/java/com/alibaba/json/bvt/serializer/PrimitiveTest.java old mode 100644 new mode 100755 similarity index 94% rename from src/test/java/com/alibaba/json/test/bvt/serializer/PrimitiveTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/PrimitiveTest.java index 67aeb1e902..e44d1e5fed --- a/src/test/java/com/alibaba/json/test/bvt/serializer/PrimitiveTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/PrimitiveTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.io.StringWriter; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ProxyTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ProxyTest.java new file mode 100644 index 0000000000..7dbcefbac2 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ProxyTest.java @@ -0,0 +1,52 @@ +package com.alibaba.json.bvt.serializer; + +import java.lang.reflect.Method; + +import javassist.util.proxy.MethodHandler; +import javassist.util.proxy.ProxyFactory; +import javassist.util.proxy.ProxyObject; +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; + +public class ProxyTest extends TestCase { + + public void test_0() throws Exception { + A a = create(A.class); + a.setId(123); + + Assert.assertEquals("{\"id\":123}", JSON.toJSONString(a)); + } + + public static T create(Class classs) throws Exception { + ProxyFactory factory = new ProxyFactory(); + factory.setSuperclass(classs); + Class clazz = factory.createClass(); + MethodHandler handler = new MethodHandler() { + + public Object invoke(Object self, Method overridden, Method forwarder, Object[] args) throws Throwable { + return forwarder.invoke(self, args); + } + }; + Object instance = clazz.newInstance(); + ((ProxyObject) instance).setHandler(handler); + return (T) instance; + } + + public static class A { + + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ProxyTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/ProxyTest2.java new file mode 100644 index 0000000000..13bb2fc952 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ProxyTest2.java @@ -0,0 +1,29 @@ +package com.alibaba.json.bvt.serializer; + +import com.alibaba.fastjson.JSON; +import junit.framework.TestCase; + +import java.lang.reflect.Proxy; + +/** + * Created by wenshao on 07/08/2017. + */ +public class ProxyTest2 extends TestCase { + public void test_0() throws Exception { + Model model = JSON.parseObject("{\"id\":1001}", Model.class); + Model model2 = JSON.parseObject("{\"id\":1001}", Model.class); + System.out.println(model.getId()); + +// System.out.println(model.getClass()); +// System.out.println(model2.getClass()); + + assertEquals("{\"id\":1001}", JSON.toJSONString(model)); + assertEquals("{\"id\":1001}", JSON.toJSONString(model)); + + } + + public static interface Model { + int getId(); + void setId(int val); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/RectangleSerializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/RectangleSerializerTest.java new file mode 100755 index 0000000000..8c0897e89c --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/RectangleSerializerTest.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.serializer; + +import java.awt.Rectangle; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.AwtCodec; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + + +public class RectangleSerializerTest extends TestCase { + + public void test_null() throws Exception { + JSONSerializer serializer = new JSONSerializer(); + Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Rectangle.class).getClass()); + + VO vo = new VO(); + + Assert.assertEquals("{\"value\":null}", JSON.toJSONString(vo, SerializerFeature.WriteMapNullValue)); + } + + private static class VO { + + private Rectangle value; + + public Rectangle getValue() { + return value; + } + + public void setValue(Rectangle value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/ReferenceDeserializerTest.java b/src/test/java/com/alibaba/json/bvt/serializer/ReferenceDeserializerTest.java new file mode 100644 index 0000000000..7bfdd91d45 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/ReferenceDeserializerTest.java @@ -0,0 +1,48 @@ +package com.alibaba.json.bvt.serializer; + +import java.lang.ref.WeakReference; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.ReferenceCodec; + +public class ReferenceDeserializerTest extends TestCase { + + public void test_0() throws Exception { + ParserConfig config = new ParserConfig(); + config.putDeserializer(MyRef.class, ReferenceCodec.instance); + Exception error = null; + try { + JSON.parseObject("{\"ref\":{}}", VO.class, config, 0); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public static class VO { + + private MyRef ref; + + public MyRef getRef() { + return ref; + } + + public void setRef(MyRef ref) { + this.ref = ref; + } + + } + + public static class MyRef extends WeakReference { + + MyRef(T referent){ + super(referent); + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerialContextTest.java b/src/test/java/com/alibaba/json/bvt/serializer/SerialContextTest.java new file mode 100755 index 0000000000..6f768dc30e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerialContextTest.java @@ -0,0 +1,16 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.serializer.SerialContext; + + +public class SerialContextTest extends TestCase { + public void test_context() throws Exception { + SerialContext root = new SerialContext(null, null, null, 0, 0); + SerialContext context = new SerialContext(root, null, "x", 0, 0); + Assert.assertEquals("x", context.fieldName); + Assert.assertEquals("$.x", context.toString()); + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/SerialWriterStringEncoderTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/SerialWriterStringEncoderTest2.java old mode 100644 new mode 100755 similarity index 75% rename from src/test/java/com/alibaba/json/test/bvt/serializer/SerialWriterStringEncoderTest2.java rename to src/test/java/com/alibaba/json/bvt/serializer/SerialWriterStringEncoderTest2.java index 9e393ad104..79eaec4e92 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/SerialWriterStringEncoderTest2.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerialWriterStringEncoderTest2.java @@ -1,27 +1,29 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; +import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; -import junit.framework.Assert; -import junit.framework.TestCase; +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.SerializeWriter; -import com.alibaba.fastjson.serializer.SerialWriterStringEncoder; +import junit.framework.TestCase; public class SerialWriterStringEncoderTest2 extends TestCase { public void test_error_0() throws Exception { Charset charset = Charset.forName("UTF-8"); CharsetEncoder charsetEncoder = new MockCharsetEncoder2(charset); - SerialWriterStringEncoder encoder = new SerialWriterStringEncoder(charsetEncoder); + Exception error = null; char[] chars = "abc".toCharArray(); try { - encoder.encode(chars, 0, chars.length); + encode(charsetEncoder, chars, 0, chars.length); } catch (Exception ex) { error = ex; } @@ -31,18 +33,24 @@ public void test_error_0() throws Exception { public void test_error_1() throws Exception { Charset charset = Charset.forName("UTF-8"); CharsetEncoder realEncoder = charset.newEncoder(); + CharsetEncoder charsetEncoder = new MockCharsetEncoder(charset, realEncoder); - SerialWriterStringEncoder encoder = new SerialWriterStringEncoder(charsetEncoder); Exception error = null; char[] chars = "abc".toCharArray(); try { - encoder.encode(chars, 0, chars.length); + encode(charsetEncoder, chars, 0, chars.length); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } + + public static byte[] encode(CharsetEncoder encoder, char[] chars, int off, int len) throws Exception { + Method method = SerializeWriter.class.getDeclaredMethod("encode", CharsetEncoder.class, char[].class, int.class, int.class); + method.setAccessible(true); + return (byte[]) method.invoke(null, encoder, chars, off, len); + } public static class MockCharsetEncoder extends CharsetEncoder { private CharsetEncoder raw; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/SerialWriterTest.java b/src/test/java/com/alibaba/json/bvt/serializer/SerialWriterTest.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/serializer/SerialWriterTest.java rename to src/test/java/com/alibaba/json/bvt/serializer/SerialWriterTest.java index 0144062dfa..0505dc0ff4 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/SerialWriterTest.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerialWriterTest.java @@ -1,4 +1,4 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import junit.framework.TestCase; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest.java new file mode 100755 index 0000000000..eb696f4728 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest.java @@ -0,0 +1,39 @@ +package com.alibaba.json.bvt.serializer; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.LinkedHashMap; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class SerializeConfigTest extends TestCase { + + public void test_0() throws Exception { + SerializeConfig config = new SerializeConfig(); + + Method method = SerializeConfig.class.getDeclaredMethod("createJavaBeanSerializer", Class.class); + method.setAccessible(true); + Exception error = null; + try { + method.invoke(config, int.class); + } catch (InvocationTargetException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setTypeKey("%type"); + Assert.assertEquals("%type", config.getTypeKey()); + + Assert.assertEquals("{\"%type\":\"java.util.LinkedHashMap\"}", + JSON.toJSONString(new LinkedHashMap(), config, SerializerFeature.WriteClassName)); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest2.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest2.java new file mode 100644 index 0000000000..583a51b7bd --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest2.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.LinkedHashMap; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class SerializeConfigTest2 extends TestCase { + + public void test_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setTypeKey("%type"); + Assert.assertEquals("%type", config.getTypeKey()); + + Model model = new Model(); + model.value = 1001; + + Assert.assertEquals("{\"%type\":\"com.alibaba.json.bvt.serializer.SerializeConfigTest2$Model\",\"value\":1001}", + JSON.toJSONString(model, config, SerializerFeature.WriteClassName)); + } + + public static class Model { + public int value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest2_private.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest2_private.java new file mode 100644 index 0000000000..a43a8f73bc --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest2_private.java @@ -0,0 +1,30 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.LinkedHashMap; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class SerializeConfigTest2_private extends TestCase { + + public void test_1() throws Exception { + SerializeConfig config = new SerializeConfig(); + config.setTypeKey("%type"); + Assert.assertEquals("%type", config.getTypeKey()); + + Model model = new Model(); + model.value = 1001; + + Assert.assertEquals("{\"%type\":\"com.alibaba.json.bvt.serializer.SerializeConfigTest2_private$Model\",\"value\":1001}", + JSON.toJSONString(model, config, SerializerFeature.WriteClassName)); + } + + private static class Model { + public int value; + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest.java new file mode 100755 index 0000000000..9e0c55c8d0 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest.java @@ -0,0 +1,229 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringWriter; +import java.lang.reflect.Field; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import junit.framework.TestCase; + +public class SerializeWriterTest extends TestCase { + + public void test_0() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.write('a'); + out.write('b'); + out.write('c'); + Assert.assertEquals("abc", out.toString()); + + StringWriter writer = new StringWriter(); + out.writeTo(writer); + Assert.assertEquals("abc", writer.toString()); + } + + public void test_1() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.write((int) 'a'); + out.write((int) 'b'); + out.write((int) 'c'); + out.write(new char[0], 0, 0); + Assert.assertEquals("abc", out.toString()); + + StringWriter writer = new StringWriter(); + out.writeTo(writer); + Assert.assertEquals("abc", writer.toString()); + + out.expandCapacity(128); + } + + public void test_12() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.append("abc"); + Assert.assertEquals("abc", out.toString()); + Assert.assertEquals(3, out.toCharArray().length); + Assert.assertEquals(3, out.size()); + + Field field = SerializeWriter.class.getDeclaredField("count"); + field.setAccessible(true); + field.setInt(out, 0); + + Assert.assertEquals("", out.toString()); + Assert.assertEquals(0, out.toCharArray().length); + Assert.assertEquals(0, out.size()); + out.writeInt(Integer.MIN_VALUE); + Assert.assertEquals(Integer.toString(Integer.MIN_VALUE), out.toString()); + out.flush(); + out.close(); + } + + public void test_13() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.writeInt(Integer.MIN_VALUE); + Assert.assertEquals(Integer.toString(Integer.MIN_VALUE), out.toString()); + } + + public void test_13_long() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.writeLong(Long.MIN_VALUE); + Assert.assertEquals(Long.toString(Long.MIN_VALUE), out.toString()); + } + + public void test_13_long_browser() throws Exception { + SerializeWriter out = new SerializeWriter(SerializerFeature.BrowserCompatible); + out.writeLong(Long.MIN_VALUE + 1); + Assert.assertEquals("\"" + Long.toString(Long.MIN_VALUE + 1) + "\"", out.toString()); + } + + public void test_13_long_browser2() throws Exception { + SerializeWriter out = new SerializeWriter(SerializerFeature.BrowserCompatible); + out.writeLong(Long.MIN_VALUE); + Assert.assertEquals("\"" + Long.toString(Long.MIN_VALUE) + "\"", out.toString()); + } + + public void test_14() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.writeInt(Integer.MAX_VALUE); + Assert.assertEquals(Integer.toString(Integer.MAX_VALUE), out.toString()); + } + + public void test_14_long() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.writeLong(Long.MAX_VALUE); + Assert.assertEquals(Long.toString(Long.MAX_VALUE), out.toString()); + } + + public void test_15() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.writeInt(Integer.MAX_VALUE); + out.write(','); + Assert.assertEquals(Integer.toString(Integer.MAX_VALUE) + ",", out.toString()); + } + + public void test_15_long() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.writeLong(Long.MAX_VALUE); + out.write(','); + Assert.assertEquals(Long.toString(Long.MAX_VALUE) + ",", out.toString()); + } + + public void test_16() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.writeInt(Integer.MIN_VALUE); + out.write(','); + Assert.assertEquals(Integer.toString(Integer.MIN_VALUE) + ",", out.toString()); + } + + public void test_16_long() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.writeLong(Long.MIN_VALUE); + out.write(','); + Assert.assertEquals(Long.toString(Long.MIN_VALUE) + ",", out.toString()); + } + + public void test_16_long_browser() throws Exception { + SerializeWriter out = new SerializeWriter(SerializerFeature.BrowserCompatible); + out.writeLong(Long.MIN_VALUE + 1); + out.write(','); + Assert.assertEquals("\"" + Long.toString(Long.MIN_VALUE + 1) + "\",", out.toString()); + } + + public void test_16_long_browser2() throws Exception { + SerializeWriter out = new SerializeWriter(SerializerFeature.BrowserCompatible); + out.writeLong(Long.MIN_VALUE); + out.write(','); + Assert.assertEquals("\"" + Long.toString(Long.MIN_VALUE) + "\",", out.toString()); + } + + public void test_17() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.append(null); + Assert.assertEquals("null", out.toString()); + } + + public void test_18() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.append(null, 0, 4); + Assert.assertEquals("null", out.toString()); + } + + public void test_19() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.append("abcd", 0, 4); + Assert.assertEquals("abcd", out.toString()); + } + + public void test_20() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.write("abcd".toCharArray(), 0, 4); + Assert.assertEquals("abcd", out.toString()); + } + + public void test_error_0() throws Exception { + Exception error = null; + try { + new SerializeWriter(-1); + } catch (IllegalArgumentException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_2() throws Exception { + Exception error = null; + try { + SerializeWriter out = new SerializeWriter(16); + out.write(new char[0], -1, 0); + } catch (IndexOutOfBoundsException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_3() throws Exception { + Exception error = null; + try { + SerializeWriter out = new SerializeWriter(16); + out.write(new char[0], 2, 0); + } catch (IndexOutOfBoundsException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_4() throws Exception { + Exception error = null; + try { + SerializeWriter out = new SerializeWriter(16); + out.write(new char[0], 0, -1); + } catch (IndexOutOfBoundsException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_5() throws Exception { + Exception error = null; + try { + SerializeWriter out = new SerializeWriter(16); + out.write(new char[0], 0, 1); + } catch (IndexOutOfBoundsException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + + public void test_error_6() throws Exception { + Exception error = null; + try { + SerializeWriter out = new SerializeWriter(16); + out.write("abcdefg".toCharArray(), 1, 1 + Integer.MAX_VALUE); + } catch (IndexOutOfBoundsException ex) { + error = ex; + } + Assert.assertNotNull(error); + } + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_1.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_1.java old mode 100644 new mode 100755 similarity index 80% rename from src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_1.java rename to src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_1.java index 71a57794ef..3f5b6c9ec0 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_1.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_1.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.io.ByteArrayOutputStream; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.SerializeWriter; @@ -27,7 +27,7 @@ public void test_1 () throws Exception { public void test_2 () throws Exception { SerializeWriter out = new SerializeWriter(SerializerFeature.UseSingleQuotes); out.writeString("abc"); - Assert.assertEquals("'abc'", new String(out.toBytes(null), "ISO-8859-1")); + Assert.assertEquals("'abc'", new String(out.toBytes((String) null), "ISO-8859-1")); } public void test_3 () throws Exception { @@ -36,12 +36,6 @@ public void test_3 () throws Exception { Assert.assertEquals("'abc'", new String(out.toBytes("UTF-16"), "UTF-16")); } - public void test_4 () throws Exception { - SerializeWriter out = new SerializeWriter(1); - out.writeBooleanArray(new boolean[] {true, true, false, false}); - Assert.assertEquals("[true,true,false,false]", new String(out.toBytes("UTF-16"), "UTF-16")); - } - public void test_5 () throws Exception { SerializeWriter out = new SerializeWriter(1); out.write((String) null); @@ -56,7 +50,7 @@ public void test_6 () throws Exception { public void test_null () throws Exception { SerializeWriter out = new SerializeWriter(1); - out.writeString(null); + out.writeString((String) null); Assert.assertEquals("null", new String(out.toBytes("UTF-16"), "UTF-16")); } } diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_10.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_10.java new file mode 100644 index 0000000000..a90840ee99 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_10.java @@ -0,0 +1,70 @@ +package com.alibaba.json.bvt.serializer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.SerializeWriter; + +public class SerializeWriterTest_10 extends TestCase { + + public void test_erro_0() throws Exception { + SerializeWriter out = new SerializeWriter(); + Exception error = null; + try { + out.write(new char[0], -1, 0); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + out.close(); + } + + public void test_erro_1() throws Exception { + SerializeWriter out = new SerializeWriter(); + Exception error = null; + try { + out.write(new char[0], 1, 0); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + out.close(); + } + + public void test_erro_2() throws Exception { + SerializeWriter out = new SerializeWriter(); + Exception error = null; + try { + out.write(new char[0], 0, -1); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + out.close(); + } + + public void test_erro_3() throws Exception { + SerializeWriter out = new SerializeWriter(); + Exception error = null; + try { + out.write(new char[] { '0', '0' }, 1, 2); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + out.close(); + } + + public void test_erro_4() throws Exception { + SerializeWriter out = new SerializeWriter(); + Exception error = null; + try { + out.write(new char[] { '0', '0' }, 1, Integer.MAX_VALUE); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + out.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_11.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_11.java new file mode 100644 index 0000000000..4ea669b4ee --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_11.java @@ -0,0 +1,22 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.ByteArrayOutputStream; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.SerializeWriter; + +public class SerializeWriterTest_11 extends TestCase { + + public void test_erro_0() throws Exception { + SerializeWriter out = new SerializeWriter(); + out.write(true); + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + out.writeTo(byteOut, "UTF-8"); + Assert.assertEquals("true", new String(byteOut.toByteArray())); + out.close(); + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_12.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_12.java new file mode 100644 index 0000000000..264304096d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_12.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.IOException; +import java.io.Writer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.SerializeWriter; + +public class SerializeWriterTest_12 extends TestCase { + + public void test_erro_0() throws Exception { + SerializeWriter out = new SerializeWriter(new ErrorWriter()); + Exception error = null; + try { + out.flush(); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + out.close(); + } + + public static class ErrorWriter extends Writer { + + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + throw new IOException(); + } + + @Override + public void flush() throws IOException { + throw new IOException(); + } + + @Override + public void close() throws IOException { + + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_13.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_13.java new file mode 100644 index 0000000000..f46c5a9b18 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_13.java @@ -0,0 +1,57 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringWriter; +import java.util.Collections; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class SerializeWriterTest_13 extends TestCase { + + public void test_default() throws Exception { + Assert.assertEquals("{\"\":\"\"}", // + JSON.toJSONStringZ(Collections.singletonMap("", ""), // + SerializeConfig.getGlobalInstance())); + } + + public void test_single() throws Exception { + Assert.assertEquals("{'':''}", // + JSON.toJSONStringZ(Collections.singletonMap("", ""), // + SerializeConfig.getGlobalInstance(), SerializerFeature.UseSingleQuotes)); + } + + public void test_writer() throws Exception { + SerializeWriter out = new SerializeWriter(3); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + serializer.write(Collections.singletonMap("", "")); + Assert.assertEquals("{\"\":\"\"}", out.toString()); + } finally { + out.close(); + } + } + + public void test_writer_single() throws Exception { + SerializeWriter out = new SerializeWriter(3); + out.config(SerializerFeature.UseSingleQuotes, true); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + serializer.write(Collections.singletonMap("", "")); + Assert.assertEquals("{'':''}", out.toString()); + } finally { + out.close(); + } + } + +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_14.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_14.java new file mode 100644 index 0000000000..a0051d0b39 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_14.java @@ -0,0 +1,61 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringWriter; +import java.util.Collections; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; + +public class SerializeWriterTest_14 extends TestCase { + @SuppressWarnings("rawtypes") + public void test_writer_1() throws Exception { + StringWriter strOut = new StringWriter(); + SerializeWriter out = new SerializeWriter(strOut, 1); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + Map map = Collections.singletonMap("", "a"); + serializer.write(map); + } finally { + out.close(); + } + Assert.assertEquals("{\"\":\"a\"}", strOut.toString()); + } + + + public void test_writer_2() throws Exception { + StringWriter strOut = new StringWriter(); + SerializeWriter out = new SerializeWriter(strOut, 1); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + Map map = Collections.singletonMap("ab", "a"); + serializer.write(map); + } finally { + out.close(); + } + Assert.assertEquals("{ab:\"a\"}", strOut.toString()); + } + + public void test_writer_3() throws Exception { + StringWriter strOut = new StringWriter(); + SerializeWriter out = new SerializeWriter(strOut, 1); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + Map map = Collections.singletonMap("ab\t<", "a"); + serializer.write(map); + } finally { + out.close(); + } + Assert.assertEquals("{\"ab\\t<\":\"a\"}", strOut.toString()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_15.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_15.java new file mode 100644 index 0000000000..75a2399540 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_15.java @@ -0,0 +1,65 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringWriter; +import java.util.Collections; +import java.util.Map; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class SerializeWriterTest_15 extends TestCase { + @SuppressWarnings("rawtypes") + public void test_writer_1() throws Exception { + StringWriter strOut = new StringWriter(); + SerializeWriter out = new SerializeWriter(strOut, 1); + out.config(SerializerFeature.UseSingleQuotes, true); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + Map map = Collections.singletonMap("", "a"); + serializer.write(map); + } finally { + out.close(); + } + Assert.assertEquals("{'':'a'}", strOut.toString()); + } + + + public void test_writer_2() throws Exception { + StringWriter strOut = new StringWriter(); + SerializeWriter out = new SerializeWriter(strOut, 1); + out.config(SerializerFeature.UseSingleQuotes, true); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + Map map = Collections.singletonMap("ab", "a"); + serializer.write(map); + } finally { + out.close(); + } + Assert.assertEquals("{ab:'a'}", strOut.toString()); + } + + public void test_writer_3() throws Exception { + StringWriter strOut = new StringWriter(); + SerializeWriter out = new SerializeWriter(strOut, 1); + out.config(SerializerFeature.UseSingleQuotes, true); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + Map map = Collections.singletonMap("ab\t", "a"); + serializer.write(map); + } finally { + out.close(); + } + Assert.assertEquals("{'ab\\t':'a'}", strOut.toString()); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_16.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_16.java new file mode 100644 index 0000000000..bf41c47327 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_16.java @@ -0,0 +1,45 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringWriter; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class SerializeWriterTest_16 extends TestCase { + + public void test_writer_1() throws Exception { + StringWriter strOut = new StringWriter(); + SerializeWriter out = new SerializeWriter(strOut, 14); + out.config(SerializerFeature.BrowserCompatible, true); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + VO vo = new VO(); + vo.setValue("abcd\t"); + serializer.write(vo); + } finally { + out.close(); + } + Assert.assertEquals("{value:\"abcd\\t\"}", strOut.toString()); + } + + private static class VO { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_17.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_17.java new file mode 100644 index 0000000000..bd97c83169 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_17.java @@ -0,0 +1,63 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringWriter; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class SerializeWriterTest_17 extends TestCase { + + public void test_writer_1() throws Exception { + StringWriter strOut = new StringWriter(); + SerializeWriter out = new SerializeWriter(strOut, 6); + out.config(SerializerFeature.QuoteFieldNames, true); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + VO vo = new VO(); + vo.setValue(123456789); + serializer.write(vo); + } finally { + out.close(); + } + Assert.assertEquals("{\"value\":123456789}", strOut.toString()); + } + + public void test_direct() throws Exception { + SerializeWriter out = new SerializeWriter(6); + out.config(SerializerFeature.QuoteFieldNames, true); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + VO vo = new VO(); + vo.setValue(123456789); + serializer.write(vo); + + Assert.assertEquals("{\"value\":123456789}", out.toString()); + } finally { + out.close(); + } + + } + + public static class VO { + + private long value; + + public long getValue() { + return value; + } + + public void setValue(long value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_18.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_18.java new file mode 100644 index 0000000000..19acc14f9b --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_18.java @@ -0,0 +1,44 @@ +package com.alibaba.json.bvt.serializer; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class SerializeWriterTest_18 extends TestCase { + + public void test_writer_1() throws Exception { + SerializeWriter out = new SerializeWriter(14); + out.config(SerializerFeature.QuoteFieldNames, true); + + try { + JSONSerializer serializer = new JSONSerializer(out); + + VO vo = new VO(); + vo.setValue("#"); + serializer.write(vo); + + Assert.assertEquals("{\"value\":\"#\"}", out.toString()); + } finally { + out.close(); + } + + } + + public static class VO { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_19.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_19.java new file mode 100644 index 0000000000..faf75e4c0d --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_19.java @@ -0,0 +1,47 @@ +package com.alibaba.json.bvt.serializer; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class SerializeWriterTest_19 extends TestCase { + + public void test_writer_1() throws Exception { + SerializeWriter out = new SerializeWriter(14); + out.config(SerializerFeature.QuoteFieldNames, true); + out.config(SerializerFeature.UseSingleQuotes, true); + try { + JSONSerializer serializer = new JSONSerializer(out); + + VO vo = new VO(); + vo.getValues().add("#"); + serializer.write(vo); + + Assert.assertEquals("{'values':['#']}", out.toString()); + } finally { + out.close(); + } + + } + + public static class VO { + + private List values = new ArrayList(); + + public List getValues() { + return values; + } + + public void setValues(List values) { + this.values = values; + } + + } +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_2.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_2.java old mode 100644 new mode 100755 similarity index 85% rename from src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_2.java rename to src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_2.java index a8d6c8cad8..da8cfe34d0 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_2.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_2.java @@ -1,11 +1,13 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; import junit.framework.TestCase; +import org.junit.Assert; + import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.serializer.SerializerFeature; +@SuppressWarnings("deprecation") public class SerializeWriterTest_2 extends TestCase { public void test_0() throws Exception { @@ -13,13 +15,15 @@ public void test_0() throws Exception { out.config(SerializerFeature.WriteTabAsSpecial, true); out.writeString("\t\n \b\n\r\f\\ \""); Assert.assertEquals("\"\\t\\n \\b\\n\\r\\f\\\\ \\\"\"", out.toString()); + out.close(); } - + public void test_1() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.WriteTabAsSpecial, true); out.config(SerializerFeature.UseSingleQuotes, true); out.writeString("\t\n \b\n\r\f\\ \""); Assert.assertEquals("'\\t\\n \\b\\n\\r\\f\\\\ \"'", out.toString()); + out.close(); } } diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_3.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_3.java new file mode 100755 index 0000000000..7ca7f57e54 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_3.java @@ -0,0 +1,40 @@ +package com.alibaba.json.bvt.serializer; + +import org.junit.Assert; +import junit.framework.TestCase; + +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class SerializeWriterTest_3 extends TestCase { + + public void test_0() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.config(SerializerFeature.QuoteFieldNames, true); + out.writeFieldValue(',', "name", "jobs"); + Assert.assertEquals(",\"name\":\"jobs\"", out.toString()); + } + + public void test_1() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.config(SerializerFeature.QuoteFieldNames, false); + out.writeFieldValue(',', "name", "jobs"); + Assert.assertEquals(",name:\"jobs\"", out.toString()); + } + + public void test_null() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.config(SerializerFeature.QuoteFieldNames, true); + out.writeFieldValue(',', "name", (String) null); + Assert.assertEquals(",\"name\":null", out.toString()); + } + + public void test_null_1() throws Exception { + SerializeWriter out = new SerializeWriter(1); + out.config(SerializerFeature.QuoteFieldNames, false); + out.writeFieldValue(',', "name", (String) null); + Assert.assertEquals(",name:null", out.toString()); + } + + +} diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_4.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_4.java old mode 100644 new mode 100755 similarity index 81% rename from src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_4.java rename to src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_4.java index c3259f2269..7899b7315b --- a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_4.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_4.java @@ -1,19 +1,22 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; import junit.framework.TestCase; +import org.junit.Assert; + import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.serializer.SerializerFeature; +@SuppressWarnings("deprecation") public class SerializeWriterTest_4 extends TestCase { public void test_0() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, true); out.config(SerializerFeature.WriteTabAsSpecial, true); - out.writeFieldValue(',', "\tname", "\t"); - Assert.assertEquals(",\"\\tname\":\"\\t\"", out.toString()); + out.writeFieldValue(',', "name", "\t"); + Assert.assertEquals(",\"name\":\"\\t\"", out.toString()); + out.close(); } public void test_1() throws Exception { @@ -22,6 +25,7 @@ public void test_1() throws Exception { out.config(SerializerFeature.WriteTabAsSpecial, true); out.writeFieldValue(',', "name", "\t\n"); Assert.assertEquals(",\"name\":\"\\t\\n\"", out.toString()); + out.close(); } public void test_3() throws Exception { @@ -30,6 +34,7 @@ public void test_3() throws Exception { out.config(SerializerFeature.WriteTabAsSpecial, true); out.writeFieldValue(',', "name", "\t\n \b\n\r\f\\ \""); Assert.assertEquals(",\"name\":\"\\t\\n \\b\\n\\r\\f\\\\ \\\"\"", out.toString()); + out.close(); } public void test_4() throws Exception { @@ -37,7 +42,8 @@ public void test_4() throws Exception { out.config(SerializerFeature.QuoteFieldNames, true); out.config(SerializerFeature.WriteTabAsSpecial, false); out.writeFieldValue(',', "name", "\t\n \b\n\r\f\\ \""); - Assert.assertEquals(",\"name\":\"\t\\n \\b\\n\\r\\f\\\\ \\\"\"", out.toString()); + Assert.assertEquals(",\"name\":\"\\t\\n \\b\\n\\r\\f\\\\ \\\"\"", out.toString()); + out.close(); } public void test_5() throws Exception { @@ -46,5 +52,6 @@ public void test_5() throws Exception { out.config(SerializerFeature.WriteTabAsSpecial, true); out.writeString("\t\n \b\n\r\f\\ \""); Assert.assertEquals("\"\\t\\n \\b\\n\\r\\f\\\\ \\\"\"", out.toString()); + out.close(); } } diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_5.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_5.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_5.java rename to src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_5.java index ee98c83909..c6e419ff46 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_5.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_5.java @@ -1,8 +1,8 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; import java.math.BigDecimal; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.SerializeWriter; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_6.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_6.java old mode 100644 new mode 100755 similarity index 87% rename from src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_6.java rename to src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_6.java index 54dde456a6..a0a991ee33 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_6.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_6.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.SerializeWriter; diff --git a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_7.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_7.java old mode 100644 new mode 100755 similarity index 95% rename from src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_7.java rename to src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_7.java index 67eb6cd5b3..78ac19dd31 --- a/src/test/java/com/alibaba/json/test/bvt/serializer/SerializeWriterTest_7.java +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_7.java @@ -1,6 +1,6 @@ -package com.alibaba.json.test.bvt.serializer; +package com.alibaba.json.bvt.serializer; -import junit.framework.Assert; +import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.SerializeWriter; diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_8.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_8.java new file mode 100644 index 0000000000..8d9b34007e --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_8.java @@ -0,0 +1,69 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringWriter; +import java.util.Collections; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.JSONSerializer; +import com.alibaba.fastjson.serializer.SerializeWriter; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class SerializeWriterTest_8 extends TestCase { + + public void test_BrowserCompatible() throws Exception { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < 1024; ++i) { + buf.append('a'); + } + buf.append("中国"); + buf.append("\0"); + JSON.toJSONString(buf.toString(), SerializerFeature.BrowserCompatible); + } + + public void test_writer() throws Exception { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < 1024; ++i) { + buf.append('a'); + } + buf.append("中国"); + buf.append("\0"); + + StringWriter out = new StringWriter(); + JSON.writeJSONStringTo(buf.toString(), out, SerializerFeature.BrowserCompatible); + } + + public void test_singleQuote() throws Exception { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < 1024; ++i) { + buf.append('a'); + } + buf.append("中国"); + buf.append("\0"); + + SerializeWriter out = new SerializeWriter(new StringWriter()); + + try { + JSONSerializer serializer = new JSONSerializer(out); + serializer.config(SerializerFeature.QuoteFieldNames, false); + serializer.config(SerializerFeature.UseSingleQuotes, true); + + serializer.write(Collections.singletonMap(buf.toString(), "")); + } finally { + out.close(); + } + } + + public void test_singleQuote_writer() throws Exception { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < 1024; ++i) { + buf.append('a'); + } + buf.append("中国"); + buf.append("\0"); + + StringWriter out = new StringWriter(); + JSON.writeJSONStringTo(Collections.singletonMap(buf.toString(), ""), out, SerializerFeature.UseSingleQuotes); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_9.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_9.java new file mode 100644 index 0000000000..7fe321e9cb --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_9.java @@ -0,0 +1,74 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.ByteArrayOutputStream; +import java.io.StringWriter; +import java.nio.charset.Charset; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.fastjson.serializer.SerializeWriter; + +public class SerializeWriterTest_9 extends TestCase { + + public void test_error() throws Exception { + SerializeWriter writer = new SerializeWriter(new StringWriter()); + Exception error = null; + try { + writer.writeTo(new StringWriter()); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + writer.close(); + } + + public void test_error_2() throws Exception { + SerializeWriter writer = new SerializeWriter(new StringWriter()); + Exception error = null; + try { + writer.writeTo(new ByteArrayOutputStream(), Charset.forName("UTF-8")); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + writer.close(); + } + + public void test_error_3() throws Exception { + SerializeWriter writer = new SerializeWriter(new StringWriter()); + Exception error = null; + try { + writer.writeTo(new ByteArrayOutputStream(), "UTF-8"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + writer.close(); + } + + public void test_error_4() throws Exception { + SerializeWriter writer = new SerializeWriter(new StringWriter()); + Exception error = null; + try { + writer.toCharArray(); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + writer.close(); + } + + public void test_error_5() throws Exception { + SerializeWriter writer = new SerializeWriter(new StringWriter()); + Exception error = null; + try { + writer.toBytes("UTF-8"); + } catch (Exception ex) { + error = ex; + } + Assert.assertNotNull(error); + writer.close(); + } +} diff --git a/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_BrowserSecure.java b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_BrowserSecure.java new file mode 100644 index 0000000000..e00c4079e7 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_BrowserSecure.java @@ -0,0 +1,87 @@ +package com.alibaba.json.bvt.serializer; + +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +public class SerializeWriterTest_BrowserSecure extends TestCase { + + public void test_0() throws Exception { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < 1024; ++i) { + buf.append('a'); + } + buf.append("中国"); + buf.append("\0"); + JSON.toJSONString(buf.toString(), SerializerFeature.BrowserSecure); + } + + public void test_1() throws Exception { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < 1024; ++i) { + buf.append('a'); + } + buf.append("中国"); + buf.append("\0"); + + StringWriter out = new StringWriter(); + JSON.writeJSONStringTo(buf.toString(), out, SerializerFeature.BrowserSecure); + } + + public void test_zh() throws Exception { + Assert.assertEquals("\"中国\"", JSON.toJSONString("中国", SerializerFeature.BrowserSecure)); + } + + public void test_all() throws Exception { + String value = ".,_~!@<>'\"\\/hello world 0123;汉字;\u2028\u2028\r\n"); + String text = JSON.toJSONString(object, SerializerFeature.BrowserSecure); +// assertEquals("{\"value\":\"<script>alert(1);<\\/script>\"}", text); + assertEquals("{\"value\":\"\\u003Cscript\\u003Ealert\\u00281\\u0029;\\u003C/script\\u003E\"}", text); + JSONObject object1 = JSON.parseObject(text); + assertEquals(object.get("value"), object1.get("value")); + } + + public void test_1() throws Exception { + String text = JSON.toJSONString("<", SerializerFeature.BrowserSecure); + assertEquals("\"\\u003C\"", text); + } + + public void test_2() throws Exception { + String text = JSON.toJSONString(""; + String text = JSON.toJSONString(object, SerializerFeature.BrowserSecure); +// assertEquals("{\"value\":\"<script>alert(1);<\\/script>\"}", text); + assertEquals("{\"value\":\"\\u003Cscript\\u003Ealert\\u00281\\u0029;\\u003C/script\\u003E\"}", text); + Model object1 = JSON.parseObject(text, Model.class); + assertEquals(object.value, object1.value); + } + + public void test_1() throws Exception { + Model object = new Model(); + object.value = "<"; + String text = JSON.toJSONString(object, SerializerFeature.BrowserSecure); +// assertEquals("{\"value\":\"<script>alert(1);<\\/script>\"}", text); + assertEquals("{\"value\":\"\\u003C\"}", text); + Model object1 = JSON.parseObject(text, Model.class); + assertEquals(object.value, object1.value); + } + + public void test_2() throws Exception { + Model object = new Model(); + object.value = "", "value"); + String text = JSON.toJSONString(object, SerializerFeature.BrowserSecure); +// assertEquals("{\"value\":\"<script>alert(1);<\\/script>\"}", text); + assertEquals("{\"\\u003Cscript\\u003Ealert\\u00281\\u0029;\\u003C/script\\u003E\":\"value\"}", text); + JSONObject object1 = JSON.parseObject(text); + assertEquals(object.get(""), object1.get("")); + } +// +// public void test_1() throws Exception { +// String text = JSON.toJSONString("<", SerializerFeature.BrowserSecure); +// assertEquals("\"\\u003C\"", text); +// } +// +// public void test_2() throws Exception { +// String text = JSON.toJSONString("