Repository: alibaba/fastjson Branch: master Commit: c942c8344311 Files: 3240 Total size: 9.5 MB Directory structure: gitextract_e_i0aaw3/ ├── .github/ │ └── workflows/ │ └── ci.yaml ├── .gitignore ├── .gitpod.yml ├── .travis.yml ├── CONTRIBUTING.md ├── README.md ├── SECURITY.md ├── license.txt ├── pom.xml ├── rfc4627.txt ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ ├── META-INF/ │ │ │ │ └── MANIFEST.MF │ │ │ └── com/ │ │ │ └── alibaba/ │ │ │ └── fastjson/ │ │ │ ├── JSON.java │ │ │ ├── JSONArray.java │ │ │ ├── JSONAware.java │ │ │ ├── JSONException.java │ │ │ ├── JSONObject.java │ │ │ ├── JSONPObject.java │ │ │ ├── JSONPatch.java │ │ │ ├── JSONPath.java │ │ │ ├── JSONPathException.java │ │ │ ├── JSONReader.java │ │ │ ├── JSONStreamAware.java │ │ │ ├── JSONStreamContext.java │ │ │ ├── JSONValidator.java │ │ │ ├── JSONWriter.java │ │ │ ├── PropertyNamingStrategy.java │ │ │ ├── TypeReference.java │ │ │ ├── annotation/ │ │ │ │ ├── JSONCreator.java │ │ │ │ ├── JSONField.java │ │ │ │ ├── JSONPOJOBuilder.java │ │ │ │ └── JSONType.java │ │ │ ├── asm/ │ │ │ │ ├── ByteVector.java │ │ │ │ ├── ClassReader.java │ │ │ │ ├── ClassWriter.java │ │ │ │ ├── FieldWriter.java │ │ │ │ ├── Item.java │ │ │ │ ├── Label.java │ │ │ │ ├── MethodCollector.java │ │ │ │ ├── MethodVisitor.java │ │ │ │ ├── MethodWriter.java │ │ │ │ ├── Opcodes.java │ │ │ │ ├── Type.java │ │ │ │ └── TypeCollector.java │ │ │ ├── parser/ │ │ │ │ ├── DefaultExtJSONParser.java │ │ │ │ ├── DefaultJSONParser.java │ │ │ │ ├── Feature.java │ │ │ │ ├── JSONLexer.java │ │ │ │ ├── JSONLexerBase.java │ │ │ │ ├── JSONReaderScanner.java │ │ │ │ ├── JSONScanner.java │ │ │ │ ├── JSONToken.java │ │ │ │ ├── ParseContext.java │ │ │ │ ├── ParserConfig.java │ │ │ │ ├── SymbolTable.java │ │ │ │ └── deserializer/ │ │ │ │ ├── ASMDeserializerFactory.java │ │ │ │ ├── AbstractDateDeserializer.java │ │ │ │ ├── ArrayListTypeFieldDeserializer.java │ │ │ │ ├── AutowiredObjectDeserializer.java │ │ │ │ ├── ContextObjectDeserializer.java │ │ │ │ ├── DefaultFieldDeserializer.java │ │ │ │ ├── EnumCreatorDeserializer.java │ │ │ │ ├── EnumDeserializer.java │ │ │ │ ├── ExtraProcessable.java │ │ │ │ ├── ExtraProcessor.java │ │ │ │ ├── ExtraTypeProvider.java │ │ │ │ ├── FieldDeserializer.java │ │ │ │ ├── FieldTypeResolver.java │ │ │ │ ├── JSONPDeserializer.java │ │ │ │ ├── JavaBeanDeserializer.java │ │ │ │ ├── JavaObjectDeserializer.java │ │ │ │ ├── Jdk8DateCodec.java │ │ │ │ ├── MapDeserializer.java │ │ │ │ ├── NumberDeserializer.java │ │ │ │ ├── ObjectDeserializer.java │ │ │ │ ├── OptionalCodec.java │ │ │ │ ├── ParseProcess.java │ │ │ │ ├── PropertyProcessable.java │ │ │ │ ├── PropertyProcessableDeserializer.java │ │ │ │ ├── ResolveFieldDeserializer.java │ │ │ │ ├── SqlDateDeserializer.java │ │ │ │ ├── StackTraceElementDeserializer.java │ │ │ │ ├── ThrowableDeserializer.java │ │ │ │ └── TimeDeserializer.java │ │ │ ├── serializer/ │ │ │ │ ├── ASMSerializerFactory.java │ │ │ │ ├── AdderSerializer.java │ │ │ │ ├── AfterFilter.java │ │ │ │ ├── AnnotationSerializer.java │ │ │ │ ├── AppendableSerializer.java │ │ │ │ ├── ArraySerializer.java │ │ │ │ ├── AtomicCodec.java │ │ │ │ ├── AutowiredObjectSerializer.java │ │ │ │ ├── AwtCodec.java │ │ │ │ ├── BeanContext.java │ │ │ │ ├── BeforeFilter.java │ │ │ │ ├── BigDecimalCodec.java │ │ │ │ ├── BigIntegerCodec.java │ │ │ │ ├── BooleanCodec.java │ │ │ │ ├── ByteBufferCodec.java │ │ │ │ ├── CalendarCodec.java │ │ │ │ ├── CharArrayCodec.java │ │ │ │ ├── CharacterCodec.java │ │ │ │ ├── ClobSerializer.java │ │ │ │ ├── CollectionCodec.java │ │ │ │ ├── ContextObjectSerializer.java │ │ │ │ ├── ContextValueFilter.java │ │ │ │ ├── DateCodec.java │ │ │ │ ├── DoubleSerializer.java │ │ │ │ ├── EnumSerializer.java │ │ │ │ ├── EnumerationSerializer.java │ │ │ │ ├── FieldSerializer.java │ │ │ │ ├── FloatCodec.java │ │ │ │ ├── GuavaCodec.java │ │ │ │ ├── IntegerCodec.java │ │ │ │ ├── JSONAwareSerializer.java │ │ │ │ ├── JSONLibDataFormatSerializer.java │ │ │ │ ├── JSONObjectCodec.java │ │ │ │ ├── JSONSerializable.java │ │ │ │ ├── JSONSerializableSerializer.java │ │ │ │ ├── JSONSerializer.java │ │ │ │ ├── JSONSerializerMap.java │ │ │ │ ├── JavaBeanSerializer.java │ │ │ │ ├── JodaCodec.java │ │ │ │ ├── LabelFilter.java │ │ │ │ ├── Labels.java │ │ │ │ ├── ListSerializer.java │ │ │ │ ├── LongCodec.java │ │ │ │ ├── MapSerializer.java │ │ │ │ ├── MiscCodec.java │ │ │ │ ├── NameFilter.java │ │ │ │ ├── ObjectArrayCodec.java │ │ │ │ ├── ObjectSerializer.java │ │ │ │ ├── PascalNameFilter.java │ │ │ │ ├── PrimitiveArraySerializer.java │ │ │ │ ├── PropertyFilter.java │ │ │ │ ├── PropertyPreFilter.java │ │ │ │ ├── ReferenceCodec.java │ │ │ │ ├── SerialContext.java │ │ │ │ ├── SerializeBeanInfo.java │ │ │ │ ├── SerializeConfig.java │ │ │ │ ├── SerializeFilter.java │ │ │ │ ├── SerializeFilterable.java │ │ │ │ ├── SerializeWriter.java │ │ │ │ ├── SerializerFeature.java │ │ │ │ ├── SimpleDateFormatSerializer.java │ │ │ │ ├── SimplePropertyPreFilter.java │ │ │ │ ├── StringCodec.java │ │ │ │ ├── ToStringSerializer.java │ │ │ │ └── ValueFilter.java │ │ │ ├── spi/ │ │ │ │ └── Module.java │ │ │ ├── support/ │ │ │ │ ├── config/ │ │ │ │ │ └── FastJsonConfig.java │ │ │ │ ├── geo/ │ │ │ │ │ ├── Feature.java │ │ │ │ │ ├── FeatureCollection.java │ │ │ │ │ ├── Geometry.java │ │ │ │ │ ├── GeometryCollection.java │ │ │ │ │ ├── LineString.java │ │ │ │ │ ├── MultiLineString.java │ │ │ │ │ ├── MultiPoint.java │ │ │ │ │ ├── MultiPolygon.java │ │ │ │ │ ├── Point.java │ │ │ │ │ └── Polygon.java │ │ │ │ ├── hsf/ │ │ │ │ │ ├── HSFJSONUtils.java │ │ │ │ │ └── MethodLocator.java │ │ │ │ ├── jaxrs/ │ │ │ │ │ ├── FastJsonAutoDiscoverable.java │ │ │ │ │ ├── FastJsonFeature.java │ │ │ │ │ └── FastJsonProvider.java │ │ │ │ ├── moneta/ │ │ │ │ │ └── MonetaCodec.java │ │ │ │ ├── retrofit/ │ │ │ │ │ └── Retrofit2ConverterFactory.java │ │ │ │ ├── spring/ │ │ │ │ │ ├── FastJsonContainer.java │ │ │ │ │ ├── FastJsonHttpMessageConverter.java │ │ │ │ │ ├── FastJsonHttpMessageConverter4.java │ │ │ │ │ ├── FastJsonJsonView.java │ │ │ │ │ ├── FastJsonRedisSerializer.java │ │ │ │ │ ├── FastJsonViewResponseBodyAdvice.java │ │ │ │ │ ├── FastJsonpHttpMessageConverter4.java │ │ │ │ │ ├── FastJsonpResponseBodyAdvice.java │ │ │ │ │ ├── FastjsonSockJsMessageCodec.java │ │ │ │ │ ├── GenericFastJsonRedisSerializer.java │ │ │ │ │ ├── JSONPResponseBodyAdvice.java │ │ │ │ │ ├── MappingFastJsonValue.java │ │ │ │ │ ├── PropertyPreFilters.java │ │ │ │ │ ├── annotation/ │ │ │ │ │ │ ├── FastJsonFilter.java │ │ │ │ │ │ ├── FastJsonView.java │ │ │ │ │ │ └── ResponseJSONP.java │ │ │ │ │ └── messaging/ │ │ │ │ │ └── MappingFastJsonMessageConverter.java │ │ │ │ └── springfox/ │ │ │ │ └── SwaggerJsonSerializer.java │ │ │ └── util/ │ │ │ ├── ASMClassLoader.java │ │ │ ├── ASMUtils.java │ │ │ ├── AntiCollisionHashMap.java │ │ │ ├── Base64.java │ │ │ ├── BiFunction.java │ │ │ ├── FieldInfo.java │ │ │ ├── Function.java │ │ │ ├── GenericArrayTypeImpl.java │ │ │ ├── IOUtils.java │ │ │ ├── IdentityHashMap.java │ │ │ ├── JavaBeanInfo.java │ │ │ ├── ModuleUtil.java │ │ │ ├── ParameterizedTypeImpl.java │ │ │ ├── RyuDouble.java │ │ │ ├── RyuFloat.java │ │ │ ├── ServiceLoader.java │ │ │ ├── ThreadLocalCache.java │ │ │ ├── TypeUtils.java │ │ │ └── UTF8Decoder.java │ │ └── resources/ │ │ └── META-INF/ │ │ ├── LICENSE.txt │ │ ├── NOTICE.txt │ │ └── services/ │ │ ├── javax.ws.rs.ext.MessageBodyReader │ │ ├── javax.ws.rs.ext.MessageBodyWriter │ │ ├── javax.ws.rs.ext.Providers │ │ └── org.glassfish.jersey.internal.spi.AutoDiscoverable │ └── test/ │ ├── java/ │ │ ├── cn/ │ │ │ └── com/ │ │ │ └── tx/ │ │ │ └── domain/ │ │ │ ├── notifyDetail/ │ │ │ │ └── NotifyDetail.java │ │ │ └── pagination/ │ │ │ └── Pagination.java │ │ ├── com/ │ │ │ ├── alibaba/ │ │ │ │ ├── china/ │ │ │ │ │ └── bolt/ │ │ │ │ │ └── biz/ │ │ │ │ │ └── daili/ │ │ │ │ │ └── merchants/ │ │ │ │ │ └── vo/ │ │ │ │ │ └── MerchantsVO.java │ │ │ │ ├── fastjson/ │ │ │ │ │ ├── JSONPathTest.java │ │ │ │ │ ├── codegen/ │ │ │ │ │ │ ├── ClassGen.java │ │ │ │ │ │ └── DeserializerGen.java │ │ │ │ │ ├── deserializer/ │ │ │ │ │ │ ├── IgnoreTypeDeserializer.java │ │ │ │ │ │ ├── TestISO8601Date.java │ │ │ │ │ │ ├── ValueBean.java │ │ │ │ │ │ ├── issue1463/ │ │ │ │ │ │ │ ├── TestIssue1463.java │ │ │ │ │ │ │ └── beans/ │ │ │ │ │ │ │ └── Person.java │ │ │ │ │ │ ├── issue2358/ │ │ │ │ │ │ │ └── TestJson.java │ │ │ │ │ │ ├── issue2638/ │ │ │ │ │ │ │ ├── Person.java │ │ │ │ │ │ │ └── TestIssue2638.java │ │ │ │ │ │ ├── issue2711/ │ │ │ │ │ │ │ ├── PageRequest.java │ │ │ │ │ │ │ ├── TestIssue.java │ │ │ │ │ │ │ └── User.java │ │ │ │ │ │ ├── issue2779/ │ │ │ │ │ │ │ ├── Issue2779Test.java │ │ │ │ │ │ │ └── LargeJavaBean.java │ │ │ │ │ │ ├── issue2898/ │ │ │ │ │ │ │ └── TestIssue2898.java │ │ │ │ │ │ ├── issue2951/ │ │ │ │ │ │ │ └── TestIssue2951.java │ │ │ │ │ │ ├── issue3050/ │ │ │ │ │ │ │ ├── TestIssue3050.java │ │ │ │ │ │ │ └── beans/ │ │ │ │ │ │ │ └── Person.java │ │ │ │ │ │ ├── issue3248/ │ │ │ │ │ │ │ └── TestIssue3248.kt │ │ │ │ │ │ ├── issue3804/ │ │ │ │ │ │ │ └── TestIssue3804.java │ │ │ │ │ │ ├── issues3671/ │ │ │ │ │ │ │ └── TestIssue3671.java │ │ │ │ │ │ ├── issues3796/ │ │ │ │ │ │ │ ├── TestIssues3796.java │ │ │ │ │ │ │ └── bean/ │ │ │ │ │ │ │ ├── CommonObject.java │ │ │ │ │ │ │ ├── CommonObject2.java │ │ │ │ │ │ │ ├── CommonObject3.java │ │ │ │ │ │ │ ├── LargeJavaBean.java │ │ │ │ │ │ │ ├── ObjectA.java │ │ │ │ │ │ │ ├── ObjectA1.java │ │ │ │ │ │ │ ├── ObjectA2.java │ │ │ │ │ │ │ ├── ObjectB.java │ │ │ │ │ │ │ ├── ObjectB1.java │ │ │ │ │ │ │ ├── ObjectB2.java │ │ │ │ │ │ │ ├── ObjectC.java │ │ │ │ │ │ │ ├── ObjectC1.java │ │ │ │ │ │ │ ├── ObjectC2.java │ │ │ │ │ │ │ ├── ObjectD.java │ │ │ │ │ │ │ ├── ObjectD1.java │ │ │ │ │ │ │ ├── ObjectD1_A.java │ │ │ │ │ │ │ ├── ObjectD2.java │ │ │ │ │ │ │ ├── ObjectD_A.java │ │ │ │ │ │ │ ├── ObjectD_B.java │ │ │ │ │ │ │ ├── ObjectE.java │ │ │ │ │ │ │ ├── ObjectE1.java │ │ │ │ │ │ │ ├── ObjectE2.java │ │ │ │ │ │ │ ├── ObjectF.java │ │ │ │ │ │ │ ├── ObjectF1.java │ │ │ │ │ │ │ ├── ObjectF2.java │ │ │ │ │ │ │ ├── ObjectG.java │ │ │ │ │ │ │ ├── ObjectG1.java │ │ │ │ │ │ │ ├── ObjectG2.java │ │ │ │ │ │ │ ├── ObjectH.java │ │ │ │ │ │ │ ├── ObjectH1.java │ │ │ │ │ │ │ ├── ObjectH2.java │ │ │ │ │ │ │ ├── ObjectH_A.java │ │ │ │ │ │ │ ├── ObjectI.java │ │ │ │ │ │ │ ├── ObjectI1.java │ │ │ │ │ │ │ ├── ObjectI2.java │ │ │ │ │ │ │ ├── ObjectI_A.java │ │ │ │ │ │ │ ├── ObjectJ.java │ │ │ │ │ │ │ ├── ObjectJ1.java │ │ │ │ │ │ │ ├── ObjectJ1_A.java │ │ │ │ │ │ │ ├── ObjectJ1_C.java │ │ │ │ │ │ │ ├── ObjectJ2.java │ │ │ │ │ │ │ ├── ObjectJ_A.java │ │ │ │ │ │ │ ├── ObjectJ_B.java │ │ │ │ │ │ │ ├── ObjectJ_C.java │ │ │ │ │ │ │ ├── ObjectK.java │ │ │ │ │ │ │ ├── ObjectK1.java │ │ │ │ │ │ │ ├── ObjectK1_A.java │ │ │ │ │ │ │ ├── ObjectK1_C.java │ │ │ │ │ │ │ ├── ObjectK2.java │ │ │ │ │ │ │ ├── ObjectK2_A.java │ │ │ │ │ │ │ ├── ObjectL.java │ │ │ │ │ │ │ ├── ObjectL1.java │ │ │ │ │ │ │ ├── ObjectL1_A.java │ │ │ │ │ │ │ ├── ObjectL2.java │ │ │ │ │ │ │ ├── ObjectL2_A.java │ │ │ │ │ │ │ ├── ObjectL2_B.java │ │ │ │ │ │ │ ├── ObjectL2_C.java │ │ │ │ │ │ │ ├── ObjectL_A.java │ │ │ │ │ │ │ ├── ObjectL_B.java │ │ │ │ │ │ │ ├── ObjectM.java │ │ │ │ │ │ │ ├── ObjectM1.java │ │ │ │ │ │ │ ├── ObjectM1_A.java │ │ │ │ │ │ │ ├── ObjectM1_B.java │ │ │ │ │ │ │ ├── ObjectM1_C.java │ │ │ │ │ │ │ ├── ObjectM2.java │ │ │ │ │ │ │ ├── ObjectM2_A.java │ │ │ │ │ │ │ ├── ObjectM_A.java │ │ │ │ │ │ │ ├── ObjectM_B.java │ │ │ │ │ │ │ ├── ObjectN.java │ │ │ │ │ │ │ ├── ObjectN1.java │ │ │ │ │ │ │ ├── ObjectN2.java │ │ │ │ │ │ │ ├── ObjectO.java │ │ │ │ │ │ │ ├── ObjectO1.java │ │ │ │ │ │ │ ├── ObjectO1_A.java │ │ │ │ │ │ │ ├── ObjectO2.java │ │ │ │ │ │ │ ├── ObjectO_A.java │ │ │ │ │ │ │ ├── ObjectP.java │ │ │ │ │ │ │ ├── ObjectP1.java │ │ │ │ │ │ │ ├── ObjectP1_A.java │ │ │ │ │ │ │ ├── ObjectP1_B.java │ │ │ │ │ │ │ ├── ObjectP_A.java │ │ │ │ │ │ │ ├── ObjectQ.java │ │ │ │ │ │ │ ├── ObjectQ1.java │ │ │ │ │ │ │ ├── ObjectQ1_A.java │ │ │ │ │ │ │ ├── ObjectQ1_B.java │ │ │ │ │ │ │ ├── ObjectR.java │ │ │ │ │ │ │ ├── ObjectR1.java │ │ │ │ │ │ │ ├── ObjectS.java │ │ │ │ │ │ │ ├── ObjectS1.java │ │ │ │ │ │ │ ├── ObjectS1_A.java │ │ │ │ │ │ │ ├── ObjectT.java │ │ │ │ │ │ │ ├── ObjectT1.java │ │ │ │ │ │ │ ├── ObjectT_A.java │ │ │ │ │ │ │ ├── ObjectU.java │ │ │ │ │ │ │ ├── ObjectU1.java │ │ │ │ │ │ │ ├── ObjectU1_A.java │ │ │ │ │ │ │ ├── ObjectU1_B.java │ │ │ │ │ │ │ ├── ObjectU1_C.java │ │ │ │ │ │ │ ├── ObjectV.java │ │ │ │ │ │ │ ├── ObjectV1.java │ │ │ │ │ │ │ ├── ObjectV1_A.java │ │ │ │ │ │ │ ├── ObjectV_A.java │ │ │ │ │ │ │ ├── ObjectW.java │ │ │ │ │ │ │ ├── ObjectW1.java │ │ │ │ │ │ │ ├── ObjectX.java │ │ │ │ │ │ │ ├── ObjectX1.java │ │ │ │ │ │ │ ├── ObjectY.java │ │ │ │ │ │ │ ├── ObjectY1.java │ │ │ │ │ │ │ ├── ObjectY_A.java │ │ │ │ │ │ │ ├── ObjectZ.java │ │ │ │ │ │ │ ├── ObjectZ1.java │ │ │ │ │ │ │ ├── ObjectZ1_A.java │ │ │ │ │ │ │ └── OjectN_A.java │ │ │ │ │ │ ├── issues569/ │ │ │ │ │ │ │ ├── TestIssues569.java │ │ │ │ │ │ │ ├── beans/ │ │ │ │ │ │ │ │ ├── Dept.java │ │ │ │ │ │ │ │ └── MyResponse.java │ │ │ │ │ │ │ └── parser/ │ │ │ │ │ │ │ ├── DefaultFieldDeserializerBug569.java │ │ │ │ │ │ │ └── ParserConfigBug569.java │ │ │ │ │ │ └── javabean/ │ │ │ │ │ │ ├── ConvertDO.java │ │ │ │ │ │ ├── ConvertEnum.java │ │ │ │ │ │ └── JavaBeanConvertTest.java │ │ │ │ │ ├── jsonpath/ │ │ │ │ │ │ ├── issue3493/ │ │ │ │ │ │ │ └── TestIssue3493.java │ │ │ │ │ │ └── issue3607/ │ │ │ │ │ │ └── TestIssue3607.java │ │ │ │ │ ├── parser/ │ │ │ │ │ │ └── JSONScannerTest.java │ │ │ │ │ ├── serializer/ │ │ │ │ │ │ ├── SerializeWriterTest.java │ │ │ │ │ │ ├── SerializeWriterToBytesTest.java │ │ │ │ │ │ ├── TestBean.java │ │ │ │ │ │ ├── TestParse.java │ │ │ │ │ │ ├── issue3084/ │ │ │ │ │ │ │ └── TestRefWithQuote.java │ │ │ │ │ │ ├── issue3177/ │ │ │ │ │ │ │ ├── Test3177Bean.java │ │ │ │ │ │ │ └── TestIssues3177.java │ │ │ │ │ │ ├── issue3473/ │ │ │ │ │ │ │ └── SerializeWriterJavaSqlDateTest.java │ │ │ │ │ │ ├── issue3479/ │ │ │ │ │ │ │ └── TestIssue3479.java │ │ │ │ │ │ ├── issue3638and3067/ │ │ │ │ │ │ │ └── Issue3638and3067Test.java │ │ │ │ │ │ └── issues3601/ │ │ │ │ │ │ ├── TestEntity.java │ │ │ │ │ │ ├── TestEnum.java │ │ │ │ │ │ └── TestIssue3601.java │ │ │ │ │ ├── support/ │ │ │ │ │ │ └── jaxrs/ │ │ │ │ │ │ ├── TestIssue885.java │ │ │ │ │ │ └── User.java │ │ │ │ │ └── validate/ │ │ │ │ │ ├── JSONValidateTest_0.java │ │ │ │ │ ├── JSONValidateTest_T1 │ │ │ │ │ ├── JSONValidateTest_basic.java │ │ │ │ │ └── JSONValidateTest_file.java │ │ │ │ └── json/ │ │ │ │ ├── ArrayRefTest2.java │ │ │ │ ├── ByteArrayTest2.java │ │ │ │ ├── SerializerFeatureDistinctTest.java │ │ │ │ ├── TestGC.java │ │ │ │ ├── bvt/ │ │ │ │ │ ├── AnnotationTest.java │ │ │ │ │ ├── AnnotationTest2.java │ │ │ │ │ ├── AnnotationTest3.java │ │ │ │ │ ├── AppendableFieldTest.java │ │ │ │ │ ├── ArmoryTest.java │ │ │ │ │ ├── ArrayListFieldTest.java │ │ │ │ │ ├── ArrayListFieldTest_1.java │ │ │ │ │ ├── ArrayListFloatFieldTest.java │ │ │ │ │ ├── ArrayRefTest.java │ │ │ │ │ ├── Base64Test.java │ │ │ │ │ ├── Base64Test2.java │ │ │ │ │ ├── BigDecimalFieldTest.java │ │ │ │ │ ├── BigIntegerFieldTest.java │ │ │ │ │ ├── BooleanArrayFieldTest.java │ │ │ │ │ ├── BooleanArrayFieldTest_primitive.java │ │ │ │ │ ├── BooleanArrayFieldTest_primitive_private.java │ │ │ │ │ ├── Bug12.java │ │ │ │ │ ├── Bug89.java │ │ │ │ │ ├── BuilderTest.java │ │ │ │ │ ├── ByteArrayFieldTest_1.java │ │ │ │ │ ├── ByteArrayFieldTest_2.java │ │ │ │ │ ├── ByteArrayFieldTest_3.java │ │ │ │ │ ├── ByteArrayFieldTest_4.java │ │ │ │ │ ├── ByteArrayFieldTest_5_base64.java │ │ │ │ │ ├── ByteArrayFieldTest_6_gzip.java │ │ │ │ │ ├── ByteArrayFieldTest_7_gzip_hex.java │ │ │ │ │ ├── ByteFieldTest.java │ │ │ │ │ ├── CastTest.java │ │ │ │ │ ├── CastTest2.java │ │ │ │ │ ├── CharTypesTest.java │ │ │ │ │ ├── CharsetFieldTest.java │ │ │ │ │ ├── ChineseSpaceTest.java │ │ │ │ │ ├── CircularReferenceTest.java │ │ │ │ │ ├── ClassFieldTest.java │ │ │ │ │ ├── CurrencyTest.java │ │ │ │ │ ├── CurrencyTest3.java │ │ │ │ │ ├── CurrencyTest4.java │ │ │ │ │ ├── CurrencyTest5.java │ │ │ │ │ ├── CurrencyTest_2.java │ │ │ │ │ ├── DefaultJSONParserTest.java │ │ │ │ │ ├── DefaultJSONParserTest_ref.java │ │ │ │ │ ├── DeprecatedClassTest.java │ │ │ │ │ ├── DisableSpecialKeyDetectTest.java │ │ │ │ │ ├── DoubleArrayFieldTest_primitive.java │ │ │ │ │ ├── DoubleFieldTest_A.java │ │ │ │ │ ├── EmptyArrayAsNullTest.java │ │ │ │ │ ├── EmptyObjectTest.java │ │ │ │ │ ├── EnumFieldTest.java │ │ │ │ │ ├── EnumFieldTest2.java │ │ │ │ │ ├── EnumFieldTest2_private.java │ │ │ │ │ ├── EnumFieldTest3.java │ │ │ │ │ ├── EnumFieldTest3_private.java │ │ │ │ │ ├── EnumerationTest.java │ │ │ │ │ ├── FastJsonBigClassTest.java │ │ │ │ │ ├── FieldBasedTest.java │ │ │ │ │ ├── FileFieldTest.java │ │ │ │ │ ├── FinalTest.java │ │ │ │ │ ├── FloatArrayFieldTest_primitive.java │ │ │ │ │ ├── FloatFieldTest.java │ │ │ │ │ ├── FloatFieldTest_A.java │ │ │ │ │ ├── FluentSetterTest.java │ │ │ │ │ ├── GetSetNotMatchTest.java │ │ │ │ │ ├── GroovyTest.java │ │ │ │ │ ├── IncomingDataPointTest.java │ │ │ │ │ ├── InetAddressFieldTest.java │ │ │ │ │ ├── InetSocketAddressFieldTest.java │ │ │ │ │ ├── IntArrayFieldTest_primitive.java │ │ │ │ │ ├── IntKeyMapTest.java │ │ │ │ │ ├── IntegerArrayFieldTest.java │ │ │ │ │ ├── Issue213Test.java │ │ │ │ │ ├── JSONArrayTest.java │ │ │ │ │ ├── JSONArrayTest2.java │ │ │ │ │ ├── JSONArrayTest3.java │ │ │ │ │ ├── JSONArrayTest_hashCode.java │ │ │ │ │ ├── JSONBytesTest.java │ │ │ │ │ ├── JSONBytesTest2.java │ │ │ │ │ ├── JSONBytesTest3.java │ │ │ │ │ ├── JSONExceptionTest.java │ │ │ │ │ ├── JSONFeidDemo2.java │ │ │ │ │ ├── JSONFieldDefaultValueTest.java │ │ │ │ │ ├── JSONFieldTest.java │ │ │ │ │ ├── JSONFromObjectTest.java │ │ │ │ │ ├── JSONObjectFluentTest.java │ │ │ │ │ ├── JSONObjectTest.java │ │ │ │ │ ├── JSONObjectTest2.java │ │ │ │ │ ├── JSONObjectTest3.java │ │ │ │ │ ├── JSONObjectTest4.java │ │ │ │ │ ├── JSONObjectTest5.java │ │ │ │ │ ├── JSONObjectTest6.java │ │ │ │ │ ├── JSONObjectTest7.java │ │ │ │ │ ├── JSONObjectTest_get.java │ │ │ │ │ ├── JSONObjectTest_getBigInteger.java │ │ │ │ │ ├── JSONObjectTest_getDate.java │ │ │ │ │ ├── JSONObjectTest_getObj.java │ │ │ │ │ ├── JSONObjectTest_getObj_2.java │ │ │ │ │ ├── JSONObjectTest_get_2.java │ │ │ │ │ ├── JSONObjectTest_hashCode.java │ │ │ │ │ ├── JSONObjectTest_readObject.java │ │ │ │ │ ├── JSONParseTest.java │ │ │ │ │ ├── JSONTest.java │ │ │ │ │ ├── JSONTest2.java │ │ │ │ │ ├── JSONTest3.java │ │ │ │ │ ├── JSONTest_Bytes.java │ │ │ │ │ ├── JSONTest_Bytes_1.java │ │ │ │ │ ├── JSONTest_null.java │ │ │ │ │ ├── JSONTest_overflow.java │ │ │ │ │ ├── JSONTokenTest.java │ │ │ │ │ ├── JSONTypeTest.java │ │ │ │ │ ├── JSONTypeTest1.java │ │ │ │ │ ├── JSONTypeTest_orders_arrayMapping.java │ │ │ │ │ ├── JSONTypeTest_orders_arrayMapping_2.java │ │ │ │ │ ├── JSON_isValid_0.java │ │ │ │ │ ├── JSON_isValid_1_error.java │ │ │ │ │ ├── JSON_toJSONStringTest.java │ │ │ │ │ ├── JSON_toJavaObject_test.java │ │ │ │ │ ├── JavaBeanMappingTest.java │ │ │ │ │ ├── JavaBeanTest.java │ │ │ │ │ ├── JsonValueTest.java │ │ │ │ │ ├── LexerTest.java │ │ │ │ │ ├── LinkedListFieldTest.java │ │ │ │ │ ├── ListFieldTest.java │ │ │ │ │ ├── ListFieldTest2.java │ │ │ │ │ ├── ListFieldTest3.java │ │ │ │ │ ├── ListFloatFieldTest.java │ │ │ │ │ ├── LocaleFieldTest.java │ │ │ │ │ ├── LongArrayFieldTest.java │ │ │ │ │ ├── LongArrayFieldTest_primitive.java │ │ │ │ │ ├── LongFieldTest.java │ │ │ │ │ ├── LongFieldTest_2.java │ │ │ │ │ ├── LongFieldTest_2_private.java │ │ │ │ │ ├── LongFieldTest_2_stream.java │ │ │ │ │ ├── LongFieldTest_3.java │ │ │ │ │ ├── LongFieldTest_3_private.java │ │ │ │ │ ├── LongFieldTest_3_stream.java │ │ │ │ │ ├── LongFieldTest_4.java │ │ │ │ │ ├── LongFieldTest_4_stream.java │ │ │ │ │ ├── LongFieldTest_primitive.java │ │ │ │ │ ├── MapRefTest.java │ │ │ │ │ ├── MapRefTest1.java │ │ │ │ │ ├── MapRefTest2.java │ │ │ │ │ ├── MapRefTest3.java │ │ │ │ │ ├── MapRefTest4.java │ │ │ │ │ ├── MapRefTest5.java │ │ │ │ │ ├── MapRefTest6.java │ │ │ │ │ ├── MapTest.java │ │ │ │ │ ├── MapTest2.java │ │ │ │ │ ├── MaterializedInterfaceTest.java │ │ │ │ │ ├── MaterializedInterfaceTest2.java │ │ │ │ │ ├── ModuleTest.java │ │ │ │ │ ├── NotWriteRootClassNameTest.java │ │ │ │ │ ├── NumberFieldTest.java │ │ │ │ │ ├── OOMTest.java │ │ │ │ │ ├── ObjectArrayFieldTest.java │ │ │ │ │ ├── ObjectFieldTest.java │ │ │ │ │ ├── OverriadeTest.java │ │ │ │ │ ├── ParseArrayTest.java │ │ │ │ │ ├── PatternFieldTest.java │ │ │ │ │ ├── PointTest.java │ │ │ │ │ ├── PointTest2.java │ │ │ │ │ ├── PublicFieldDoubleTest.java │ │ │ │ │ ├── PublicFieldFloatTest.java │ │ │ │ │ ├── PublicFieldLongTest.java │ │ │ │ │ ├── PublicFieldStringTest.java │ │ │ │ │ ├── RectangleTest.java │ │ │ │ │ ├── SerializeEnumAsJavaBeanTest.java │ │ │ │ │ ├── SerializeEnumAsJavaBeanTest_manual.java │ │ │ │ │ ├── SerializeEnumAsJavaBeanTest_private.java │ │ │ │ │ ├── SerializeWriterTest.java │ │ │ │ │ ├── ServiceLoaderTest.java │ │ │ │ │ ├── ShortArrayFieldTest_primitive.java │ │ │ │ │ ├── SlashTest.java │ │ │ │ │ ├── SpecialKeyTest.java │ │ │ │ │ ├── SpecialKeyTest2.java │ │ │ │ │ ├── SqlDateTest1.java │ │ │ │ │ ├── SqlTimestampTest.java │ │ │ │ │ ├── StringBufferFieldTest.java │ │ │ │ │ ├── StringBuilderFieldTest.java │ │ │ │ │ ├── StringDeserializerTest.java │ │ │ │ │ ├── StringFieldTest.java │ │ │ │ │ ├── StringFieldTest2.java │ │ │ │ │ ├── StringFieldTest_special.java │ │ │ │ │ ├── StringFieldTest_special_1.java │ │ │ │ │ ├── StringFieldTest_special_2.java │ │ │ │ │ ├── StringFieldTest_special_3.java │ │ │ │ │ ├── StringFieldTest_special_reader.java │ │ │ │ │ ├── StringFieldTest_special_singquote.java │ │ │ │ │ ├── SymbolTableTest.java │ │ │ │ │ ├── TabCharTest.java │ │ │ │ │ ├── TestDeprecate.java │ │ │ │ │ ├── TestExternal.java │ │ │ │ │ ├── TestExternal2.java │ │ │ │ │ ├── TestExternal3.java │ │ │ │ │ ├── TestExternal4.java │ │ │ │ │ ├── TestExternal5.java │ │ │ │ │ ├── TestExternal6.java │ │ │ │ │ ├── TestFlase.java │ │ │ │ │ ├── TestForEmoji.java │ │ │ │ │ ├── TestForPascalStyle.java │ │ │ │ │ ├── TestMultiLevelClass.java │ │ │ │ │ ├── TestMultiLevelClass2.java │ │ │ │ │ ├── TestNullKeyMap.java │ │ │ │ │ ├── TestSerializable.java │ │ │ │ │ ├── TestTimeUnit.java │ │ │ │ │ ├── TimeZoneFieldTest.java │ │ │ │ │ ├── TimestampTest.java │ │ │ │ │ ├── TypeUtilstTest.java │ │ │ │ │ ├── URIFieldTest.java │ │ │ │ │ ├── URLFieldTest.java │ │ │ │ │ ├── UUIDFieldTest.java │ │ │ │ │ ├── UnQuoteFieldNamesTest.java │ │ │ │ │ ├── WildcardTypeTest.java │ │ │ │ │ ├── WriteClassNameTest.java │ │ │ │ │ ├── WriteClassNameTest2.java │ │ │ │ │ ├── XX01.java │ │ │ │ │ ├── annotation/ │ │ │ │ │ │ ├── AnnotationTest.java │ │ │ │ │ │ ├── CustomDeserializerTest.java │ │ │ │ │ │ ├── CustomSerializerTest.java │ │ │ │ │ │ ├── CustomSerializerTest_enum.java │ │ │ │ │ │ ├── DeserializeUsingTest.java │ │ │ │ │ │ ├── JSONTypeAutoTypeCheckHandlerTest.java │ │ │ │ │ │ ├── JSONTypejsonType_alphabetic_Test.java │ │ │ │ │ │ ├── JsonSeeAlsoTest.java │ │ │ │ │ │ ├── SerializeUsingTest.java │ │ │ │ │ │ └── SerializeUsingWhenString.java │ │ │ │ │ ├── asm/ │ │ │ │ │ │ ├── ASMDeserTest.java │ │ │ │ │ │ ├── ASMDeserTest2.java │ │ │ │ │ │ ├── ASMUtilsTest.java │ │ │ │ │ │ ├── Case0.java │ │ │ │ │ │ ├── Case_Eishay.java │ │ │ │ │ │ ├── ClassReaderTest.java │ │ │ │ │ │ ├── Huge_200_ClassTest.java │ │ │ │ │ │ ├── Huge_300_ClassTest.java │ │ │ │ │ │ ├── JSONASMUtilTest.java │ │ │ │ │ │ ├── LoopTest.java │ │ │ │ │ │ ├── SortFieldTest.java │ │ │ │ │ │ ├── TestList.java │ │ │ │ │ │ ├── TestNonASM.java │ │ │ │ │ │ └── TestType.java │ │ │ │ │ ├── atomic/ │ │ │ │ │ │ ├── AtomicBooleanReadOnlyTest.java │ │ │ │ │ │ ├── AtomicIntegerArrayFieldTest.java │ │ │ │ │ │ ├── AtomicIntegerReadOnlyTest.java │ │ │ │ │ │ ├── AtomicLongArrayFieldTest.java │ │ │ │ │ │ └── AtomicLongReadOnlyTest.java │ │ │ │ │ ├── awt/ │ │ │ │ │ │ ├── ColorTest.java │ │ │ │ │ │ ├── FontTest.java │ │ │ │ │ │ └── FontTest2.java │ │ │ │ │ ├── basicType/ │ │ │ │ │ │ ├── BigDecimal_BrowserCompatible.java │ │ │ │ │ │ ├── BigDecimal_field.java │ │ │ │ │ │ ├── BigDecimal_type.java │ │ │ │ │ │ ├── BigInteger_BrowserCompatible.java │ │ │ │ │ │ ├── DoubleNullTest.java │ │ │ │ │ │ ├── DoubleNullTest_primitive.java │ │ │ │ │ │ ├── DoubleTest.java │ │ │ │ │ │ ├── DoubleTest2_obj.java │ │ │ │ │ │ ├── DoubleTest3_random.java │ │ │ │ │ │ ├── FloatNullTest.java │ │ │ │ │ │ ├── FloatNullTest_primitive.java │ │ │ │ │ │ ├── FloatTest.java │ │ │ │ │ │ ├── FloatTest2_obj.java │ │ │ │ │ │ ├── FloatTest3_array_random.java │ │ │ │ │ │ ├── FloatTest3_random.java │ │ │ │ │ │ ├── IntNullTest_primitive.java │ │ │ │ │ │ ├── IntTest.java │ │ │ │ │ │ ├── IntegerNullTest.java │ │ │ │ │ │ ├── LongNullTest.java │ │ │ │ │ │ ├── LongNullTest_primitive.java │ │ │ │ │ │ ├── LongTest.java │ │ │ │ │ │ ├── LongTest2.java │ │ │ │ │ │ ├── LongTest2_obj.java │ │ │ │ │ │ └── LongTest_browserCompatible.java │ │ │ │ │ ├── bug/ │ │ │ │ │ │ ├── Bug1.java │ │ │ │ │ │ ├── Bug11.java │ │ │ │ │ │ ├── Bug13.java │ │ │ │ │ │ ├── Bug14.java │ │ │ │ │ │ ├── Bug2.java │ │ │ │ │ │ ├── Bug_10.java │ │ │ │ │ │ ├── Bug_101_for_rongganlin.java │ │ │ │ │ │ ├── Bug_101_for_rongganlin_case2.java │ │ │ │ │ │ ├── Bug_101_for_rongganlin_case3.java │ │ │ │ │ │ ├── Bug_102_for_rongganlin.java │ │ │ │ │ │ ├── Bug_105_for_SpitFire.java │ │ │ │ │ │ ├── Bug_127_for_qiuyan81.java │ │ │ │ │ │ ├── Bug_376_for_iso8601.java │ │ │ │ │ │ ├── Bug_6.java │ │ │ │ │ │ ├── Bug_7.java │ │ │ │ │ │ ├── Bug_8.java │ │ │ │ │ │ ├── Bug_KimShen.java │ │ │ │ │ │ ├── Bug_for_42283905.java │ │ │ │ │ │ ├── Bug_for_42283905_1.java │ │ │ │ │ │ ├── Bug_for_80108116.java │ │ │ │ │ │ ├── Bug_for_ArrayMember.java │ │ │ │ │ │ ├── Bug_for_BlankRain_Issue_502.java │ │ │ │ │ │ ├── Bug_for_DiffType.java │ │ │ │ │ │ ├── Bug_for_Double2Tag.java │ │ │ │ │ │ ├── Bug_for_Exception.java │ │ │ │ │ │ ├── Bug_for_Issue_519.java │ │ │ │ │ │ ├── Bug_for_Issue_534.java │ │ │ │ │ │ ├── Bug_for_Issue_535.java │ │ │ │ │ │ ├── Bug_for_Issue_603.java │ │ │ │ │ │ ├── Bug_for_JSONObject.java │ │ │ │ │ │ ├── Bug_for_Jay.java │ │ │ │ │ │ ├── Bug_for_Jay_1.java │ │ │ │ │ │ ├── Bug_for_JeryZeng.java │ │ │ │ │ │ ├── Bug_for_Johnny.java │ │ │ │ │ │ ├── Bug_for_Next.java │ │ │ │ │ │ ├── Bug_for_NonStringKeyMap.java │ │ │ │ │ │ ├── Bug_for_O_I_See_you.java │ │ │ │ │ │ ├── Bug_for_SpitFire.java │ │ │ │ │ │ ├── Bug_for_SpitFire_2.java │ │ │ │ │ │ ├── Bug_for_SpitFire_3.java │ │ │ │ │ │ ├── Bug_for_SpitFire_4.java │ │ │ │ │ │ ├── Bug_for_SpitFire_5.java │ │ │ │ │ │ ├── Bug_for_SpitFire_6.java │ │ │ │ │ │ ├── Bug_for_agapple.java │ │ │ │ │ │ ├── Bug_for_agapple_2.java │ │ │ │ │ │ ├── Bug_for_akvadrako.java │ │ │ │ │ │ ├── Bug_for_alibank.java │ │ │ │ │ │ ├── Bug_for_apollo0317.java │ │ │ │ │ │ ├── Bug_for_array.java │ │ │ │ │ │ ├── Bug_for_ascii_0_31.java │ │ │ │ │ │ ├── Bug_for_bbl.java │ │ │ │ │ │ ├── Bug_for_booleanField.java │ │ │ │ │ │ ├── Bug_for_builder.java │ │ │ │ │ │ ├── Bug_for_cduym.java │ │ │ │ │ │ ├── Bug_for_chengchao.java │ │ │ │ │ │ ├── Bug_for_chengchao_1.java │ │ │ │ │ │ ├── Bug_for_chengyi.java │ │ │ │ │ │ ├── Bug_for_cnhans.java │ │ │ │ │ │ ├── Bug_for_dargoner.java │ │ │ │ │ │ ├── Bug_for_divde_zero.java │ │ │ │ │ │ ├── Bug_for_dongqi.java │ │ │ │ │ │ ├── Bug_for_dragoon.java │ │ │ │ │ │ ├── Bug_for_dragoon26.java │ │ │ │ │ │ ├── Bug_for_dragoon26_1.java │ │ │ │ │ │ ├── Bug_for_dubbo.java │ │ │ │ │ │ ├── Bug_for_dubbo1.java │ │ │ │ │ │ ├── Bug_for_dubbo2.java │ │ │ │ │ │ ├── Bug_for_dubbo3.java │ │ │ │ │ │ ├── Bug_for_dubbo_long.java │ │ │ │ │ │ ├── Bug_for_field.java │ │ │ │ │ │ ├── Bug_for_franklee77.java │ │ │ │ │ │ ├── Bug_for_fushou.java │ │ │ │ │ │ ├── Bug_for_generic.java │ │ │ │ │ │ ├── Bug_for_generic_1.java │ │ │ │ │ │ ├── Bug_for_generic_huansi.java │ │ │ │ │ │ ├── Bug_for_gongwenhua.java │ │ │ │ │ │ ├── Bug_for_hifor_issue_511.java │ │ │ │ │ │ ├── Bug_for_hmy8.java │ │ │ │ │ │ ├── Bug_for_huangchun.java │ │ │ │ │ │ ├── Bug_for_huling.java │ │ │ │ │ │ ├── Bug_for_issue_184.java │ │ │ │ │ │ ├── Bug_for_issue_229.java │ │ │ │ │ │ ├── Bug_for_issue_232.java │ │ │ │ │ │ ├── Bug_for_issue_236.java │ │ │ │ │ │ ├── Bug_for_issue_242.java │ │ │ │ │ │ ├── Bug_for_issue_252.java │ │ │ │ │ │ ├── Bug_for_issue_253.java │ │ │ │ │ │ ├── Bug_for_issue_256.java │ │ │ │ │ │ ├── Bug_for_issue_262.java │ │ │ │ │ │ ├── Bug_for_issue_265.java │ │ │ │ │ │ ├── Bug_for_issue_268.java │ │ │ │ │ │ ├── Bug_for_issue_269.java │ │ │ │ │ │ ├── Bug_for_issue_273.java │ │ │ │ │ │ ├── Bug_for_issue_278.java │ │ │ │ │ │ ├── Bug_for_issue_280.java │ │ │ │ │ │ ├── Bug_for_issue_283.java │ │ │ │ │ │ ├── Bug_for_issue_285.java │ │ │ │ │ │ ├── Bug_for_issue_291.java │ │ │ │ │ │ ├── Bug_for_issue_296.java │ │ │ │ │ │ ├── Bug_for_issue_297.java │ │ │ │ │ │ ├── Bug_for_issue_304.java │ │ │ │ │ │ ├── Bug_for_issue_316.java │ │ │ │ │ │ ├── Bug_for_issue_318.java │ │ │ │ │ │ ├── Bug_for_issue_320.java │ │ │ │ │ │ ├── Bug_for_issue_330.java │ │ │ │ │ │ ├── Bug_for_issue_331.java │ │ │ │ │ │ ├── Bug_for_issue_336.java │ │ │ │ │ │ ├── Bug_for_issue_349.java │ │ │ │ │ │ ├── Bug_for_issue_352.java │ │ │ │ │ │ ├── Bug_for_issue_364.java │ │ │ │ │ │ ├── Bug_for_issue_372.java │ │ │ │ │ │ ├── Bug_for_issue_383.java │ │ │ │ │ │ ├── Bug_for_issue_389.java │ │ │ │ │ │ ├── Bug_for_issue_414.java │ │ │ │ │ │ ├── Bug_for_issue_415.java │ │ │ │ │ │ ├── Bug_for_issue_423.java │ │ │ │ │ │ ├── Bug_for_issue_426.java │ │ │ │ │ │ ├── Bug_for_issue_427.java │ │ │ │ │ │ ├── Bug_for_issue_430.java │ │ │ │ │ │ ├── Bug_for_issue_434.java │ │ │ │ │ │ ├── Bug_for_issue_435.java │ │ │ │ │ │ ├── Bug_for_issue_439.java │ │ │ │ │ │ ├── Bug_for_issue_446.java │ │ │ │ │ │ ├── Bug_for_issue_447.java │ │ │ │ │ │ ├── Bug_for_issue_448.java │ │ │ │ │ │ ├── Bug_for_issue_449.java │ │ │ │ │ │ ├── Bug_for_issue_457.java │ │ │ │ │ │ ├── Bug_for_issue_462.java │ │ │ │ │ │ ├── Bug_for_issue_465.java │ │ │ │ │ │ ├── Bug_for_issue_469.java │ │ │ │ │ │ ├── Bug_for_issue_470.java │ │ │ │ │ │ ├── Bug_for_issue_479.java │ │ │ │ │ │ ├── Bug_for_issue_489.java │ │ │ │ │ │ ├── Bug_for_issue_491.java │ │ │ │ │ │ ├── Bug_for_issue_492.java │ │ │ │ │ │ ├── Bug_for_issue_537.java │ │ │ │ │ │ ├── Bug_for_issue_545.java │ │ │ │ │ │ ├── Bug_for_issue_555.java │ │ │ │ │ │ ├── Bug_for_issue_555_setter.java │ │ │ │ │ │ ├── Bug_for_issue_555_setter2.java │ │ │ │ │ │ ├── Bug_for_issue_569.java │ │ │ │ │ │ ├── Bug_for_issue_569_1.java │ │ │ │ │ │ ├── Bug_for_issue_572.java │ │ │ │ │ │ ├── Bug_for_issue_572_field.java │ │ │ │ │ │ ├── Bug_for_issue_572_field2.java │ │ │ │ │ │ ├── Bug_for_issue_572_private.java │ │ │ │ │ │ ├── Bug_for_issue_630.java │ │ │ │ │ │ ├── Bug_for_issue_676.java │ │ │ │ │ │ ├── Bug_for_issue_694.java │ │ │ │ │ │ ├── Bug_for_issue_729.java │ │ │ │ │ │ ├── Bug_for_issue_807.java │ │ │ │ │ │ ├── Bug_for_issue_937.java │ │ │ │ │ │ ├── Bug_for_jared1.java │ │ │ │ │ │ ├── Bug_for_javaeye_litterJava.java │ │ │ │ │ │ ├── Bug_for_jial10802.java │ │ │ │ │ │ ├── Bug_for_jiangwei.java │ │ │ │ │ │ ├── Bug_for_jiangwei1.java │ │ │ │ │ │ ├── Bug_for_jiangwei2.java │ │ │ │ │ │ ├── Bug_for_jinghui70.java │ │ │ │ │ │ ├── Bug_for_jinguwei.java │ │ │ │ │ │ ├── Bug_for_json_array.java │ │ │ │ │ │ ├── Bug_for_jsonobj_null.java │ │ │ │ │ │ ├── Bug_for_juewu.java │ │ │ │ │ │ ├── Bug_for_km.java │ │ │ │ │ │ ├── Bug_for_lenolix.java │ │ │ │ │ │ ├── Bug_for_lenolix_1.java │ │ │ │ │ │ ├── Bug_for_lenolix_10.java │ │ │ │ │ │ ├── Bug_for_lenolix_11.java │ │ │ │ │ │ ├── Bug_for_lenolix_2.java │ │ │ │ │ │ ├── Bug_for_lenolix_3.java │ │ │ │ │ │ ├── Bug_for_lenolix_4.java │ │ │ │ │ │ ├── Bug_for_lenolix_5.java │ │ │ │ │ │ ├── Bug_for_lenolix_6.java │ │ │ │ │ │ ├── Bug_for_lenolix_7.java │ │ │ │ │ │ ├── Bug_for_lenolix_8.java │ │ │ │ │ │ ├── Bug_for_lenolix_9.java │ │ │ │ │ │ ├── Bug_for_leupom.java │ │ │ │ │ │ ├── Bug_for_leupom_2.java │ │ │ │ │ │ ├── Bug_for_leupom_3.java │ │ │ │ │ │ ├── Bug_for_liqing.java │ │ │ │ │ │ ├── Bug_for_liuwanzhen_ren.java │ │ │ │ │ │ ├── Bug_for_liuying.java │ │ │ │ │ │ ├── Bug_for_long_whitespace.java │ │ │ │ │ │ ├── Bug_for_ludong.java │ │ │ │ │ │ ├── Bug_for_luogongwu.java │ │ │ │ │ │ ├── Bug_for_maiksagill.java │ │ │ │ │ │ ├── Bug_for_melin.java │ │ │ │ │ │ ├── Bug_for_primitive_boolean.java │ │ │ │ │ │ ├── Bug_for_primitive_byte.java │ │ │ │ │ │ ├── Bug_for_primitive_double.java │ │ │ │ │ │ ├── Bug_for_primitive_float.java │ │ │ │ │ │ ├── Bug_for_primitive_int.java │ │ │ │ │ │ ├── Bug_for_primitive_long.java │ │ │ │ │ │ ├── Bug_for_primitive_short.java │ │ │ │ │ │ ├── Bug_for_qianbi.java │ │ │ │ │ │ ├── Bug_for_qqdwll2012.java │ │ │ │ │ │ ├── Bug_for_rd.java │ │ │ │ │ │ ├── Bug_for_rendong.java │ │ │ │ │ │ ├── Bug_for_ruiqi.java │ │ │ │ │ │ ├── Bug_for_sankun.java │ │ │ │ │ │ ├── Bug_for_sanxiao.java │ │ │ │ │ │ ├── Bug_for_set.java │ │ │ │ │ │ ├── Bug_for_shortArray.java │ │ │ │ │ │ ├── Bug_for_smoothrat.java │ │ │ │ │ │ ├── Bug_for_smoothrat2.java │ │ │ │ │ │ ├── Bug_for_smoothrat3.java │ │ │ │ │ │ ├── Bug_for_smoothrat4.java │ │ │ │ │ │ ├── Bug_for_smoothrat5.java │ │ │ │ │ │ ├── Bug_for_smoothrat6.java │ │ │ │ │ │ ├── Bug_for_smoothrat7.java │ │ │ │ │ │ ├── Bug_for_smoothrat8.java │ │ │ │ │ │ ├── Bug_for_smoothrat9.java │ │ │ │ │ │ ├── Bug_for_stv_liu.java │ │ │ │ │ │ ├── Bug_for_sunai.java │ │ │ │ │ │ ├── Bug_for_taolei0628.java │ │ │ │ │ │ ├── Bug_for_typeReference.java │ │ │ │ │ │ ├── Bug_for_uin57.java │ │ │ │ │ │ ├── Bug_for_vikingschow.java │ │ │ │ │ │ ├── Bug_for_wangran.java │ │ │ │ │ │ ├── Bug_for_wangran1.java │ │ │ │ │ │ ├── Bug_for_wangran2.java │ │ │ │ │ │ ├── Bug_for_wsky.java │ │ │ │ │ │ ├── Bug_for_wtusmchen.java │ │ │ │ │ │ ├── Bug_for_wuyexiong.java │ │ │ │ │ │ ├── Bug_for_wuzhengmao.java │ │ │ │ │ │ ├── Bug_for_xiayucai2012.java │ │ │ │ │ │ ├── Bug_for_xiedun.java │ │ │ │ │ │ ├── Bug_for_xujin.java │ │ │ │ │ │ ├── Bug_for_xujin2.java │ │ │ │ │ │ ├── Bug_for_xujin_int.java │ │ │ │ │ │ ├── Bug_for_xuzebin.java │ │ │ │ │ │ ├── Bug_for_yangqi.java │ │ │ │ │ │ ├── Bug_for_yangzhou.java │ │ │ │ │ │ ├── Bug_for_yannywang.java │ │ │ │ │ │ ├── Bug_for_yanpei.java │ │ │ │ │ │ ├── Bug_for_yanpei2.java │ │ │ │ │ │ ├── Bug_for_yanpei3.java │ │ │ │ │ │ ├── Bug_for_yanpei4.java │ │ │ │ │ │ ├── Bug_for_yaoming.java │ │ │ │ │ │ ├── Bug_for_yaoming_1.java │ │ │ │ │ │ ├── Bug_for_yuanmomo_Issue_504.java │ │ │ │ │ │ ├── Bug_for_yuanmomo_Issue_505_1.java │ │ │ │ │ │ ├── Bug_for_yunban.java │ │ │ │ │ │ ├── Bug_for_zengjie.java │ │ │ │ │ │ ├── Bug_for_zhaoyao.java │ │ │ │ │ │ ├── Bug_for_zhongyin.java │ │ │ │ │ │ ├── Bug_for_zhuangzaowen.java │ │ │ │ │ │ ├── Bug_for_zhuel.java │ │ │ │ │ │ ├── CollectionEmptyMapTest.java │ │ │ │ │ │ ├── FastJsonSerializeIterableTest.java │ │ │ │ │ │ ├── Issue1005.java │ │ │ │ │ │ ├── Issue101.java │ │ │ │ │ │ ├── Issue1013.java │ │ │ │ │ │ ├── Issue1017.java │ │ │ │ │ │ ├── Issue101_NoneASM.java │ │ │ │ │ │ ├── Issue101_field.java │ │ │ │ │ │ ├── Issue101_field_NoneASM.java │ │ │ │ │ │ ├── Issue1020.java │ │ │ │ │ │ ├── Issue1023.java │ │ │ │ │ │ ├── Issue1030.java │ │ │ │ │ │ ├── Issue1036.java │ │ │ │ │ │ ├── Issue1063.java │ │ │ │ │ │ ├── Issue1063_date.java │ │ │ │ │ │ ├── Issue1074.java │ │ │ │ │ │ ├── Issue1075.java │ │ │ │ │ │ ├── Issue109.java │ │ │ │ │ │ ├── Issue115.java │ │ │ │ │ │ ├── Issue117.java │ │ │ │ │ │ ├── Issue118.java │ │ │ │ │ │ ├── Issue119.java │ │ │ │ │ │ ├── Issue124.java │ │ │ │ │ │ ├── Issue125.java │ │ │ │ │ │ ├── Issue126.java │ │ │ │ │ │ ├── Issue127.java │ │ │ │ │ │ ├── Issue1296.java │ │ │ │ │ │ ├── Issue141.java │ │ │ │ │ │ ├── Issue143.java │ │ │ │ │ │ ├── Issue146.java │ │ │ │ │ │ ├── Issue153.java │ │ │ │ │ │ ├── Issue157.java │ │ │ │ │ │ ├── Issue166.java │ │ │ │ │ │ ├── Issue169.java │ │ │ │ │ │ ├── Issue171.java │ │ │ │ │ │ ├── Issue176.java │ │ │ │ │ │ ├── Issue177.java │ │ │ │ │ │ ├── Issue179.java │ │ │ │ │ │ ├── Issue183.java │ │ │ │ │ │ ├── Issue184.java │ │ │ │ │ │ ├── Issue190.java │ │ │ │ │ │ ├── Issue199.java │ │ │ │ │ │ ├── Issue204.java │ │ │ │ │ │ ├── Issue208.java │ │ │ │ │ │ ├── Issue215.java │ │ │ │ │ │ ├── Issue215_boolean_array.java │ │ │ │ │ │ ├── Issue215_char_array.java │ │ │ │ │ │ ├── Issue215_double_array.java │ │ │ │ │ │ ├── Issue215_float_array.java │ │ │ │ │ │ ├── Issue215_int_array.java │ │ │ │ │ │ ├── Issue215_long_array.java │ │ │ │ │ │ ├── Issue215_short_array.java │ │ │ │ │ │ ├── Issue220.java │ │ │ │ │ │ ├── Issue243.java │ │ │ │ │ │ ├── Issue248_orderedField.java │ │ │ │ │ │ ├── Issue274.java │ │ │ │ │ │ ├── Issue363.java │ │ │ │ │ │ ├── Issue408.java │ │ │ │ │ │ ├── Issue569.java │ │ │ │ │ │ ├── Issue569_1.java │ │ │ │ │ │ ├── Issue585.java │ │ │ │ │ │ ├── Issue62.java │ │ │ │ │ │ ├── Issue64.java │ │ │ │ │ │ ├── Issue688.java │ │ │ │ │ │ ├── Issue689.java │ │ │ │ │ │ ├── Issue69.java │ │ │ │ │ │ ├── Issue72.java │ │ │ │ │ │ ├── Issue74.java │ │ │ │ │ │ ├── Issue743.java │ │ │ │ │ │ ├── Issue744.java │ │ │ │ │ │ ├── Issue744_1.java │ │ │ │ │ │ ├── Issue763.java │ │ │ │ │ │ ├── Issue771.java │ │ │ │ │ │ ├── Issue776.java │ │ │ │ │ │ ├── Issue779.java │ │ │ │ │ │ ├── Issue780.java │ │ │ │ │ │ ├── Issue784.java │ │ │ │ │ │ ├── Issue79.java │ │ │ │ │ │ ├── Issue793.java │ │ │ │ │ │ ├── Issue798.java │ │ │ │ │ │ ├── Issue798_1.java │ │ │ │ │ │ ├── Issue799.java │ │ │ │ │ │ ├── Issue801.java │ │ │ │ │ │ ├── Issue804.java │ │ │ │ │ │ ├── Issue821.java │ │ │ │ │ │ ├── Issue859.java │ │ │ │ │ │ ├── Issue868.java │ │ │ │ │ │ ├── Issue869.java │ │ │ │ │ │ ├── Issue869_1.java │ │ │ │ │ │ ├── Issue87.java │ │ │ │ │ │ ├── Issue878.java │ │ │ │ │ │ ├── Issue87_hashset.java │ │ │ │ │ │ ├── Issue87_treeset.java │ │ │ │ │ │ ├── Issue887.java │ │ │ │ │ │ ├── Issue89.java │ │ │ │ │ │ ├── Issue894.java │ │ │ │ │ │ ├── Issue900.java │ │ │ │ │ │ ├── Issue900_1.java │ │ │ │ │ │ ├── Issue912.java │ │ │ │ │ │ ├── Issue922.java │ │ │ │ │ │ ├── Issue923.java │ │ │ │ │ │ ├── Issue939.java │ │ │ │ │ │ ├── Issue94.java │ │ │ │ │ │ ├── Issue942.java │ │ │ │ │ │ ├── Issue943.java │ │ │ │ │ │ ├── Issue944.java │ │ │ │ │ │ ├── Issue952.java │ │ │ │ │ │ ├── Issue955.java │ │ │ │ │ │ ├── Issue96.java │ │ │ │ │ │ ├── Issue963.java │ │ │ │ │ │ ├── Issue975.java │ │ │ │ │ │ ├── Issue978.java │ │ │ │ │ │ ├── Issue983.java │ │ │ │ │ │ ├── Issue983_1.java │ │ │ │ │ │ ├── Issue987.java │ │ │ │ │ │ ├── Issue989.java │ │ │ │ │ │ ├── Issue993.java │ │ │ │ │ │ ├── Issue995.java │ │ │ │ │ │ ├── Issue997.java │ │ │ │ │ │ ├── Issue998.java │ │ │ │ │ │ ├── Issue998_private.java │ │ │ │ │ │ ├── Issue_611.java │ │ │ │ │ │ ├── Issue_717.java │ │ │ │ │ │ ├── Issue_748.java │ │ │ │ │ │ ├── Issue_for_huangfeng.java │ │ │ │ │ │ ├── Issue_for_jiongxiong.java │ │ │ │ │ │ ├── Issue_for_oschina_3087749_2215732.java │ │ │ │ │ │ ├── Issue_for_zuojing.java │ │ │ │ │ │ ├── JSONTest.java │ │ │ │ │ │ ├── KeyBug_for_zhongl.java │ │ │ │ │ │ ├── Mogujie_01.java │ │ │ │ │ │ ├── Mogujie_02.java │ │ │ │ │ │ ├── SerDeserTest.java │ │ │ │ │ │ ├── StackTraceElementTest.java │ │ │ │ │ │ ├── StackTraceElementTest2.java │ │ │ │ │ │ ├── TestDouble.java │ │ │ │ │ │ ├── TestJSONMap.java │ │ │ │ │ │ ├── WuqiTest.java │ │ │ │ │ │ ├── bug201806/ │ │ │ │ │ │ │ └── Bug_for_weiqiang.java │ │ │ │ │ │ ├── bug201810/ │ │ │ │ │ │ │ └── LatLngTest.java │ │ │ │ │ │ ├── bug2019/ │ │ │ │ │ │ │ └── Bug20190729_01.java │ │ │ │ │ │ ├── bug2020/ │ │ │ │ │ │ │ ├── Bug_for_emptyList.java │ │ │ │ │ │ │ └── Bug_for_money.java │ │ │ │ │ │ ├── bug_for_caoyaojun1988.java │ │ │ │ │ │ └── bug_for_pengsong0302.java │ │ │ │ │ ├── builder/ │ │ │ │ │ │ ├── BuilderTest0.java │ │ │ │ │ │ ├── BuilderTest0_private.java │ │ │ │ │ │ ├── BuilderTest1.java │ │ │ │ │ │ ├── BuilderTest1_private.java │ │ │ │ │ │ ├── BuilderTest2.java │ │ │ │ │ │ ├── BuilderTest2_private.java │ │ │ │ │ │ ├── BuilderTest3.java │ │ │ │ │ │ ├── BuilderTest3_private.java │ │ │ │ │ │ ├── BuilderTest_error.java │ │ │ │ │ │ └── BuilderTest_error_private.java │ │ │ │ │ ├── cglib/ │ │ │ │ │ │ └── TestCglib.java │ │ │ │ │ ├── comparing_json_modules/ │ │ │ │ │ │ ├── ComplexAndDecimalTest.java │ │ │ │ │ │ ├── Floating_point_Test.java │ │ │ │ │ │ ├── Integral_types_Test.java │ │ │ │ │ │ └── Invalid_Test.java │ │ │ │ │ ├── compatible/ │ │ │ │ │ │ ├── ThreadLocalCacheTest.java │ │ │ │ │ │ ├── TypeUtilsComputeGettersTest.java │ │ │ │ │ │ └── jsonlib/ │ │ │ │ │ │ ├── CompatibleTest0.java │ │ │ │ │ │ └── CompatibleTest_noasm.java │ │ │ │ │ ├── date/ │ │ │ │ │ │ ├── CalendarTest.java │ │ │ │ │ │ ├── DateFieldFormatTest.java │ │ │ │ │ │ ├── DateFieldTest.java │ │ │ │ │ │ ├── DateFieldTest10.java │ │ │ │ │ │ ├── DateFieldTest11_reader.java │ │ │ │ │ │ ├── DateFieldTest12_t.java │ │ │ │ │ │ ├── DateFieldTest2.java │ │ │ │ │ │ ├── DateFieldTest3.java │ │ │ │ │ │ ├── DateFieldTest4.java │ │ │ │ │ │ ├── DateFieldTest5.java │ │ │ │ │ │ ├── DateFieldTest6.java │ │ │ │ │ │ ├── DateFieldTest7.java │ │ │ │ │ │ ├── DateFieldTest8.java │ │ │ │ │ │ ├── DateFieldTest9.java │ │ │ │ │ │ ├── DateFormatPriorityTest.java │ │ │ │ │ │ ├── DateNewTest.java │ │ │ │ │ │ ├── DateTest.java │ │ │ │ │ │ ├── DateTest1.java │ │ │ │ │ │ ├── DateTest2.java │ │ │ │ │ │ ├── DateTest_dotnet.java │ │ │ │ │ │ ├── DateTest_dotnet_1.java │ │ │ │ │ │ ├── DateTest_dotnet_2.java │ │ │ │ │ │ ├── DateTest_dotnet_3.java │ │ │ │ │ │ ├── DateTest_dotnet_4.java │ │ │ │ │ │ ├── DateTest_dotnet_5.java │ │ │ │ │ │ ├── DateTest_error.java │ │ │ │ │ │ ├── DateTest_tz.java │ │ │ │ │ │ └── XMLGregorianCalendarTest.java │ │ │ │ │ ├── dubbo/ │ │ │ │ │ │ └── TestForDubbo.java │ │ │ │ │ ├── emoji/ │ │ │ │ │ │ └── EmojiTest0.java │ │ │ │ │ ├── feature/ │ │ │ │ │ │ ├── DisableFieldSmartMatchTest.java │ │ │ │ │ │ ├── DisableFieldSmartMatchTest_2.java │ │ │ │ │ │ ├── FeatureTest_8.java │ │ │ │ │ │ ├── FeaturesTest.java │ │ │ │ │ │ ├── FeaturesTest2.java │ │ │ │ │ │ ├── FeaturesTest3.java │ │ │ │ │ │ ├── FeaturesTest4.java │ │ │ │ │ │ ├── FeaturesTest5.java │ │ │ │ │ │ ├── FeaturesTest5_1.java │ │ │ │ │ │ ├── FeaturesTest6.java │ │ │ │ │ │ ├── FeaturesTest7.java │ │ │ │ │ │ ├── IgnoreErrorGetterTest.java │ │ │ │ │ │ ├── IgnoreErrorGetterTest_field.java │ │ │ │ │ │ ├── IgnoreErrorGetterTest_private.java │ │ │ │ │ │ ├── InitStringFieldAsEmptyTest.java │ │ │ │ │ │ ├── WriteNullStringAsEmptyTest.java │ │ │ │ │ │ └── WriteNullStringAsEmptyTest2.java │ │ │ │ │ ├── fullSer/ │ │ │ │ │ │ ├── EmtpyLinkedHashMapTest.java │ │ │ │ │ │ ├── LongTest.java │ │ │ │ │ │ ├── ToJavaObjectTest.java │ │ │ │ │ │ ├── ToJavaObjectTest2.java │ │ │ │ │ │ ├── get_set_Test.java │ │ │ │ │ │ ├── getfTest.java │ │ │ │ │ │ ├── getfTest_2.java │ │ │ │ │ │ └── is_set_test_2.java │ │ │ │ │ ├── geo/ │ │ │ │ │ │ ├── FeatureCollectionTest.java │ │ │ │ │ │ ├── FeatureTest.java │ │ │ │ │ │ ├── GeometryCollectionTest.java │ │ │ │ │ │ ├── LineStringTest.java │ │ │ │ │ │ ├── MultiLineStringTest.java │ │ │ │ │ │ ├── MultiPointTest.java │ │ │ │ │ │ ├── MultiPolygonTest.java │ │ │ │ │ │ ├── PointTest.java │ │ │ │ │ │ └── PolygonTest.java │ │ │ │ │ ├── guava/ │ │ │ │ │ │ ├── ArrayListMultimapTest.java │ │ │ │ │ │ ├── HashMultimapTest.java │ │ │ │ │ │ ├── ImmutableMapTest.java │ │ │ │ │ │ ├── LinkedListMultimapTest.java │ │ │ │ │ │ └── MultiMapTes.java │ │ │ │ │ ├── issue_1000/ │ │ │ │ │ │ ├── Issue1066.java │ │ │ │ │ │ ├── Issue1079.java │ │ │ │ │ │ ├── Issue1080.java │ │ │ │ │ │ ├── Issue1082.java │ │ │ │ │ │ ├── Issue1083.java │ │ │ │ │ │ ├── Issue1085.java │ │ │ │ │ │ ├── Issue1086.java │ │ │ │ │ │ ├── Issue1089.java │ │ │ │ │ │ ├── Issue1089_private.java │ │ │ │ │ │ └── Issue1095.java │ │ │ │ │ ├── issue_1100/ │ │ │ │ │ │ ├── Issue1109.java │ │ │ │ │ │ ├── Issue1112.java │ │ │ │ │ │ ├── Issue1120.java │ │ │ │ │ │ ├── Issue1121.java │ │ │ │ │ │ ├── Issue1134.java │ │ │ │ │ │ ├── Issue1138.java │ │ │ │ │ │ ├── Issue1140.java │ │ │ │ │ │ ├── Issue1144.java │ │ │ │ │ │ ├── Issue1146.java │ │ │ │ │ │ ├── Issue1150.java │ │ │ │ │ │ ├── Issue1151.java │ │ │ │ │ │ ├── Issue1152.java │ │ │ │ │ │ ├── Issue1153.java │ │ │ │ │ │ ├── Issue1165.java │ │ │ │ │ │ ├── Issue1177.java │ │ │ │ │ │ ├── Issue1177_1.java │ │ │ │ │ │ ├── Issue1177_2.java │ │ │ │ │ │ ├── Issue1177_3.java │ │ │ │ │ │ ├── Issue1177_4.java │ │ │ │ │ │ ├── Issue1178.java │ │ │ │ │ │ ├── Issue1187.java │ │ │ │ │ │ ├── Issue1188.java │ │ │ │ │ │ ├── Issue1189.java │ │ │ │ │ │ └── Issue969.java │ │ │ │ │ ├── issue_1200/ │ │ │ │ │ │ ├── Issue1202.java │ │ │ │ │ │ ├── Issue1203.java │ │ │ │ │ │ ├── Issue1205.java │ │ │ │ │ │ ├── Issue1222.java │ │ │ │ │ │ ├── Issue1222_1.java │ │ │ │ │ │ ├── Issue1225.java │ │ │ │ │ │ ├── Issue1226.java │ │ │ │ │ │ ├── Issue1227.java │ │ │ │ │ │ ├── Issue1229.java │ │ │ │ │ │ ├── Issue1231.java │ │ │ │ │ │ ├── Issue1233.java │ │ │ │ │ │ ├── Issue1235.java │ │ │ │ │ │ ├── Issue1235_noasm.java │ │ │ │ │ │ ├── Issue1240.java │ │ │ │ │ │ ├── Issue1246.java │ │ │ │ │ │ ├── Issue1254.java │ │ │ │ │ │ ├── Issue1256.java │ │ │ │ │ │ ├── Issue1262.java │ │ │ │ │ │ ├── Issue1265.java │ │ │ │ │ │ ├── Issue1267.java │ │ │ │ │ │ ├── Issue1271.java │ │ │ │ │ │ ├── Issue1272.java │ │ │ │ │ │ ├── Issue1272_IgnoreError.java │ │ │ │ │ │ ├── Issue1274.java │ │ │ │ │ │ ├── Issue1276.java │ │ │ │ │ │ ├── Issue1278.java │ │ │ │ │ │ ├── Issue1281.java │ │ │ │ │ │ ├── Issue1293.java │ │ │ │ │ │ ├── Issue1298.java │ │ │ │ │ │ └── Issue1299.java │ │ │ │ │ ├── issue_1300/ │ │ │ │ │ │ ├── Issue1300.java │ │ │ │ │ │ ├── Issue1303.java │ │ │ │ │ │ ├── Issue1306.java │ │ │ │ │ │ ├── Issue1307.java │ │ │ │ │ │ ├── Issue1310.java │ │ │ │ │ │ ├── Issue1310_noasm.java │ │ │ │ │ │ ├── Issue1319.java │ │ │ │ │ │ ├── Issue1320.java │ │ │ │ │ │ ├── Issue1330.java │ │ │ │ │ │ ├── Issue1330_boolean.java │ │ │ │ │ │ ├── Issue1330_byte.java │ │ │ │ │ │ ├── Issue1330_decimal.java │ │ │ │ │ │ ├── Issue1330_double.java │ │ │ │ │ │ ├── Issue1330_float.java │ │ │ │ │ │ ├── Issue1330_long.java │ │ │ │ │ │ ├── Issue1330_short.java │ │ │ │ │ │ ├── Issue1335.java │ │ │ │ │ │ ├── Issue1341.java │ │ │ │ │ │ ├── Issue1344.java │ │ │ │ │ │ ├── Issue1357.java │ │ │ │ │ │ ├── Issue1362.java │ │ │ │ │ │ ├── Issue1363.java │ │ │ │ │ │ ├── Issue1367.java │ │ │ │ │ │ ├── Issue1367_jaxrs.java │ │ │ │ │ │ ├── Issue1368.java │ │ │ │ │ │ ├── Issue1369.java │ │ │ │ │ │ ├── Issue1370.java │ │ │ │ │ │ ├── Issue1371.java │ │ │ │ │ │ ├── Issue1375.java │ │ │ │ │ │ ├── Issue1392.java │ │ │ │ │ │ ├── Issue1399.java │ │ │ │ │ │ └── Issue_for_zuojian.java │ │ │ │ │ ├── issue_1400/ │ │ │ │ │ │ ├── Issue1400.java │ │ │ │ │ │ ├── Issue1405.java │ │ │ │ │ │ ├── Issue1422.java │ │ │ │ │ │ ├── Issue1423.java │ │ │ │ │ │ ├── Issue1424.java │ │ │ │ │ │ ├── Issue1425.java │ │ │ │ │ │ ├── Issue1429.java │ │ │ │ │ │ ├── Issue1443.java │ │ │ │ │ │ ├── Issue1445.java │ │ │ │ │ │ ├── Issue1449.java │ │ │ │ │ │ ├── Issue1450.java │ │ │ │ │ │ ├── Issue1458.java │ │ │ │ │ │ ├── Issue1465.java │ │ │ │ │ │ ├── Issue1472.java │ │ │ │ │ │ ├── Issue1474.java │ │ │ │ │ │ ├── Issue1478.java │ │ │ │ │ │ ├── Issue1480.java │ │ │ │ │ │ ├── Issue1482.java │ │ │ │ │ │ ├── Issue1486.java │ │ │ │ │ │ ├── Issue1487.java │ │ │ │ │ │ ├── Issue1492.java │ │ │ │ │ │ ├── Issue1493.java │ │ │ │ │ │ ├── Issue1494.java │ │ │ │ │ │ ├── Issue1496.java │ │ │ │ │ │ ├── Issue1498.java │ │ │ │ │ │ └── Issue_for_wuye.java │ │ │ │ │ ├── issue_1500/ │ │ │ │ │ │ ├── Issue1500.java │ │ │ │ │ │ ├── Issue1503.java │ │ │ │ │ │ ├── Issue1510.java │ │ │ │ │ │ ├── Issue1513.java │ │ │ │ │ │ ├── Issue1524.java │ │ │ │ │ │ ├── Issue1529.java │ │ │ │ │ │ ├── Issue1548.java │ │ │ │ │ │ ├── Issue1555.java │ │ │ │ │ │ ├── Issue1556.java │ │ │ │ │ │ ├── Issue1558.java │ │ │ │ │ │ ├── Issue1565.java │ │ │ │ │ │ ├── Issue1570.java │ │ │ │ │ │ ├── Issue1570_private.java │ │ │ │ │ │ ├── Issue1572.java │ │ │ │ │ │ ├── Issue1576.java │ │ │ │ │ │ ├── Issue1580.java │ │ │ │ │ │ ├── Issue1580_private.java │ │ │ │ │ │ ├── Issue1582.java │ │ │ │ │ │ ├── Issue1583.java │ │ │ │ │ │ ├── Issue1584.java │ │ │ │ │ │ ├── Issue1588.java │ │ │ │ │ │ └── StringSerializer.java │ │ │ │ │ ├── issue_1600/ │ │ │ │ │ │ ├── Issue1603_field.java │ │ │ │ │ │ ├── Issue1603_getter.java │ │ │ │ │ │ ├── Issue1603_map.java │ │ │ │ │ │ ├── Issue1603_map_getter.java │ │ │ │ │ │ ├── Issue1611.java │ │ │ │ │ │ ├── Issue1612.java │ │ │ │ │ │ ├── Issue1627.java │ │ │ │ │ │ ├── Issue1628.java │ │ │ │ │ │ ├── Issue1633.java │ │ │ │ │ │ ├── Issue1635.java │ │ │ │ │ │ ├── Issue1636.java │ │ │ │ │ │ ├── Issue1644.java │ │ │ │ │ │ ├── Issue1645.java │ │ │ │ │ │ ├── Issue1647.java │ │ │ │ │ │ ├── Issue1649.java │ │ │ │ │ │ ├── Issue1649_private.java │ │ │ │ │ │ ├── Issue1653.java │ │ │ │ │ │ ├── Issue1657.java │ │ │ │ │ │ ├── Issue1660.java │ │ │ │ │ │ ├── Issue1662.java │ │ │ │ │ │ ├── Issue1662_1.java │ │ │ │ │ │ ├── Issue1665.java │ │ │ │ │ │ ├── Issue1679.java │ │ │ │ │ │ ├── Issue1683.java │ │ │ │ │ │ ├── Issue_for_gaorui.java │ │ │ │ │ │ └── issue_1699/ │ │ │ │ │ │ ├── TestJson.java │ │ │ │ │ │ ├── def/ │ │ │ │ │ │ │ ├── FeeTypeMEnum.java │ │ │ │ │ │ │ ├── InnerTypeMEnum.java │ │ │ │ │ │ │ ├── RatingDetailIsJoinMEnum.java │ │ │ │ │ │ │ ├── RatingDetailStatusMEnum.java │ │ │ │ │ │ │ └── RatingDetailTypeMEnum.java │ │ │ │ │ │ └── obj/ │ │ │ │ │ │ └── RatingDetailBO.java │ │ │ │ │ ├── issue_1700/ │ │ │ │ │ │ ├── Issue1701.java │ │ │ │ │ │ ├── Issue1723.java │ │ │ │ │ │ ├── Issue1725.java │ │ │ │ │ │ ├── Issue1727.java │ │ │ │ │ │ ├── Issue1733_jsonpath.java │ │ │ │ │ │ ├── Issue1739.java │ │ │ │ │ │ ├── Issue1761.java │ │ │ │ │ │ ├── Issue1763.java │ │ │ │ │ │ ├── Issue1764.java │ │ │ │ │ │ ├── Issue1764_bean.java │ │ │ │ │ │ ├── Issue1764_bean_biginteger.java │ │ │ │ │ │ ├── Issue1764_bean_biginteger_field.java │ │ │ │ │ │ ├── Issue1764_bean_biginteger_type.java │ │ │ │ │ │ ├── Issue1766.java │ │ │ │ │ │ ├── Issue1769.java │ │ │ │ │ │ ├── Issue1772.java │ │ │ │ │ │ ├── Issue1780_JSONObject.java │ │ │ │ │ │ ├── Issue1780_Module.java │ │ │ │ │ │ ├── Issue1785.java │ │ │ │ │ │ └── issue1763_2/ │ │ │ │ │ │ ├── TestIssue1763_2.java │ │ │ │ │ │ ├── TypeReferenceBug1763_2.java │ │ │ │ │ │ └── bean/ │ │ │ │ │ │ ├── BaseResult.java │ │ │ │ │ │ ├── CouponResult.java │ │ │ │ │ │ └── PageResult.java │ │ │ │ │ ├── issue_1800/ │ │ │ │ │ │ ├── Issue1821.java │ │ │ │ │ │ ├── Issue1834.java │ │ │ │ │ │ ├── Issue1856.java │ │ │ │ │ │ ├── Issue1870.java │ │ │ │ │ │ ├── Issue1871.java │ │ │ │ │ │ ├── Issue1879.java │ │ │ │ │ │ ├── Issue1892.java │ │ │ │ │ │ ├── Issue_for_dianxing.java │ │ │ │ │ │ └── Issue_for_float_zero.java │ │ │ │ │ ├── issue_1900/ │ │ │ │ │ │ ├── Issue1901.java │ │ │ │ │ │ ├── Issue1903.java │ │ │ │ │ │ ├── Issue1909.java │ │ │ │ │ │ ├── Issue1933.java │ │ │ │ │ │ ├── Issue1939.java │ │ │ │ │ │ ├── Issue1941.java │ │ │ │ │ │ ├── Issue1941_JSONField_order.java │ │ │ │ │ │ ├── Issue1944.java │ │ │ │ │ │ ├── Issue1945.java │ │ │ │ │ │ ├── Issue1955.java │ │ │ │ │ │ ├── Issue1972.java │ │ │ │ │ │ ├── Issue1977.java │ │ │ │ │ │ ├── Issue1987.java │ │ │ │ │ │ └── Issue1996.java │ │ │ │ │ ├── issue_2000/ │ │ │ │ │ │ ├── Issue2012.java │ │ │ │ │ │ ├── Issue2040.java │ │ │ │ │ │ ├── Issue2065.java │ │ │ │ │ │ ├── Issue2066.java │ │ │ │ │ │ ├── Issue2074.java │ │ │ │ │ │ ├── Issue2086.java │ │ │ │ │ │ └── Issue2088.java │ │ │ │ │ ├── issue_2100/ │ │ │ │ │ │ ├── Issue2129.java │ │ │ │ │ │ ├── Issue2130.java │ │ │ │ │ │ ├── Issue2132.java │ │ │ │ │ │ ├── Issue2150.java │ │ │ │ │ │ ├── Issue2156.java │ │ │ │ │ │ ├── Issue2164.java │ │ │ │ │ │ ├── Issue2165.java │ │ │ │ │ │ ├── Issue2179.java │ │ │ │ │ │ ├── Issue2182.java │ │ │ │ │ │ ├── Issue2185.java │ │ │ │ │ │ └── Issue2189.java │ │ │ │ │ ├── issue_2200/ │ │ │ │ │ │ ├── Issue2201.java │ │ │ │ │ │ ├── Issue2206.java │ │ │ │ │ │ ├── Issue2214.java │ │ │ │ │ │ ├── Issue2216.java │ │ │ │ │ │ ├── Issue2224.java │ │ │ │ │ │ ├── Issue2229.java │ │ │ │ │ │ ├── Issue2234.java │ │ │ │ │ │ ├── Issue2238.java │ │ │ │ │ │ ├── Issue2239.java │ │ │ │ │ │ ├── Issue2240.java │ │ │ │ │ │ ├── Issue2241.java │ │ │ │ │ │ ├── Issue2244.java │ │ │ │ │ │ ├── Issue2249.java │ │ │ │ │ │ ├── Issue2251.java │ │ │ │ │ │ ├── Issue2253.java │ │ │ │ │ │ ├── Issue2254.java │ │ │ │ │ │ ├── Issue2260.java │ │ │ │ │ │ ├── Issue2262.java │ │ │ │ │ │ ├── Issue2264.java │ │ │ │ │ │ ├── Issue2289.java │ │ │ │ │ │ ├── Issue_for_luohaoyu.java │ │ │ │ │ │ ├── issue2224/ │ │ │ │ │ │ │ ├── CollectionEx.java │ │ │ │ │ │ │ ├── KeyedCollection.java │ │ │ │ │ │ │ ├── Person.java │ │ │ │ │ │ │ └── PersonCollection.java │ │ │ │ │ │ ├── issue2224_2/ │ │ │ │ │ │ │ ├── GroupedCollection.java │ │ │ │ │ │ │ ├── PersonGroupedCollection.java │ │ │ │ │ │ │ └── StringGroupedCollection.java │ │ │ │ │ │ ├── issue2224_3/ │ │ │ │ │ │ │ ├── ArrayGroupedCollection.java │ │ │ │ │ │ │ ├── ArrayPersonGroupedCollection.java │ │ │ │ │ │ │ └── ArrayStringGroupedCollection.java │ │ │ │ │ │ ├── issue2224_4/ │ │ │ │ │ │ │ ├── MAGroupedCollection.java │ │ │ │ │ │ │ ├── MAPersonGroupedCollection.java │ │ │ │ │ │ │ └── MAStringGroupedCollection.java │ │ │ │ │ │ └── issue2224_5/ │ │ │ │ │ │ ├── MA2GroupedCollection.java │ │ │ │ │ │ ├── MA2PersonGroupedCollection.java │ │ │ │ │ │ └── MA2StringGroupedCollection.java │ │ │ │ │ ├── issue_2300/ │ │ │ │ │ │ ├── Issue2300.java │ │ │ │ │ │ ├── Issue2306.java │ │ │ │ │ │ ├── Issue2311.java │ │ │ │ │ │ ├── Issue2334.java │ │ │ │ │ │ ├── Issue2341.java │ │ │ │ │ │ ├── Issue2343.java │ │ │ │ │ │ ├── Issue2344.java │ │ │ │ │ │ ├── Issue2346.java │ │ │ │ │ │ ├── Issue2348.java │ │ │ │ │ │ ├── Issue2351.java │ │ │ │ │ │ ├── Issue2355.java │ │ │ │ │ │ ├── Issue2357.java │ │ │ │ │ │ ├── Issue2358.java │ │ │ │ │ │ ├── Issue2371.java │ │ │ │ │ │ ├── Issue2387.java │ │ │ │ │ │ └── Issue2397.java │ │ │ │ │ ├── issue_2400/ │ │ │ │ │ │ ├── Issue2428.java │ │ │ │ │ │ ├── Issue2429.java │ │ │ │ │ │ ├── Issue2430.java │ │ │ │ │ │ ├── Issue2447.java │ │ │ │ │ │ ├── Issue2464.java │ │ │ │ │ │ └── Issue2488.java │ │ │ │ │ ├── issue_2500/ │ │ │ │ │ │ ├── Issue2515.java │ │ │ │ │ │ ├── Issue2516.java │ │ │ │ │ │ └── Issue2579.java │ │ │ │ │ ├── issue_2600/ │ │ │ │ │ │ ├── Issue2606.java │ │ │ │ │ │ ├── Issue2617.java │ │ │ │ │ │ ├── Issue2628.java │ │ │ │ │ │ ├── Issue2635.java │ │ │ │ │ │ ├── Issue2678.java │ │ │ │ │ │ ├── Issue2685.java │ │ │ │ │ │ └── Issue2689.java │ │ │ │ │ ├── issue_2700/ │ │ │ │ │ │ ├── Issue2703.java │ │ │ │ │ │ ├── Issue2721Test.java │ │ │ │ │ │ ├── Issue2736.java │ │ │ │ │ │ ├── Issue2743.java │ │ │ │ │ │ ├── Issue2752.java │ │ │ │ │ │ ├── Issue2754.java │ │ │ │ │ │ ├── Issue2772.java │ │ │ │ │ │ ├── Issue2779.java │ │ │ │ │ │ ├── Issue2784.java │ │ │ │ │ │ ├── Issue2787.java │ │ │ │ │ │ ├── Issue2791.java │ │ │ │ │ │ └── Issue2792.java │ │ │ │ │ ├── issue_2800/ │ │ │ │ │ │ ├── Issue2830.java │ │ │ │ │ │ ├── Issue2866.java │ │ │ │ │ │ ├── Issue2894.java │ │ │ │ │ │ └── Issue2903.java │ │ │ │ │ ├── issue_2900/ │ │ │ │ │ │ ├── Issue2914.java │ │ │ │ │ │ ├── Issue2939.java │ │ │ │ │ │ ├── Issue2952.java │ │ │ │ │ │ ├── Issue2962.java │ │ │ │ │ │ └── Issue2982.java │ │ │ │ │ ├── issue_3000/ │ │ │ │ │ │ ├── Issue3031.java │ │ │ │ │ │ ├── Issue3049.java │ │ │ │ │ │ ├── Issue3057.java │ │ │ │ │ │ ├── Issue3060.java │ │ │ │ │ │ ├── Issue3065.java │ │ │ │ │ │ ├── Issue3066.java │ │ │ │ │ │ ├── Issue3075.java │ │ │ │ │ │ ├── Issue3082.java │ │ │ │ │ │ ├── Issue3083.kt │ │ │ │ │ │ ├── Issue3093.java │ │ │ │ │ │ └── Issue3138.java │ │ │ │ │ ├── issue_3100/ │ │ │ │ │ │ ├── Issue3109.java │ │ │ │ │ │ ├── Issue3131.java │ │ │ │ │ │ ├── Issue3132.java │ │ │ │ │ │ ├── Issue3150.java │ │ │ │ │ │ └── Issue3160.java │ │ │ │ │ ├── issue_3200/ │ │ │ │ │ │ ├── Issue3206.java │ │ │ │ │ │ ├── Issue3217.java │ │ │ │ │ │ ├── Issue3227.java │ │ │ │ │ │ ├── Issue3245.java │ │ │ │ │ │ ├── Issue3246.java │ │ │ │ │ │ ├── Issue3264.java │ │ │ │ │ │ ├── Issue3266.java │ │ │ │ │ │ ├── Issue3266_mixedin.java │ │ │ │ │ │ ├── Issue3267.java │ │ │ │ │ │ ├── Issue3274.kt │ │ │ │ │ │ ├── Issue3279.java │ │ │ │ │ │ ├── Issue3281.java │ │ │ │ │ │ ├── Issue3282.java │ │ │ │ │ │ ├── Issue3283.java │ │ │ │ │ │ ├── Issue3293.java │ │ │ │ │ │ └── TestIssue3223.kt │ │ │ │ │ ├── issue_3300/ │ │ │ │ │ │ ├── Issue3217.java │ │ │ │ │ │ ├── Issue3309.java │ │ │ │ │ │ ├── Issue3313.java │ │ │ │ │ │ ├── Issue3326.java │ │ │ │ │ │ ├── Issue3329.java │ │ │ │ │ │ ├── Issue3334.java │ │ │ │ │ │ ├── Issue3336.java │ │ │ │ │ │ ├── Issue3338.java │ │ │ │ │ │ ├── Issue3343.java │ │ │ │ │ │ ├── Issue3344.java │ │ │ │ │ │ ├── Issue3347.java │ │ │ │ │ │ ├── Issue3351.java │ │ │ │ │ │ ├── Issue3352.java │ │ │ │ │ │ ├── Issue3356.java │ │ │ │ │ │ ├── Issue3358.java │ │ │ │ │ │ ├── Issue3361.java │ │ │ │ │ │ ├── Issue3373.java │ │ │ │ │ │ ├── Issue3375.java │ │ │ │ │ │ ├── Issue3376.java │ │ │ │ │ │ ├── Issue3397.java │ │ │ │ │ │ ├── Issue3443.java │ │ │ │ │ │ ├── Issue3448.java │ │ │ │ │ │ └── IssueForJSONFieldMatch.java │ │ │ │ │ ├── issue_3400/ │ │ │ │ │ │ ├── Issue3436.java │ │ │ │ │ │ ├── Issue3452.java │ │ │ │ │ │ ├── Issue3453.java │ │ │ │ │ │ ├── Issue3460.java │ │ │ │ │ │ ├── Issue3465.java │ │ │ │ │ │ ├── Issue3470.java │ │ │ │ │ │ └── Issue_20201016_01.java │ │ │ │ │ ├── issue_3500/ │ │ │ │ │ │ ├── Issue3516.java │ │ │ │ │ │ ├── Issue3539.java │ │ │ │ │ │ ├── Issue3544.java │ │ │ │ │ │ ├── Issue3571.java │ │ │ │ │ │ └── Issue3579.java │ │ │ │ │ ├── issue_3600/ │ │ │ │ │ │ ├── Issue3614.java │ │ │ │ │ │ ├── Issue3628.java │ │ │ │ │ │ ├── Issue3629.java │ │ │ │ │ │ ├── Issue3631.java │ │ │ │ │ │ ├── Issue3637.java │ │ │ │ │ │ ├── Issue3652.java │ │ │ │ │ │ ├── Issue3655.java │ │ │ │ │ │ ├── Issue3671.java │ │ │ │ │ │ ├── Issue3672.java │ │ │ │ │ │ ├── Issue3682.java │ │ │ │ │ │ ├── Issue3689.java │ │ │ │ │ │ └── Issue3693.java │ │ │ │ │ ├── issue_3800/ │ │ │ │ │ │ └── Issue3810.java │ │ │ │ │ ├── jdk7/ │ │ │ │ │ │ └── PathTest.java │ │ │ │ │ ├── jdk8/ │ │ │ │ │ │ ├── DoubleAdderTest.java │ │ │ │ │ │ ├── DurationTest.java │ │ │ │ │ │ ├── InstantTest.java │ │ │ │ │ │ ├── LocalDateTest.java │ │ │ │ │ │ ├── LocalDateTest2.java │ │ │ │ │ │ ├── LocalDateTest3.java │ │ │ │ │ │ ├── LocalDateTest4.java │ │ │ │ │ │ ├── LocalDateTest5.java │ │ │ │ │ │ ├── LocalDateTimeTest.java │ │ │ │ │ │ ├── LocalDateTimeTest2.java │ │ │ │ │ │ ├── LocalDateTimeTest3.java │ │ │ │ │ │ ├── LocalDateTimeTest3_private.java │ │ │ │ │ │ ├── LocalDateTimeTest4.java │ │ │ │ │ │ ├── LocalDateTimeTest5.java │ │ │ │ │ │ ├── LocalTimeTest.java │ │ │ │ │ │ ├── LocalTimeTest2.java │ │ │ │ │ │ ├── LocalTimeTest3.java │ │ │ │ │ │ ├── LongAdderTest.java │ │ │ │ │ │ ├── OffseTimeTest.java │ │ │ │ │ │ ├── OffsetDateTimeTest.java │ │ │ │ │ │ ├── OptionalDouble_Test.java │ │ │ │ │ │ ├── OptionalInt_Test.java │ │ │ │ │ │ ├── OptionalLong_Test.java │ │ │ │ │ │ ├── OptionalTest.java │ │ │ │ │ │ ├── OptionalTest2.java │ │ │ │ │ │ ├── OptionalTest3.java │ │ │ │ │ │ ├── OptionalTest4.java │ │ │ │ │ │ ├── OptionalTest_empty.java │ │ │ │ │ │ ├── PeriodTest.java │ │ │ │ │ │ ├── ZoneIdTest.java │ │ │ │ │ │ ├── ZonedDateTimeTest.java │ │ │ │ │ │ └── ZonedDateTimeTest2.java │ │ │ │ │ ├── joda/ │ │ │ │ │ │ ├── JodaTest_0.java │ │ │ │ │ │ ├── JodaTest_1_LocalDateTime.java │ │ │ │ │ │ ├── JodaTest_2_LocalDateTimeTest3_private.java │ │ │ │ │ │ ├── JodaTest_3_LocalTimeTest.java │ │ │ │ │ │ ├── JodaTest_4_InstantTest.java │ │ │ │ │ │ ├── JodaTest_5_DateTimeFormatter.java │ │ │ │ │ │ ├── JodaTest_6_Duration.java │ │ │ │ │ │ ├── JodaTest_6_Period.java │ │ │ │ │ │ ├── JodaTest_7_DateTimeZone.java │ │ │ │ │ │ └── JodaTest_8_DateTimeTest.java │ │ │ │ │ ├── jsonfield/ │ │ │ │ │ │ ├── JSONFieldTest_0.java │ │ │ │ │ │ └── JSONFieldTest_1.java │ │ │ │ │ ├── jsonp/ │ │ │ │ │ │ ├── JSONPParseTest.java │ │ │ │ │ │ ├── JSONPParseTest1.java │ │ │ │ │ │ ├── JSONPParseTest2.java │ │ │ │ │ │ ├── JSONPParseTest3.java │ │ │ │ │ │ └── JSONPParseTest4.java │ │ │ │ │ ├── jsonpatch/ │ │ │ │ │ │ └── JSONPatchTest_0.java │ │ │ │ │ ├── kotlin/ │ │ │ │ │ │ ├── ClassWithPairMixedTypesTest.java │ │ │ │ │ │ ├── ClassWithPairTest.java │ │ │ │ │ │ ├── ClassWithRangesTest.java │ │ │ │ │ │ ├── ClassWithTripleTest.java │ │ │ │ │ │ ├── Class_WithPrimaryAndSecondaryConstructorTest.java │ │ │ │ │ │ ├── DataClassSimpleTest.java │ │ │ │ │ │ ├── DataClassTest.java │ │ │ │ │ │ ├── Issue1420.java │ │ │ │ │ │ ├── Issue1462.java │ │ │ │ │ │ ├── Issue1483.java │ │ │ │ │ │ ├── Issue1524.java │ │ │ │ │ │ ├── Issue1543.java │ │ │ │ │ │ ├── Issue1547.java │ │ │ │ │ │ ├── Issue1569.java │ │ │ │ │ │ ├── Issue1750.java │ │ │ │ │ │ ├── Issue_for_kotlin_20181203.java │ │ │ │ │ │ ├── ResponseKotlin2Test.java │ │ │ │ │ │ ├── ResponseKotlinTest.java │ │ │ │ │ │ └── Zoujing.java │ │ │ │ │ ├── lombok/ │ │ │ │ │ │ └── LomBokTest.java │ │ │ │ │ ├── mixins/ │ │ │ │ │ │ ├── MixInRemovalTest.java │ │ │ │ │ │ ├── MixinAPITest.java │ │ │ │ │ │ ├── MixinDeserForClassTest.java │ │ │ │ │ │ ├── MixinDeserForMethodsTest.java │ │ │ │ │ │ ├── MixinInheritanceTest.java │ │ │ │ │ │ ├── MixinJSONTypeTest.java │ │ │ │ │ │ ├── MixinMergingTest.java │ │ │ │ │ │ ├── MixinSerForFieldsTest.java │ │ │ │ │ │ └── MixinSerForMethodsTest.java │ │ │ │ │ ├── naming/ │ │ │ │ │ │ ├── ListCaseTest.java │ │ │ │ │ │ └── NamingSerTest.java │ │ │ │ │ ├── parser/ │ │ │ │ │ │ ├── AEHuangliang2Test.java │ │ │ │ │ │ ├── AETest.java │ │ │ │ │ │ ├── Alipay1213.java │ │ │ │ │ │ ├── AmbiguousTest.java │ │ │ │ │ │ ├── AsmParserTest0.java │ │ │ │ │ │ ├── AsmParserTest1.java │ │ │ │ │ │ ├── AtomicIntegerComptableAndroidTest.java │ │ │ │ │ │ ├── AtomicLongComptableAndroidTest.java │ │ │ │ │ │ ├── AutoTypeCheckHandlerTest.java │ │ │ │ │ │ ├── BigDecimalKeyFieldTest.java │ │ │ │ │ │ ├── BigListStringFieldTest.java │ │ │ │ │ │ ├── BigListStringFieldTest_private.java │ │ │ │ │ │ ├── BigSpecailKeyTest.java │ │ │ │ │ │ ├── BigSpecailKeyTest2.java │ │ │ │ │ │ ├── BigSpecailStringTest.java │ │ │ │ │ │ ├── BigStringFieldTest.java │ │ │ │ │ │ ├── BigStringFieldTest_private.java │ │ │ │ │ │ ├── ClassConstructorTest1.java │ │ │ │ │ │ ├── ClassTest.java │ │ │ │ │ │ ├── CommentTest.java │ │ │ │ │ │ ├── CreateInstanceErrorTest.java │ │ │ │ │ │ ├── CreateInstanceErrorTest2.java │ │ │ │ │ │ ├── DateParserTest.java │ │ │ │ │ │ ├── DateParserTest_sql.java │ │ │ │ │ │ ├── DateParserTest_sql_timestamp.java │ │ │ │ │ │ ├── DateTest.java │ │ │ │ │ │ ├── DefaultExtJSONParserTest.java │ │ │ │ │ │ ├── DefaultExtJSONParserTest_0.java │ │ │ │ │ │ ├── DefaultExtJSONParserTest_1.java │ │ │ │ │ │ ├── DefaultExtJSONParserTest_2.java │ │ │ │ │ │ ├── DefaultExtJSONParserTest_3.java │ │ │ │ │ │ ├── DefaultExtJSONParserTest_4.java │ │ │ │ │ │ ├── DefaultExtJSONParserTest_5.java │ │ │ │ │ │ ├── DefaultExtJSONParserTest_6.java │ │ │ │ │ │ ├── DefaultExtJSONParserTest_7.java │ │ │ │ │ │ ├── DefaultExtJSONParser_parseArray.java │ │ │ │ │ │ ├── DefaultExtJSONParser_parseArray_2.java │ │ │ │ │ │ ├── DefaultJSONParserTest2.java │ │ │ │ │ │ ├── DefaultJSONParserTest_charArray.java │ │ │ │ │ │ ├── DefaultJSONParserTest_comma.java │ │ │ │ │ │ ├── DefaultJSONParserTest_date.java │ │ │ │ │ │ ├── DefaultJSONParserTest_error.java │ │ │ │ │ │ ├── EmptyImmutableTest.java │ │ │ │ │ │ ├── EnumParserTest.java │ │ │ │ │ │ ├── FastMatchCheckTest.java │ │ │ │ │ │ ├── FeatureCountTest.java │ │ │ │ │ │ ├── FeatureParserTest.java │ │ │ │ │ │ ├── FeatureTest.java │ │ │ │ │ │ ├── InetSocketAddressTest.java │ │ │ │ │ │ ├── JSONArrayParseTest.java │ │ │ │ │ │ ├── JSONLexerAllowCommentTest.java │ │ │ │ │ │ ├── JSONLexerTest.java │ │ │ │ │ │ ├── JSONLexerTest_10.java │ │ │ │ │ │ ├── JSONLexerTest_11.java │ │ │ │ │ │ ├── JSONLexerTest_12.java │ │ │ │ │ │ ├── JSONLexerTest_13.java │ │ │ │ │ │ ├── JSONLexerTest_14.java │ │ │ │ │ │ ├── JSONLexerTest_15.java │ │ │ │ │ │ ├── JSONLexerTest_16.java │ │ │ │ │ │ ├── JSONLexerTest_2.java │ │ │ │ │ │ ├── JSONLexerTest_3.java │ │ │ │ │ │ ├── JSONLexerTest_4.java │ │ │ │ │ │ ├── JSONLexerTest_5.java │ │ │ │ │ │ ├── JSONLexerTest_6.java │ │ │ │ │ │ ├── JSONLexerTest_7.java │ │ │ │ │ │ ├── JSONLexerTest_8.java │ │ │ │ │ │ ├── JSONLexerTest_9.java │ │ │ │ │ │ ├── JSONLexerTest_set.java │ │ │ │ │ │ ├── JSONReaderScannerTest__entity_boolean.java │ │ │ │ │ │ ├── JSONReaderScannerTest__entity_double.java │ │ │ │ │ │ ├── JSONReaderScannerTest__entity_double_2.java │ │ │ │ │ │ ├── JSONReaderScannerTest__entity_enum.java │ │ │ │ │ │ ├── JSONReaderScannerTest__entity_float.java │ │ │ │ │ │ ├── JSONReaderScannerTest__entity_int.java │ │ │ │ │ │ ├── JSONReaderScannerTest__entity_long.java │ │ │ │ │ │ ├── JSONReaderScannerTest__entity_string.java │ │ │ │ │ │ ├── JSONReaderScannerTest__entity_stringList.java │ │ │ │ │ │ ├── JSONReaderScannerTest__map_string.java │ │ │ │ │ │ ├── JSONReaderScannerTest_array_string.java │ │ │ │ │ │ ├── JSONReaderScannerTest_bytes.java │ │ │ │ │ │ ├── JSONReaderScannerTest_decimal.java │ │ │ │ │ │ ├── JSONReaderScannerTest_enum.java │ │ │ │ │ │ ├── JSONReaderScannerTest_error.java │ │ │ │ │ │ ├── JSONReaderScannerTest_error2.java │ │ │ │ │ │ ├── JSONReaderScannerTest_error3.java │ │ │ │ │ │ ├── JSONReaderScannerTest_error4.java │ │ │ │ │ │ ├── JSONReaderScannerTest_error5.java │ │ │ │ │ │ ├── JSONReaderScannerTest_int.java │ │ │ │ │ │ ├── JSONReaderScannerTest_jsonobject.java │ │ │ │ │ │ ├── JSONReaderScannerTest_long.java │ │ │ │ │ │ ├── JSONReaderTest_array_array.java │ │ │ │ │ │ ├── JSONReaderTest_array_array_2.java │ │ │ │ │ │ ├── JSONReaderTest_array_object.java │ │ │ │ │ │ ├── JSONReaderTest_array_object_2.java │ │ │ │ │ │ ├── JSONReaderTest_object_int.java │ │ │ │ │ │ ├── JSONReaderTest_object_int_unquote.java │ │ │ │ │ │ ├── JSONReaderTest_object_long.java │ │ │ │ │ │ ├── JSONReaderTest_object_object.java │ │ │ │ │ │ ├── JSONReaderTest_object_string.java │ │ │ │ │ │ ├── JSONReader_error.java │ │ │ │ │ │ ├── JSONReader_top.java │ │ │ │ │ │ ├── JSONScannerTest_ISO8601.java │ │ │ │ │ │ ├── JSONScannerTest__nextToken.java │ │ │ │ │ │ ├── JSONScannerTest__x.java │ │ │ │ │ │ ├── JSONScannerTest_colon.java │ │ │ │ │ │ ├── JSONScannerTest_false.java │ │ │ │ │ │ ├── JSONScannerTest_ident.java │ │ │ │ │ │ ├── JSONScannerTest_int.java │ │ │ │ │ │ ├── JSONScannerTest_isEOF.java │ │ │ │ │ │ ├── JSONScannerTest_long.java │ │ │ │ │ │ ├── JSONScannerTest_new.java │ │ │ │ │ │ ├── JSONScannerTest_null.java │ │ │ │ │ │ ├── JSONScannerTest_scanFieldBoolean.java │ │ │ │ │ │ ├── JSONScannerTest_scanFieldBoolean_unquote.java │ │ │ │ │ │ ├── JSONScannerTest_scanFieldDouble.java │ │ │ │ │ │ ├── JSONScannerTest_scanFieldFloat.java │ │ │ │ │ │ ├── JSONScannerTest_scanFieldInt.java │ │ │ │ │ │ ├── JSONScannerTest_scanFieldLong.java │ │ │ │ │ │ ├── JSONScannerTest_scanFieldString.java │ │ │ │ │ │ ├── JSONScannerTest_scanFieldStringArray.java │ │ │ │ │ │ ├── JSONScannerTest_scanFieldString_error.java │ │ │ │ │ │ ├── JSONScannerTest_scanSymbol.java │ │ │ │ │ │ ├── JSONScannerTest_singQuoteString.java │ │ │ │ │ │ ├── JSONScannerTest_symbol.java │ │ │ │ │ │ ├── JSONScannerTest_true.java │ │ │ │ │ │ ├── MapResetTest.java │ │ │ │ │ │ ├── MaximumLevelTest.java │ │ │ │ │ │ ├── NullCheckTest.java │ │ │ │ │ │ ├── OrderedFieldTest.java │ │ │ │ │ │ ├── ParseContextTest.java │ │ │ │ │ │ ├── ParseRestTest.java │ │ │ │ │ │ ├── ParserSpecialCharTest.java │ │ │ │ │ │ ├── ParserSpecialCharTest_map.java │ │ │ │ │ │ ├── ParserSpecialCharTest_map_singleQuote.java │ │ │ │ │ │ ├── PrivateConstrunctorTest.java │ │ │ │ │ │ ├── ProductViewTest.java │ │ │ │ │ │ ├── ReadOnlyAtomicBooleanTest.java │ │ │ │ │ │ ├── ReadOnlyAtomicBooleanTest_field.java │ │ │ │ │ │ ├── ReadOnlyAtomicIntegerTest.java │ │ │ │ │ │ ├── ReadOnlyAtomicIntegerTest_field.java │ │ │ │ │ │ ├── ReadOnlyAtomicLongTest.java │ │ │ │ │ │ ├── ReadOnlyAtomicLongTest_field.java │ │ │ │ │ │ ├── ReadOnlyCollectionTest.java │ │ │ │ │ │ ├── ReadOnlyCollectionTest_final_field.java │ │ │ │ │ │ ├── ReadOnlyCollectionTest_final_field_null.java │ │ │ │ │ │ ├── ReadOnlyMapTest.java │ │ │ │ │ │ ├── ReadOnlyMapTest2.java │ │ │ │ │ │ ├── ReadOnlyMapTest2_final_field.java │ │ │ │ │ │ ├── ReadOnlyMapTest_final_field.java │ │ │ │ │ │ ├── RedundantTest.java │ │ │ │ │ │ ├── SafeModeTest.java │ │ │ │ │ │ ├── TestException.java │ │ │ │ │ │ ├── TestInitStringFieldAsEmpty.java │ │ │ │ │ │ ├── TestInitStringFieldAsEmpty2.java │ │ │ │ │ │ ├── TestUTF8.java │ │ │ │ │ │ ├── TestUTF8_2.java │ │ │ │ │ │ ├── TypeReferenceTest.java │ │ │ │ │ │ ├── TypeUtilsTest.java │ │ │ │ │ │ ├── TypeUtilsTest2.java │ │ │ │ │ │ ├── TypeUtilsTest3.java │ │ │ │ │ │ ├── TypeUtilsTest4.java │ │ │ │ │ │ ├── TypeUtilsTest_cast.java │ │ │ │ │ │ ├── TypeUtilsTest_castToBigDecimal.java │ │ │ │ │ │ ├── TypeUtilsTest_castToBigInteger.java │ │ │ │ │ │ ├── TypeUtilsTest_castToBytes.java │ │ │ │ │ │ ├── TypeUtilsTest_castToDate.java │ │ │ │ │ │ ├── TypeUtilsTest_castToJavaBean.java │ │ │ │ │ │ ├── TypeUtilsTest_castToJavaBean_JSONType.java │ │ │ │ │ │ ├── TypeUtilsTest_compatibleWithJavaBean.java │ │ │ │ │ │ ├── TypeUtilsTest_compatibleWithJavaBean_boolean.java │ │ │ │ │ │ ├── TypeUtilsTest_interface.java │ │ │ │ │ │ ├── TypeUtilsTest_loadClass.java │ │ │ │ │ │ ├── TypeUtilsToJSONTest.java │ │ │ │ │ │ ├── TypeUtils_parseDouble_Test.java │ │ │ │ │ │ ├── TypeUtils_parseFloat_Test.java │ │ │ │ │ │ ├── UTF8ByteArrayLexerTest_symbol.java │ │ │ │ │ │ ├── UTF8ByteArrayParseTest.java │ │ │ │ │ │ ├── UnquoteNameTest.java │ │ │ │ │ │ ├── array/ │ │ │ │ │ │ │ ├── BeanToArrayAutoTypeTest.java │ │ │ │ │ │ │ ├── BeanToArrayAutoTypeTest2.java │ │ │ │ │ │ │ ├── BeanToArrayAutoTypeTest3.java │ │ │ │ │ │ │ ├── BeanToArrayTest.java │ │ │ │ │ │ │ ├── BeanToArrayTest2.java │ │ │ │ │ │ │ ├── BeanToArrayTest3.java │ │ │ │ │ │ │ ├── BeanToArrayTest3_private.java │ │ │ │ │ │ │ ├── BeanToArrayTest_date.java │ │ │ │ │ │ │ ├── BeanToArrayTest_date_private.java │ │ │ │ │ │ │ ├── BeanToArrayTest_enum.java │ │ │ │ │ │ │ ├── BeanToArrayTest_enum_private.java │ │ │ │ │ │ │ ├── BeanToArrayTest_int.java │ │ │ │ │ │ │ ├── BeanToArrayTest_long.java │ │ │ │ │ │ │ └── BeanToArrayTest_private.java │ │ │ │ │ │ ├── bug/ │ │ │ │ │ │ │ ├── Bug0.java │ │ │ │ │ │ │ ├── Bug2.java │ │ │ │ │ │ │ ├── Bug_for_changhao.java │ │ │ │ │ │ │ ├── Bug_for_dingzhu.java │ │ │ │ │ │ │ ├── Bug_for_guanxiu.java │ │ │ │ │ │ │ ├── Bug_for_kongmu.java │ │ │ │ │ │ │ ├── Bug_for_lingzhi.java │ │ │ │ │ │ │ ├── Bug_for_lixianfeng.java │ │ │ │ │ │ │ ├── Bug_for_yihaodian.java │ │ │ │ │ │ │ ├── Bug_for_zitao.java │ │ │ │ │ │ │ ├── EmptyParseArrayTest.java │ │ │ │ │ │ │ └── JSONObectNullTest.java │ │ │ │ │ │ ├── creator/ │ │ │ │ │ │ │ ├── JSONCreatorFactoryTest.java │ │ │ │ │ │ │ ├── JSONCreatorTest.java │ │ │ │ │ │ │ ├── JSONCreatorTest10.java │ │ │ │ │ │ │ ├── JSONCreatorTest11.java │ │ │ │ │ │ │ ├── JSONCreatorTest2.java │ │ │ │ │ │ │ ├── JSONCreatorTest3.java │ │ │ │ │ │ │ ├── JSONCreatorTest4.java │ │ │ │ │ │ │ ├── JSONCreatorTest5.java │ │ │ │ │ │ │ ├── JSONCreatorTest6.java │ │ │ │ │ │ │ ├── JSONCreatorTest7.java │ │ │ │ │ │ │ ├── JSONCreatorTest8.java │ │ │ │ │ │ │ ├── JSONCreatorTest9.java │ │ │ │ │ │ │ ├── JSONCreatorTest_default_boolean.java │ │ │ │ │ │ │ ├── JSONCreatorTest_default_byte.java │ │ │ │ │ │ │ ├── JSONCreatorTest_default_double.java │ │ │ │ │ │ │ ├── JSONCreatorTest_default_float.java │ │ │ │ │ │ │ ├── JSONCreatorTest_default_int.java │ │ │ │ │ │ │ ├── JSONCreatorTest_default_long.java │ │ │ │ │ │ │ ├── JSONCreatorTest_default_short.java │ │ │ │ │ │ │ ├── JSONCreatorTest_double.java │ │ │ │ │ │ │ ├── JSONCreatorTest_double_obj.java │ │ │ │ │ │ │ ├── JSONCreatorTest_error.java │ │ │ │ │ │ │ ├── JSONCreatorTest_error2.java │ │ │ │ │ │ │ ├── JSONCreatorTest_error3.java │ │ │ │ │ │ │ ├── JSONCreatorTest_float.java │ │ │ │ │ │ │ └── JSONCreatorTest_float_obj.java │ │ │ │ │ │ ├── deser/ │ │ │ │ │ │ │ ├── AbstractSerializeTest.java │ │ │ │ │ │ │ ├── AbstractSerializeTest2.java │ │ │ │ │ │ │ ├── BigDecimalDeserializerTest.java │ │ │ │ │ │ │ ├── BigDecimalTest.java │ │ │ │ │ │ │ ├── BigIntegerDeserializerTest.java │ │ │ │ │ │ │ ├── BooleanDeserializerTest.java │ │ │ │ │ │ │ ├── BooleanFieldDeserializerTest.java │ │ │ │ │ │ │ ├── BooleanFieldDeserializerTest2.java │ │ │ │ │ │ │ ├── CharArrayDeserializerTest.java │ │ │ │ │ │ │ ├── ClassTest.java │ │ │ │ │ │ │ ├── CollectionFieldTest.java │ │ │ │ │ │ │ ├── ConcurrentHashMapDeserializerTest.java │ │ │ │ │ │ │ ├── ConstructorErrorTest.java │ │ │ │ │ │ │ ├── ConstructorErrorTest_initError.java │ │ │ │ │ │ │ ├── ConstructorErrorTest_initError_private.java │ │ │ │ │ │ │ ├── ConstructorErrorTest_inner.java │ │ │ │ │ │ │ ├── ConstructorErrorTest_private.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest10.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest11.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest12.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest2.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest3.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest4.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest5.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest6.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest7.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest8.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest9.java │ │ │ │ │ │ │ ├── DefaultObjectDeserializerTest_collection.java │ │ │ │ │ │ │ ├── DoubleArrayFieldDeserializerTest.java │ │ │ │ │ │ │ ├── DoubleDeserializerTest.java │ │ │ │ │ │ │ ├── DoubleFieldDeserializerTest.java │ │ │ │ │ │ │ ├── DupTest.java │ │ │ │ │ │ │ ├── EnumMapTest.java │ │ │ │ │ │ │ ├── EnumTest.java │ │ │ │ │ │ │ ├── FactoryTest.java │ │ │ │ │ │ │ ├── FactoryTest_error.java │ │ │ │ │ │ │ ├── FieldDeserializerTest.java │ │ │ │ │ │ │ ├── FieldDeserializerTest1.java │ │ │ │ │ │ │ ├── FieldDeserializerTest10.java │ │ │ │ │ │ │ ├── FieldDeserializerTest2.java │ │ │ │ │ │ │ ├── FieldDeserializerTest3.java │ │ │ │ │ │ │ ├── FieldDeserializerTest4.java │ │ │ │ │ │ │ ├── FieldDeserializerTest5.java │ │ │ │ │ │ │ ├── FieldDeserializerTest6.java │ │ │ │ │ │ │ ├── FieldDeserializerTest7.java │ │ │ │ │ │ │ ├── FieldDeserializerTest8.java │ │ │ │ │ │ │ ├── FieldDeserializerTest9.java │ │ │ │ │ │ │ ├── FieldSerializerTest.java │ │ │ │ │ │ │ ├── FieldSerializerTest2.java │ │ │ │ │ │ │ ├── FieldSerializerTest3.java │ │ │ │ │ │ │ ├── FieldSerializerTest4.java │ │ │ │ │ │ │ ├── FloatDeserializerTest.java │ │ │ │ │ │ │ ├── GetOnlyCollectionTest.java │ │ │ │ │ │ │ ├── HashtableFieldTest.java │ │ │ │ │ │ │ ├── InetAddressDeserializerTest.java │ │ │ │ │ │ │ ├── InnerClassDeser.java │ │ │ │ │ │ │ ├── InnerClassDeser2.java │ │ │ │ │ │ │ ├── InnerClassDeser3.java │ │ │ │ │ │ │ ├── InnerClassDeser4.java │ │ │ │ │ │ │ ├── IntegerDeserializerTest.java │ │ │ │ │ │ │ ├── IntegerFieldDeserializerTest.java │ │ │ │ │ │ │ ├── IntegerFieldDeserializerTest2.java │ │ │ │ │ │ │ ├── IntegerFieldDeserializerTest3.java │ │ │ │ │ │ │ ├── IntegerParseTest.java │ │ │ │ │ │ │ ├── InterfaceParseTest.java │ │ │ │ │ │ │ ├── JSONFieldSetterTest.java │ │ │ │ │ │ │ ├── LocaleFieldTest.java │ │ │ │ │ │ │ ├── LocaleTest.java │ │ │ │ │ │ │ ├── LongDeserializerTest.java │ │ │ │ │ │ │ ├── LongFieldDeserializerTest.java │ │ │ │ │ │ │ ├── LongFieldDeserializerTest2.java │ │ │ │ │ │ │ ├── LongFieldDeserializerTest3.java │ │ │ │ │ │ │ ├── MapDeserializerTest.java │ │ │ │ │ │ │ ├── MapTest.java │ │ │ │ │ │ │ ├── MultiArrayTest.java │ │ │ │ │ │ │ ├── MyMapFieldTest.java │ │ │ │ │ │ │ ├── NumberDeserializerTest.java │ │ │ │ │ │ │ ├── NumberDeserializerTest2.java │ │ │ │ │ │ │ ├── ParseNullTest.java │ │ │ │ │ │ │ ├── PatternDeserializerTest.java │ │ │ │ │ │ │ ├── PropertyProcessableTest_0.java │ │ │ │ │ │ │ ├── ResolveFieldDeserializerTest.java │ │ │ │ │ │ │ ├── ShortFieldDeserializerTest.java │ │ │ │ │ │ │ ├── SmartMatchTest.java │ │ │ │ │ │ │ ├── SmartMatchTest2.java │ │ │ │ │ │ │ ├── SmartMatchTest_boolean_is.java │ │ │ │ │ │ │ ├── SmartMatchTest_snake.java │ │ │ │ │ │ │ ├── SmartMatchTest_snake2.java │ │ │ │ │ │ │ ├── SortedSetFieldTest.java │ │ │ │ │ │ │ ├── SqlDateDeserializerTest.java │ │ │ │ │ │ │ ├── SqlDateDeserializerTest2.java │ │ │ │ │ │ │ ├── StackTraceElementDeserializerTest.java │ │ │ │ │ │ │ ├── TestEnum.java │ │ │ │ │ │ │ ├── TestNull.java │ │ │ │ │ │ │ ├── ThrowableDeserializerTest.java │ │ │ │ │ │ │ ├── ThrowableDeserializerTest_2.java │ │ │ │ │ │ │ ├── TimeDeserializerTest.java │ │ │ │ │ │ │ ├── TimeDeserializerTest2.java │ │ │ │ │ │ │ ├── TimeDeserializerTest3.java │ │ │ │ │ │ │ ├── TimeZoneDeserializerTest.java │ │ │ │ │ │ │ ├── TreeMapDeserializerTest.java │ │ │ │ │ │ │ ├── TreeSetFieldTest.java │ │ │ │ │ │ │ ├── URIDeserializerTest.java │ │ │ │ │ │ │ ├── URLDeserializerTest.java │ │ │ │ │ │ │ ├── UUIDDeserializerTest.java │ │ │ │ │ │ │ ├── array/ │ │ │ │ │ │ │ │ ├── FieldBoolArrayTest.java │ │ │ │ │ │ │ │ ├── FieldByteArrayTest.java │ │ │ │ │ │ │ │ ├── FieldDoubleArrayTest.java │ │ │ │ │ │ │ │ ├── FieldFloatArray2Test.java │ │ │ │ │ │ │ │ ├── FieldFloatArray2Test_private.java │ │ │ │ │ │ │ │ ├── FieldFloatArrayTest.java │ │ │ │ │ │ │ │ ├── FieldFloatArrayTest2.java │ │ │ │ │ │ │ │ ├── FieldFloatArrayTest_private.java │ │ │ │ │ │ │ │ ├── FieldIntArrayTest.java │ │ │ │ │ │ │ │ ├── FieldIntArrayTest2.java │ │ │ │ │ │ │ │ ├── FieldIntArrayTest_private.java │ │ │ │ │ │ │ │ ├── FieldLongArrayTest.java │ │ │ │ │ │ │ │ └── FieldShortArrayTest.java │ │ │ │ │ │ │ ├── arraymapping/ │ │ │ │ │ │ │ │ ├── ArrayMappingErrorTest.java │ │ │ │ │ │ │ │ ├── ArrayMappingErrorTest2.java │ │ │ │ │ │ │ │ ├── ArrayMappingErrorTest3.java │ │ │ │ │ │ │ │ ├── ArrayMapping_bool.java │ │ │ │ │ │ │ │ ├── ArrayMapping_double.java │ │ │ │ │ │ │ │ ├── ArrayMapping_float.java │ │ │ │ │ │ │ │ ├── ArrayMapping_long.java │ │ │ │ │ │ │ │ └── ArrayMapping_long_stream.java │ │ │ │ │ │ │ ├── asm/ │ │ │ │ │ │ │ │ ├── TestASM.java │ │ │ │ │ │ │ │ ├── TestASM2.java │ │ │ │ │ │ │ │ ├── TestASMEishay.java │ │ │ │ │ │ │ │ ├── TestASM_BigDecimal.java │ │ │ │ │ │ │ │ ├── TestASM_Byte_0.java │ │ │ │ │ │ │ │ ├── TestASM_Date.java │ │ │ │ │ │ │ │ ├── TestASM_Integer.java │ │ │ │ │ │ │ │ ├── TestASM_List.java │ │ │ │ │ │ │ │ ├── TestASM_Long_0.java │ │ │ │ │ │ │ │ ├── TestASM_Short_0.java │ │ │ │ │ │ │ │ ├── TestASM_boolean.java │ │ │ │ │ │ │ │ ├── TestASM_byte.java │ │ │ │ │ │ │ │ ├── TestASM_char.java │ │ │ │ │ │ │ │ ├── TestASM_double.java │ │ │ │ │ │ │ │ ├── TestASM_float.java │ │ │ │ │ │ │ │ ├── TestASM_int.java │ │ │ │ │ │ │ │ ├── TestASM_long.java │ │ │ │ │ │ │ │ ├── TestASM_null.java │ │ │ │ │ │ │ │ ├── TestASM_object.java │ │ │ │ │ │ │ │ ├── TestASM_primitive.java │ │ │ │ │ │ │ │ └── TestASM_short.java │ │ │ │ │ │ │ ├── awt/ │ │ │ │ │ │ │ │ ├── ColorDeserializerTest.java │ │ │ │ │ │ │ │ ├── FontDeserializerTest.java │ │ │ │ │ │ │ │ ├── PointDeserializerTest.java │ │ │ │ │ │ │ │ ├── PointDeserializerTest2.java │ │ │ │ │ │ │ │ └── RectangleDeserializerTest.java │ │ │ │ │ │ │ ├── date/ │ │ │ │ │ │ │ │ ├── DateDeserializerTest.java │ │ │ │ │ │ │ │ ├── DateFormatDeserializerTest.java │ │ │ │ │ │ │ │ ├── DateParseTest1.java │ │ │ │ │ │ │ │ ├── DateParseTest10.java │ │ │ │ │ │ │ │ ├── DateParseTest11.java │ │ │ │ │ │ │ │ ├── DateParseTest12.java │ │ │ │ │ │ │ │ ├── DateParseTest13.java │ │ │ │ │ │ │ │ ├── DateParseTest14.java │ │ │ │ │ │ │ │ ├── DateParseTest2.java │ │ │ │ │ │ │ │ ├── DateParseTest3.java │ │ │ │ │ │ │ │ ├── DateParseTest4.java │ │ │ │ │ │ │ │ ├── DateParseTest5.java │ │ │ │ │ │ │ │ ├── DateParseTest6.java │ │ │ │ │ │ │ │ ├── DateParseTest7.java │ │ │ │ │ │ │ │ ├── DateParseTest8.java │ │ │ │ │ │ │ │ ├── DateParseTest9.java │ │ │ │ │ │ │ │ └── DateTest.java │ │ │ │ │ │ │ ├── deny/ │ │ │ │ │ │ │ │ ├── DenyTest.java │ │ │ │ │ │ │ │ ├── DenyTest10.java │ │ │ │ │ │ │ │ ├── DenyTest11.java │ │ │ │ │ │ │ │ ├── DenyTest12.java │ │ │ │ │ │ │ │ ├── DenyTest13.java │ │ │ │ │ │ │ │ ├── DenyTest14.java │ │ │ │ │ │ │ │ ├── DenyTest15.java │ │ │ │ │ │ │ │ ├── DenyTest16.java │ │ │ │ │ │ │ │ ├── DenyTest2.java │ │ │ │ │ │ │ │ ├── DenyTest3.java │ │ │ │ │ │ │ │ ├── DenyTest4.java │ │ │ │ │ │ │ │ ├── DenyTest5.java │ │ │ │ │ │ │ │ ├── DenyTest6.java │ │ │ │ │ │ │ │ ├── DenyTest7.java │ │ │ │ │ │ │ │ ├── DenyTest8.java │ │ │ │ │ │ │ │ ├── DenyTest9.java │ │ │ │ │ │ │ │ └── InitJavaBeanDeserializerTest.java │ │ │ │ │ │ │ ├── extra/ │ │ │ │ │ │ │ │ └── ExtraTest.java │ │ │ │ │ │ │ ├── generic/ │ │ │ │ │ │ │ │ ├── ByteListTest.java │ │ │ │ │ │ │ │ ├── GenericArrayTest.java │ │ │ │ │ │ │ │ ├── GenericArrayTest2.java │ │ │ │ │ │ │ │ ├── GenericArrayTest3.java │ │ │ │ │ │ │ │ ├── GenericArrayTest4.java │ │ │ │ │ │ │ │ ├── GenericArrayTest5.java │ │ │ │ │ │ │ │ ├── GenericMap.java │ │ │ │ │ │ │ │ ├── GenericTest.java │ │ │ │ │ │ │ │ ├── GenericTest2.java │ │ │ │ │ │ │ │ ├── GenericTest3.java │ │ │ │ │ │ │ │ ├── GenericTest4.java │ │ │ │ │ │ │ │ ├── GenericTest5.java │ │ │ │ │ │ │ │ └── ListStrFieldTest.java │ │ │ │ │ │ │ ├── list/ │ │ │ │ │ │ │ │ ├── ArrayDeserializerTest.java │ │ │ │ │ │ │ │ ├── ArrayLisMapDeserializerTest.java │ │ │ │ │ │ │ │ ├── ArrayListEnumFieldDeserializerTest.java │ │ │ │ │ │ │ │ ├── ArrayListStringDeserializerTest.java │ │ │ │ │ │ │ │ ├── ArrayListTypeDeserializerTest.java │ │ │ │ │ │ │ │ ├── ArrayListTypeFieldTest.java │ │ │ │ │ │ │ │ ├── ListFieldTest.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest_array_big.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest_createError.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest_dom.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest_dom_array.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest_dom_array_2.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest_dom_hashSet.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest_dom_treeSet.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest_stream.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest_stream_TreeSet.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest_stream_array.java │ │ │ │ │ │ │ │ ├── ListStringFieldTest_stream_array_2.java │ │ │ │ │ │ │ │ └── ListStringFieldTest_stream_hashSet.java │ │ │ │ │ │ │ ├── nonctor/ │ │ │ │ │ │ │ │ └── NonDefaultConstructorTest0.java │ │ │ │ │ │ │ ├── stream/ │ │ │ │ │ │ │ │ ├── ReaderBooleanFieldTest.java │ │ │ │ │ │ │ │ ├── ReaderIntFieldTest.java │ │ │ │ │ │ │ │ └── ReaderLongFieldTest.java │ │ │ │ │ │ │ └── var/ │ │ │ │ │ │ │ └── TwoTypeTest.java │ │ │ │ │ │ ├── error/ │ │ │ │ │ │ │ ├── JSONReaderError.java │ │ │ │ │ │ │ ├── ParseErrorTest_10.java │ │ │ │ │ │ │ ├── ParseErrorTest_11.java │ │ │ │ │ │ │ ├── ParseErrorTest_12.java │ │ │ │ │ │ │ ├── ParseErrorTest_13.java │ │ │ │ │ │ │ ├── ParseErrorTest_14.java │ │ │ │ │ │ │ ├── ParseErrorTest_15.java │ │ │ │ │ │ │ ├── ParseErrorTest_16.java │ │ │ │ │ │ │ ├── ParseErrorTest_17.java │ │ │ │ │ │ │ ├── ParseErrorTest_18.java │ │ │ │ │ │ │ ├── ParseErrorTest_19.java │ │ │ │ │ │ │ ├── ParseErrorTest_20.java │ │ │ │ │ │ │ ├── ParseErrorTest_21.java │ │ │ │ │ │ │ ├── ParseErrorTest_8.java │ │ │ │ │ │ │ ├── ParseErrorTest_9.java │ │ │ │ │ │ │ ├── ParseErrorTest_date.java │ │ │ │ │ │ │ └── TypeNotMatchError.java │ │ │ │ │ │ ├── fieldTypeResolver/ │ │ │ │ │ │ │ └── FieldTypeResolverTest.java │ │ │ │ │ │ ├── number/ │ │ │ │ │ │ │ ├── NumberEmtpyObjectTest.java │ │ │ │ │ │ │ ├── NumberValueTest.java │ │ │ │ │ │ │ ├── NumberValueTest2.java │ │ │ │ │ │ │ ├── NumberValueTest3.java │ │ │ │ │ │ │ ├── NumberValueTest4.java │ │ │ │ │ │ │ ├── NumberValueTest_error_0.java │ │ │ │ │ │ │ ├── NumberValueTest_error_1.java │ │ │ │ │ │ │ ├── NumberValueTest_error_10.java │ │ │ │ │ │ │ ├── NumberValueTest_error_11.java │ │ │ │ │ │ │ ├── NumberValueTest_error_12.java │ │ │ │ │ │ │ ├── NumberValueTest_error_13.java │ │ │ │ │ │ │ ├── NumberValueTest_error_2.java │ │ │ │ │ │ │ ├── NumberValueTest_error_3.java │ │ │ │ │ │ │ ├── NumberValueTest_error_4.java │ │ │ │ │ │ │ ├── NumberValueTest_error_5.java │ │ │ │ │ │ │ ├── NumberValueTest_error_6.java │ │ │ │ │ │ │ ├── NumberValueTest_error_7.java │ │ │ │ │ │ │ ├── NumberValueTest_error_8.java │ │ │ │ │ │ │ └── NumberValueTest_error_9.java │ │ │ │ │ │ ├── str/ │ │ │ │ │ │ │ ├── EmptyStringTest.java │ │ │ │ │ │ │ ├── StringTest_00.java │ │ │ │ │ │ │ ├── StringTest_01.java │ │ │ │ │ │ │ └── StringTest_02.java │ │ │ │ │ │ ├── stream/ │ │ │ │ │ │ │ ├── JSONReaderScannerTest.java │ │ │ │ │ │ │ ├── JSONReaderScannerTest_boolean.java │ │ │ │ │ │ │ ├── JSONReaderScannerTest_chars.java │ │ │ │ │ │ │ ├── JSONReaderScannerTest_enum.java │ │ │ │ │ │ │ ├── JSONReaderScannerTest_matchField.java │ │ │ │ │ │ │ ├── JSONReaderScannerTest_negative.java │ │ │ │ │ │ │ ├── JSONReaderScannerTest_type.java │ │ │ │ │ │ │ ├── JSONReaderTest.java │ │ │ │ │ │ │ ├── JSONReaderTest_0.java │ │ │ │ │ │ │ ├── JSONReaderTest_1.java │ │ │ │ │ │ │ ├── JSONReaderTest_2.java │ │ │ │ │ │ │ ├── JSONReaderTest_3.java │ │ │ │ │ │ │ ├── JSONReaderTest_4.java │ │ │ │ │ │ │ ├── JSONReaderTest_5.java │ │ │ │ │ │ │ ├── JSONReaderTest_error.java │ │ │ │ │ │ │ ├── JSONReaderTest_error2.java │ │ │ │ │ │ │ ├── JSONReader_array.java │ │ │ │ │ │ │ ├── JSONReader_map.java │ │ │ │ │ │ │ ├── JSONReader_obj.java │ │ │ │ │ │ │ ├── JSONReader_obj_2.java │ │ │ │ │ │ │ ├── JSONReader_obj_3.java │ │ │ │ │ │ │ ├── JSONReader_string.java │ │ │ │ │ │ │ ├── JSONReader_string_1.java │ │ │ │ │ │ │ └── JSONReader_typeRef.java │ │ │ │ │ │ └── taobao/ │ │ │ │ │ │ ├── BooleanObjectFieldTest.java │ │ │ │ │ │ ├── DoubleObjectFieldTest.java │ │ │ │ │ │ ├── FloatObjectFieldTest.java │ │ │ │ │ │ ├── IntAsStringTest.java │ │ │ │ │ │ ├── IntegerAsStringTest.java │ │ │ │ │ │ ├── LongAsStringTest.java │ │ │ │ │ │ ├── LongObjectAsStringTest.java │ │ │ │ │ │ └── SpecialStringTest.java │ │ │ │ │ ├── path/ │ │ │ │ │ │ ├── BookEvalTest.java │ │ │ │ │ │ ├── BookExtractTest.java │ │ │ │ │ │ ├── DLATest_0.java │ │ │ │ │ │ ├── DeepScanTest.java │ │ │ │ │ │ ├── JSONPath_0.java │ │ │ │ │ │ ├── JSONPath_1.java │ │ │ │ │ │ ├── JSONPath_10_contains.java │ │ │ │ │ │ ├── JSONPath_11.java │ │ │ │ │ │ ├── JSONPath_12.java │ │ │ │ │ │ ├── JSONPath_13.java │ │ │ │ │ │ ├── JSONPath_14.java │ │ │ │ │ │ ├── JSONPath_15.java │ │ │ │ │ │ ├── JSONPath_16.java │ │ │ │ │ │ ├── JSONPath_17.java │ │ │ │ │ │ ├── JSONPath_2.java │ │ │ │ │ │ ├── JSONPath_3.java │ │ │ │ │ │ ├── JSONPath_4.java │ │ │ │ │ │ ├── JSONPath_5.java │ │ │ │ │ │ ├── JSONPath_6.java │ │ │ │ │ │ ├── JSONPath_7.java │ │ │ │ │ │ ├── JSONPath_8.java │ │ │ │ │ │ ├── JSONPath_9.java │ │ │ │ │ │ ├── JSONPath_array_length.java │ │ │ │ │ │ ├── JSONPath_array_multi.java │ │ │ │ │ │ ├── JSONPath_array_put.java │ │ │ │ │ │ ├── JSONPath_array_put_2.java │ │ │ │ │ │ ├── JSONPath_array_remove_0.java │ │ │ │ │ │ ├── JSONPath_between_double.java │ │ │ │ │ │ ├── JSONPath_between_int.java │ │ │ │ │ │ ├── JSONPath_calenar_test.java │ │ │ │ │ │ ├── JSONPath_conatinas_null.java │ │ │ │ │ │ ├── JSONPath_containsValue.java │ │ │ │ │ │ ├── JSONPath_containsValue_2.java │ │ │ │ │ │ ├── JSONPath_containsValue_bigdecimal.java │ │ │ │ │ │ ├── JSONPath_containsValue_biginteger.java │ │ │ │ │ │ ├── JSONPath_containsValue_double.java │ │ │ │ │ │ ├── JSONPath_deepScan_test.java │ │ │ │ │ │ ├── JSONPath_deepScan_test2.java │ │ │ │ │ │ ├── JSONPath_enum.java │ │ │ │ │ │ ├── JSONPath_field_access.java │ │ │ │ │ │ ├── JSONPath_field_access_filter_compare_int.java │ │ │ │ │ │ ├── JSONPath_field_access_filter_compare_int_simple.java │ │ │ │ │ │ ├── JSONPath_field_access_filter_compare_string.java │ │ │ │ │ │ ├── JSONPath_field_access_filter_compare_string_simple.java │ │ │ │ │ │ ├── JSONPath_field_access_filter_in_decimal.java │ │ │ │ │ │ ├── JSONPath_field_access_filter_in_int.java │ │ │ │ │ │ ├── JSONPath_field_access_filter_in_string.java │ │ │ │ │ │ ├── JSONPath_field_access_filter_like.java │ │ │ │ │ │ ├── JSONPath_field_access_filter_like_simple.java │ │ │ │ │ │ ├── JSONPath_field_access_filter_notNull.java │ │ │ │ │ │ ├── JSONPath_field_access_filter_rlike.java │ │ │ │ │ │ ├── JSONPath_field_access_multi.java │ │ │ │ │ │ ├── JSONPath_field_wildcard.java │ │ │ │ │ │ ├── JSONPath_field_wildcard_filter.java │ │ │ │ │ │ ├── JSONPath_field_wildcard_filter_double.java │ │ │ │ │ │ ├── JSONPath_field_wildcard_filter_float.java │ │ │ │ │ │ ├── JSONPath_issue1208.java │ │ │ │ │ │ ├── JSONPath_keySet.java │ │ │ │ │ │ ├── JSONPath_like.java │ │ │ │ │ │ ├── JSONPath_list.java │ │ │ │ │ │ ├── JSONPath_list_field.java │ │ │ │ │ │ ├── JSONPath_list_multi.java │ │ │ │ │ │ ├── JSONPath_list_range.java │ │ │ │ │ │ ├── JSONPath_list_size.java │ │ │ │ │ │ ├── JSONPath_list_size_1.java │ │ │ │ │ │ ├── JSONPath_list_size_2.java │ │ │ │ │ │ ├── JSONPath_list_size_3.java │ │ │ │ │ │ ├── JSONPath_map_size.java │ │ │ │ │ │ ├── JSONPath_max.java │ │ │ │ │ │ ├── JSONPath_min.java │ │ │ │ │ │ ├── JSONPath_none_root.java │ │ │ │ │ │ ├── JSONPath_object_filter.java │ │ │ │ │ │ ├── JSONPath_oracle_compatible_test.java │ │ │ │ │ │ ├── JSONPath_paths_test.java │ │ │ │ │ │ ├── JSONPath_paths_test1.java │ │ │ │ │ │ ├── JSONPath_paths_test2.java │ │ │ │ │ │ ├── JSONPath_paths_test3.java │ │ │ │ │ │ ├── JSONPath_paths_test4.java │ │ │ │ │ │ ├── JSONPath_paths_test5.java │ │ │ │ │ │ ├── JSONPath_remove_test.java │ │ │ │ │ │ ├── JSONPath_reverse_test.java │ │ │ │ │ │ ├── JSONPath_set.java │ │ │ │ │ │ ├── JSONPath_set_test2.java │ │ │ │ │ │ ├── JSONPath_set_test3.java │ │ │ │ │ │ ├── JSONPath_set_test4.java │ │ │ │ │ │ ├── JSONPath_set_test5.java │ │ │ │ │ │ ├── JSONPath_set_test6.java │ │ │ │ │ │ ├── JSONPath_set_test7.java │ │ │ │ │ │ ├── JSONPath_size.java │ │ │ │ │ │ ├── JSONPath_toString.java │ │ │ │ │ │ ├── JSONPointTest_0.java │ │ │ │ │ │ ├── JSONPointTest_1.java │ │ │ │ │ │ ├── TestSpecial_0.java │ │ │ │ │ │ ├── TestSpecial_1.java │ │ │ │ │ │ ├── TestSpecial_2.java │ │ │ │ │ │ ├── TestSpecial_3.java │ │ │ │ │ │ ├── TestSpecial_4.java │ │ │ │ │ │ └── extract/ │ │ │ │ │ │ ├── JSONPath_extract_0.java │ │ │ │ │ │ ├── JSONPath_extract_1.java │ │ │ │ │ │ ├── JSONPath_extract_2_book.java │ │ │ │ │ │ ├── JSONPath_extract_3.java │ │ │ │ │ │ └── JSONPath_extract_4_multi.java │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ └── TestProxy.java │ │ │ │ │ ├── ref/ │ │ │ │ │ │ ├── RefTest.java │ │ │ │ │ │ ├── RefTest10.java │ │ │ │ │ │ ├── RefTest11.java │ │ │ │ │ │ ├── RefTest12.java │ │ │ │ │ │ ├── RefTest13.java │ │ │ │ │ │ ├── RefTest14.java │ │ │ │ │ │ ├── RefTest15.java │ │ │ │ │ │ ├── RefTest16.java │ │ │ │ │ │ ├── RefTest17.java │ │ │ │ │ │ ├── RefTest18.java │ │ │ │ │ │ ├── RefTest19.java │ │ │ │ │ │ ├── RefTest2.java │ │ │ │ │ │ ├── RefTest20.java │ │ │ │ │ │ ├── RefTest21.java │ │ │ │ │ │ ├── RefTest22.java │ │ │ │ │ │ ├── RefTest23.java │ │ │ │ │ │ ├── RefTest24.java │ │ │ │ │ │ ├── RefTest3.java │ │ │ │ │ │ ├── RefTest4.java │ │ │ │ │ │ ├── RefTest5.java │ │ │ │ │ │ ├── RefTest6.java │ │ │ │ │ │ ├── RefTest7.java │ │ │ │ │ │ ├── RefTest8.java │ │ │ │ │ │ ├── RefTest9.java │ │ │ │ │ │ └── RefTest_for_huanxige.java │ │ │ │ │ ├── serializer/ │ │ │ │ │ │ ├── AbstractTest.java │ │ │ │ │ │ ├── BooleanArraySerializerTest.java │ │ │ │ │ │ ├── BooleanFieldSerializerTest.java │ │ │ │ │ │ ├── BooleanFieldSerializerTest_primitive.java │ │ │ │ │ │ ├── BooleanFieldTest.java │ │ │ │ │ │ ├── BooleanFieldTest2.java │ │ │ │ │ │ ├── BooleanFieldTest3.java │ │ │ │ │ │ ├── BooleanFieldTest_array.java │ │ │ │ │ │ ├── BugTest0.java │ │ │ │ │ │ ├── BugTest1.java │ │ │ │ │ │ ├── BugTest2.java │ │ │ │ │ │ ├── Bug_for_yegaofei.java │ │ │ │ │ │ ├── ByteArrayFieldSerializerTest.java │ │ │ │ │ │ ├── ByteArraySerializerTest.java │ │ │ │ │ │ ├── ByteArrayTest.java │ │ │ │ │ │ ├── CharArraySerializerTest.java │ │ │ │ │ │ ├── CharTest.java │ │ │ │ │ │ ├── CharsetSerializerTest.java │ │ │ │ │ │ ├── CharsetTest.java │ │ │ │ │ │ ├── CircularReferencesTest.java │ │ │ │ │ │ ├── ClassFieldTest.java │ │ │ │ │ │ ├── ClassLoaderTest.java │ │ │ │ │ │ ├── ClobSerializerTest.java │ │ │ │ │ │ ├── CollectionSerializerTest.java │ │ │ │ │ │ ├── ColorSerializerTest.java │ │ │ │ │ │ ├── ConcurrentHashMapTest.java │ │ │ │ │ │ ├── ConcurrentHashMapTest2.java │ │ │ │ │ │ ├── ConcurrentHashMapTest3.java │ │ │ │ │ │ ├── ConcurrentHashMapTest4.java │ │ │ │ │ │ ├── ConcurrentHashMapTest5.java │ │ │ │ │ │ ├── ConcurrentHashMapTest6.java │ │ │ │ │ │ ├── ConcurrentHashMapTest7.java │ │ │ │ │ │ ├── DateFormatSerializerTest.java │ │ │ │ │ │ ├── DoubleArraySerializerTest.java │ │ │ │ │ │ ├── DoubleFormatTest.java │ │ │ │ │ │ ├── DoubleFormatTest2.java │ │ │ │ │ │ ├── DoubleTest.java │ │ │ │ │ │ ├── DoubleTest_custom.java │ │ │ │ │ │ ├── DoubleTest_custom2.java │ │ │ │ │ │ ├── DupSetterTest.java │ │ │ │ │ │ ├── DupSetterTest2.java │ │ │ │ │ │ ├── DupSetterTest3.java │ │ │ │ │ │ ├── DupSetterTest4.java │ │ │ │ │ │ ├── DupSetterTest5.java │ │ │ │ │ │ ├── DupSetterTest6.java │ │ │ │ │ │ ├── EnumerationSeriliazerTest.java │ │ │ │ │ │ ├── ErrorGetterTest.java │ │ │ │ │ │ ├── ErrorTest.java │ │ │ │ │ │ ├── ExtendsTest.java │ │ │ │ │ │ ├── FieldOrderTest.java │ │ │ │ │ │ ├── FileTest.java │ │ │ │ │ │ ├── FloatArraySerializerTest.java │ │ │ │ │ │ ├── FloatFormatTest.java │ │ │ │ │ │ ├── FloatFormatTest2.java │ │ │ │ │ │ ├── FloatTest.java │ │ │ │ │ │ ├── FontSerializerTest.java │ │ │ │ │ │ ├── GenericTypeNotMatchTest.java │ │ │ │ │ │ ├── GenericTypeNotMatchTest2.java │ │ │ │ │ │ ├── GenericTypeTest.java │ │ │ │ │ │ ├── GenericTypeTest2.java │ │ │ │ │ │ ├── IgnoreGetMethodTest.java │ │ │ │ │ │ ├── IgnoreNonFieldGetterTest.java │ │ │ │ │ │ ├── IgnoreNonFieldGetterTest2.java │ │ │ │ │ │ ├── IgoreGetterTest.java │ │ │ │ │ │ ├── InetAddressTest.java │ │ │ │ │ │ ├── InetSocketAddressTest.java │ │ │ │ │ │ ├── IntArrayEncodeTest.java │ │ │ │ │ │ ├── IntFieldTest.java │ │ │ │ │ │ ├── IntFieldTest2.java │ │ │ │ │ │ ├── IntegerArrayEncodeTest.java │ │ │ │ │ │ ├── IntegerArrayFieldSerializerTest.java │ │ │ │ │ │ ├── IntegerSerializerTest.java │ │ │ │ │ │ ├── InterfaceTest.java │ │ │ │ │ │ ├── JSONFieldTest.java │ │ │ │ │ │ ├── JSONFieldTest2.java │ │ │ │ │ │ ├── JSONFieldTest3.java │ │ │ │ │ │ ├── JSONFieldTest4.java │ │ │ │ │ │ ├── JSONFieldTest5.java │ │ │ │ │ │ ├── JSONFieldTest6.java │ │ │ │ │ │ ├── JSONFieldTest_unwrapped_0.java │ │ │ │ │ │ ├── JSONFieldTest_unwrapped_1.java │ │ │ │ │ │ ├── JSONFieldTest_unwrapped_2.java │ │ │ │ │ │ ├── JSONFieldTest_unwrapped_3.java │ │ │ │ │ │ ├── JSONFieldTest_unwrapped_4.java │ │ │ │ │ │ ├── JSONFieldTest_unwrapped_5.java │ │ │ │ │ │ ├── JSONFieldTest_unwrapped_6.java │ │ │ │ │ │ ├── JSONFieldTest_unwrapped_7.java │ │ │ │ │ │ ├── JSONObjectOrderTest.java │ │ │ │ │ │ ├── JSONSerializerDeprecatedTest.java │ │ │ │ │ │ ├── JSONSerializerFeatureTest.java │ │ │ │ │ │ ├── JSONSerializerMapTest.java │ │ │ │ │ │ ├── JSONSerializerTest.java │ │ │ │ │ │ ├── JSONSerializerTest1.java │ │ │ │ │ │ ├── JSONSerializerTest2.java │ │ │ │ │ │ ├── JSONSerializerTest3.java │ │ │ │ │ │ ├── JSONTypeIncludesTest.java │ │ │ │ │ │ ├── JavaBeanSerializerTest.java │ │ │ │ │ │ ├── JavaBeanSerializerTest2.java │ │ │ │ │ │ ├── ListFieldTest.java │ │ │ │ │ │ ├── ListSerializerTest.java │ │ │ │ │ │ ├── ListSerializerTest2.java │ │ │ │ │ │ ├── ListSerializerTest3.java │ │ │ │ │ │ ├── ListTest.java │ │ │ │ │ │ ├── LocalTest.java │ │ │ │ │ │ ├── LongArraySerializerTest.java │ │ │ │ │ │ ├── MapSerializerTest.java │ │ │ │ │ │ ├── MapTest.java │ │ │ │ │ │ ├── MaxBufSizeTest.java │ │ │ │ │ │ ├── MaxBufSizeTest2.java │ │ │ │ │ │ ├── MultiFieldIntTest_writer.java │ │ │ │ │ │ ├── MultiFieldIntTest_writer2.java │ │ │ │ │ │ ├── NoneStringKeyTest.java │ │ │ │ │ │ ├── NotWriteDefaultValueTest.java │ │ │ │ │ │ ├── NotWriteDefaultValueTest_NoneASM.java │ │ │ │ │ │ ├── ObjectArraySerializerTest.java │ │ │ │ │ │ ├── ObjectSerializerTest.java │ │ │ │ │ │ ├── ObjectWriteTest.java │ │ │ │ │ │ ├── ParserConfigTest.java │ │ │ │ │ │ ├── PascalNameFilterTest.java │ │ │ │ │ │ ├── PascalNameFilterTest_1.java │ │ │ │ │ │ ├── PatternTest.java │ │ │ │ │ │ ├── PointSerializerTest.java │ │ │ │ │ │ ├── PrePropertyFilterTest.java │ │ │ │ │ │ ├── PrettyFormatTest.java │ │ │ │ │ │ ├── PrettyFormatTest2.java │ │ │ │ │ │ ├── PrimitiveTest.java │ │ │ │ │ │ ├── ProxyTest.java │ │ │ │ │ │ ├── ProxyTest2.java │ │ │ │ │ │ ├── RectangleSerializerTest.java │ │ │ │ │ │ ├── ReferenceDeserializerTest.java │ │ │ │ │ │ ├── SerialContextTest.java │ │ │ │ │ │ ├── SerialWriterStringEncoderTest2.java │ │ │ │ │ │ ├── SerialWriterTest.java │ │ │ │ │ │ ├── SerializeConfigTest.java │ │ │ │ │ │ ├── SerializeConfigTest2.java │ │ │ │ │ │ ├── SerializeConfigTest2_private.java │ │ │ │ │ │ ├── SerializeWriterTest.java │ │ │ │ │ │ ├── SerializeWriterTest_1.java │ │ │ │ │ │ ├── SerializeWriterTest_10.java │ │ │ │ │ │ ├── SerializeWriterTest_11.java │ │ │ │ │ │ ├── SerializeWriterTest_12.java │ │ │ │ │ │ ├── SerializeWriterTest_13.java │ │ │ │ │ │ ├── SerializeWriterTest_14.java │ │ │ │ │ │ ├── SerializeWriterTest_15.java │ │ │ │ │ │ ├── SerializeWriterTest_16.java │ │ │ │ │ │ ├── SerializeWriterTest_17.java │ │ │ │ │ │ ├── SerializeWriterTest_18.java │ │ │ │ │ │ ├── SerializeWriterTest_19.java │ │ │ │ │ │ ├── SerializeWriterTest_2.java │ │ │ │ │ │ ├── SerializeWriterTest_3.java │ │ │ │ │ │ ├── SerializeWriterTest_4.java │ │ │ │ │ │ ├── SerializeWriterTest_5.java │ │ │ │ │ │ ├── SerializeWriterTest_6.java │ │ │ │ │ │ ├── SerializeWriterTest_7.java │ │ │ │ │ │ ├── SerializeWriterTest_8.java │ │ │ │ │ │ ├── SerializeWriterTest_9.java │ │ │ │ │ │ ├── SerializeWriterTest_BrowserSecure.java │ │ │ │ │ │ ├── SerializeWriterTest_BrowserSecure3.java │ │ │ │ │ │ ├── SerializeWriterTest_BrowserSecure_4_script.java │ │ │ │ │ │ ├── SerializeWriterTest_BrowserSecure_5_script_model.java │ │ │ │ │ │ ├── SerializeWriterTest_BrowserSecure_6_name_script.java │ │ │ │ │ │ ├── SerializerFeatureTest.java │ │ │ │ │ │ ├── SerilaizeFilterTest.java │ │ │ │ │ │ ├── ShortArraySerializerTest.java │ │ │ │ │ │ ├── ShortFieldSerializerTest.java │ │ │ │ │ │ ├── ShortSerializerTest.java │ │ │ │ │ │ ├── SimpleDataFormatSerializerTest.java │ │ │ │ │ │ ├── SimplePropertyPreFilterTest.java │ │ │ │ │ │ ├── SpecialTest.java │ │ │ │ │ │ ├── SpecicalStringTest.java │ │ │ │ │ │ ├── StringArraySerializerTest.java │ │ │ │ │ │ ├── StringSerializerTest.java │ │ │ │ │ │ ├── TestInnerClass.java │ │ │ │ │ │ ├── TestInnerClass1.java │ │ │ │ │ │ ├── TestInnerClass2.java │ │ │ │ │ │ ├── TestPivateStaticClass.java │ │ │ │ │ │ ├── TestSortField.java │ │ │ │ │ │ ├── TestSpecial.java │ │ │ │ │ │ ├── TestSpecial2.java │ │ │ │ │ │ ├── TestSpecial3.java │ │ │ │ │ │ ├── TestSpecial4.java │ │ │ │ │ │ ├── TestSpecial5.java │ │ │ │ │ │ ├── TestSpecial6.java │ │ │ │ │ │ ├── TestSpecial_entity.java │ │ │ │ │ │ ├── TestSpecial_map.java │ │ │ │ │ │ ├── TimeZoneTest.java │ │ │ │ │ │ ├── TransientTest.java │ │ │ │ │ │ ├── TreeSetTest.java │ │ │ │ │ │ ├── URITest.java │ │ │ │ │ │ ├── URLTest.java │ │ │ │ │ │ ├── UUIDTest.java │ │ │ │ │ │ ├── UnicodeTest.java │ │ │ │ │ │ ├── WriteClassNameTest.java │ │ │ │ │ │ ├── WriteNullListAsEmptyTest.java │ │ │ │ │ │ ├── WriteSlashAsSpecialTest.java │ │ │ │ │ │ ├── date/ │ │ │ │ │ │ │ ├── DateTest.java │ │ │ │ │ │ │ ├── DateTest2.java │ │ │ │ │ │ │ ├── DateTest3.java │ │ │ │ │ │ │ ├── DateTest4.java │ │ │ │ │ │ │ ├── DateTest4_indian.java │ │ │ │ │ │ │ ├── DateTest5_iso8601.java │ │ │ │ │ │ │ ├── DateTest_ISO8601_OneLetterISO8601TimeZone.java │ │ │ │ │ │ │ ├── DateTest_ISO8601_ThreeLetterISO8601TimeZone.java │ │ │ │ │ │ │ ├── DateTest_ISO8601_TimeZone.java │ │ │ │ │ │ │ ├── DateTest_ISO8601_TwoLetterISO8601TimeZone.java │ │ │ │ │ │ │ └── DateTest_ISO8601_UTCTime.java │ │ │ │ │ │ ├── enum_/ │ │ │ │ │ │ │ ├── EnumCustomCodecTest.java │ │ │ │ │ │ │ ├── EnumFieldsTest.java │ │ │ │ │ │ │ ├── EnumFieldsTest2.java │ │ │ │ │ │ │ ├── EnumFieldsTest3.java │ │ │ │ │ │ │ ├── EnumFieldsTest4.java │ │ │ │ │ │ │ ├── EnumFieldsTest5.java │ │ │ │ │ │ │ ├── EnumFieldsTest6.java │ │ │ │ │ │ │ ├── EnumFieldsTest7.java │ │ │ │ │ │ │ ├── EnumFieldsTest8.java │ │ │ │ │ │ │ ├── EnumOrdinalTest.java │ │ │ │ │ │ │ ├── EnumTest.java │ │ │ │ │ │ │ ├── EnumTest2.java │ │ │ │ │ │ │ ├── EnumTest3.java │ │ │ │ │ │ │ ├── EnumTest4.java │ │ │ │ │ │ │ ├── EnumUsingToString.java │ │ │ │ │ │ │ └── EnumUsingToString_JSONType.java │ │ │ │ │ │ ├── exception/ │ │ │ │ │ │ │ ├── ExceptionTest.java │ │ │ │ │ │ │ └── RuntimeExceptionTest.java │ │ │ │ │ │ ├── features/ │ │ │ │ │ │ │ ├── JSONDirectTest.java │ │ │ │ │ │ │ ├── JSONDirectTest_number.java │ │ │ │ │ │ │ ├── JSONDirectTest_private.java │ │ │ │ │ │ │ ├── MapSortFieldTest.java │ │ │ │ │ │ │ ├── NotWriteDefaultValueFieldTest.java │ │ │ │ │ │ │ ├── NotWriteDefaultValueFieldTest2.java │ │ │ │ │ │ │ ├── WriteBigDecimalAsPlainTest.java │ │ │ │ │ │ │ ├── WriteNonStringValueAsStringTestBooleanField.java │ │ │ │ │ │ │ ├── WriteNonStringValueAsStringTestByteField.java │ │ │ │ │ │ │ ├── WriteNonStringValueAsStringTestByteObjectField.java │ │ │ │ │ │ │ ├── WriteNonStringValueAsStringTestDoubleField.java │ │ │ │ │ │ │ ├── WriteNonStringValueAsStringTestFloatField.java │ │ │ │ │ │ │ ├── WriteNonStringValueAsStringTestFloatField2.java │ │ │ │ │ │ │ ├── WriteNonStringValueAsStringTestIntField.java │ │ │ │ │ │ │ ├── WriteNonStringValueAsStringTestIntegerField.java │ │ │ │ │ │ │ ├── WriteNonStringValueAsStringTestLongField.java │ │ │ │ │ │ │ ├── WriteNonStringValueAsStringTestMap.java │ │ │ │ │ │ │ └── WriteNonStringValueAsStringTestShortField.java │ │ │ │ │ │ ├── fieldbase/ │ │ │ │ │ │ │ ├── FieldBaseTest0.java │ │ │ │ │ │ │ └── FieldBaseTest1.java │ │ │ │ │ │ ├── filters/ │ │ │ │ │ │ │ ├── AfterFilterClassLevelTest.java │ │ │ │ │ │ │ ├── AfterFilterClassLevelTest_private.java │ │ │ │ │ │ │ ├── AfterFilterTest.java │ │ │ │ │ │ │ ├── AfterFilterTest2.java │ │ │ │ │ │ │ ├── AfterFilterTest3.java │ │ │ │ │ │ │ ├── AppendableTest.java │ │ │ │ │ │ │ ├── ArraySerializerTest.java │ │ │ │ │ │ │ ├── BeforeFilterClassLevelTest.java │ │ │ │ │ │ │ ├── BeforeFilterClassLevelTest_private.java │ │ │ │ │ │ │ ├── BeforeFilterTest.java │ │ │ │ │ │ │ ├── BeforeFilterTest2.java │ │ │ │ │ │ │ ├── BeforeFilterTest3.java │ │ │ │ │ │ │ ├── ClassLevelFeatureConfigTest.java │ │ │ │ │ │ │ ├── ClassLevelFeatureConfigTest2.java │ │ │ │ │ │ │ ├── ClassLevelFeatureConfigTest3.java │ │ │ │ │ │ │ ├── ClassLevelFeatureConfigTest_private.java │ │ │ │ │ │ │ ├── ClassNameFilterTest.java │ │ │ │ │ │ │ ├── ClassNameFilterTest_private.java │ │ │ │ │ │ │ ├── ContextValueClassLevelTest.java │ │ │ │ │ │ │ ├── MTopFilterTest.java │ │ │ │ │ │ │ ├── NameFilterClassLevelTest.java │ │ │ │ │ │ │ ├── NameFilterClassLevelTest_private.java │ │ │ │ │ │ │ ├── NameFilterTest.java │ │ │ │ │ │ │ ├── NameFilterTest_IntegerKey.java │ │ │ │ │ │ │ ├── NameFilterTest_boolean.java │ │ │ │ │ │ │ ├── NameFilterTest_boolean_field.java │ │ │ │ │ │ │ ├── NameFilterTest_byte.java │ │ │ │ │ │ │ ├── NameFilterTest_byte_field.java │ │ │ │ │ │ │ ├── NameFilterTest_char.java │ │ │ │ │ │ │ ├── NameFilterTest_double.java │ │ │ │ │ │ │ ├── NameFilterTest_double_field.java │ │ │ │ │ │ │ ├── NameFilterTest_float.java │ │ │ │ │ │ │ ├── NameFilterTest_float_field.java │ │ │ │ │ │ │ ├── NameFilterTest_int.java │ │ │ │ │ │ │ ├── NameFilterTest_int_field.java │ │ │ │ │ │ │ ├── NameFilterTest_long.java │ │ │ │ │ │ │ ├── NameFilterTest_long_field.java │ │ │ │ │ │ │ ├── NameFilterTest_short.java │ │ │ │ │ │ │ ├── NameFilterTest_short_field.java │ │ │ │ │ │ │ ├── PropertyFilterClassLevelTest.java │ │ │ │ │ │ │ ├── PropertyFilterClassLevelTest_private.java │ │ │ │ │ │ │ ├── PropertyFilterTest.java │ │ │ │ │ │ │ ├── PropertyFilterTest2.java │ │ │ │ │ │ │ ├── PropertyFilter_bool_field.java │ │ │ │ │ │ │ ├── PropertyFilter_byte.java │ │ │ │ │ │ │ ├── PropertyFilter_char.java │ │ │ │ │ │ │ ├── PropertyFilter_double.java │ │ │ │ │ │ │ ├── PropertyFilter_float.java │ │ │ │ │ │ │ ├── PropertyFilter_int_field.java │ │ │ │ │ │ │ ├── PropertyFilter_long.java │ │ │ │ │ │ │ ├── PropertyFilter_long_field.java │ │ │ │ │ │ │ ├── PropertyFilter_short.java │ │ │ │ │ │ │ ├── PropertyPathTest.java │ │ │ │ │ │ │ ├── PropertyPathTest2.java │ │ │ │ │ │ │ ├── PropertyPathTest3.java │ │ │ │ │ │ │ ├── PropertyPreFilterClassLevelTest.java │ │ │ │ │ │ │ ├── PropertyPreFilterClassLevelTest_private.java │ │ │ │ │ │ │ ├── PropertyPrefFilterTest_IntegerKey.java │ │ │ │ │ │ │ ├── ValueClassLevelTest.java │ │ │ │ │ │ │ ├── ValueClassLevelTest_private.java │ │ │ │ │ │ │ ├── ValueFilterTest.java │ │ │ │ │ │ │ ├── ValueFilterTest_IntegerKey.java │ │ │ │ │ │ │ ├── ValueFilterTest_field.java │ │ │ │ │ │ │ ├── ValueFilterTest_field_boolean.java │ │ │ │ │ │ │ ├── ValueFilterTest_field_int.java │ │ │ │ │ │ │ └── ValueFilterTest_field_long.java │ │ │ │ │ │ ├── label/ │ │ │ │ │ │ │ ├── LabelIncludeTest.java │ │ │ │ │ │ │ ├── LabelIncludeTest2.java │ │ │ │ │ │ │ └── LabelIncludeTest3.java │ │ │ │ │ │ ├── prettyFormat/ │ │ │ │ │ │ │ ├── ArrayListFieldTest.java │ │ │ │ │ │ │ └── ArrayListTest.java │ │ │ │ │ │ ├── stream/ │ │ │ │ │ │ │ ├── StreamWriterTest_writeArray.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeArray2.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeBytes.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeBytes1.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeChar.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeChar1.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeFieldValue.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeFieldValue_bool.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeFieldValue_int.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeFieldValue_int_1.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeFieldValue_long.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeFieldValue_string.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeFieldValue_string_singQuote.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeInt.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeIntAndChar.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeJSONStringTo.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeLong.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeLongAndChar.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeString.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeString1.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeValueString.java │ │ │ │ │ │ │ ├── StreamWriterTest_writeValueString1.java │ │ │ │ │ │ │ └── StreamWriterTest_writeValueString2.java │ │ │ │ │ │ └── writeJSONStringToTest.java │ │ │ │ │ ├── stream/ │ │ │ │ │ │ ├── JSONWriterTest.java │ │ │ │ │ │ ├── JSONWriterTest_0.java │ │ │ │ │ │ ├── JSONWriterTest_1.java │ │ │ │ │ │ ├── JSONWriterTest_2.java │ │ │ │ │ │ ├── JSONWriterTest_3.java │ │ │ │ │ │ ├── JSONWriterTest_4.java │ │ │ │ │ │ ├── JSONWriterTest_5.java │ │ │ │ │ │ ├── JSONWriterTest_6.java │ │ │ │ │ │ ├── JSONWriterTest_error.java │ │ │ │ │ │ └── LargeTest.java │ │ │ │ │ ├── support/ │ │ │ │ │ │ ├── FastJsonConfigTest.java │ │ │ │ │ │ ├── hsf/ │ │ │ │ │ │ │ ├── HSFJSONUtilsTest_0.java │ │ │ │ │ │ │ ├── HSFJSONUtilsTest_1.java │ │ │ │ │ │ │ ├── HSFJSONUtilsTest_2.java │ │ │ │ │ │ │ ├── HSFJSONUtilsTest_3.java │ │ │ │ │ │ │ └── HSFJSONUtilsTest_4.java │ │ │ │ │ │ ├── jaxrs/ │ │ │ │ │ │ │ ├── FastJsonProviderTest.java │ │ │ │ │ │ │ └── mock/ │ │ │ │ │ │ │ ├── entity/ │ │ │ │ │ │ │ │ ├── FastJsonParentTestVO.java │ │ │ │ │ │ │ │ ├── FastJsonSonTestVO.java │ │ │ │ │ │ │ │ └── FastJsonTestVO.java │ │ │ │ │ │ │ ├── service/ │ │ │ │ │ │ │ │ ├── FastJsonRestfulServiceTest.java │ │ │ │ │ │ │ │ └── FastJsonRestfulServiceTestImpl.java │ │ │ │ │ │ │ └── testcase/ │ │ │ │ │ │ │ └── FastJsonProviderTest.java │ │ │ │ │ │ ├── moneta/ │ │ │ │ │ │ │ ├── MoneyNumberTest.java │ │ │ │ │ │ │ └── MoneyTest.java │ │ │ │ │ │ ├── oracle/ │ │ │ │ │ │ │ ├── TestOracleDATE.java │ │ │ │ │ │ │ └── TestOracleTIMESTAMP.java │ │ │ │ │ │ ├── retrofit/ │ │ │ │ │ │ │ └── Retrofit2ConverterFactoryTest0.java │ │ │ │ │ │ ├── spring/ │ │ │ │ │ │ │ ├── FastJsonHttpMessageConverter4Test.java │ │ │ │ │ │ │ ├── FastJsonHttpMessageConverterTest.java │ │ │ │ │ │ │ ├── FastJsonJsonViewTest.java │ │ │ │ │ │ │ ├── FastJsonRedisSerializerTest.java │ │ │ │ │ │ │ ├── FastJsonpHttpMessageConverter4Test.java │ │ │ │ │ │ │ ├── FastjsonSockJsMessageCodecTest_encode.java │ │ │ │ │ │ │ ├── GenericFastJsonRedisSerializerTest.java │ │ │ │ │ │ │ ├── data/ │ │ │ │ │ │ │ │ └── PageToJSONTest.java │ │ │ │ │ │ │ ├── messaging/ │ │ │ │ │ │ │ │ └── MappingFastJsonMessageConverterTest.java │ │ │ │ │ │ │ ├── mock/ │ │ │ │ │ │ │ │ ├── controller/ │ │ │ │ │ │ │ │ │ ├── FastJsonControllerTest.java │ │ │ │ │ │ │ │ │ ├── FastJsonViewAndJSONPControllerTest.java │ │ │ │ │ │ │ │ │ └── FastJsonViewControllerTest.java │ │ │ │ │ │ │ │ ├── entity/ │ │ │ │ │ │ │ │ │ ├── FastJsonEnumTestVO.java │ │ │ │ │ │ │ │ │ ├── FastJsonGenericityTestVO.java │ │ │ │ │ │ │ │ │ ├── FastJsonParentTestVO.java │ │ │ │ │ │ │ │ │ ├── FastJsonSonTestVO.java │ │ │ │ │ │ │ │ │ └── FastJsonTestVO.java │ │ │ │ │ │ │ │ └── testcase/ │ │ │ │ │ │ │ │ ├── FastJsonHttpMessageConverter4Test.java │ │ │ │ │ │ │ │ ├── FastJsonHttpMessageConverterCase2Test.java │ │ │ │ │ │ │ │ ├── FastJsonHttpMessageConverterJSONPCaseTest.java │ │ │ │ │ │ │ │ ├── FastJsonHttpMessageConverterTest.java │ │ │ │ │ │ │ │ ├── FastJsonJsonViewTest.java │ │ │ │ │ │ │ │ ├── FastJsonViewTest.java │ │ │ │ │ │ │ │ ├── FastJsonpHttpMessageConverter4Case1Test.java │ │ │ │ │ │ │ │ ├── FastJsonpHttpMessageConverter4Case2Test.java │ │ │ │ │ │ │ │ └── FastJsonpHttpMessageConverter4Case3Test.java │ │ │ │ │ │ │ └── security/ │ │ │ │ │ │ │ ├── DefaultOAuth2AccessTokenTest.java │ │ │ │ │ │ │ └── DefaultSavedRequestTest.java │ │ │ │ │ │ └── springfox/ │ │ │ │ │ │ └── JsonValueTest.java │ │ │ │ │ ├── taobao/ │ │ │ │ │ │ ├── ItemUpdateDOTest.java │ │ │ │ │ │ ├── MTopTest.java │ │ │ │ │ │ └── TradeTest.java │ │ │ │ │ ├── typeRef/ │ │ │ │ │ │ ├── TypeReferenceTest.java │ │ │ │ │ │ ├── TypeReferenceTest10.java │ │ │ │ │ │ ├── TypeReferenceTest11.java │ │ │ │ │ │ ├── TypeReferenceTest12.java │ │ │ │ │ │ ├── TypeReferenceTest13.java │ │ │ │ │ │ ├── TypeReferenceTest14.java │ │ │ │ │ │ ├── TypeReferenceTest2.java │ │ │ │ │ │ ├── TypeReferenceTest3.java │ │ │ │ │ │ ├── TypeReferenceTest4.java │ │ │ │ │ │ ├── TypeReferenceTest5.java │ │ │ │ │ │ ├── TypeReferenceTest6.java │ │ │ │ │ │ ├── TypeReferenceTest7.java │ │ │ │ │ │ ├── TypeReferenceTest8.java │ │ │ │ │ │ └── TypeReferenceTest9.java │ │ │ │ │ ├── util/ │ │ │ │ │ │ ├── AntiCollisionHashMapTest.java │ │ │ │ │ │ ├── AntiCollisionHashMapTest_writeClassName.java │ │ │ │ │ │ ├── Base64Test.java │ │ │ │ │ │ ├── FieldInfoTest.java │ │ │ │ │ │ ├── GenericFieldInfoTest.java │ │ │ │ │ │ ├── GenericFieldInfoTest2.java │ │ │ │ │ │ ├── IOUtilsTest.java │ │ │ │ │ │ ├── JSONASMUtilTest.java │ │ │ │ │ │ ├── JavaBeanInfoTest.java │ │ │ │ │ │ ├── RyuDoubleTest.java │ │ │ │ │ │ ├── RyuFloatTest.java │ │ │ │ │ │ ├── ThreadLocalCacheTest.java │ │ │ │ │ │ ├── TypeUtilsCastLinkedHashMap.java │ │ │ │ │ │ ├── TypeUtilsTest.java │ │ │ │ │ │ └── UTF8DecoderTest.java │ │ │ │ │ ├── validate/ │ │ │ │ │ │ └── JSONValidatorTest.java │ │ │ │ │ ├── value/ │ │ │ │ │ │ └── LongValueTest.java │ │ │ │ │ ├── writeAsArray/ │ │ │ │ │ │ ├── WriteAsArray_0_private.java │ │ │ │ │ │ ├── WriteAsArray_0_public.java │ │ │ │ │ │ ├── WriteAsArray_Eishay.java │ │ │ │ │ │ ├── WriteAsArray_Eishay_Image.java │ │ │ │ │ │ ├── WriteAsArray_Eishay_Media.java │ │ │ │ │ │ ├── WriteAsArray_Object.java │ │ │ │ │ │ ├── WriteAsArray_Object_2_public.java │ │ │ │ │ │ ├── WriteAsArray_Object_public.java │ │ │ │ │ │ ├── WriteAsArray_boolean_public.java │ │ │ │ │ │ ├── WriteAsArray_byte_public.java │ │ │ │ │ │ ├── WriteAsArray_char_public.java │ │ │ │ │ │ ├── WriteAsArray_double_private.java │ │ │ │ │ │ ├── WriteAsArray_double_public.java │ │ │ │ │ │ ├── WriteAsArray_enum_public.java │ │ │ │ │ │ ├── WriteAsArray_float2_private.java │ │ │ │ │ │ ├── WriteAsArray_float2_public.java │ │ │ │ │ │ ├── WriteAsArray_float_public.java │ │ │ │ │ │ ├── WriteAsArray_int_public.java │ │ │ │ │ │ ├── WriteAsArray_jsonType.java │ │ │ │ │ │ ├── WriteAsArray_list_obj_first_public.java │ │ │ │ │ │ ├── WriteAsArray_list_obj_public.java │ │ │ │ │ │ ├── WriteAsArray_list_public.java │ │ │ │ │ │ ├── WriteAsArray_long_private.java │ │ │ │ │ │ ├── WriteAsArray_long_public.java │ │ │ │ │ │ ├── WriteAsArray_long_stream_public.java │ │ │ │ │ │ ├── WriteAsArray_short_public.java │ │ │ │ │ │ ├── WriteAsArray_string.java │ │ │ │ │ │ ├── WriteAsArray_string_special.java │ │ │ │ │ │ ├── WriteAsArray_string_special_2.java │ │ │ │ │ │ └── WriteAsArray_string_special_Reader.java │ │ │ │ │ └── writeClassName/ │ │ │ │ │ ├── MapTest.java │ │ │ │ │ ├── StrictAutoTypeTest_0.java │ │ │ │ │ ├── WriteClassNameTest.java │ │ │ │ │ ├── WriteClassNameTest2.java │ │ │ │ │ ├── WriteClassNameTest3.java │ │ │ │ │ ├── WriteClassNameTest5.java │ │ │ │ │ ├── WriteClassNameTest6.java │ │ │ │ │ ├── WriteClassNameTest_Collection.java │ │ │ │ │ ├── WriteClassNameTest_Collection2.java │ │ │ │ │ ├── WriteClassNameTest_List.java │ │ │ │ │ ├── WriteClassNameTest_List2.java │ │ │ │ │ ├── WriteClassNameTest_List3.java │ │ │ │ │ ├── WriteClassNameTest_Map.java │ │ │ │ │ ├── WriteClassNameTest_Set.java │ │ │ │ │ ├── WriteClassNameTest_Set2.java │ │ │ │ │ ├── WriteClassNameTest_Set3.java │ │ │ │ │ ├── WriteClassNameTest_Set4.java │ │ │ │ │ ├── WriteClassNameTest_Set5.java │ │ │ │ │ ├── WriteClassNameTest_bytes.java │ │ │ │ │ └── WriteDuplicateType.java │ │ │ │ ├── bvtVO/ │ │ │ │ │ ├── AccessHttpConfigModel.java │ │ │ │ │ ├── ArgCheckTest.java │ │ │ │ │ ├── AuditStatusType.java │ │ │ │ │ ├── Bean.java │ │ │ │ │ ├── BigClass.java │ │ │ │ │ ├── ContactTemplateParam.java │ │ │ │ │ ├── DataTransaction.java │ │ │ │ │ ├── DataTransaction2.java │ │ │ │ │ ├── IEvent.java │ │ │ │ │ ├── IEventDto.java │ │ │ │ │ ├── Image.java │ │ │ │ │ ├── IncomingDataPoint.java │ │ │ │ │ ├── IncomingDataPoint_double.java │ │ │ │ │ ├── IncomingDataPoint_ext_double.java │ │ │ │ │ ├── IntEnum.java │ │ │ │ │ ├── Main.java │ │ │ │ │ ├── OfferRankResultVO.java │ │ │ │ │ ├── OptionKey.java │ │ │ │ │ ├── OptionValue.java │ │ │ │ │ ├── Page.java │ │ │ │ │ ├── PayDO.java │ │ │ │ │ ├── PhysicalQueue.java │ │ │ │ │ ├── ProductView.java │ │ │ │ │ ├── PushMsg.java │ │ │ │ │ ├── QueryResult.java │ │ │ │ │ ├── QueueEntity.java │ │ │ │ │ ├── RainbowStats.java │ │ │ │ │ ├── TempAttachMetaOption.java │ │ │ │ │ ├── TestDTO.java │ │ │ │ │ ├── VirtualTopic.java │ │ │ │ │ ├── WareHouseInfo.java │ │ │ │ │ ├── ae/ │ │ │ │ │ │ ├── Area.java │ │ │ │ │ │ ├── Data.java │ │ │ │ │ │ ├── Floor.java │ │ │ │ │ │ ├── Item.java │ │ │ │ │ │ └── huangliang2/ │ │ │ │ │ │ ├── Area.java │ │ │ │ │ │ ├── Floor.java │ │ │ │ │ │ ├── FloorPageData.java │ │ │ │ │ │ ├── FloorV1.java │ │ │ │ │ │ ├── FloorV2.java │ │ │ │ │ │ ├── MockResult.java │ │ │ │ │ │ ├── NetResponse.java │ │ │ │ │ │ └── Section.java │ │ │ │ │ ├── alipay/ │ │ │ │ │ │ └── PlatformDepartmentVO.java │ │ │ │ │ ├── basic/ │ │ │ │ │ │ └── LongPrimitiveEntity.java │ │ │ │ │ ├── bbc/ │ │ │ │ │ │ ├── BaseResult.java │ │ │ │ │ │ └── MyResultResult.java │ │ │ │ │ ├── deny/ │ │ │ │ │ │ └── A.java │ │ │ │ │ ├── mogujie/ │ │ │ │ │ │ ├── BankCard.java │ │ │ │ │ │ ├── BaseDTO.java │ │ │ │ │ │ └── BindQueryRespDTO.java │ │ │ │ │ ├── vip_com/ │ │ │ │ │ │ ├── QueryLoanOrderRsp.java │ │ │ │ │ │ └── TxnListItsm.java │ │ │ │ │ ├── wuqi/ │ │ │ │ │ │ ├── InstanceSchema.java │ │ │ │ │ │ ├── Result.java │ │ │ │ │ │ └── SchemaResult.java │ │ │ │ │ └── 一个中文名字的包/ │ │ │ │ │ └── User.java │ │ │ │ ├── demo/ │ │ │ │ │ ├── BooleanFieldDemo.java │ │ │ │ │ ├── DateDemo.java │ │ │ │ │ ├── Demo1.java │ │ │ │ │ ├── Demo2.java │ │ │ │ │ ├── EncodeDemo.java │ │ │ │ │ ├── ErrorObjectSerializer.java │ │ │ │ │ ├── FilterDemo.java │ │ │ │ │ ├── Forguard.java │ │ │ │ │ ├── Group.java │ │ │ │ │ ├── JSONFeidDemo.java │ │ │ │ │ ├── MapDemo.java │ │ │ │ │ ├── ReuseObject.java │ │ │ │ │ ├── User.java │ │ │ │ │ ├── X.java │ │ │ │ │ ├── XAutowiredObjectSerializer.java │ │ │ │ │ └── hibernate/ │ │ │ │ │ ├── ForceLazyLoadingTest.java │ │ │ │ │ ├── LazyLoadingTest.java │ │ │ │ │ └── data/ │ │ │ │ │ ├── Customer.java │ │ │ │ │ ├── Employee.java │ │ │ │ │ ├── Office.java │ │ │ │ │ ├── Order.java │ │ │ │ │ ├── OrderDetail.java │ │ │ │ │ ├── OrderDetailId.java │ │ │ │ │ ├── Payment.java │ │ │ │ │ ├── PaymentId.java │ │ │ │ │ └── Product.java │ │ │ │ └── test/ │ │ │ │ ├── A1.java │ │ │ │ ├── Base64.java │ │ │ │ ├── Bug_0_Test.java │ │ │ │ ├── DateTest.java │ │ │ │ ├── DetectProhibitChar.java │ │ │ │ ├── DigitTest.java │ │ │ │ ├── ErrorAppendable.java │ │ │ │ ├── FNV32_CollisionTest.java │ │ │ │ ├── FNV32_CollisionTest_2.java │ │ │ │ ├── FNV32_CollisionTest_All.java │ │ │ │ ├── FNVHashTest.java │ │ │ │ ├── GenerateJavaTest.java │ │ │ │ ├── InnerInnerTest.java │ │ │ │ ├── IntArrayFieldTest_primitive.java │ │ │ │ ├── Issue1001.java │ │ │ │ ├── Issue1407.java │ │ │ │ ├── Issue1488.java │ │ │ │ ├── Issue3805.java │ │ │ │ ├── JSONLibXmlTest.java │ │ │ │ ├── JSONParser2Test.java │ │ │ │ ├── JavaHash_CollisionTest.java │ │ │ │ ├── JsonIteratorByteArrayTest.java │ │ │ │ ├── JsonIteratorImageTest.java │ │ │ │ ├── JsonIteratorTest.java │ │ │ │ ├── SymbolTableDupTest.java │ │ │ │ ├── TestASM.java │ │ │ │ ├── TestFor_iteye_resolute.java │ │ │ │ ├── TestSysProperty.java │ │ │ │ ├── TestUtils.java │ │ │ │ ├── TestWriteSlashAsSpecial.java │ │ │ │ ├── UTF8Test.java │ │ │ │ ├── UTF8Test_decode.java │ │ │ │ ├── VansParseTest.java │ │ │ │ ├── a/ │ │ │ │ │ ├── A20170327_0.java │ │ │ │ │ ├── Alipay1206.java │ │ │ │ │ ├── AlipayJSONPathReplace.java │ │ │ │ │ ├── CompilerTest.java │ │ │ │ │ ├── Group.java │ │ │ │ │ ├── GsonTest.java │ │ │ │ │ ├── IncomingDataPointBenchmark.java │ │ │ │ │ ├── IncomingDataPointBenchmark_file.java │ │ │ │ │ ├── IncomingDataPointBenchmark_file_double.java │ │ │ │ │ ├── IncomingDataPointBenchmark_file_ext_double.java │ │ │ │ │ ├── JTest.java │ │ │ │ │ ├── SpecialTest.java │ │ │ │ │ ├── User.java │ │ │ │ │ ├── VRTest.java │ │ │ │ │ └── WhiteSpaceTest.java │ │ │ │ ├── benchmark/ │ │ │ │ │ ├── BenchmarkCase.java │ │ │ │ │ ├── BenchmarkExecutor.java │ │ │ │ │ ├── BenchmarkMain.java │ │ │ │ │ ├── BenchmarkMain_EishayDecode.java │ │ │ │ │ ├── BenchmarkMain_EishayDecode_WriteAsArray.java │ │ │ │ │ ├── BenchmarkMain_EishayEncode.java │ │ │ │ │ ├── BenchmarkMain_EishayEncode_WriteAsArray.java │ │ │ │ │ ├── BenchmarkTest.java │ │ │ │ │ ├── JSONPathBenchmarkTest.java │ │ │ │ │ ├── RyuDoubleBenchmark.java │ │ │ │ │ ├── RyuFloatBenchmark.java │ │ │ │ │ ├── basic/ │ │ │ │ │ │ ├── BigDecimalBenchmark.java │ │ │ │ │ │ ├── BigIntegerBenchmark.java │ │ │ │ │ │ ├── BooleanBenchmark.java │ │ │ │ │ │ ├── ByteBenchmark.java │ │ │ │ │ │ ├── ByteBenchmark_arrayMapping_obj.java │ │ │ │ │ │ ├── ByteBenchmark_obj.java │ │ │ │ │ │ ├── DateBenchmark.java │ │ │ │ │ │ ├── DoubleBenchmark.java │ │ │ │ │ │ ├── DoubleBenchmark_arrayMapping.java │ │ │ │ │ │ ├── DoubleBenchmark_arrayMapping_obj.java │ │ │ │ │ │ ├── DoubleBenchmark_obj.java │ │ │ │ │ │ ├── FloatBenchmark.java │ │ │ │ │ │ ├── FloatBenchmark_arrayMapping.java │ │ │ │ │ │ ├── FloatBenchmark_arrayMapping_obj.java │ │ │ │ │ │ ├── FloatBenchmark_obj.java │ │ │ │ │ │ ├── IntBenchmark.java │ │ │ │ │ │ ├── IntBenchmark_arrayMapping_obj.java │ │ │ │ │ │ ├── IntBenchmark_obj.java │ │ │ │ │ │ ├── LinkedListBenchmark.java │ │ │ │ │ │ ├── LongBenchmark.java │ │ │ │ │ │ ├── LongBenchmark_obj.java │ │ │ │ │ │ ├── ShortBenchmark.java │ │ │ │ │ │ ├── ShortBenchmark_arrayMappinng_obj.java │ │ │ │ │ │ ├── ShortBenchmark_obj.java │ │ │ │ │ │ └── UUIDBenchmark.java │ │ │ │ │ ├── decode/ │ │ │ │ │ │ ├── BooleanArray1000Decode.java │ │ │ │ │ │ ├── EishayDecode.java │ │ │ │ │ │ ├── EishayDecode2Bytes.java │ │ │ │ │ │ ├── EishayDecodeByClassName.java │ │ │ │ │ │ ├── EishayDecodeBytes.java │ │ │ │ │ │ ├── EishayTreeDecode.java │ │ │ │ │ │ ├── Entity100IntDecode.java │ │ │ │ │ │ ├── Entity100StringDecode.java │ │ │ │ │ │ ├── GroupDecode.java │ │ │ │ │ │ ├── IntArray1000Decode.java │ │ │ │ │ │ ├── Map1000StringDecode.java │ │ │ │ │ │ ├── Map1Decode.java │ │ │ │ │ │ ├── StringArray1000Decode.java │ │ │ │ │ │ └── TradeObjectParse.java │ │ │ │ │ ├── encode/ │ │ │ │ │ │ ├── ArrayBoolean1000Encode.java │ │ │ │ │ │ ├── ArrayByte1000Encode.java │ │ │ │ │ │ ├── ArrayEmptyList1000Encode.java │ │ │ │ │ │ ├── ArrayEmptyMap1000Encode.java │ │ │ │ │ │ ├── ArrayInt1000Encode.java │ │ │ │ │ │ ├── ArrayLong1000Encode.java │ │ │ │ │ │ ├── ArrayObjectEmptyMap1000Encode.java │ │ │ │ │ │ ├── ArrayString1000Encode.java │ │ │ │ │ │ ├── CategoryEncode.java │ │ │ │ │ │ ├── EishayEncode.java │ │ │ │ │ │ ├── EishayEncodeOutputStream.java │ │ │ │ │ │ ├── EishayEncodeToBytes.java │ │ │ │ │ │ ├── Entity100IntEncode.java │ │ │ │ │ │ ├── GroupEncode.java │ │ │ │ │ │ ├── ListBoolean1000Encode.java │ │ │ │ │ │ └── Map1000Encode.java │ │ │ │ │ ├── entity/ │ │ │ │ │ │ ├── Entity100Int.java │ │ │ │ │ │ └── Entity100String.java │ │ │ │ │ └── jdk10/ │ │ │ │ │ ├── StringBenchmark.java │ │ │ │ │ └── StringBenchmark_jackson.java │ │ │ │ ├── codec/ │ │ │ │ │ ├── Codec.java │ │ │ │ │ ├── FastjsonArrayMappingCodec.java │ │ │ │ │ ├── FastjsonBeanToArrayCodec.java │ │ │ │ │ ├── FastjsonCodec.java │ │ │ │ │ ├── FastjsonGenCodec.java │ │ │ │ │ ├── FastjsonManualCodec.java │ │ │ │ │ ├── FastjsonSCodec.java │ │ │ │ │ ├── GsonCodec.java │ │ │ │ │ ├── Jackson2AfterBurnCodec.java │ │ │ │ │ ├── Jackson2Codec.java │ │ │ │ │ ├── JacksonCodec.java │ │ │ │ │ ├── JsonLibCodec.java │ │ │ │ │ ├── JsonSmartCodec.java │ │ │ │ │ └── SimpleJsonCodec.java │ │ │ │ ├── codegen/ │ │ │ │ │ ├── Department.java │ │ │ │ │ ├── DepartmentCodec.java │ │ │ │ │ ├── DepartmentType.java │ │ │ │ │ ├── Employee.java │ │ │ │ │ ├── GenMediaTest.java │ │ │ │ │ ├── GenTest.java │ │ │ │ │ └── MediaContentGenTest.java │ │ │ │ ├── deny/ │ │ │ │ │ └── NotExistsTest.java │ │ │ │ ├── dubbo/ │ │ │ │ │ ├── EnumTest.java │ │ │ │ │ ├── FullAddress.java │ │ │ │ │ ├── HelloServiceImpl.java │ │ │ │ │ ├── Image.java │ │ │ │ │ ├── Person.java │ │ │ │ │ ├── PersonInfo.java │ │ │ │ │ ├── PersonStatus.java │ │ │ │ │ ├── Phone.java │ │ │ │ │ ├── Tiger.java │ │ │ │ │ └── Tigers.java │ │ │ │ ├── entity/ │ │ │ │ │ ├── Company.java │ │ │ │ │ ├── Department.java │ │ │ │ │ ├── Employee.java │ │ │ │ │ ├── Group.java │ │ │ │ │ ├── TestEntity.java │ │ │ │ │ ├── case1/ │ │ │ │ │ │ ├── IntObject_100_Entity.java │ │ │ │ │ │ ├── Int_100_Entity.java │ │ │ │ │ │ ├── LongObject_100_Entity.java │ │ │ │ │ │ ├── Long_100_Entity.java │ │ │ │ │ │ └── String_100_Entity.java │ │ │ │ │ ├── case2/ │ │ │ │ │ │ └── Category.java │ │ │ │ │ └── pagemodel/ │ │ │ │ │ ├── ComponentInstance.java │ │ │ │ │ ├── ComponentInstanceParam.java │ │ │ │ │ ├── LayoutInstance.java │ │ │ │ │ ├── PageInstance.java │ │ │ │ │ ├── RegionEnum.java │ │ │ │ │ ├── RegionInstance.java │ │ │ │ │ ├── SegmentInstance.java │ │ │ │ │ └── WidgetInstance.java │ │ │ │ ├── epubview/ │ │ │ │ │ ├── EpubViewBook.java │ │ │ │ │ ├── EpubViewHotPoint.java │ │ │ │ │ ├── EpubViewHotPointZone.java │ │ │ │ │ ├── EpubViewMetaData.java │ │ │ │ │ ├── EpubViewPage.java │ │ │ │ │ ├── TestKlutz.java │ │ │ │ │ ├── TestKlutz2.java │ │ │ │ │ └── TestKlutz3.java │ │ │ │ ├── generic/ │ │ │ │ │ ├── GenericTypeTest.java │ │ │ │ │ ├── TBean.java │ │ │ │ │ ├── TGen.java │ │ │ │ │ └── TStr.java │ │ │ │ ├── gson/ │ │ │ │ │ └── TestChineseQuote.java │ │ │ │ ├── jackson/ │ │ │ │ │ ├── JacksonInnerClassTest.java │ │ │ │ │ ├── JacksonTest.java │ │ │ │ │ ├── JacksonTypeInfoTest.java │ │ │ │ │ └── JacksonUnwrappedTest.java │ │ │ │ ├── knowissue/ │ │ │ │ │ └── Bug_for_loveflying.java │ │ │ │ ├── performance/ │ │ │ │ │ ├── DecoderPerformanceTest.java │ │ │ │ │ ├── IntArrayEncodePerformanceTest.java │ │ │ │ │ ├── IntegerArrayEncodePerformanceTest.java │ │ │ │ │ ├── IntegerListEncodePerformanceTest.java │ │ │ │ │ ├── JacksonGroupDecoder.java │ │ │ │ │ ├── JacksonGroupParser.java │ │ │ │ │ ├── JacksonPageModelParser.java │ │ │ │ │ ├── JsonitorCollisionTest.java │ │ │ │ │ ├── ObjectDecodePerformanceTest.java │ │ │ │ │ ├── ObjectEncodePerformanceTest.java │ │ │ │ │ ├── PageModelPerformanceTest.java │ │ │ │ │ └── case1/ │ │ │ │ │ ├── GenerateTest.java │ │ │ │ │ ├── IntDecoderPerformanceTest.java │ │ │ │ │ ├── IntObjectDecodePerformanceTest.java │ │ │ │ │ └── IntObjectEncodePerformanceTest.java │ │ │ │ ├── ryu/ │ │ │ │ │ ├── RyuDoubleTest.java │ │ │ │ │ └── RyuFloatTest.java │ │ │ │ ├── tmall/ │ │ │ │ │ ├── EngineResult.java │ │ │ │ │ ├── Head.java │ │ │ │ │ ├── RateResult.java │ │ │ │ │ ├── RateSearchItemDO.java │ │ │ │ │ └── TmallTest.java │ │ │ │ └── vans/ │ │ │ │ ├── VansAnimation.java │ │ │ │ ├── VansData.java │ │ │ │ ├── VansGeometry.java │ │ │ │ ├── VansGeometryData.java │ │ │ │ ├── VansGeometryDataMetaData.java │ │ │ │ ├── VansMetaData.java │ │ │ │ ├── VansObject.java │ │ │ │ └── VansObjectChildren.java │ │ │ ├── derbysoft/ │ │ │ │ └── spitfire/ │ │ │ │ └── fastjson/ │ │ │ │ ├── ABCTest.java │ │ │ │ ├── Generic.java │ │ │ │ ├── Header.java │ │ │ │ ├── TestFastJson.java │ │ │ │ └── dto/ │ │ │ │ ├── AbstractDTO.java │ │ │ │ ├── AbstractRS.java │ │ │ │ ├── AgeQualifyingType.java │ │ │ │ ├── AvailGuaranteeDTO.java │ │ │ │ ├── AvailRoomStayDTO.java │ │ │ │ ├── BathType.java │ │ │ │ ├── CancelPenaltyType.java │ │ │ │ ├── CancelPolicyDTO.java │ │ │ │ ├── CardCode.java │ │ │ │ ├── ChargeItemDTO.java │ │ │ │ ├── ChargeType.java │ │ │ │ ├── ChargeUnit.java │ │ │ │ ├── CompositeType.java │ │ │ │ ├── Currency.java │ │ │ │ ├── DateRangeDTO.java │ │ │ │ ├── ErrorsDTO.java │ │ │ │ ├── FreeMealDTO.java │ │ │ │ ├── FreeMealType.java │ │ │ │ ├── GenericRS.java │ │ │ │ ├── GuaranteeType.java │ │ │ │ ├── GuestCountDTO.java │ │ │ │ ├── HotelAvailRS.java │ │ │ │ ├── HotelAvailRoomStayDTO.java │ │ │ │ ├── HotelRefDTO.java │ │ │ │ ├── InternetDTO.java │ │ │ │ ├── InternetType.java │ │ │ │ ├── LanguageType.java │ │ │ │ ├── MealsIncludedDTO.java │ │ │ │ ├── MealsIncludedType.java │ │ │ │ ├── PaymentType.java │ │ │ │ ├── ProviderChainDTO.java │ │ │ │ ├── RateDTO.java │ │ │ │ ├── RatePlanDTO.java │ │ │ │ ├── ResponseHeader.java │ │ │ │ ├── RoomRateDTO.java │ │ │ │ ├── RoomStayCandidateDTO.java │ │ │ │ ├── RoomTypeDTO.java │ │ │ │ ├── SimpleAmountDTO.java │ │ │ │ ├── SmokingType.java │ │ │ │ ├── StayDateRangeDTO.java │ │ │ │ ├── SuccessDTO.java │ │ │ │ ├── TPAExtensionsDTO.java │ │ │ │ ├── UniqueIDDTO.java │ │ │ │ ├── UniqueIDType.java │ │ │ │ ├── WarningDTO.java │ │ │ │ └── WarningsDTO.java │ │ │ ├── mchange/ │ │ │ │ └── v2/ │ │ │ │ └── c3p0/ │ │ │ │ └── impl/ │ │ │ │ └── PoolBackedDataSourceBase.java │ │ │ └── wheelchair/ │ │ │ ├── parser/ │ │ │ │ └── JSONScannerTest.java │ │ │ └── validate/ │ │ │ ├── testcase_accurate_json.json │ │ │ ├── testcase_colon_error.json │ │ │ ├── testcase_num_error1.json │ │ │ ├── testcase_num_error2.json │ │ │ ├── testcase_quotation_mark_error.json │ │ │ ├── testcase_square_brackets_error.json │ │ │ └── testcase_tfn_error.json │ │ ├── data/ │ │ │ ├── ReprUtil.java │ │ │ └── media/ │ │ │ ├── FieldMapping.java │ │ │ ├── Image.java │ │ │ ├── ImageGenDecoder.java │ │ │ ├── Media.java │ │ │ ├── MediaContent.java │ │ │ ├── MediaContentDeserializer.java │ │ │ ├── MediaContentGenDecoder.java │ │ │ ├── MediaGenDecoder.java │ │ │ └── writeAsArray/ │ │ │ ├── ImageDeserializer.java │ │ │ ├── ImageSerializer.java │ │ │ ├── MediaContentDeserializer.java │ │ │ ├── MediaContentSerializer.java │ │ │ ├── MediaDeserializer.java │ │ │ └── MediaSerializer.java │ │ └── oracle/ │ │ └── sql/ │ │ ├── DATE.java │ │ └── TIMESTAMP.java │ └── resources/ │ ├── 1.txt │ ├── 2.json │ ├── META-INF/ │ │ ├── persistence.xml │ │ └── services/ │ │ └── com.alibaba.fastjson.serializer.AutowiredObjectSerializer │ ├── classicmodels.sql │ ├── com/ │ │ └── alibaba/ │ │ └── json/ │ │ └── bvt/ │ │ └── support/ │ │ ├── jaxrs/ │ │ │ └── mock/ │ │ │ └── resource/ │ │ │ └── applicationContext-rest.xml │ │ └── spring/ │ │ └── mock/ │ │ └── resource/ │ │ ├── applicationContext-mvc1.xml │ │ ├── applicationContext-mvc2.xml │ │ └── applicationContext-mvc3.xml │ ├── config/ │ │ ├── applicationContext-mvc1.xml │ │ ├── applicationContext-mvc2.xml │ │ ├── applicationContext-mvc3.xml │ │ ├── applicationContext-mvc4.xml │ │ ├── applicationContext-mvc5.xml │ │ └── applicationContext-rest.xml │ ├── data/ │ │ ├── media.1.cks │ │ ├── media.1.json │ │ ├── media.2.cks │ │ ├── media.2.json │ │ ├── media.3.cks │ │ └── media.4.cks │ ├── epub.json │ ├── external/ │ │ ├── Demo.clazz │ │ ├── EsbHashMapBean.clazz │ │ ├── EsbListBean.clazz │ │ ├── EsbResultModel.clazz │ │ ├── MockDemoService.clazz │ │ ├── MyEsbResultModel2.clazz │ │ ├── VO.clazz │ │ └── VO2.clazz │ ├── fastjson.properties │ ├── hashcollide.txt │ ├── issue72.json │ ├── issue74.json │ ├── json/ │ │ ├── Bug_0_Test.json │ │ ├── Bug_1_Test.json │ │ ├── Bug_2_Test.json │ │ ├── Bug_for_sanxiao.json │ │ ├── Issue408.json │ │ ├── a.js │ │ ├── book.json │ │ ├── dla_01.json │ │ ├── group.json │ │ ├── int_100.json │ │ ├── int_1000.json │ │ ├── int_10000.json │ │ ├── int_500.json │ │ ├── int_array_100.json │ │ ├── int_array_1000.json │ │ ├── int_array_10000.json │ │ ├── int_array_200.json │ │ ├── int_array_500.json │ │ ├── json_with_comment.json │ │ ├── maiksagill.json │ │ ├── object_f_emptyobj_10000.json │ │ ├── object_f_false_10000.json │ │ ├── object_f_int_1000.json │ │ ├── object_f_int_10000.json │ │ ├── object_f_null_10000.json │ │ ├── object_f_string_10000.json │ │ ├── object_f_true_10000.json │ │ ├── page_model_cached.json │ │ ├── string_array_10000.json │ │ ├── taobao/ │ │ │ └── cart.json │ │ ├── trade.json │ │ ├── wangran.json │ │ ├── yannywang.js │ │ └── yannywang.json │ ├── json.json │ ├── jvmargs │ ├── kotlin/ │ │ ├── A.clazz │ │ ├── ClassWithPair.clazz │ │ ├── ClassWithPairMixedTypes.clazz │ │ ├── ClassWithRanges.clazz │ │ ├── ClassWithTriple.clazz │ │ ├── Class_WithPrimaryAndSecondaryConstructor.clazz │ │ ├── DataClass.clazz │ │ ├── DataClassPropsGeneric.clazz │ │ ├── DataClassSimple.clazz │ │ ├── Issue1488_Server.clazz │ │ ├── Issue1569_User.clazz │ │ ├── Issue1750_ProcessBO.clazz │ │ ├── ObjectA.clazz │ │ ├── Person.clazz │ │ ├── ProjectItemCheckItemRelation1.clazz │ │ ├── ResponseKotlin.clazz │ │ ├── ResponseKotlin2.clazz │ │ ├── issue1526/ │ │ │ └── DataClass.clazz │ │ ├── issue1543/ │ │ │ ├── Cluster.clazz │ │ │ └── User1.clazz │ │ ├── issue1547/ │ │ │ └── Head.clazz │ │ └── zuojing/ │ │ ├── NoticeData.clazz │ │ ├── NoticeDataKt.clazz │ │ └── NoticeData_Companion.clazz │ ├── log4j.properties │ ├── log4j2.xml │ └── wuyexiong.json ├── vtune.sh └── x.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/ci.yaml ================================================ --- name: Java CI on: [push, pull_request] jobs: test: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-18.04, macOS-latest] java: [8] fail-fast: false max-parallel: 4 name: Test JDK ${{ matrix.java }}, ${{ matrix.os }} steps: - uses: actions/checkout@v2 - name: Set up JDK uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} - uses: actions/cache@v2 env: cache-name: cache-maven-modules with: path: ~/.m2/repository key: ${{ runner.os }}-build-${{ env.cache-name }}-maven-${{ hashFiles('**/pom.xml') }} restore-keys: | ${{ runner.os }}-build-${{ env.cache-name }}- ${{ runner.os }}-build- ${{ runner.os }} - name: Test with Maven run: mvn test -B --file pom.xml ================================================ FILE: .gitignore ================================================ /target /.project /.settings /.classpath /.idea /.DS_Store *.iml /src/test/java/com/alibaba/json/bvt/parser/autoType/ /bin/ ================================================ FILE: .gitpod.yml ================================================ tasks: - init: mvn install -DskipTests=true vscode: extensions: - vscjava.vscode-maven@0.21.0:37ZOg7jK2M04yXsE+ItbZg== - GabrielBB.vscode-lombok@1.0.0:fYRHVd+UkrccCfjaRz7jKw== ================================================ FILE: .travis.yml ================================================ language: java jdk: - openjdk8 before_install: - pip install --user codecov after_success: - codecov branches: except: - appveyor cache: directories: - $HOME/.m2 ================================================ FILE: CONTRIBUTING.md ================================================ ## Contributing If you want to contribute to a project and make it better, your help is very welcome. Contributing is also a great way to learn more about social coding on Github, new technologies and their ecosystems, and how to make constructive, helpful bug reports, feature requests and the noblest of all contributions: a good, clean pull request. ### How to make a clean pull request Look for a project's contribution instructions. If there are any, follow them. - Create a personal fork of the project on Github. - Clone the fork on your local machine. Your remote repo on Github is called `origin`. - Add the original repository as a remote called `upstream`. - If you created your fork a while ago be sure to pull upstream changes into your local repository. - Create a new branch to work on! Branch from `develop` if it exists, else from `master`. - Implement/fix your feature, comment your code. - Follow the code style of the project, including indentation. - If the project has tests run them! - Write or adapt tests as needed. - Add or change the documentation as needed. - Create a new branch if necessary. - Push your branch to your fork on Github, the remote `origin`. - From your fork open a pull request in the correct branch. Target the project's `develop` branch if there is one, else go for `master`! - Wait for approval. - Once the pull request is approved and merged you can pull the changes from `upstream` to your local repo and delete your extra branch(es). And last but not least: Always write your commit messages in the present tense. Your commit message should describe what the commit, when applied, does to the code – not what you did to the code. ================================================ FILE: README.md ================================================ # fastjson [![Java CI](https://github.com/alibaba/fastjson/actions/workflows/ci.yaml/badge.svg?branch=master)](https://github.com/alibaba/fastjson/actions/workflows/ci.yaml) [![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) [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/alibaba/fastjson) [![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/fastjson2.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:fastjson2) [![QualityGate](https://quality-gate.com/backend/api/timeline?branchName=master&projectName=alibaba_fastjson)](https://quality-gate.com/dashboard/branches/7816#overview) 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 2.0.x](https://github.com/alibaba/fastjson2/releases) has been released, faster and more secure, we recommend you [upgrade](https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn) to the latest version. ### Fastjson Goals * Provide the best performance on the 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) - [Contributing Code](https://github.com/nschaffner/fastjson/blob/master/CONTRIBUTING.md) - [Frequently Asked Questions](https://github.com/alibaba/fastjson/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98) - FASTJSON 1.x User Upgrade Guid [https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn](https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn ) ## Benchmark * Eishay benchmark https://github.com/eishay/jvm-serializers/wiki * fastjson2 benchmark [https://github.com/alibaba/fastjson2/wiki/fastjson_benchmark](https://github.com/alibaba/fastjson2/wiki/fastjson_benchmark) ## Download - [maven][1] - [the latest JAR][2] [1]: https://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 2.0.31 ``` ## Gradle via JCenter ``` groovy compile 'com.alibaba:fastjson:2.0.28' ``` Please see this [Wiki Download Page][Wiki] for more repository info. [Wiki]: https://github.com/alibaba/fastjson/wiki#download ### *License* Fastjson is released under the [Apache 2.0 license](license.txt). ``` Copyright 1999-2020 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 the 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. ``` ================================================ FILE: SECURITY.md ================================================ # 漏洞奖励计划 ## 报告 如果您认为自己在本程序中发现了任何安全(技术)漏洞,欢迎您通过 https://security.alibaba.com 向我们提交漏洞报告。 如果您报告任何安全漏洞,请注意您可能包含以下信息(合格报告): * git程序URL地址,运行的环境 * 包含必要屏幕截图的详细说明 * 重现漏洞的步骤以及修复漏洞的建议。 * 其他有用信息 ## 处理 ASRC(Alibaba Security Response Center阿里安全响应中心)将尽快审核并回复您的提交内容,并在我们努力修复您提交的漏洞时随时通知您。如有必要,我们可能会与您联系以获取更多信息。 ## 条款和条件 1. 仅接受技术漏洞并对其进行评级 2. 出于安全原因,上报者同意与ASRC合作完成他/她提交的漏洞,不向任何第三方透露任何漏洞信息 3. 如果不止一个人报告相同的安全漏洞,奖励将给予完成合格报告的第一个人 4. 为了保护程序的用户,请在修复之前不要直接提交git的issue,也不要在社区讨论任何漏洞信息 5. 所有奖励和声誉积分将提供给仅向ASRC提交其安全漏洞的上报者 6. 安全漏洞奖励的解释权利归ASRC所有 ## 收集范围 我们的主要收集漏洞类别是: * 服务器端请求伪造(SSRF) * SQL注入 * 拒绝服务攻击 * 远程执行代码(RCE) * XML外部实体攻击(XXE) * 访问控制问题(不安全的直接对象参考问题等) * 敏感目录遍历问题 * 本地文件读取(LFD) * 敏感信息泄露(密钥,Cookie,Session等) ## 奖励 * 可直接导致严重问题的每个漏洞奖励7000元人民币 * 存在限制及需要一定特殊环境下才能利用的问题将给予700-5600元人民币不等的奖励,比如需要用户主动点击才会触发的问题或需要admin权限 * 只有在指定环境下才可以运行的利用将有可能被收纳但不给予奖励,或直接被忽略,比如只在fastjson+linux特定版本才会出现的问题 ## 不在收集范围的报告 * 影响过时浏览器或平台用户的漏洞 * Self-XSS * 会话固定 * 内容欺骗 * 缺少cookie标记 * 混合内容警告 * SSL / TLS问题 * Clickjacking * 基于Flash的漏洞 * 反射文件下载攻击(RFD) * 物理或社会工程攻击 * 未验证自动化工具或扫描仪的结果 * 登录/注销/未认证/低影响CSRF * 需要MITM或物理访问用户设备的攻击 * 与网络协议或行业标准相关的问题 * 不能用于直接攻击的错误信息泄露 * 缺少与安全相关的HTTP标头等 # Vulnerability Reward Program ## Reporting If you believe you have found any security (technical) vulnerability in the Program, you are welcome to submit a vulnerability report to us at https://security.alibaba.com In the case of reporting any security vulnerability, please note that you may include the following information (Qualified Reporting): * The git program URL and running version * A detailed description with applicable screenshots * Steps to reproduce the vulnerability/exploit and your advice to fix it * Other useful information ## Processing ASRC (Alibaba Security Response Center) will review and respond as quickly as possible to your submission, and keep you informed as we work to fix the vulnerability you submitted. We may contact you for further information, if necessary. ## Terms and Conditions 1. ONLY technical vulnerabilities will be accepted and rated. 2. For security reasons, reporters agree to cooperate with ASRC exclusively on the vulnerability he/she submitted and not disclose any information of vulnerability to any third-parties. 3. In the case that more than one person report the same security vulnerability, the reward will be given to the first person who accomplish a Qualified Reporting. 4. To protect users of the program, please do not directly submit issue on github or discuss anything with the community. 5. All Rewards and Reputation Credits are given to the reporters who submit his/her security vulnerabilities ONLY to ASRC. 6. All rights for the security vulnerability rewards are reserved by ASRC. ## Scope of Collecting The main categories of vulnerabilities that we are sincerely looking for are: * Server-Side Request Forgery (SSRF) * SQL Injection * Denial of Service Attack * Remote Code Execution (RCE) * XML External Entity Attacks (XXE) * Access Control Issues (Insecure Direct Object Reference issues, etc.) * Directory Traversal Issues * Local File Disclosure (LFD) * Sensitive Information Leakage (Key, Cookie, Session etc.) ## Reward * $1,000 for one valid report * $100-$800 for Vuls which is limited. For example, Vuls that need user interactions or administrator authority * Vuls which only work on the special version will be accepted but no reward, or directly rejected. For example, Vul runs only on a special linux version ## Ineligible Reports * Vulnerabilities affecting users of outdated browsers or platforms * "Self" XSS * Session fixation * Content Spoofing * Missing cookie flags * Mixed content warnings * SSL/TLS best practices * Clickjacking/UI redressing * Flash-based vulnerabilities * Reflected file download attacks (RFD) * Physical or social engineering attacks * Unverified Results of automated tools or scanners * Login/logout/unauthenticated/low-impact CSRF * Attacks requiring MITM or physical access to a user's device * Issues related to networking protocols or industry standards * Error information disclosure that cannot be used to make a direct attack * Missing security-related HTTP headers which do not lead directly to a vulnerability ================================================ FILE: license.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 1999-2019 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. ================================================ FILE: pom.xml ================================================ 4.0.0 org.sonatype.oss oss-parent 9 com.alibaba fastjson 1.2.84-SNAPSHOT jar fastjson Fastjson is a JSON processor (JSON parser + JSON generator) written in Java https://github.com/alibaba/fastjson 2012 4.13.1 4.13.1 true true true true UTF-8 1.5 https://github.com/alibaba/fastjson scm:git:https://git@github.com/alibaba/fastjson.git 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 Omega-Ariston Jiechuan Chen 654815312@qq.com Apache 2 http://www.apache.org/licenses/LICENSE-2.0.txt repo A business-friendly OSS license org.apache.maven.plugins maven-compiler-plugin 3.8.0 UTF-8 ${jdk.version} ${jdk.version} org.codehaus.plexus plexus-compiler-javac 2.7 org.apache.maven.plugins maven-source-plugin 3.2.0 attach-sources jar-no-fork true org.apache.maven.plugins maven-surefire-plugin 3.0.0-M5 **/bvt/**/*.java org.apache.maven.plugins maven-javadoc-plugin 3.2.0 attach-javadoc jar ${javadoc.skip} public UTF-8 UTF-8 UTF-8 http://docs.oracle.com/javase/6/docs/api org.apache.maven.plugins maven-gpg-plugin 1.6 ${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.5.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 joda-time joda-time 2.10 provided net.sf.trove4j core 3.1.0 provided org.javamoney.moneta moneta-core 1.3 provided io.airlift slice 0.36 provided com.google.protobuf protobuf-java 3.11.0 provided com.google.protobuf protobuf-java-util 3.11.0 provided org.jacoco jacoco-maven-plugin 0.7.6.201602180812 provided org.eclipse.jetty jetty-server 9.4.17.v20190418 test true org.eclipse.jetty jetty-webapp 9.4.17.v20190418 test true junit junit ${junit.version} test com.fasterxml.jackson.core jackson-databind 2.10.0 test com.fasterxml.jackson.module jackson-module-afterburner 2.10.0 test com.fasterxml.jackson.module jackson-module-kotlin 2.9.10 test cglib cglib-nodep 2.2.2 test com.fasterxml.jackson.jaxrs jackson-jaxrs-json-provider 2.9.10 test com.googlecode.json-simple json-simple 1.1.1 test commons-io commons-io 2.7 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.4.8 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 2.1.2.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.5 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.4.21 test org.jetbrains.kotlin kotlin-reflect 1.4.21 test org.springframework.security spring-security-web 5.2.10.RELEASE test org.apache.commons commons-collections4 4.1 test org.mockito mockito-all 1.10.19 test org.powermock powermock-module-junit4 1.6.6 test com.diffblue deeptestutils 1.1.0 test org.projectlombok lombok 1.18.4 test org.openjdk.jmh jmh-core 1.21 test org.openjdk.jmh jmh-generator-annprocess 1.21 test org.springframework.security.oauth spring-security-oauth2 2.3.5.RELEASE commons-codec commons-codec jackson jackson-mapper-asl jackson jackson-core-asl test org.gitlab4j gitlab4j-api 4.8.42 test org.json json 20180130 test com.chinamobile.cmos sms-core 2.1.9 test github_actions env.GITHUB_ACTIONS true org.jacoco jacoco-maven-plugin 0.8.7 prepare-agent report test report ================================================ FILE: rfc4627.txt ================================================ Network Working Group D. Crockford Request for Comments: 4627 JSON.org Category: Informational July 2006 The application/json Media Type for JavaScript Object Notation (JSON) Status of This Memo This memo provides information for the Internet community. It does not specify an Internet standard of any kind. Distribution of this memo is unlimited. Copyright Notice Copyright (C) The Internet Society (2006). Abstract JavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format. It was derived from the ECMAScript Programming Language Standard. JSON defines a small set of formatting rules for the portable representation of structured data. 1. Introduction JavaScript Object Notation (JSON) is a text format for the serialization of structured data. It is derived from the object literals of JavaScript, as defined in the ECMAScript Programming Language Standard, Third Edition [ECMA]. JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays). A string is a sequence of zero or more Unicode characters [UNICODE]. An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array. An array is an ordered sequence of zero or more values. The terms "object" and "array" come from the conventions of JavaScript. JSON's design goals were for it to be minimal, portable, textual, and a subset of JavaScript. Crockford Informational [Page 1] RFC 4627 JSON July 2006 1.1. Conventions Used in This Document The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119]. The grammatical rules in this document are to be interpreted as described in [RFC4234]. 2. JSON Grammar A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names. A JSON text is a serialized object or array. JSON-text = object / array These are the six structural characters: begin-array = ws %x5B ws ; [ left square bracket begin-object = ws %x7B ws ; { left curly bracket end-array = ws %x5D ws ; ] right square bracket end-object = ws %x7D ws ; } right curly bracket name-separator = ws %x3A ws ; : colon value-separator = ws %x2C ws ; , comma Insignificant whitespace is allowed before or after any of the six structural characters. ws = *( %x20 / ; Space %x09 / ; Horizontal tab %x0A / ; Line feed or New line %x0D ; Carriage return ) 2.1. Values A JSON value MUST be an object, array, number, or string, or one of the following three literal names: false null true Crockford Informational [Page 2] RFC 4627 JSON July 2006 The literal names MUST be lowercase. No other literal names are allowed. value = false / null / true / object / array / number / string false = %x66.61.6c.73.65 ; false null = %x6e.75.6c.6c ; null true = %x74.72.75.65 ; true 2.2. Objects An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique. object = begin-object [ member *( value-separator member ) ] end-object member = string name-separator value 2.3. Arrays An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas. array = begin-array [ value *( value-separator value ) ] end-array 2.4. Numbers The representation of numbers is similar to that used in most programming languages. A number contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Octal and hex forms are not allowed. Leading zeros are not allowed. A fraction part is a decimal point followed by one or more digits. An exponent part begins with the letter E in upper or lowercase, which may be followed by a plus or minus sign. The E and optional sign are followed by one or more digits. Numeric values that cannot be represented as sequences of digits (such as Infinity and NaN) are not permitted. Crockford Informational [Page 3] RFC 4627 JSON July 2006 number = [ minus ] int [ frac ] [ exp ] decimal-point = %x2E ; . digit1-9 = %x31-39 ; 1-9 e = %x65 / %x45 ; e E exp = e [ minus / plus ] 1*DIGIT frac = decimal-point 1*DIGIT int = zero / ( digit1-9 *DIGIT ) minus = %x2D ; - plus = %x2B ; + zero = %x30 ; 0 2.5. Strings The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F). Any character may be escaped. If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point. The hexadecimal letters A though F can be upper or lowercase. So, for example, a string containing only a single reverse solidus character may be represented as "\u005C". Alternatively, there are two-character sequence escape representations of some popular characters. So, for example, a string containing only a single reverse solidus character may be represented more compactly as "\\". To escape an extended character that is not in the Basic Multilingual Plane, the character is represented as a twelve-character sequence, encoding the UTF-16 surrogate pair. So, for example, a string containing only the G clef character (U+1D11E) may be represented as "\uD834\uDD1E". Crockford Informational [Page 4] RFC 4627 JSON July 2006 string = quotation-mark *char quotation-mark char = unescaped / escape ( %x22 / ; " quotation mark U+0022 %x5C / ; \ reverse solidus U+005C %x2F / ; / solidus U+002F %x62 / ; b backspace U+0008 %x66 / ; f form feed U+000C %x6E / ; n line feed U+000A %x72 / ; r carriage return U+000D %x74 / ; t tab U+0009 %x75 4HEXDIG ) ; uXXXX U+XXXX escape = %x5C ; \ quotation-mark = %x22 ; " unescaped = %x20-21 / %x23-5B / %x5D-10FFFF 3. Encoding JSON text SHALL be encoded in Unicode. The default encoding is UTF-8. Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets. 00 00 00 xx UTF-32BE 00 xx 00 xx UTF-16BE xx 00 00 00 UTF-32LE xx 00 xx 00 UTF-16LE xx xx xx xx UTF-8 4. Parsers A JSON parser transforms a JSON text into another representation. A JSON parser MUST accept all texts that conform to the JSON grammar. A JSON parser MAY accept non-JSON forms or extensions. An implementation may set limits on the size of texts that it accepts. An implementation may set limits on the maximum depth of nesting. An implementation may set limits on the range of numbers. An implementation may set limits on the length and character contents of strings. Crockford Informational [Page 5] RFC 4627 JSON July 2006 5. Generators A JSON generator produces JSON text. The resulting text MUST strictly conform to the JSON grammar. 6. IANA Considerations The MIME media type for JSON text is application/json. Type name: application Subtype name: json Required parameters: n/a Optional parameters: n/a Encoding considerations: 8bit if UTF-8; binary if UTF-16 or UTF-32 JSON may be represented using UTF-8, UTF-16, or UTF-32. When JSON is written in UTF-8, JSON is 8bit compatible. When JSON is written in UTF-16 or UTF-32, the binary content-transfer-encoding must be used. Security considerations: Generally there are security issues with scripting languages. JSON is a subset of JavaScript, but it is a safe subset that excludes assignment and invocation. A JSON text can be safely passed into JavaScript's eval() function (which compiles and executes a string) if all the characters not enclosed in strings are in the set of characters that form JSON tokens. This can be quickly determined in JavaScript with two regular expressions and calls to the test and replace methods. var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test( text.replace(/"(\\.|[^"\\])*"/g, ''))) && eval('(' + text + ')'); Interoperability considerations: n/a Published specification: RFC 4627 Crockford Informational [Page 6] RFC 4627 JSON July 2006 Applications that use this media type: JSON has been used to exchange data between applications written in all of these programming languages: ActionScript, C, C#, ColdFusion, Common Lisp, E, Erlang, Java, JavaScript, Lua, Objective CAML, Perl, PHP, Python, Rebol, Ruby, and Scheme. Additional information: Magic number(s): n/a File extension(s): .json Macintosh file type code(s): TEXT Person & email address to contact for further information: Douglas Crockford douglas@crockford.com Intended usage: COMMON Restrictions on usage: none Author: Douglas Crockford douglas@crockford.com Change controller: Douglas Crockford douglas@crockford.com 7. Security Considerations See Security Considerations in Section 6. 8. Examples This is a JSON object: { "Image": { "Width": 800, "Height": 600, "Title": "View from 15th Floor", "Thumbnail": { "Url": "http://www.example.com/image/481989943", "Height": 125, "Width": "100" }, "IDs": [116, 943, 234, 38793] Crockford Informational [Page 7] RFC 4627 JSON July 2006 } } Its Image member is an object whose Thumbnail member is an object and whose IDs member is an array of numbers. This is a JSON array containing two objects: [ { "precision": "zip", "Latitude": 37.7668, "Longitude": -122.3959, "Address": "", "City": "SAN FRANCISCO", "State": "CA", "Zip": "94107", "Country": "US" }, { "precision": "zip", "Latitude": 37.371991, "Longitude": -122.026020, "Address": "", "City": "SUNNYVALE", "State": "CA", "Zip": "94085", "Country": "US" } ] 9. References 9.1. Normative References [ECMA] European Computer Manufacturers Association, "ECMAScript Language Specification 3rd Edition", December 1999, . [RFC0020] Cerf, V., "ASCII format for network interchange", RFC 20, October 1969. [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997. [RFC4234] Crocker, D. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", RFC 4234, October 2005. Crockford Informational [Page 8] RFC 4627 JSON July 2006 [UNICODE] The Unicode Consortium, "The Unicode Standard Version 4.0", 2003, . Author's Address Douglas Crockford JSON.org EMail: douglas@crockford.com Crockford Informational [Page 9] RFC 4627 JSON July 2006 Full Copyright Statement Copyright (C) The Internet Society (2006). This document is subject to the rights, licenses and restrictions contained in BCP 78, and except as set forth therein, the authors retain all their rights. This document and the information contained herein are provided on an "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Intellectual Property The IETF takes no position regarding the validity or scope of any Intellectual Property Rights or other rights that might be claimed to pertain to the implementation or use of the technology described in this document or the extent to which any license under such rights might or might not be available; nor does it represent that it has made any independent effort to identify any such rights. Information on the procedures with respect to rights in RFC documents can be found in BCP 78 and BCP 79. Copies of IPR disclosures made to the IETF Secretariat and any assurances of licenses to be made available, or the result of an attempt made to obtain a general license or permission for the use of such proprietary rights by implementers or users of this specification can be obtained from the IETF on-line IPR repository at http://www.ietf.org/ipr. The IETF invites any interested party to bring to its attention any copyrights, patents or patent applications, or other proprietary rights that may cover technology that may be required to implement this standard. Please address the information to the IETF at ietf-ipr@ietf.org. Acknowledgement Funding for the RFC Editor function is provided by the IETF Administrative Support Activity (IASA). Crockford Informational [Page 10] ================================================ FILE: src/main/java/META-INF/MANIFEST.MF ================================================ Manifest-Version: 1.1.35 Class-Path: ================================================ FILE: src/main/java/com/alibaba/fastjson/JSON.java ================================================ /* * 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.*; import java.lang.reflect.Array; 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 java.util.concurrent.ConcurrentHashMap; import java.util.zip.GZIPInputStream; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.parser.*; 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; /** * 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 int DEFAULT_PARSER_FEATURE; public static int DEFAULT_GENERATE_FEATURE; private static final ConcurrentHashMap mixInsMapper = new ConcurrentHashMap(16); 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; } static { int features = 0; features |= SerializerFeature.QuoteFieldNames.getMask(); features |= SerializerFeature.SkipTransientField.getMask(); features |= SerializerFeature.WriteEnumUsingName.getMask(); features |= SerializerFeature.SortField.getMask(); DEFAULT_GENERATE_FEATURE = features; config(IOUtils.DEFAULT_PROPERTIES); } private static void config(Properties properties) { { String featuresProperty = properties.getProperty("fastjson.serializerFeatures.MapSortField"); int mask = SerializerFeature.MapSortField.getMask(); if ("true".equals(featuresProperty)) { DEFAULT_GENERATE_FEATURE |= mask; } else if ("false".equals(featuresProperty)) { DEFAULT_GENERATE_FEATURE &= ~mask; } } { if ("true".equals(properties.getProperty("parser.features.NonStringKeyAsString"))) { DEFAULT_PARSER_FEATURE |= Feature.NonStringKeyAsString.getMask(); } } { if ("true".equals(properties.getProperty("parser.features.ErrorOnEnumNotMatch")) || "true".equals(properties.getProperty("fastjson.parser.features.ErrorOnEnumNotMatch"))) { DEFAULT_PARSER_FEATURE |= Feature.ErrorOnEnumNotMatch.getMask(); } } { if ("false".equals(properties.getProperty("fastjson.asmEnable"))) { ParserConfig.global.setAsmEnable(false); SerializeConfig.globalInstance.setAsmEnable(false); } } } /** * 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.68 */ public static Object parse(String text, ParserConfig config, Feature... features) { int featureValues = DEFAULT_PARSER_FEATURE; for (Feature feature : features) { featureValues = Feature.config(featureValues, feature, true); } return parse(text, config, featureValues); } /** * * @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 parser features * @return an object of type T from the string */ @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 || input.length() == 0) { 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) { return (T) parseObject(bytes, offset, len, charset, clazz, ParserConfig.global, null, DEFAULT_PARSER_FEATURE, features); } /** * @since 1.2.55 */ @SuppressWarnings("unchecked") public static T parseObject(byte[] bytes, Charset charset, Type clazz, ParserConfig config, ParseProcess processor, int featureValues, Feature... features) { return (T) parseObject(bytes, 0, bytes.length, charset, clazz, config, processor, featureValues, features); } /** * @since 1.2.55 */ @SuppressWarnings("unchecked") public static T parseObject(byte[] bytes, int offset, int len, Charset charset, Type clazz, ParserConfig config, ParseProcess processor, int featureValues, Feature... features) { if (charset == null) { charset = IOUtils.UTF8; } String strVal = null; if (charset == IOUtils.UTF8) { char[] chars = allocateChars(bytes.length); int chars_len = IOUtils.decodeUTF8(bytes, offset, len, chars); if (chars_len < 0) { InputStreamReader gzipReader = null; try { gzipReader = new InputStreamReader( new GZIPInputStream( new ByteArrayInputStream(bytes, offset, len)), "UTF-8"); strVal = IOUtils.readAll(gzipReader); } catch (Exception ex) { return null; } finally { IOUtils.close(gzipReader); } } if (strVal == null && chars_len < 0) { return null; } if (strVal == 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, config, processor, featureValues, 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 { return (T) parseObject(is, charset, type, ParserConfig.global, features); } /** * @since 1.2.55 */ @SuppressWarnings("unchecked") public static T parseObject(InputStream is, // Charset charset, // Type type, // ParserConfig config, // Feature... features) throws IOException { return (T) parseObject(is, charset, type, config, null, DEFAULT_PARSER_FEATURE, features); } /** * @since 1.2.55 */ @SuppressWarnings("unchecked") public static T parseObject(InputStream is, // Charset charset, // Type type, // ParserConfig config, // ParseProcess processor, // int featureValues, // 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, config, processor, featureValues, features); } public static T parseObject(String text, Class clazz) { return parseObject(text, clazz, new Feature[0]); } public static JSONArray parseArray(String text) { return parseArray(text, ParserConfig.global); } public static JSONArray parseArray(String text, ParserConfig parserConfig) { if (text == null) { return null; } DefaultJSONParser parser = new DefaultJSONParser(text, parserConfig); JSONArray array; JSONLexer lexer = parser.lexer; if (lexer.token() == JSONToken.NULL) { lexer.nextToken(); array = null; } else if (lexer.token() == JSONToken.EOF && lexer.isBlankInput()) { array = null; } else { array = new JSONArray(); parser.parseArray(array); parser.handleResovleTask(array); } parser.close(); return array; } public static List parseArray(String text, Class clazz) { return parseArray(text, clazz, ParserConfig.global); } public static List parseArray(String text, Class clazz, ParserConfig config) { if (text == null) { return null; } List list; DefaultJSONParser parser = new DefaultJSONParser(text, config); 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) { return parseArray(text, types, ParserConfig.global); } public static List parseArray(String text, Type[] types, ParserConfig config) { if (text == null) { return null; } List list; DefaultJSONParser parser = new DefaultJSONParser(text, config); 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); String outString = out.toString(); int len = outString.length(); if (len > 0 && outString.charAt(len -1) == '.' && object instanceof Number && !out.isEnabled(SerializerFeature.WriteClassName)) { return outString.substring(0, len - 1); } return outString; } 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) { return toJSONBytes(object, config, filters, null, defaultFeatures, features); } /** * @since 1.2.55 */ public static byte[] toJSONBytes(Object object, SerializeConfig config, SerializeFilter[] filters, String dateFormat, int defaultFeatures, SerializerFeature... features) { return toJSONBytes(IOUtils.UTF8, object, config, filters, dateFormat, defaultFeatures, features); } /** * @since 1.2.55 */ public static byte[] toJSONBytes(Charset charset, // 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.toBytes(charset); } finally { out.close(); } } /** * Use the date format in FastJsonConfig to serialize JSON * * @param dateFormat the date format in FastJsonConfigs * @since 1.2.55 */ public static byte[] toJSONBytesWithFastJsonConfig(Charset charset, // 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.setFastJsonConfigDateFormatPattern(dateFormat); serializer.config(SerializerFeature.WriteDateUseDateFormat, true); } if (filters != null) { for (SerializeFilter filter : filters) { serializer.addFilter(filter); } } serializer.write(object); return out.toBytes(charset); } 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(); } } public static final int writeJSONStringWithFastJsonConfig(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.setFastJsonConfigDateFormatPattern(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(); } } /** * @since 1.2.57 */ public String toString(SerializerFeature... features) { SerializeWriter out = new SerializeWriter(null, JSON.DEFAULT_GENERATE_FEATURE, features); 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(), config); 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, config); 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; JSONType jsonType = javaBeanSerializer.getJSONType(); boolean ordered = false; if (jsonType != null) { for (SerializerFeature serializerFeature : jsonType.serialzeFeatures()) { if (serializerFeature == SerializerFeature.SortField || serializerFeature == SerializerFeature.MapSortField) { ordered = true; } } } JSONObject json = new JSONObject(ordered); try { Map values = javaBeanSerializer.getFieldValuesMap(javaObject); for (Map.Entry entry : values.entrySet()) { json.put(entry.getKey(), toJSON(entry.getValue(), config)); } } catch (Exception e) { throw new JSONException("toJSON error", e); } return json; } String text = JSON.toJSONString(javaObject, config); 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) { if (clazz == JSONArray.class || clazz == JSON.class || clazz == Collection.class || clazz == List.class) { return (T) this; } 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; } /** * @deprecated Please use {@link com.alibaba.fastjson.JSONValidator} instead. */ public static boolean isValid(String str) { if (str == null || str.length() == 0) { return false; } JSONScanner lexer = new JSONScanner(str); try { lexer.nextToken(); final int token = lexer.token(); switch (token) { case JSONToken.LBRACE: if (lexer.getCurrent() == JSONLexer.EOI) { return false; } lexer.skipObject(true); break; case JSONToken.LBRACKET: lexer.skipArray(true); break; case JSONToken.LITERAL_INT: case JSONToken.LITERAL_STRING: case JSONToken.LITERAL_FLOAT: case JSONToken.LITERAL_ISO8601_DATE: case JSONToken.NULL: case JSONToken.TRUE: case JSONToken.FALSE: lexer.nextToken(); break; default: return false; } return lexer.token() == JSONToken.EOF; } catch (Exception ex) { return false; } finally { lexer.close(); } } /** * @deprecated Please use {@link com.alibaba.fastjson.JSONValidator} instead. */ public static boolean isValidObject(String str) { if (str == null || str.length() == 0) { return false; } JSONScanner lexer = new JSONScanner(str); try { lexer.nextToken(); final int token = lexer.token(); if (token == JSONToken.LBRACE) { if (lexer.getCurrent() == JSONLexer.EOI) { return false; } lexer.skipObject(true); return lexer.token() == JSONToken.EOF; } return false; } catch (Exception ex) { return false; } finally { lexer.close(); } } /** * @deprecated Please use {@link com.alibaba.fastjson.JSONValidator} instead. */ public static boolean isValidArray(String str) { if (str == null || str.length() == 0) { return false; } JSONScanner lexer = new JSONScanner(str); try { lexer.nextToken(); final int token = lexer.token(); if (token == JSONToken.LBRACKET) { lexer.skipArray(true); return lexer.token() == JSONToken.EOF; } return false; } catch (Exception ex) { return false; } finally { lexer.close(); } } public static void handleResovleTask(DefaultJSONParser parser, T value) { parser.handleResovleTask(value); } public static void addMixInAnnotations(Type target, Type mixinSource) { if (target != null && mixinSource != null) { mixInsMapper.put(target, mixinSource); } } public static void removeMixInAnnotations(Type target) { if (target != null) { mixInsMapper.remove(target); } } public static void clearMixInAnnotations() { mixInsMapper.clear(); } public static Type getMixInAnnotations(Type target) { if (target != null) { return mixInsMapper.get(target); } return null; } public final static String VERSION = "1.2.84"; } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONArray.java ================================================ /* * 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 static com.alibaba.fastjson.util.TypeUtils.castToBigDecimal; 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.castToDate; import static com.alibaba.fastjson.util.TypeUtils.castToDouble; import static com.alibaba.fastjson.util.TypeUtils.castToFloat; import static com.alibaba.fastjson.util.TypeUtils.castToInt; import static com.alibaba.fastjson.util.TypeUtils.castToLong; import static com.alibaba.fastjson.util.TypeUtils.castToShort; import static com.alibaba.fastjson.util.TypeUtils.castToSqlDate; import static com.alibaba.fastjson.util.TypeUtils.castToString; import static com.alibaba.fastjson.util.TypeUtils.castToTimestamp; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.util.TypeUtils; /** * @author wenshao[szujobs@hotmail.com] */ 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(); } public JSONArray(List list){ if (list == null){ throw new IllegalArgumentException("list is null."); } this.list = list; } 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(); } public boolean isEmpty() { return list.isEmpty(); } public boolean contains(Object o) { return list.contains(o); } public Iterator iterator() { return list.iterator(); } public Object[] toArray() { return list.toArray(); } public T[] toArray(T[] a) { return list.toArray(a); } 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); } 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); } public int lastIndexOf(Object o) { return list.lastIndexOf(o); } public ListIterator listIterator() { return list.listIterator(); } public ListIterator listIterator(int index) { return list.listIterator(index); } public List subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } public Object get(int index) { return list.get(index); } public JSONObject getJSONObject(int index) { Object value = list.get(index); if (value instanceof JSONObject) { return (JSONObject) value; } if (value instanceof Map) { return new JSONObject((Map) value); } return (JSONObject) toJSON(value); } public JSONArray getJSONArray(int index) { Object value = list.get(index); if (value instanceof JSONArray) { return (JSONArray) value; } if (value instanceof List) { return new JSONArray((List) value); } return (JSONArray) toJSON(value); } public T getObject(int index, Class clazz) { Object obj = list.get(index); 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); if (value == null) { return null; } return castToBoolean(value); } public boolean getBooleanValue(int index) { Object value = get(index); if (value == null) { return false; } return castToBoolean(value).booleanValue(); } public Byte getByte(int index) { Object value = get(index); return castToByte(value); } public byte getByteValue(int index) { Object value = get(index); Byte byteVal = castToByte(value); if (byteVal == null) { return 0; } return byteVal; } public Short getShort(int index) { Object value = get(index); return castToShort(value); } public short getShortValue(int index) { Object value = get(index); Short shortVal = castToShort(value); if (shortVal == null) { return 0; } return shortVal; } public Integer getInteger(int index) { Object value = get(index); return castToInt(value); } public int getIntValue(int index) { Object value = get(index); Integer intVal = castToInt(value); if (intVal == null) { return 0; } return intVal; } public Long getLong(int index) { Object value = get(index); return castToLong(value); } public long getLongValue(int index) { Object value = get(index); Long longVal = castToLong(value); if (longVal == null) { return 0L; } return longVal; } public Float getFloat(int index) { Object value = get(index); return castToFloat(value); } public float getFloatValue(int index) { Object value = get(index); Float floatValue = castToFloat(value); if (floatValue == null) { return 0F; } return floatValue; } public Double getDouble(int index) { Object value = get(index); return castToDouble(value); } public double getDoubleValue(int index) { Object value = get(index); Double doubleValue = castToDouble(value); if (doubleValue == null) { return 0D; } return doubleValue; } public BigDecimal getBigDecimal(int index) { Object value = get(index); return castToBigDecimal(value); } public BigInteger getBigInteger(int index) { Object value = get(index); return castToBigInteger(value); } public String getString(int index) { Object value = get(index); return castToString(value); } public java.util.Date getDate(int index) { Object value = get(index); return castToDate(value); } public Object getSqlDate(int index) { Object value = get(index); return castToSqlDate(value); } public Object getTimestamp(int index) { Object value = get(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) { if (this == obj) { return true; } if (obj instanceof JSONArray) { return this.list.equals(((JSONArray) obj).list); } return this.list.equals(obj); } public int hashCode() { return this.list.hashCode(); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONAware.java ================================================ /* * 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; /** * Beans that support customized output of JSON text shall implement this interface. * * @author wenshao[szujobs@hotmail.com] */ public interface JSONAware { /** * @return JSON text */ String toJSONString(); } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONException.java ================================================ /* * Copyright 1999-2019 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; /** * @author wenshao[szujobs@hotmail.com] */ @SuppressWarnings("serial") public class JSONException extends RuntimeException { public JSONException() { super(); } public JSONException(String message) { super(message); } public JSONException(String message, Throwable cause) { super(message, cause); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONObject.java ================================================ /* * 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 static com.alibaba.fastjson.util.TypeUtils.castToBigDecimal; 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; import static com.alibaba.fastjson.util.TypeUtils.castToInt; import static com.alibaba.fastjson.util.TypeUtils.castToLong; import static com.alibaba.fastjson.util.TypeUtils.castToShort; import static com.alibaba.fastjson.util.TypeUtils.castToSqlDate; import static com.alibaba.fastjson.util.TypeUtils.castToTimestamp; import java.io.*; import java.lang.reflect.Field; 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.*; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.util.TypeUtils; /** * @author wenshao[szujobs@hotmail.com] */ public class JSONObject extends JSON implements Map, Cloneable, Serializable, InvocationHandler { private static final long serialVersionUID = 1L; private static final int DEFAULT_INITIAL_CAPACITY = 16; private final Map map; public JSONObject(){ this(DEFAULT_INITIAL_CAPACITY, false); } public JSONObject(Map map){ if (map == null) { throw new IllegalArgumentException("map is null."); } this.map = map; } public JSONObject(boolean ordered){ this(DEFAULT_INITIAL_CAPACITY, ordered); } public JSONObject(int initialCapacity){ this(initialCapacity, false); } public JSONObject(int initialCapacity, boolean ordered){ if (ordered) { map = new LinkedHashMap(initialCapacity); } else { map = new HashMap(initialCapacity); } } public int size() { return map.size(); } public boolean isEmpty() { return map.isEmpty(); } public boolean containsKey(Object key) { boolean result = map.containsKey(key); if (!result) { if (key instanceof Number || key instanceof Character || key instanceof Boolean || key instanceof UUID ) { result = map.containsKey(key.toString()); } } return result; } public boolean containsValue(Object value) { return map.containsValue(value); } public Object get(Object key) { Object val = map.get(key); if (val == null) { if (key instanceof Number || key instanceof Character || key instanceof Boolean || key instanceof UUID ) { val = map.get(key.toString()); } } return val; } public Object getOrDefault(Object key, Object defaultValue) { Object v; return ((v = get(key)) != null) ? v : defaultValue; } public JSONObject getJSONObject(String key) { Object value = map.get(key); if (value instanceof JSONObject) { return (JSONObject) value; } if (value instanceof Map) { return new JSONObject((Map) value); } if (value instanceof String) { return JSON.parseObject((String) value); } return (JSONObject) toJSON(value); } public JSONArray getJSONArray(String key) { Object value = map.get(key); if (value instanceof JSONArray) { return (JSONArray) value; } if (value instanceof List) { return new JSONArray((List) value); } if (value instanceof String) { return (JSONArray) JSON.parse((String) value); } return (JSONArray) toJSON(value); } public T getObject(String key, Class clazz) { Object obj = map.get(key); 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); if (value == null) { return null; } return castToBoolean(value); } 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 booleanVal.booleanValue(); } public Byte getByte(String key) { Object value = get(key); return castToByte(value); } public byte getByteValue(String key) { Object value = get(key); Byte byteVal = castToByte(value); if (byteVal == null) { return 0; } return byteVal.byteValue(); } public Short getShort(String key) { Object value = get(key); return castToShort(value); } public short getShortValue(String key) { Object value = get(key); Short shortVal = castToShort(value); if (shortVal == null) { return 0; } return shortVal.shortValue(); } public Integer getInteger(String key) { Object value = get(key); return castToInt(value); } public int getIntValue(String key) { Object value = get(key); Integer intVal = castToInt(value); if (intVal == null) { return 0; } return intVal.intValue(); } public Long getLong(String key) { Object value = get(key); return castToLong(value); } public long getLongValue(String key) { Object value = get(key); Long longVal = castToLong(value); if (longVal == null) { return 0L; } return longVal.longValue(); } public Float getFloat(String key) { Object value = get(key); return castToFloat(value); } public float getFloatValue(String key) { Object value = get(key); Float floatValue = castToFloat(value); if (floatValue == null) { return 0F; } return floatValue.floatValue(); } public Double getDouble(String key) { Object value = get(key); return castToDouble(value); } public double getDoubleValue(String key) { Object value = get(key); Double doubleValue = castToDouble(value); if (doubleValue == null) { return 0D; } return doubleValue.doubleValue(); } public BigDecimal getBigDecimal(String key) { Object value = get(key); return castToBigDecimal(value); } public BigInteger getBigInteger(String key) { Object value = get(key); return castToBigInteger(value); } public String getString(String key) { Object value = get(key); if (value == null) { return null; } return value.toString(); } public Date getDate(String key) { Object value = get(key); return castToDate(value); } public Object getSqlDate(String key) { Object value = get(key); return castToSqlDate(value); } public Object getTimestamp(String key) { Object value = get(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(); } public Collection values() { return map.values(); } public Set> entrySet() { return map.entrySet(); } @Override public JSONObject clone() { return new JSONObject(map instanceof LinkedHashMap // ? new LinkedHashMap(map) // : new HashMap(map) ); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof JSONObject) { return this.map.equals(((JSONObject) obj).map); } return this.map.equals(obj); } @Override 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 = TypeUtils.getAnnotation(method, 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 = TypeUtils.getAnnotation(method, 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; } public T toJavaObject(Class clazz) { if (clazz == Map.class || clazz == JSONObject.class || clazz == JSON.class) { return (T) this; } if (clazz == Object.class && !containsKey(JSON.DEFAULT_TYPE_KEY)) { return (T) this; } return TypeUtils.castToJavaBean(this, clazz, ParserConfig.getGlobalInstance()); } public T toJavaObject(Class clazz, ParserConfig config, int features) { if (clazz == Map.class) { return (T) this; } if (clazz == Object.class && !containsKey(JSON.DEFAULT_TYPE_KEY)) { return (T) this; } return TypeUtils.castToJavaBean(this, clazz, config); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONPObject.java ================================================ 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 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 & SerializerFeature.BrowserSecure.mask) != 0 || (writer.isEnabled(SerializerFeature.BrowserSecure.mask))) { 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONPatch.java ================================================ package com.alibaba.fastjson; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.JSONScanner; public class JSONPatch { public static String apply(String original, String patch) { Object object = apply( JSON.parse(original, Feature.OrderedField), patch); return JSON.toJSONString(object); } public static Object apply(Object object, String patch) { Operation[] operations; if (isObject(patch)) { operations = new Operation[] { JSON.parseObject(patch, Operation.class)}; } else { operations = JSON.parseObject(patch, Operation[].class); } for (Operation op : operations) { JSONPath path = JSONPath.compile(op.path); switch (op.type) { case add: path.patchAdd(object, op.value, false); break; case replace: path.patchAdd(object, op.value, true); break; case remove: path.remove(object); break; case copy: case move: JSONPath from = JSONPath.compile(op.from); Object fromValue = from.eval(object); if (op.type == OperationType.move) { boolean success = from.remove(object); if (!success) { throw new JSONException("json patch move error : " + op.from + " -> " + op.path); } } path.set(object, fromValue); break; case test: Object result = path.eval(object); if (result == null) { return op.value == null; } return result.equals(op.value); default: break; } } return object; } private static boolean isObject(String patch) { if (patch == null) { return false; } for (int i = 0; i < patch.length(); ++i) { char ch = patch.charAt(i); if (JSONScanner.isWhitespace(ch)) { continue; } return ch == '{'; } return false; } @JSONType(orders = {"op", "from", "path", "value"}) public static class Operation { @JSONField(name = "op") public OperationType type; public String from; public String path; public Object value; } public enum OperationType { add, remove, replace, move, copy, test } } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONPath.java ================================================ package com.alibaba.fastjson; 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.JSONToken; 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; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; 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.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @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 Segment[] segments; private boolean hasRefSegment; private SerializeConfig serializeConfig; private ParserConfig parserConfig; private boolean ignoreNullValue; public JSONPath(String path){ this(path, SerializeConfig.getGlobalInstance(), ParserConfig.getGlobalInstance(), true); } public JSONPath(String path, boolean ignoreNullValue){ this(path, SerializeConfig.getGlobalInstance(), ParserConfig.getGlobalInstance(), ignoreNullValue); } public JSONPath(String path, SerializeConfig serializeConfig, ParserConfig parserConfig, boolean ignoreNullValue){ 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; this.ignoreNullValue = ignoreNullValue; } protected void init() { if (segments != null) { return; } if ("*".equals(path)) { this.segments = new Segment[] { WildCardSegment.instance }; } else { JSONPathParser parser = new JSONPathParser(path); this.segments = parser.explain(); this.hasRefSegment = parser.hasRefSegment; } } public boolean isRef() { try { init(); for (int i = 0; i < segments.length; ++i) { Segment segment = segments[i]; Class segmentType = segment.getClass(); if (segmentType == ArrayAccessSegment.class || segmentType == PropertySegment.class) { continue; } return false; } return true; } catch (JSONPathException ex) { // skip return false; } } public Object eval(Object rootObject) { if (rootObject == null) { return null; } init(); Object currentObject = rootObject; for (int i = 0; i < segments.length; ++i) { Segment segment = segments[i]; currentObject = segment.eval(this, rootObject, currentObject); } return currentObject; } /** * @since 1.2.76 * @param rootObject * @param clazz * @param parserConfig * @return */ public T eval(Object rootObject, Type clazz, ParserConfig parserConfig) { Object obj = this.eval(rootObject); return TypeUtils.cast(obj, clazz, parserConfig); } /** * @since 1.2.76 * @param rootObject * @param clazz * @return */ public T eval(Object rootObject, Type clazz) { return this.eval(rootObject, clazz, ParserConfig.getGlobalInstance()); } public Object extract(DefaultJSONParser parser) { if (parser == null) { return null; } init(); if (hasRefSegment) { Object root = parser.parse(); return this.eval(root); } if (segments.length == 0) { return parser.parse(); } Segment lastSegment = segments[segments.length - 1]; if (lastSegment instanceof TypeSegment || lastSegment instanceof FloorSegment || lastSegment instanceof MultiIndexSegment) { return eval( parser.parse()); } Context context = null; for (int i = 0; i < segments.length; ++i) { Segment segment = segments[i]; boolean last = i == segments.length - 1; if (context != null && context.object != null) { context.object = segment.eval(this, null, context.object); continue; } boolean eval; if (!last) { Segment nextSegment = segments[i + 1]; if (segment instanceof PropertySegment && ((PropertySegment) segment).deep && (nextSegment instanceof ArrayAccessSegment || nextSegment instanceof MultiIndexSegment || nextSegment instanceof MultiPropertySegment || nextSegment instanceof SizeSegment || nextSegment instanceof PropertySegment || nextSegment instanceof FilterSegment)) { eval = true; } else if (nextSegment instanceof ArrayAccessSegment && ((ArrayAccessSegment) nextSegment).index < 0) { eval = true; } else if (nextSegment instanceof FilterSegment) { eval = true; } else if (segment instanceof WildCardSegment) { eval = true; }else if(segment instanceof MultiIndexSegment){ eval = true; } else { eval = false; } } else { eval = true; } context = new Context(context, eval); segment.extract(this, parser, context); } return context.object; } private static class Context { final Context parent; final boolean eval; Object object; public Context(Context parent, boolean eval) { this.parent = parent; this.eval = eval; } } public boolean contains(Object rootObject) { if (rootObject == null) { return false; } init(); Object currentObject = rootObject; for (int i = 0; i < segments.length; ++i) { Object parentObject = currentObject; currentObject = segments[i].eval(this, rootObject, currentObject); if (currentObject == null) { return false; } if (currentObject == Collections.EMPTY_LIST && parentObject instanceof List) { return ((List) parentObject).contains(currentObject); } } 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); } /** * Extract keySet or field names from rootObject on this JSONPath. * * @param rootObject Can be a map or custom object. Array and Collection are not supported. * @return Set of keys, or null if not supported. */ public Set keySet(Object rootObject) { if (rootObject == null) { return null; } init(); Object currentObject = rootObject; for (int i = 0; i < segments.length; ++i) { currentObject = segments[i].eval(this, rootObject, currentObject); } return evalKeySet(currentObject); } public void patchAdd(Object rootObject, Object value, boolean replace) { if (rootObject == null) { return; } init(); Object currentObject = rootObject; Object parentObject = null; for (int i = 0; i < segments.length; ++i) { parentObject = currentObject; Segment segment = segments[i]; currentObject = segment.eval(this, rootObject, currentObject); if (currentObject == null && i != segments.length - 1) { if (segment instanceof PropertySegment) { currentObject = new JSONObject(); ((PropertySegment) segment).setValue(this, parentObject, currentObject); } } } Object result = currentObject; if ((!replace) && result instanceof Collection) { Collection collection = (Collection) result; collection.add(value); return; } Object newResult; if (result != null && !replace) { Class resultClass = result.getClass(); if (resultClass.isArray()) { int length = Array.getLength(result); Object descArray = Array.newInstance(resultClass.getComponentType(), length + 1); System.arraycopy(result, 0, descArray, 0, length); Array.set(descArray, length, value); newResult = descArray; } else if (Map.class.isAssignableFrom(resultClass)) { newResult = value; } else { throw new JSONException("unsupported array put operation. " + resultClass); } } else { newResult = value; } Segment lastSegment = segments[segments.length - 1]; if (lastSegment instanceof PropertySegment) { PropertySegment propertySegment = (PropertySegment) lastSegment; propertySegment.setValue(this, parentObject, newResult); return; } if (lastSegment instanceof ArrayAccessSegment) { ((ArrayAccessSegment) lastSegment).setValue(this, parentObject, newResult); return; } throw new UnsupportedOperationException(); } @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); } Segment lastSegment = segments[segments.length - 1]; if (lastSegment instanceof PropertySegment) { PropertySegment propertySegment = (PropertySegment) lastSegment; propertySegment.setValue(this, parentObject, newResult); return; } if (lastSegment instanceof ArrayAccessSegment) { ((ArrayAccessSegment) lastSegment).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; Segment lastSegment = segments[segments.length - 1]; for (int i = 0; i < segments.length; ++i) { if (i == segments.length - 1) { parentObject = currentObject; break; } Segment segement = segments[i]; if (i == segments.length - 2 && lastSegment instanceof FilterSegment && segement instanceof PropertySegment ) { FilterSegment filterSegment = (FilterSegment) lastSegment; if (currentObject instanceof List) { PropertySegment propertySegment = (PropertySegment) segement; List list = (List) currentObject; for (Iterator it = list.iterator();it.hasNext();) { Object item = it.next(); Object result = propertySegment.eval(this, rootObject, item); if (result instanceof Iterable) { filterSegment.remove(this, rootObject, result); } else if (result instanceof Map) { if (filterSegment.filter.apply(this, rootObject, currentObject, result)) { it.remove(); } } } return true; } else if (currentObject instanceof Map) { PropertySegment propertySegment = (PropertySegment) segement; Object result = propertySegment.eval(this, rootObject, currentObject); if (result == null) { return false; } if (result instanceof Map && filterSegment.filter.apply(this, rootObject, currentObject, result)) { propertySegment.remove(this, currentObject); return true; } } } currentObject = segement.eval(this, rootObject, currentObject); if (currentObject == null) { break; } } if (parentObject == null) { return false; } if (lastSegment instanceof PropertySegment) { PropertySegment propertySegment = (PropertySegment) lastSegment; if (parentObject instanceof Collection) { if (segments.length > 1) { Segment parentSegment = segments[segments.length - 2]; if (parentSegment instanceof RangeSegment || parentSegment instanceof MultiIndexSegment) { Collection collection = (Collection) parentObject; boolean removedOnce = false; for (Object item : collection) { boolean removed = propertySegment.remove(this, item); if (removed) { removedOnce = true; } } return removedOnce; } } } return propertySegment.remove(this, parentObject); } if (lastSegment instanceof ArrayAccessSegment) { return ((ArrayAccessSegment) lastSegment).remove(this, parentObject); } if (lastSegment instanceof FilterSegment) { FilterSegment filterSegment = (FilterSegment) lastSegment; return filterSegment.remove(this, rootObject, 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; Segment segment = segments[i]; currentObject = segment.eval(this, rootObject, currentObject); if (currentObject == null) { Segment nextSegment = null; if (i < segments.length - 1) { nextSegment = segments[i + 1]; } Object newObj = null; if (nextSegment instanceof PropertySegment) { JavaBeanDeserializer beanDeserializer = null; Class fieldClass = null; if (segment instanceof PropertySegment) { String propertyName = ((PropertySegment) 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 (nextSegment instanceof ArrayAccessSegment) { newObj = new JSONArray(); } if (newObj != null) { if (segment instanceof PropertySegment) { PropertySegment propSegement = (PropertySegment) segment; propSegement.setValue(this, parentObject, newObj); currentObject = newObj; continue; } else if (segment instanceof ArrayAccessSegment) { ArrayAccessSegment arrayAccessSegement = (ArrayAccessSegment) segment; arrayAccessSegement.setValue(this, parentObject, newObj); currentObject = newObj; continue; } } break; } } if (parentObject == null) { return false; } Segment lastSegment = segments[segments.length - 1]; if (lastSegment instanceof PropertySegment) { PropertySegment propertySegment = (PropertySegment) lastSegment; propertySegment.setValue(this, parentObject, value); return true; } if (lastSegment instanceof ArrayAccessSegment) { return ((ArrayAccessSegment) lastSegment).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 Object eval(Object rootObject, String path, boolean ignoreNullValue) { JSONPath jsonpath = compile(path, ignoreNullValue); 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); } /** * Compile jsonPath and use it to extract keySet or field names from rootObject. * * @param rootObject Can be a map or custom object. Array and Collection are not supported. * @param path JSONPath string to be compiled. * @return Set of keys, or null if not supported. */ public static Set keySet(Object rootObject, String path) { JSONPath jsonpath = compile(path); Object result = jsonpath.eval(rootObject); return jsonpath.evalKeySet(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; } public static JSONPath compile(String path, boolean ignoreNullValue) { if (path == null) { throw new JSONPathException("jsonpath can not be null"); } JSONPath jsonpath = pathCache.get(path); if (jsonpath == null) { jsonpath = new JSONPath(path, ignoreNullValue); 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) { return compile(path) .eval( JSON.parse(json) ); } /** * @since 1.2.76 * @param json * @param path * @param clazz * @param parserConfig * @return */ public static T read(String json, String path, Type clazz, ParserConfig parserConfig) { return compile(path).eval(JSON.parse(json), clazz, parserConfig); } /** * @since 1.2.76 * @param json * @param path * @param clazz * @return */ public static T read(String json, String path, Type clazz) { return read(json, path, clazz, null); } /** * @since 1.2.51 * @param json * @param path * @return */ public static Object extract(String json, String path, ParserConfig config, int features, Feature... optionFeatures) { features |= Feature.OrderedField.mask; DefaultJSONParser parser = new DefaultJSONParser(json, config, features); JSONPath jsonPath = compile(path); Object result = jsonPath.extract(parser); parser.lexer.close(); return result; } public static Object extract(String json, String path) { return extract(json, path, ParserConfig.global, JSON.DEFAULT_PARSER_FEATURE); } 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) { Class type = javaObject.getClass(); boolean basicType = type == String.class || type == Boolean.class || type == Character.class || type == UUID.class || type.isEnum() || javaObject instanceof Number || javaObject instanceof Date ; 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; } public String getPath() { return path; } static class JSONPathParser { private final String path; private int pos; private char ch; private int level; private boolean hasRefSegment; private static final String strArrayRegex = "\'\\s*,\\s*\'"; private static final Pattern strArrayPatternx = Pattern.compile(strArrayRegex); 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(); } Segment readSegement() { if (level == 0 && path.length() == 1) { if (isDigitFirst(ch)) { int index = ch - '0'; return new ArrayAccessSegment(index); } else if ((ch >= 'a' && ch <= 'z') || ((ch >= 'A' && ch <= 'Z'))) { return new PropertySegment(Character.toString(ch), false); } } while (!isEOF()) { skipWhitespace(); if (ch == '$') { next(); skipWhitespace(); if (ch == '?') { return new FilterSegment( (Filter) parseArrayAccessFilter(false)); } 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 == '*' || (deep && ch == '[')) { boolean objectOnly = ch == '['; if (!isEOF()) { next(); } if (deep) { if (objectOnly) { return WildCardSegment.instance_deep_objectOnly; } else { return WildCardSegment.instance_deep; } } else { return WildCardSegment.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 SizeSegment.instance; } else if ("max".equals(propertyName)) { return MaxSegment.instance; } else if ("min".equals(propertyName)) { return MinSegment.instance; } else if ("keySet".equals(propertyName)) { return KeySetSegment.instance; } else if ("type".equals(propertyName)) { return TypeSegment.instance; } else if ("floor".equals(propertyName)) { return FloorSegment.instance; } throw new JSONPathException("not support jsonpath : " + path); } throw new JSONPathException("not support jsonpath : " + path); } return new PropertySegment(propertyName, deep); } if (ch == '[') { return parseArrayAccess(true); } if (level == 0) { String propertyName = readName(); return new PropertySegment(propertyName, false); } if (ch == '?') { return new FilterSegment( (Filter) parseArrayAccessFilter(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; } } } Segment parseArrayAccess(boolean acceptBracket) { Object object = parseArrayAccessFilter(acceptBracket); if (object instanceof Segment) { return ((Segment) object); } return new FilterSegment((Filter) object); } Object parseArrayAccessFilter(boolean acceptBracket) { if (acceptBracket) { accept('['); } boolean predicateFlag = false; int lparanCount = 0; if (ch == '?') { next(); accept('('); lparanCount++; while (ch == '(') { next(); lparanCount++; } predicateFlag = true; } skipWhitespace(); if (predicateFlag || IOUtils.firstIdentifier(ch) || Character.isJavaIdentifierStart(ch) || ch == '\\' || ch == '@') { boolean self = false; if (ch == '@') { next(); accept('.'); self = true; } String propertyName = readName(); skipWhitespace(); if (predicateFlag && ch == ')') { next(); Filter filter = new NotNullSegement(propertyName, false); while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } if (acceptBracket) { accept(']'); } return filter; } if (acceptBracket && ch == ']') { if (isEOF()) { if (propertyName.equals("last")) { return new MultiIndexSegment(new int[]{-1}); } } next(); Filter filter = new NotNullSegement(propertyName, false); while (ch == ' ') { next(); } if (ch == '&' || ch == '|') { filter = filterRest(filter); } accept(')'); if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } boolean function = false; skipWhitespace(); if (ch == '(') { next(); accept(')'); skipWhitespace(); function = true; } 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 , function , TypeUtils.longExtractValue((Number) startValue) , TypeUtils.longExtractValue((Number) endValue) , 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, function); } else { filter = new NullSegement(propertyName, function); } 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 = TypeUtils.longExtractValue((Number) valueList.get(0)); Operator intOp = not ? Operator.NE : Operator.EQ; Filter filter = new IntOpSegement(propertyName, function, 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] = TypeUtils.longExtractValue((Number) valueList.get(i)); } Filter filter = new IntInSegement(propertyName, function, 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, function, 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, function, 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] = TypeUtils.longExtractValue(item); } } Filter filter = new IntObjInSegement(propertyName, function, 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, function, strValue, false); } else if (op == Operator.NOT_RLIKE) { filter = new RlikeSegement(propertyName, function, 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, function, 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) == '%') { if (items.length == 1) { startsWithValue = items[0]; } else { 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, function, startsWithValue, endsWithValue, containsValues, not); } } else { filter = new StringOpSegement(propertyName, function, 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, function, value, op); } else { filter = new DoubleOpSegement(propertyName, function, doubleValue, op); } while (ch == ' ') { next(); } if (lparanCount > 1 && ch == ')') { next(); lparanCount--; } if (ch == '&' || ch == '|') { filter = filterRest(filter); } if (predicateFlag) { lparanCount--; accept(')'); } if (acceptBracket) { accept(']'); } return filter; } else if (ch == '$') { Segment segment = readSegement(); RefOpSegement filter = new RefOpSegement(propertyName, function, segment, op); hasRefSegment = true; while (ch == ' ') { next(); } if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } else if (ch == '/') { int flags = 0; StringBuilder regBuf = new StringBuilder(); for (;;) { next(); if (ch == '/') { next(); if (ch == 'i') { next(); flags |= Pattern.CASE_INSENSITIVE; } break; } if (ch == '\\') { next(); regBuf.append(ch); } else { regBuf.append(ch); } } Pattern pattern = Pattern.compile(regBuf.toString(), flags); RegMatchSegement filter = new RegMatchSegement(propertyName, function, pattern, op); if (predicateFlag) { accept(')'); } if (acceptBracket) { accept(']'); } return filter; } if (ch == 'n') { String name = readName(); if ("null".equals(name)) { Filter filter = null; if (op == Operator.EQ) { filter = new NullSegement(propertyName, function); } else if (op == Operator.NE) { filter = new NotNullSegement(propertyName, function); } 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, function, Boolean.TRUE, true); } else if (op == Operator.NE) { filter = new ValueSegment(propertyName, function, 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, function, Boolean.FALSE, true); } else if (op == Operator.NE) { filter = new ValueSegment(propertyName, function, 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; char startCh = ch; while (ch != ']' && ch != '/' && !isEOF()) { if (ch == '.' // && (!predicateFlag) // && !predicateFlag && startCh != '\'' ) { 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('\\') != 0) { StringBuilder buf = new StringBuilder(text.length()); for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (ch == '\\' && i < text.length() - 1) { char c2 = text.charAt(i + 1); if (c2 == '@' || ch == '\\' || ch == '\"') { buf.append(c2); i++; continue; } } buf.append(ch); } text = buf.toString(); } if (text.indexOf("\\.") != -1) { String propName; if (startCh == '\'' && text.length() > 2 && text.charAt(text.length() - 1) == startCh) { propName = text.substring(1, text.length() - 1); } else { propName = text.replaceAll("\\\\\\.", "\\."); if (propName.indexOf("\\-") != -1) { propName = propName.replaceAll("\\\\-", "-"); } } if (predicateFlag) { accept(')'); } return new PropertySegment(propName, false); } Segment segment = buildArraySegement(text); if (acceptBracket && !isEOF()) { accept(']'); } return segment; } Filter filterRest(Filter filter) { boolean and = ch == '&'; if ((ch == '&' && getNextChar() == '&') || (ch == '|' && getNextChar() == '|')) { next(); next(); boolean paren = false; if (ch == '(') { paren = true; next(); } while (ch == ' ') { next(); } Filter right = (Filter) parseArrayAccessFilter(false); filter = new FilterGroup(filter, right, and); if (paren && ch == ')') { next(); } } 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(); if (ch == '~') { next(); op = Operator.REG_MATCH; } else if (ch == '=') { next(); op = Operator.EQ; } else { 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 ("nin".equalsIgnoreCase(name)) { op = Operator.NOT_IN; } 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 != '\\' && !Character.isJavaIdentifierStart(ch)) { throw new JSONPathException("illeal jsonpath syntax. " + path); } StringBuilder buf = new StringBuilder(); while (!isEOF()) { if (ch == '\\') { next(); buf.append(ch); if (isEOF()) { return buf.toString(); } next(); continue; } boolean identifierFlag = Character.isJavaIdentifierPart(ch); if (!identifierFlag) { break; } buf.append(ch); next(); } if (isEOF() && Character.isJavaIdentifierPart(ch)) { buf.append(ch); } return buf.toString(); } 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 == ' ') { next(); } if (ch != expect) { throw new JSONPathException("expect '" + expect + ", but '" + ch + "'"); } if (!isEOF()) { next(); } } public Segment[] explain() { if (path == null || path.length() == 0) { throw new IllegalArgumentException(); } Segment[] segments = new Segment[8]; for (;;) { Segment segment = readSegement(); if (segment == null) { break; } if (segment instanceof PropertySegment) { PropertySegment propertySegment = (PropertySegment) segment; if ((!propertySegment.deep) && propertySegment.propertyName.equals("*")) { continue; } } if (level == segments.length) { Segment[] t = new Segment[level * 3 / 2]; System.arraycopy(segments, 0, t, 0, level); segments = t; } segments[level++] = segment; } if (level == segments.length) { return segments; } Segment[] result = new Segment[level]; System.arraycopy(segments, 0, result, 0, level); return result; } Segment 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 == '\'') { String propertyName = indexText.substring(1, indexTextLen - 1); if (commaIndex == -1 || !strArrayPatternx.matcher(indexText).find()) { return new PropertySegment(propertyName, false); } String[] propertyNames = propertyName.split(strArrayRegex); return new MultiPropertySegment(propertyNames); } int colonIndex = indexText.indexOf(':'); if (commaIndex == -1 && colonIndex == -1) { if (TypeUtils.isNumber(indexText)) { try { int index = Integer.parseInt(indexText); return new ArrayAccessSegment(index); }catch (NumberFormatException ex){ return new PropertySegment(indexText, false); // fix ISSUE-1208 } } else { if (indexText.charAt(0) == '"' && indexText.charAt(indexText.length() - 1) == '"') { indexText = indexText.substring(1, indexText.length() - 1); } return new PropertySegment(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 MultiIndexSegment(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 RangeSegment(start, end, step); } throw new UnsupportedOperationException(); } } interface Segment { Object eval(JSONPath path, Object rootObject, Object currentObject); void extract(JSONPath path, DefaultJSONParser parser, Context context); } static class SizeSegment implements Segment { public final static SizeSegment instance = new SizeSegment(); public Integer eval(JSONPath path, Object rootObject, Object currentObject) { return path.evalSize(currentObject); } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { Object object = parser.parse(); context.object = path.evalSize(object); } } static class TypeSegment implements Segment { public final static TypeSegment instance = new TypeSegment(); public String eval(JSONPath path, Object rootObject, Object currentObject) { if (currentObject == null) { return "null"; } if (currentObject instanceof Collection) { return "array"; } if (currentObject instanceof Number) { return "number"; } if (currentObject instanceof Boolean) { return "boolean"; } if (currentObject instanceof String || currentObject instanceof UUID || currentObject instanceof Enum) { return "string"; } return "object"; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static class FloorSegment implements Segment { public final static FloorSegment instance = new FloorSegment(); public Object eval(JSONPath path, Object rootObject, Object currentObject) { if (currentObject instanceof JSONArray) { JSONArray array = ((JSONArray) ((JSONArray) currentObject).clone()); for (int i = 0; i < array.size(); i++) { Object item = array.get(i); Object newItem = floor(item); if (newItem != item) { array.set(i , newItem); } } return array; } return floor(currentObject); } private static Object floor(Object item) { if (item == null) { return null; } if (item instanceof Float) { return Math.floor((Float) item); } if (item instanceof Double) { return Math.floor((Double) item); } if (item instanceof BigDecimal) { BigDecimal decimal = (BigDecimal) item; return decimal.setScale(0, RoundingMode.FLOOR); } if (item instanceof Byte || item instanceof Short || item instanceof Integer || item instanceof Long || item instanceof BigInteger) { return item; } throw new UnsupportedOperationException(); } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static class MaxSegment implements Segment { public final static MaxSegment instance = new MaxSegment(); public Object eval(JSONPath path, Object rootObject, Object currentObject) { Object max = null; if (currentObject instanceof Collection) { Iterator iterator = ((Collection) currentObject).iterator(); while (iterator.hasNext()) { Object next = iterator.next(); if (next == null) { continue; } if (max == null) { max = next; } else if (compare(max, next) < 0) { max = next; } } } else { throw new UnsupportedOperationException(); } return max; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static class MinSegment implements Segment { public final static MinSegment instance = new MinSegment(); public Object eval(JSONPath path, Object rootObject, Object currentObject) { Object min = null; if (currentObject instanceof Collection) { Iterator iterator = ((Collection) currentObject).iterator(); while (iterator.hasNext()) { Object next = iterator.next(); if (next == null) { continue; } if (min == null) { min = next; } else if (compare(min, next) > 0) { min = next; } } } else { throw new UnsupportedOperationException(); } return min; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static int compare(Object a, Object b) { if (a.getClass() == b.getClass()) { return ((Comparable) a).compareTo(b); } Class typeA = a.getClass(); Class typeB = b.getClass(); if (typeA == BigDecimal.class) { if (typeB == Integer.class) { b = new BigDecimal((Integer) b); } else if (typeB == Long.class) { b = new BigDecimal((Long) b); } else if (typeB == Float.class) { b = new BigDecimal((Float) b); } else if (typeB == Double.class) { b = new BigDecimal((Double) b); } } else if (typeA == Long.class) { if (typeB == Integer.class) { b = new Long((Integer) b); } else if (typeB == BigDecimal.class) { a = new BigDecimal((Long) a); } else if (typeB == Float.class) { a = new Float((Long) a); } else if (typeB == Double.class) { a = new Double((Long) a); } } else if (typeA == Integer.class) { if (typeB == Long.class) { a = new Long((Integer) a); } else if (typeB == BigDecimal.class) { a = new BigDecimal((Integer) a); } else if (typeB == Float.class) { a = new Float((Integer) a); } else if (typeB == Double.class) { a = new Double((Integer) a); } } else if (typeA == Double.class) { if (typeB == Integer.class) { b = new Double((Integer) b); } else if (typeB == Long.class) { b = new Double((Long) b); } else if (typeB == Float.class) { b = new Double((Float) b); } } else if (typeA == Float.class) { if (typeB == Integer.class) { b = new Float((Integer) b); } else if (typeB == Long.class) { b = new Float((Long) b); } else if (typeB == Double.class) { a = new Double((Float) a); } } return ((Comparable) a).compareTo(b); } static class KeySetSegment implements Segment { public final static KeySetSegment instance = new KeySetSegment(); public Object eval(JSONPath path, Object rootObject, Object currentObject) { return path.evalKeySet(currentObject); } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static class PropertySegment implements Segment { private final String propertyName; private final long propertyNameHash; private final boolean deep; public PropertySegment(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 extract(JSONPath path, DefaultJSONParser parser, Context context) { JSONLexerBase lexer = (JSONLexerBase) parser.lexer; if (deep && context.object == null) { context.object = new JSONArray(); } if (lexer.token() == JSONToken.LBRACKET) { if ("*".equals(propertyName)) { return; } lexer.nextToken(); JSONArray array; if (deep) { array =(JSONArray) context.object; } else { array = new JSONArray(); } for (;;) { switch (lexer.token()) { case JSONToken.LBRACE: { if (deep) { extract(path, parser, context); break; } int matchStat = lexer.seekObjectToField(propertyNameHash, deep); if (matchStat == JSONLexer.VALUE) { Object value; switch (lexer.token()) { case JSONToken.LITERAL_INT: value = lexer.integerValue(); lexer.nextToken(); break; case JSONToken.LITERAL_STRING: value = lexer.stringVal(); lexer.nextToken(); break; default: value = parser.parse(); break; } array.add(value); if (lexer.token() == JSONToken.RBRACE) { lexer.nextToken(); continue; } else { lexer.skipObject(false); } } else if (matchStat == JSONLexer.NOT_MATCH) { continue; } else { if (deep) { throw new UnsupportedOperationException(lexer.info()); } else { lexer.skipObject(false); } } break; } case JSONToken.LBRACKET: if (deep) { extract(path, parser, context); } else { lexer.skipObject(false); } break; case JSONToken.LITERAL_STRING: case JSONToken.LITERAL_INT: case JSONToken.LITERAL_FLOAT: case JSONToken.LITERAL_ISO8601_DATE: case JSONToken.TRUE: case JSONToken.FALSE: case JSONToken.NULL: lexer.nextToken(); break; default: break; } if (lexer.token() == JSONToken.RBRACKET) { lexer.nextToken(); break; } else if (lexer.token() == JSONToken.COMMA) { lexer.nextToken(); continue; } else { throw new JSONException("illegal json : " + lexer.info()); } } if (!deep) { if (array.size() > 0) { context.object = array; } } return; } if (!deep) { int matchStat = lexer.seekObjectToField(propertyNameHash, deep); if (matchStat == JSONLexer.VALUE) { if (context.eval) { Object value; switch (lexer.token()) { case JSONToken.LITERAL_INT: value = lexer.integerValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_FLOAT: value = lexer.decimalValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_STRING: value = lexer.stringVal(); lexer.nextToken(JSONToken.COMMA); break; default: value = parser.parse(); break; } if (context.eval) { context.object = value; } } } return; } // deep for (;;) { int matchStat = lexer.seekObjectToField(propertyNameHash, deep); if (matchStat == JSONLexer.NOT_MATCH) { break; } if (matchStat == JSONLexer.VALUE) { if (context.eval) { Object value; switch (lexer.token()) { case JSONToken.LITERAL_INT: value = lexer.integerValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_FLOAT: value = lexer.decimalValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_STRING: value = lexer.stringVal(); lexer.nextToken(JSONToken.COMMA); break; default: value = parser.parse(); break; } if (context.eval) { if (context.object instanceof List) { List list = (List) context.object; if (list.size() == 0 && value instanceof List) { context.object = value; } else { list.add(value); } } else { context.object = value; } } } } else if (matchStat == JSONLexer.OBJECT || matchStat == JSONLexer.ARRAY) { extract(path, parser, context); } } } 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, deep); } } static class MultiPropertySegment implements Segment { private final String[] propertyNames; private final long[] propertyNamesHash; public MultiPropertySegment(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; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { JSONLexerBase lexer = (JSONLexerBase) parser.lexer; JSONArray array; if (context.object == null) { context.object = array = new JSONArray(); } else { array = (JSONArray) context.object; } for (int i = array.size(); i < propertyNamesHash.length; ++i) { array.add(null); } // if (lexer.token() == JSONToken.LBRACKET) { // lexer.nextToken(); // JSONArray array; // // array = new JSONArray(); // for (;;) { // if (lexer.token() == JSONToken.LBRACE) { // int index = lexer.seekObjectToField(propertyNamesHash); // int matchStat = lexer.matchStat; // if (matchStat == JSONLexer.VALUE) { // Object value; // switch (lexer.token()) { // case JSONToken.LITERAL_INT: // value = lexer.integerValue(); // lexer.nextToken(); // break; // case JSONToken.LITERAL_STRING: // value = lexer.stringVal(); // lexer.nextToken(); // break; // default: // value = parser.parse(); // break; // } // // array.add(index, value); // if (lexer.token() == JSONToken.RBRACE) { // lexer.nextToken(); // continue; // } else { // lexer.skipObject(); // } // } else { // lexer.skipObject(); // } // } // // if (lexer.token() == JSONToken.RBRACKET) { // break; // } else if (lexer.token() == JSONToken.COMMA) { // lexer.nextToken(); // continue; // } else { // throw new JSONException("illegal json."); // } // } // // context.object = array; // return; // } for_: for (;;) { int index = lexer.seekObjectToField(propertyNamesHash); int matchStat = lexer.matchStat; if (matchStat == JSONLexer.VALUE) { Object value; switch (lexer.token()) { case JSONToken.LITERAL_INT: value = lexer.integerValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_FLOAT: value = lexer.decimalValue(); lexer.nextToken(JSONToken.COMMA); break; case JSONToken.LITERAL_STRING: value = lexer.stringVal(); lexer.nextToken(JSONToken.COMMA); break; default: value = parser.parse(); break; } array.set(index, value); if (lexer.token() == JSONToken.COMMA) { continue for_; } } break; } } } static class WildCardSegment implements Segment { private boolean deep; private boolean objectOnly; private WildCardSegment(boolean deep, boolean objectOnly) { this.deep = deep; this.objectOnly = objectOnly; } public final static WildCardSegment instance = new WildCardSegment(false, false); public final static WildCardSegment instance_deep = new WildCardSegment(true, false); public final static WildCardSegment instance_deep_objectOnly = new WildCardSegment(true, true); public Object eval(JSONPath path, Object rootObject, Object currentObject) { if (!deep) { return path.getPropertyValues(currentObject); } List values = new ArrayList(); path.deepGetPropertyValues(currentObject, values); return values; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { if (context.eval) { Object object = parser.parse(); if (deep) { List values = new ArrayList(); if (objectOnly) { path.deepGetObjects(object, values); } else { path.deepGetPropertyValues(object, values); } context.object = values; return; } if (object instanceof JSONObject) { Collection values = ((JSONObject) object).values(); JSONArray array = new JSONArray(values.size()); array.addAll(values); context.object = array; return; } else if (object instanceof JSONArray) { context.object = object; return; } } throw new JSONException("TODO"); } } static class ArrayAccessSegment implements Segment { private final int index; public ArrayAccessSegment(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); } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { JSONLexerBase lexer = (JSONLexerBase) parser.lexer; if (lexer.seekArrayToItem(index) && context.eval) { context.object = parser.parse(); } } } static class MultiIndexSegment implements Segment { private final int[] indexes; public MultiIndexSegment(int[] indexes){ this.indexes = indexes; } public Object eval(JSONPath path, Object rootObject, Object currentObject) { List items = new JSONArray(indexes.length); for (int i = 0; i < indexes.length; ++i) { Object item = path.getArrayItem(currentObject, indexes[i]); items.add(item); } return items; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { if (context.eval) { Object object = parser.parse(); if (object instanceof List) { int[] indexes = new int[this.indexes.length]; System.arraycopy(this.indexes, 0, indexes, 0, indexes.length); boolean noneNegative = indexes[0] >= 0; List list = (List) object; if (noneNegative) { for (int i = list.size() - 1; i >= 0; i--) { if (Arrays.binarySearch(indexes, i) < 0) { list.remove(i); } } context.object = list; return; } } } throw new UnsupportedOperationException(); } } static class RangeSegment implements Segment { private final int start; private final int end; private final int step; public RangeSegment(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 = SizeSegment.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; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { throw new UnsupportedOperationException(); } } static class NotNullSegement extends PropertyFilter { public NotNullSegement(String propertyName, boolean function){ super(propertyName, function); } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { return path.getPropertyValue(item, propertyName, propertyNameHash) != null; } } static class NullSegement extends PropertyFilter { public NullSegement(String propertyName, boolean function){ super(propertyName, function); } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); return propertyValue == null; } } static class ValueSegment extends PropertyFilter { private final Object value; private boolean eq = true; public ValueSegment(String propertyName,boolean function, Object value, boolean eq){ super(propertyName, function); if (value == null) { throw new IllegalArgumentException("value is null"); } this.value = value; this.eq = eq; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); boolean result = value.equals(propertyValue); if (!eq) { result = !result; } return result; } } static class IntInSegement extends PropertyFilter { private final long[] values; private final boolean not; public IntInSegement(String propertyName, boolean function, long[] values, boolean not){ super(propertyName, function); this.values = values; this.not = not; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (propertyValue instanceof Number) { long longPropertyValue = TypeUtils.longExtractValue((Number) propertyValue); for (long value : values) { if (value == longPropertyValue) { return !not; } } } return not; } } static class IntBetweenSegement extends PropertyFilter { private final long startValue; private final long endValue; private final boolean not; public IntBetweenSegement(String propertyName, boolean function, long startValue, long endValue, boolean not){ super(propertyName, function); this.startValue = startValue; this.endValue = endValue; this.not = not; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (propertyValue instanceof Number) { long longPropertyValue = TypeUtils.longExtractValue((Number) propertyValue); if (longPropertyValue >= startValue && longPropertyValue <= endValue) { return !not; } } return not; } } static class IntObjInSegement extends PropertyFilter { private final Long[] values; private final boolean not; public IntObjInSegement(String propertyName, boolean function, Long[] values, boolean not){ super(propertyName, function); this.values = values; this.not = not; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { for (Long value : values) { if (value == null) { return !not; } } return not; } if (propertyValue instanceof Number) { long longPropertyValue = TypeUtils.longExtractValue((Number) propertyValue); for (Long value : values) { if (value == null) { continue; } if (value.longValue() == longPropertyValue) { return !not; } } } return not; } } static class StringInSegement extends PropertyFilter { private final String[] values; private final boolean not; public StringInSegement(String propertyName, boolean function, String[] values, boolean not){ super(propertyName, function); this.values = values; this.not = not; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); for (String value : values) { if (value == propertyValue) { return !not; } else if (value != null && value.equals(propertyValue)) { return !not; } } return not; } } static class IntOpSegement extends PropertyFilter { private final long value; private final Operator op; private BigDecimal valueDecimal; private Float valueFloat; private Double valueDouble; public IntOpSegement(String propertyName, boolean function, long value, Operator op){ super(propertyName, function); this.value = value; this.op = op; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (!(propertyValue instanceof Number)) { return false; } if (propertyValue instanceof BigDecimal) { if (valueDecimal == null) { valueDecimal = BigDecimal.valueOf(value); } int result = valueDecimal.compareTo((BigDecimal) propertyValue); switch (op) { case EQ: return result == 0; case NE: return result != 0; case GE: return 0 >= result; case GT: return 0 > result; case LE: return 0 <= result; case LT: return 0 < result; } return false; } if (propertyValue instanceof Float) { if (valueFloat == null) { valueFloat = Float.valueOf(value); } int result = valueFloat.compareTo((Float) propertyValue); switch (op) { case EQ: return result == 0; case NE: return result != 0; case GE: return 0 >= result; case GT: return 0 > result; case LE: return 0 <= result; case LT: return 0 < result; } return false; } if (propertyValue instanceof Double) { if (valueDouble == null) { valueDouble = Double.valueOf(value); } int result = valueDouble.compareTo((Double) propertyValue); switch (op) { case EQ: return result == 0; case NE: return result != 0; case GE: return 0 >= result; case GT: return 0 > result; case LE: return 0 <= result; case LT: return 0 < result; } return false; } long longValue = TypeUtils.longExtractValue((Number) propertyValue); switch (op) { case EQ: return longValue == value; case NE: return longValue != value; case GE: return longValue >= value; case GT: return longValue > value; case LE: return longValue <= value; case LT: return longValue < value; } return false; } } static abstract class PropertyFilter implements Filter { static long TYPE = TypeUtils.fnv1a_64("type"); protected final String propertyName; protected final long propertyNameHash; protected final boolean function; protected Segment functionExpr; protected PropertyFilter(String propertyName, boolean function) { this.propertyName = propertyName; this.propertyNameHash = TypeUtils.fnv1a_64(propertyName); this.function = function; if (function) { if (propertyNameHash == TYPE) { functionExpr = TypeSegment.instance; } else if (propertyNameHash == SIZE) { functionExpr = SizeSegment.instance; } else { throw new JSONPathException("unsupported funciton : " + propertyName); } } } protected Object get(JSONPath path, Object rootObject, Object currentObject) { if (functionExpr != null) { return functionExpr.eval(path, rootObject, currentObject); } return path.getPropertyValue(currentObject, propertyName, propertyNameHash); } } static class DoubleOpSegement extends PropertyFilter { private final double value; private final Operator op; public DoubleOpSegement(String propertyName, boolean function, double value, Operator op){ super(propertyName, function); this.value = value; this.op = op; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (!(propertyValue instanceof Number)) { return false; } double doubleValue = ((Number) propertyValue).doubleValue(); switch (op) { case EQ: return doubleValue == value; case NE: return doubleValue != value; case GE: return doubleValue >= value; case GT: return doubleValue > value; case LE: return doubleValue <= value; case LT: return doubleValue < value; } return false; } } static class RefOpSegement extends PropertyFilter { private final Segment refSgement; private final Operator op; public RefOpSegement(String propertyName, boolean function, Segment refSgement, Operator op){ super(propertyName, function); this.refSgement = refSgement; this.op = op; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (!(propertyValue instanceof Number)) { return false; } Object refValue = refSgement.eval(path, rootObject, rootObject); if (refValue instanceof Integer || refValue instanceof Long || refValue instanceof Short || refValue instanceof Byte) { long value = TypeUtils.longExtractValue((Number) refValue); if (propertyValue instanceof Integer || propertyValue instanceof Long || propertyValue instanceof Short || propertyValue instanceof Byte) { long longValue = TypeUtils.longExtractValue((Number) propertyValue); switch (op) { case EQ: return longValue == value; case NE: return longValue != value; case GE: return longValue >= value; case GT: return longValue > value; case LE: return longValue <= value; case LT: return longValue < value; } } else if (propertyValue instanceof BigDecimal) { BigDecimal valueDecimal = BigDecimal.valueOf(value); int result = valueDecimal.compareTo((BigDecimal) propertyValue); switch (op) { case EQ: return result == 0; case NE: return result != 0; case GE: return 0 >= result; case GT: return 0 > result; case LE: return 0 <= result; case LT: return 0 < result; } return false; } } throw new UnsupportedOperationException(); } } static class MatchSegement extends PropertyFilter { private final String startsWithValue; private final String endsWithValue; private final String[] containsValues; private final int minLength; private final boolean not; public MatchSegement( String propertyName, boolean function, String startsWithValue, String endsWithValue, String[] containsValues, boolean not) { super(propertyName, function); 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 = get(path, rootObject, item); 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 extends PropertyFilter { private final Pattern pattern; private final boolean not; public RlikeSegement(String propertyName, boolean function, String pattern, boolean not){ super(propertyName, function); this.pattern = Pattern.compile(pattern); this.not = not; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); 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 extends PropertyFilter { private final String value; private final Operator op; public StringOpSegement(String propertyName, boolean function, String value, Operator op){ super(propertyName, function); this.value = value; this.op = op; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); 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; } } static class RegMatchSegement extends PropertyFilter { private final Pattern pattern; private final Operator op; public RegMatchSegement(String propertyName, boolean function, Pattern pattern, Operator op){ super(propertyName, function); this.pattern = pattern; this.op = op; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } String str = propertyValue.toString(); Matcher m = pattern.matcher(str); return m.matches(); } } enum Operator { EQ, NE, GT, GE, LT, LE, LIKE, NOT_LIKE, RLIKE, NOT_RLIKE, IN, NOT_IN, BETWEEN, NOT_BETWEEN, And, Or, REG_MATCH } static public class FilterSegment implements Segment { private final Filter filter; public FilterSegment(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; } public void extract(JSONPath path, DefaultJSONParser parser, Context context) { Object object = parser.parse(); context.object = eval(path, object, object); } public boolean remove(JSONPath path, Object rootObject, Object currentObject) { if (currentObject == null) { return false; } if (currentObject instanceof Iterable) { Iterator it = ((Iterable) currentObject).iterator(); while (it.hasNext()) { Object item = it.next(); if (filter.apply(path, rootObject, currentObject, item)) { it.remove(); } } return true; } return false; } } 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 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; } if (index == 0) { return currentObject; } 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) { if (currentObject == null) { return null; } 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(); } if (currentObject instanceof Collection) { return (Collection) currentObject; } throw new UnsupportedOperationException(); } protected void deepGetObjects(final Object currentObject, List outValues) { final Class currentClass = currentObject.getClass(); JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); Collection collection = null; if (beanSerializer != null) { try { collection = beanSerializer.getFieldValues(currentObject); outValues.add(currentObject); } catch (Exception e) { throw new JSONPathException("jsonpath error, path " + path, e); } } else if (currentObject instanceof Map) { outValues.add(currentObject); Map map = (Map) currentObject; collection = map.values(); } else if (currentObject instanceof Collection) { collection = (Collection) currentObject; } if (collection != null) { for (Object fieldValue : collection) { if (fieldValue == null || ParserConfig.isPrimitive2(fieldValue.getClass())) { // skip } else { deepGetObjects(fieldValue, outValues); } } return; } throw new UnsupportedOperationException(currentClass.getName()); } protected void deepGetPropertyValues(final Object currentObject, List outValues) { final Class currentClass = currentObject.getClass(); JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentClass); Collection collection = null; if (beanSerializer != null) { try { collection = beanSerializer.getFieldValues(currentObject); } catch (Exception e) { throw new JSONPathException("jsonpath error, path " + path, e); } } else if (currentObject instanceof Map) { Map map = (Map) currentObject; collection = map.values(); } else if (currentObject instanceof Collection) { collection = (Collection) currentObject; } if (collection != null) { for (Object fieldValue : collection) { if (fieldValue == null || ParserConfig.isPrimitive2(fieldValue.getClass())) { outValues.add(fieldValue); } else { deepGetPropertyValues(fieldValue, outValues); } } return; } throw new UnsupportedOperationException(currentClass.getName()); } 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(TypeUtils.longExtractValue(b))); } } 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(TypeUtils.longExtractValue(b)); 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 String) { try { JSONObject object = (JSONObject) JSON.parse((String) currentObject, parserConfig); currentObject = object; } catch (Exception ex) { // skip } } 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 = null; for (int i = 0; i < list.size(); ++i) { Object obj = list.get(i); // if (obj == list) { if (fieldValues == null) { fieldValues = new JSONArray(list.size()); } fieldValues.add(obj); continue; } Object itemValue = getPropertyValue(obj, propertyName, propertyNameHash); if (itemValue instanceof Collection) { Collection collection = (Collection) itemValue; if (fieldValues == null) { fieldValues = new JSONArray(list.size()); } fieldValues.addAll(collection); } else if (itemValue != null || !ignoreNullValue) { if (fieldValues == null) { fieldValues = new JSONArray(list.size()); } fieldValues.add(itemValue); } } if (fieldValues == null) { fieldValues = Collections.emptyList(); } return fieldValues; } if (currentObject instanceof Object[]) { Object[] array = (Object[]) currentObject; if (SIZE == propertyNameHash || LENGTH == propertyNameHash) { return array.length; } List fieldValues = new JSONArray(array.length); for (int i = 0; i < array.length; ++i) { Object obj = array[i]; // if (obj == array) { 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 || !ignoreNullValue) { 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; for (Map.Entry entry : map.entrySet()) { Object val = entry.getValue(); if (propertyName.equals(entry.getKey())) { if (val instanceof Collection) { results.addAll((Collection) val); } else { results.add(val); } continue; } if (val == null || ParserConfig.isPrimitive2(val.getClass())) { continue; } deepScan(val, propertyName, results); } return; } if (currentObject instanceof Collection) { Iterator iterator = ((Collection) currentObject).iterator(); while (iterator.hasNext()) { Object next = iterator.next(); if (ParserConfig.isPrimitive2(next.getClass())) { continue; } deepScan(next, 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 deserializer = parserConfig.getDeserializer(parent.getClass()); JavaBeanDeserializer beanDeserializer = null; if (deserializer instanceof JavaBeanDeserializer) { beanDeserializer = (JavaBeanDeserializer) deserializer; } if (beanDeserializer != null) { FieldDeserializer fieldDeserializer = beanDeserializer.getFieldDeserializer(propertyNameHash); if (fieldDeserializer == null) { return false; } if (value != null && value.getClass() != fieldDeserializer.fieldInfo.fieldClass) { value = TypeUtils.cast(value, fieldDeserializer.fieldInfo.fieldType, parserConfig); } fieldDeserializer.setValue(parent, value); return true; } throw new UnsupportedOperationException(); } @SuppressWarnings({"rawtypes" }) protected boolean removePropertyValue(Object parent, String name, boolean deep) { if (parent instanceof Map) { Object origin = ((Map) parent).remove(name); boolean found = origin != null; if (deep) { for (Object item : ((Map) parent).values()) { removePropertyValue(item, name, deep); } } return found; } ObjectDeserializer deserializer = parserConfig.getDeserializer(parent.getClass()); JavaBeanDeserializer beanDeserializer = null; if (deserializer instanceof JavaBeanDeserializer) { beanDeserializer = (JavaBeanDeserializer) deserializer; } if (beanDeserializer != null) { FieldDeserializer fieldDeserializer = beanDeserializer.getFieldDeserializer(name); boolean found = false; if (fieldDeserializer != null) { fieldDeserializer.setValue(parent, null); found = true; } if (deep) { Collection propertyValues = this.getPropertyValues(parent); for (Object item : propertyValues) { if (item == null) { continue; } removePropertyValue(item, name, deep); } } return found; } if (deep) { return false; } 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); } } @SuppressWarnings({"rawtypes", "unchecked"}) Set evalKeySet(Object currentObject) { if (currentObject == null) { return null; } if (currentObject instanceof Map) { // For performance reasons return keySet directly, without filtering null-value key. return ((Map)currentObject).keySet(); } if (currentObject instanceof Collection || currentObject instanceof Object[] || currentObject.getClass().isArray()) { return null; } JavaBeanSerializer beanSerializer = getJavaBeanSerializer(currentObject.getClass()); if (beanSerializer == null) { return null; } try { return beanSerializer.getFieldNames(currentObject); } catch (Exception e) { throw new JSONPathException("evalKeySet error : " + path, e); } } public String toJSONString() { return JSON.toJSONString(path); } public static Object reserveToArray(Object object, String... paths) { JSONArray reserved = new JSONArray(); if (paths == null || paths.length == 0) { return reserved; } for (String item : paths) { JSONPath path = JSONPath.compile(item); path.init(); Object value = path.eval(object); reserved.add(value); } return reserved; } public static Object reserveToObject(Object object, String... paths) { if (paths == null || paths.length == 0) { return object; } JSONObject reserved = new JSONObject(true); for (String item : paths) { JSONPath path = JSONPath.compile(item); path.init(); Segment lastSegement = path.segments[path.segments.length - 1]; if (lastSegement instanceof PropertySegment) { Object value = path.eval(object); if (value == null) { continue; } path.set(reserved, value); } else { // skip } } return reserved; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONPathException.java ================================================ 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONReader.java ================================================ 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; private transient JSONStreamContext lastContext; 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(); if (lastContext != null && lastContext.parent == context) { context = lastContext; if (context.state != JSONStreamContext.StartObject) { context.state = JSONStreamContext.StartObject; } } else { 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() { lastContext = context; 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); parser.handleResovleTask(object); 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; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONStreamAware.java ================================================ /* * 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; /** * Beans that support customized output of JSON text to a writer shall implement this interface. * * @author wenshao[szujobs@hotmail.com] */ public interface JSONStreamAware { /** * write JSON string to out. */ void writeJSONString(Appendable out) throws IOException; } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONStreamContext.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONValidator.java ================================================ package com.alibaba.fastjson; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.Reader; public abstract class JSONValidator implements Cloneable, Closeable { public enum Type { Object, Array, Value } protected boolean eof; protected int pos = -1; protected char ch; protected Type type; private Boolean validateResult; protected int count = 0; protected boolean supportMultiValue = false; public static JSONValidator fromUtf8(byte[] jsonBytes) { return new UTF8Validator(jsonBytes); } public static JSONValidator fromUtf8(InputStream is) { return new UTF8InputStreamValidator(is); } public static JSONValidator from(String jsonStr) { return new UTF16Validator(jsonStr); } public static JSONValidator from(Reader r) { return new ReaderValidator(r); } public boolean isSupportMultiValue() { return supportMultiValue; } public JSONValidator setSupportMultiValue(boolean supportMultiValue) { this.supportMultiValue = supportMultiValue; return this; } public Type getType() { if (type == null) { validate(); } return type; } abstract void next(); public boolean validate() { if (validateResult != null) { return validateResult; } for (;;) { if (!any()) { validateResult = false; return false; } skipWhiteSpace(); count++; if (eof) { validateResult = true; return true; } if (supportMultiValue) { skipWhiteSpace(); if (eof) { break; } continue; } else { validateResult = false; return false; } } validateResult = true; return true; } public void close() throws IOException { } private boolean any() { switch (ch) { case '{': next(); while (isWhiteSpace(ch)) { next(); } if (ch == '}') { next(); type = Type.Object; return true; } for (;;) { if (ch == '"') { fieldName(); } else { return false; } skipWhiteSpace(); if (ch == ':') { next(); } else { return false; } skipWhiteSpace(); if (!any()) { return false; } // kv 结束时,只能是 "," 或 "}" skipWhiteSpace(); if (ch == ',') { next(); skipWhiteSpace(); } else if (ch == '}') { next(); type = Type.Object; return true; } else { return false; } } case '[': next(); skipWhiteSpace(); if (ch == ']') { next(); type = Type.Array; return true; } for (;;) { if (!any()) { return false; } skipWhiteSpace(); if (ch == ',') { next(); skipWhiteSpace(); } else if (ch == ']') { next(); type = Type.Array; return true; } else { return false; } } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': if (ch == '-' || ch == '+') { next(); skipWhiteSpace(); if (ch < '0' || ch > '9') { return false; } } do { next(); } while (ch >= '0' && ch <= '9'); if (ch == '.') { next(); // bug fix: 0.e7 should not pass the test if (ch < '0' || ch > '9') { return false; } while (ch >= '0' && ch <= '9') { next(); } } if (ch == 'e' || ch == 'E') { next(); if (ch == '-' || ch == '+') { next(); } if (ch >= '0' && ch <= '9') { next(); } else { return false; } while (ch >= '0' && ch <= '9') { next(); } } type = Type.Value; break; case '"': next(); for (;;) { if (eof) { return false; } if (ch == '\\') { next(); if (ch == 'u') { next(); next(); next(); next(); next(); } else { next(); } } else if (ch == '"') { next(); type = Type.Value; return true; } else { next(); } } case 't': next(); if (ch != 'r') { return false; } next(); if (ch != 'u') { return false; } next(); if (ch != 'e') { return false; } next(); if (isWhiteSpace(ch) || ch == ',' || ch == ']' || ch == '}' || ch == '\0') { type = Type.Value; return true; } return false; case 'f': next(); if (ch != 'a') { return false; } next(); if (ch != 'l') { return false; } next(); if (ch != 's') { return false; } next(); if (ch != 'e') { return false; } next(); if (isWhiteSpace(ch) || ch == ',' || ch == ']' || ch == '}' || ch == '\0') { type = Type.Value; return true; } return false; case 'n': next(); if (ch != 'u') { return false; } next(); if (ch != 'l') { return false; } next(); if (ch != 'l') { return false; } next(); if (isWhiteSpace(ch) || ch == ',' || ch == ']' || ch == '}' || ch == '\0') { type = Type.Value; return true; } return false; default: return false; } return true; } protected void fieldName() { next(); for (; ; ) { if (ch == '\\') { next(); if (ch == 'u') { next(); next(); next(); next(); next(); } else { next(); } } else if (ch == '"') { next(); break; } else { next(); } } } protected boolean string() { next(); for (; !eof; ) { if (ch == '\\') { next(); if (ch == 'u') { next(); next(); next(); next(); next(); } else { next(); } } else if (ch == '"') { next(); return true; } else { next(); } } return false; } void skipWhiteSpace() { while (isWhiteSpace(ch)) { next(); } } static final boolean isWhiteSpace(char ch) { return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\f' || ch == '\b' ; } static class UTF8Validator extends JSONValidator { private final byte[] bytes; public UTF8Validator(byte[] bytes) { this.bytes = bytes; next(); skipWhiteSpace(); } void next() { ++pos; if (pos >= bytes.length) { ch = '\0'; eof = true; } else { ch = (char) bytes[pos]; } } } static class UTF8InputStreamValidator extends JSONValidator { private final static ThreadLocal bufLocal = new ThreadLocal(); private final InputStream is; private byte[] buf; private int end = -1; private int readCount = 0; public UTF8InputStreamValidator(InputStream is) { this.is = is; buf = bufLocal.get(); if (buf != null) { bufLocal.set(null); } else { buf = new byte[1024 * 8]; } next(); skipWhiteSpace(); } void next() { if (pos < end) { ch = (char) buf[++pos]; } else { if (!eof) { int len; try { len = is.read(buf, 0, buf.length); readCount++; } catch (IOException ex) { throw new JSONException("read error"); } if (len > 0) { ch = (char) buf[0]; pos = 0; end = len - 1; } else if (len == -1) { pos = 0; end = 0; buf = null; ch = '\0'; eof = true; } else { pos = 0; end = 0; buf = null; ch = '\0'; eof = true; throw new JSONException("read error"); } } } } public void close() throws IOException { bufLocal.set(buf); is.close(); } } static class UTF16Validator extends JSONValidator { private final String str; public UTF16Validator(String str) { this.str = str; next(); skipWhiteSpace(); } void next() { ++pos; if (pos >= str.length()) { ch = '\0'; eof = true; } else { ch = str.charAt(pos); } } protected final void fieldName() { for (int i = pos + 1; i < str.length(); ++i) { char ch = str.charAt(i); if (ch == '\\') { break; } if (ch == '\"') { this.ch = str.charAt(i + 1); pos = i + 1; return; } } next(); for (; ; ) { if (ch == '\\') { next(); if (ch == 'u') { next(); next(); next(); next(); next(); } else { next(); } } else if (ch == '"') { next(); break; } else if(eof){ break; }else { next(); } } } } static class ReaderValidator extends JSONValidator { private final static ThreadLocal bufLocal = new ThreadLocal(); final Reader r; private char[] buf; private int end = -1; private int readCount = 0; ReaderValidator(Reader r) { this.r = r; buf = bufLocal.get(); if (buf != null) { bufLocal.set(null); } else { buf = new char[1024 * 8]; } next(); skipWhiteSpace(); } void next() { if (pos < end) { ch = buf[++pos]; } else { if (!eof) { int len; try { len = r.read(buf, 0, buf.length); readCount++; } catch (IOException ex) { throw new JSONException("read error"); } if (len > 0) { ch = buf[0]; pos = 0; end = len - 1; } else if (len == -1) { pos = 0; end = 0; buf = null; ch = '\0'; eof = true; } else { pos = 0; end = 0; buf = null; ch = '\0'; eof = true; throw new JSONException("read error"); } } } } public void close() throws IOException { bufLocal.set(buf); r.close(); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/JSONWriter.java ================================================ 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); afterWrite(); } public void writeObject(Object object) { beforeWrite(); serializer.write(object); afterWrite(); } 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 afterWrite() { 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(); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/PropertyNamingStrategy.java ================================================ package com.alibaba.fastjson; /** * @since 1.2.15 */ public enum PropertyNamingStrategy { CamelCase, // camelCase PascalCase, // PascalCase SnakeCase, // snake_case KebabCase, // kebab-case NoChange, // NeverUseThisValueExceptDefaultValue; 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; } case NoChange: case NeverUseThisValueExceptDefaultValue: default: return propertyName; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/TypeReference.java ================================================ 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); 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 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; } public static Type intern(ParameterizedTypeImpl type) { Type cachedType = classTypeCache.get(type); if (cachedType == null) { classTypeCache.putIfAbsent(type, type); cachedType = classTypeCache.get(type); } return 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) { argTypes[i] = 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(); } ================================================ FILE: src/main/java/com/alibaba/fastjson/annotation/JSONCreator.java ================================================ 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 { } ================================================ FILE: src/main/java/com/alibaba/fastjson/annotation/JSONField.java ================================================ /* * 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.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.parser.Feature; import com.alibaba.fastjson.serializer.SerializerFeature; /** * @author wenshao[szujobs@hotmail.com] */ @Retention(RetentionPolicy.RUNTIME) @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 ""; String format() default ""; boolean serialize() default true; boolean deserialize() default true; 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; /** * Only support Object * * @since 1.2.61 */ String defaultValue() default ""; } ================================================ FILE: src/main/java/com/alibaba/fastjson/annotation/JSONPOJOBuilder.java ================================================ 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". */ 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. */ String withPrefix() default "with"; } ================================================ FILE: src/main/java/com/alibaba/fastjson/annotation/JSONType.java ================================================ 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.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializeFilter; 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.NeverUseThisValueExceptDefaultValue; /** * @since 1.2.49 */ Class[] serialzeFilters() default {}; /** * @since 1.2.71 * @return */ Class autoTypeCheckHandler() default ParserConfig.AutoTypeCheckHandler.class; } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/ByteVector.java ================================================ /*** * 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 dynamically extensible vector of bytes. This class is roughly equivalent to * a DataOutputStream on top of a ByteArrayOutputStream, but is more efficient. * * @author Eric Bruneton */ public class ByteVector { /** * The content of this vector. */ public byte[] data; /** * Actual number of bytes in this vector. */ public int length; /** * Constructs a new {@link ByteVector ByteVector} with a default initial size. */ public ByteVector() { data = new byte[64]; } /** * Constructs a new {@link ByteVector ByteVector} with the given initial size. * * @param initialSize the initial size of the byte vector to be constructed. */ public ByteVector(final int initialSize) { data = new byte[initialSize]; } /** * Puts a byte into this byte vector. The byte vector is automatically enlarged * if necessary. * * @param b a byte. * @return this byte vector. */ public ByteVector putByte(final int b) { int length = this.length; if (length + 1 > data.length) { enlarge(1); } data[length++] = (byte) b; this.length = length; return this; } /** * Puts two bytes into this byte vector. The byte vector is automatically * enlarged if necessary. * * @param b1 a byte. * @param b2 another byte. * @return this byte vector. */ ByteVector put11(final int b1, final int b2) { int length = this.length; if (length + 2 > data.length) { enlarge(2); } final byte[] data = this.data; data[length++] = (byte) b1; data[length++] = (byte) b2; this.length = length; return this; } /** * Puts a short into this byte vector. The byte vector is automatically enlarged * if necessary. * * @param s a short. * @return this byte vector. */ public ByteVector putShort(final int s) { int length = this.length; if (length + 2 > data.length) { enlarge(2); } final byte[] data = this.data; data[length++] = (byte) (s >>> 8); data[length++] = (byte) s; this.length = length; return this; } /** * Puts a byte and a short into this byte vector. The byte vector is * automatically enlarged if necessary. * * @param b a byte. * @param s a short. * @return this byte vector. */ public ByteVector put12(final int b, final int s) { int length = this.length; if (length + 3 > data.length) { enlarge(3); } final byte[] data = this.data; data[length++] = (byte) b; data[length++] = (byte) (s >>> 8); data[length++] = (byte) s; this.length = length; return this; } /** * Puts an int into this byte vector. The byte vector is automatically enlarged * if necessary. * * @param i an int. * @return this byte vector. */ public ByteVector putInt(final int i) { int length = this.length; if (length + 4 > data.length) { enlarge(4); } final byte[] data = this.data; data[length++] = (byte) (i >>> 24); data[length++] = (byte) (i >>> 16); data[length++] = (byte) (i >>> 8); data[length++] = (byte) i; this.length = length; return this; } /** * Puts an UTF8 string into this byte vector. The byte vector is automatically * enlarged if necessary. * * @param s a String. * @return this byte vector. */ public ByteVector putUTF8(final String s) { final int charLength = s.length(); int len = length; if (len + 2 + charLength > data.length) { enlarge(2 + charLength); } final byte[] data = this.data; // optimistic algorithm: instead of computing the byte length and then // serializing the string (which requires two loops), we assume the byte // length is equal to char length (which is the most frequent case), and // we start serializing the string right away. During the serialization, // if we find that this assumption is wrong, we continue with the // general method. data[len++] = (byte) (charLength >>> 8); data[len++] = (byte) charLength; for (int i = 0; i < charLength; ++i) { final char c = s.charAt(i); if ((c >= '\001' && c <= '\177') || (c >= '\u4E00' && c <= '\u9FFF')) { data[len++] = (byte) c; } else { throw new UnsupportedOperationException(); } } length = len; return this; } /** * Puts an array of bytes into this byte vector. The byte vector is * automatically enlarged if necessary. * * @param b an array of bytes. May be null to put len null * bytes into this byte vector. * @param off index of the fist byte of b that must be copied. * @param len number of bytes of b that must be copied. * @return this byte vector. */ public ByteVector putByteArray(final byte[] b, final int off, final int len) { if (length + len > data.length) { enlarge(len); } if (b != null) { System.arraycopy(b, off, data, length, len); } length += len; return this; } /** * Enlarge this byte vector so that it can receive n more bytes. * * @param size number of additional bytes that this byte vector should be able * to receive. */ private void enlarge(final int size) { final int length1 = 2 * data.length; final int length2 = length + size; final byte[] newData = new byte[length1 > length2 ? length1 : length2]; System.arraycopy(data, 0, newData, 0, length); data = newData; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/ClassReader.java ================================================ 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; private boolean readAnnotations; public ClassReader(InputStream is, boolean readAnnotations) throws IOException { this.readAnnotations = readAnnotations; { 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; // loop variables int u, v; // indexes in b int anns = 0; //read annotations if (readAnnotations) { u = getAttributes(); for (i = readUnsignedShort(u); i > 0; --i) { String attrName = readUTF8(u + 2, c); if ("RuntimeVisibleAnnotations".equals(attrName)) { anns = u + 8; break; } u += 6 + readInt(u + 4); } } // visits the header u = header; int len = readUnsignedShort(u + 6); 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); } if (anns != 0) { for (i = readUnsignedShort(anns), v = anns + 2; i > 0; --i) { String name = readUTF8(v, c); classVisitor.visitAnnotation(name); } } // 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 getAttributes() { // skips the header int u = header + 8 + readUnsignedShort(header + 6) * 2; // skips fields and methods for (int i = readUnsignedShort(u); i > 0; --i) { for (int j = readUnsignedShort(u + 8); j > 0; --j) { u += 6 + readInt(u + 12); } u += 8; } u += 2; for (int i = readUnsignedShort(u); i > 0; --i) { for (int j = readUnsignedShort(u + 8); j > 0; --j) { u += 6 + readInt(u + 12); } u += 8; } // the attribute_info structure starts just after the methods return u + 2; } 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/ClassWriter.java ================================================ /*** * 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; /** * * @author Eric Bruneton */ public class ClassWriter { /** * Minor and major version numbers of the class to be generated. */ int version; /** * Index of the next item to be added in the constant pool. */ int index; /** * The constant pool of this class. */ final ByteVector pool; /** * The constant pool's hash table data. */ Item[] items; /** * The threshold of the constant pool's hash table. */ int threshold; /** * A reusable key used to look for items in the {@link #items} hash table. */ final Item key; /** * A reusable key used to look for items in the {@link #items} hash table. */ final Item key2; /** * A reusable key used to look for items in the {@link #items} hash table. */ final Item key3; /** * A type table used to temporarily store internal names that will not necessarily be stored in the constant pool. * This type table is used by the control flow and data flow analysis algorithm used to compute stack map frames * from scratch. This array associates to each index i the Item whose index is i. All Item objects * stored in this array are also stored in the {@link #items} hash table. These two arrays allow to retrieve an Item * from its index or, conversely, to get the index of an Item from its value. Each Item stores an internal name in * its {@link Item#strVal1} field. */ Item[] typeTable; /** * The access flags of this class. */ private int access; /** * The constant pool item that contains the internal name of this class. */ private int name; /** * The internal name of this class. */ String thisName; /** * The constant pool item that contains the internal name of the super class of this class. */ private int superName; /** * Number of interfaces implemented or extended by this class or interface. */ private int interfaceCount; /** * The interfaces implemented or extended by this class or interface. More precisely, this array contains the * indexes of the constant pool items that contain the internal names of these interfaces. */ private int[] interfaces; /** * The fields of this class. These fields are stored in a linked list of {@link FieldWriter} objects, linked to each * other by their {@link FieldWriter#next} field. This field stores the first element of this list. */ FieldWriter firstField; /** * The fields of this class. These fields are stored in a linked list of {@link FieldWriter} objects, linked to each * other by their {@link FieldWriter#next} field. This field stores the last element of this list. */ FieldWriter lastField; /** * The methods of this class. These methods are stored in a linked list of {@link MethodWriter} objects, linked to * each other by their {@link MethodWriter#next} field. This field stores the first element of this list. */ MethodWriter firstMethod; /** * The methods of this class. These methods are stored in a linked list of {@link MethodWriter} objects, linked to * each other by their {@link MethodWriter#next} field. This field stores the last element of this list. */ MethodWriter lastMethod; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ public ClassWriter(){ this(0); } private ClassWriter(final int flags){ index = 1; pool = new ByteVector(); items = new Item[256]; threshold = (int) (0.75d * items.length); key = new Item(); key2 = new Item(); key3 = new Item(); } // ------------------------------------------------------------------------ // Implementation of the ClassVisitor interface // ------------------------------------------------------------------------ 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 = newClassItem(name).index; thisName = name; 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] = newClassItem(interfaces[i]).index; } } } // ------------------------------------------------------------------------ // Other public methods // ------------------------------------------------------------------------ /** * Returns the bytecode of the class that was build with this class writer. * * @return the bytecode of the class that was build with this class writer. */ public byte[] toByteArray() { // computes the real size of the bytecode of this class int size = 24 + 2 * interfaceCount; int nbFields = 0; FieldWriter fb = firstField; while (fb != null) { ++nbFields; size += fb.getSize(); fb = fb.next; } int nbMethods = 0; MethodWriter mb = firstMethod; while (mb != null) { ++nbMethods; size += mb.getSize(); mb = mb.next; } int attributeCount = 0; size += pool.length; // allocates a byte vector of this size, in order to avoid unnecessary // arraycopy operations in the ByteVector.enlarge() method ByteVector out = new ByteVector(size); out.putInt(0xCAFEBABE).putInt(version); out.putShort(index).putByteArray(pool.data, 0, pool.length); 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) { out.putShort(interfaces[i]); } out.putShort(nbFields); fb = firstField; while (fb != null) { fb.put(out); fb = fb.next; } out.putShort(nbMethods); mb = firstMethod; while (mb != null) { mb.put(out); mb = mb.next; } out.putShort(attributeCount); return out.data; } // ------------------------------------------------------------------------ // Utility methods: constant pool management // ------------------------------------------------------------------------ /** * Adds a number or string constant to the constant pool of the class being build. Does nothing if the constant pool * already contains a similar item. * * @param cst the value of the constant to be added to the constant pool. This parameter must be an {@link Integer}, * a {@link Float}, a {@link Long}, a {@link Double}, a {@link String} or a {@link Type}. * @return a new or already existing constant item with the given value. */ Item newConstItem(final Object cst) { 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.sort == 10 /*Type.OBJECT*/ ? t.getInternalName() : t.getDescriptor()); } else { throw new IllegalArgumentException("value " + cst); } } public int newUTF8(final String value) { key.set(1 /* UTF8 */, value, null, null); Item result = get(key); if (result == null) { pool.putByte(1 /* UTF8 */).putUTF8(value); result = new Item(index++, key); put(result); } return result.index; } public Item newClassItem(final String value) { key2.set(7 /* CLASS */, value, null, null); Item result = get(key2); if (result == null) { pool.put12(7 /* CLASS */, newUTF8(value)); result = new Item(index++, key2); put(result); } return result; } /** * Adds a field reference to the constant pool of the class being build. Does nothing if the constant pool already * contains a similar item. * * @param owner the internal name of the field's owner class. * @param name the field's name. * @param desc the field's descriptor. * @return a new or already existing field reference item. */ Item newFieldItem(final String owner, final String name, final String desc) { key3.set(9 /* FIELD */, owner, name, desc); Item result = get(key3); if (result == null) { // 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); } return result; } /** * Adds a method reference to the constant pool of the class being build. Does nothing if the constant pool already * contains a similar item. * * @param owner the internal name of the method's owner class. * @param name the method's name. * @param desc the method's descriptor. * @param itf true if owner is an interface. * @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 ? 11 /* IMETH */ : 10 /* METH */; key3.set(type, owner, name, desc); Item result = get(key3); if (result == null) { // 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; } private Item newString(final String value) { key2.set(8 /* STR */, value, null, null); Item result = get(key2); if (result == null) { pool.put12(8 /*STR*/, newUTF8(value)); result = new Item(index++, key2); put(result); } return result; } 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(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; } private Item get(final Item key) { Item i = items[key.hashCode % items.length]; while (i != null && (i.type != key.type || !key.isEqualTo(i))) { i = i.next; } return i; } private void put(final Item i) { if (index > threshold) { int ll = items.length; int nl = ll * 2 + 1; Item[] newItems = new Item[nl]; for (int l = ll - 1; l >= 0; --l) { Item j = items[l]; while (j != null) { int index = j.hashCode % newItems.length; Item k = j.next; j.next = newItems[index]; newItems[index] = j; j = k; } } items = newItems; threshold = (int) (nl * 0.75); } int index = i.hashCode % items.length; i.next = items[index]; items[index] = i; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/FieldWriter.java ================================================ /*** * 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; /** * An FieldWriter that generates Java fields in bytecode form. * * @author Eric Bruneton */ public final class FieldWriter { FieldWriter next; /** * Access flags of this field. */ private final int access; /** * The index of the constant pool item that contains the name of this method. */ private final int name; /** * The index of the constant pool item that contains the descriptor of this field. */ private final int desc; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ public FieldWriter(final ClassWriter cw, final int access, final String name, final String desc){ if (cw.firstField == null) { cw.firstField = this; } else { cw.lastField.next = this; } cw.lastField = this; this.access = access; this.name = cw.newUTF8(name); this.desc = cw.newUTF8(desc); } // ------------------------------------------------------------------------ // Implementation of the FieldVisitor interface // ------------------------------------------------------------------------ public void visitEnd() { } // ------------------------------------------------------------------------ // Utility methods // ------------------------------------------------------------------------ /** * Returns the size of this field. * * @return the size of this field. */ int getSize() { return 8; } /** * Puts the content of this field into the given byte vector. * * @param out where the content of this field must be put. */ void put(final ByteVector out) { 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/Item.java ================================================ /*** * 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 constant pool item. Constant pool items can be created with the 'newXXX' methods in the {@link ClassWriter} class. * * @author Eric Bruneton */ final class Item { /** * Index of this item in the constant pool. */ int index; int type; /** * Value of this item, for an integer item. */ int intVal; /** * Value of this item, for a long item. */ long longVal; /** * First part of the value of this item, for items that do not hold a primitive value. */ String strVal1; /** * Second part of the value of this item, for items that do not hold a primitive value. */ String strVal2; /** * Third part of the value of this item, for items that do not hold a primitive value. */ String strVal3; /** * The hash code value of this constant pool item. */ int hashCode; /** * Link to another constant pool item, used for collision lists in the constant pool's hash table. */ Item next; /** * Constructs an uninitialized {@link Item}. */ Item(){ } /** * Constructs a copy of the given item. * * @param index index of the item to be constructed. * @param i the item that must be copied into the item to be constructed. */ Item(final int index, final Item i){ this.index = index; type = i.type; intVal = i.intVal; longVal = i.longVal; strVal1 = i.strVal1; strVal2 = i.strVal2; strVal3 = i.strVal3; hashCode = i.hashCode; } /** * Sets this item to an item that do not hold a primitive value. * * @param type the type of this item. * @param strVal1 first part of the value of this item. * @param strVal2 second part of the value of this item. * @param strVal3 third part of the value of this item. */ void set(final int type, final String strVal1, final String strVal2, final String strVal3) { this.type = type; this.strVal1 = strVal1; this.strVal2 = strVal2; this.strVal3 = strVal3; switch (type) { case 1 /* ClassWriter.UTF8 */: case 8 /* ClassWriter.STR */: case 7 /* ClassWriter.CLASS */: case 13 /* ClassWriter.TYPE_NORMAL */: hashCode = 0x7FFFFFFF & (type + strVal1.hashCode()); return; case 12 /* ClassWriter.NAME_TYPE */: hashCode = 0x7FFFFFFF & (type + strVal1.hashCode() * strVal2.hashCode()); return; // ClassWriter.FIELD: // ClassWriter.METH: // ClassWriter.IMETH: default: 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 * {@link #type}. * * @param i the item to be compared to this one. Both items must have the same {@link #type}. * @return true if the given item if equal to this one, false otherwise. */ boolean isEqualTo(final Item i) { switch (type) { case 1 /* ClassWriter.UTF8 */: case 8 /* ClassWriter.STR */: case 7 /* ClassWriter.CLASS */ : case 13 /* ClassWriter.TYPE_NORMAL */ : return i.strVal1.equals(strVal1); case 15 /* ClassWriter.TYPE_MERGED */ : case 5 /* ClassWriter.LONG */ : case 6 /* ClassWriter.DOUBLE */: return i.longVal == longVal; case 3 /* ClassWriter.INT */ : case 4 /* ClassWriter.FLOAT */: return i.intVal == intVal; case 12 /* ClassWriter.NAME_TYPE */: return i.strVal1.equals(strVal1) && i.strVal2.equals(strVal2); // case ClassWriter.FIELD: // case ClassWriter.METH: // case ClassWriter.IMETH: default: return i.strVal1.equals(strVal1) && i.strVal2.equals(strVal2) && i.strVal3.equals(strVal3); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/Label.java ================================================ /*** * 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 label represents a position in the bytecode of a method. Labels are used for jump, goto, and switch instructions, * and for try catch blocks. A label designates the instruction that is just after. Note however that there can * be other elements between a label and the instruction it designates (such as other labels, stack map frames, line * numbers, etc.). * * @author Eric Bruneton */ public class Label { int status; /** * The position of this label in the code, if known. */ int position; /** * Number of forward references to this label, times two. */ private int referenceCount; /** * Informations about forward references. Each forward reference is described by two consecutive integers in this * array: the first one is the position of the first byte of the bytecode instruction that contains the forward * 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 MethodWriter#visitMaxs, after all forward references have been * resolved. Hence the same array can be used for both purposes without problems. */ private int[] srcAndRefPositions; /** * The bit mask to extract the type of a forward reference to this label. The extracted type is * either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link #FORWARD_REFERENCE_TYPE_WIDE}. */ static final int FORWARD_REFERENCE_TYPE_MASK = 0xF0000000; /** * The bit mask to extract the 'handle' of a forward reference to this label. The extracted handle * is the bytecode offset where the forward reference value is stored (using either 2 or 4 bytes, * as indicated by the {@link #FORWARD_REFERENCE_TYPE_MASK}). */ static final int FORWARD_REFERENCE_HANDLE_MASK = 0x0FFFFFFF; /** * The type of forward references stored with two bytes in the bytecode. This is the case, for * instance, of a forward reference from an ifnull instruction. */ static final int FORWARD_REFERENCE_TYPE_SHORT = 0x10000000; /** * The type of forward references stored in four bytes in the bytecode. This is the case, for * instance, of a forward reference from a lookupswitch instruction. */ static final int FORWARD_REFERENCE_TYPE_WIDE = 0x20000000; // ------------------------------------------------------------------------ /* * Fields for the control flow and data flow graph analysis algorithms (used to compute the maximum stack size or * the stack map frames). A control flow graph contains one node per "basic block", and one edge per "jump" from one * basic block to another. Each node (i.e., each basic block) is represented by the Label object that corresponds to * the first instruction of this basic block. Each node also stores the list of its successors in the graph, as a * linked list of Edge objects. The control flow analysis algorithms used to compute the maximum stack size or the * 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, * 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 * and absolute input stack heights, while the algorithm used to compute stack map frames computes relative output * frames and absolute input frames. */ /** * Start of the output stack relatively to the input stack. The exact semantics of this field depends on the * algorithm that is used. When only the maximum stack size is computed, this field is the number of elements in the * input stack. When the stack map frames are completely computed, this field is the offset of the first output * stack element relatively to the top of the input stack. This offset is always negative or null. A null offset * means that the output stack must be appended to the input stack. A -n offset means that the first n output stack * elements must replace the top n input stack elements, and that the other elements must be appended to the input * stack. */ int inputStackTop; /** * Maximum height reached by the output stack, relatively to the top of the input stack. This maximum is always * positive or null. */ int outputStackMax; /** * The successor of this label, in the order they are visited. This linked list does not include labels used for * 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). */ Label successor; /** * The next basic block in the basic block stack. This stack is used in the main loop of the fix point algorithm * used in the second step of the control flow analysis algorithms. It is also used in {@link #visitSubroutine} to * avoid using a recursive method. * * @see MethodWriter#visitMaxs */ Label next; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ /** * Constructs a new label. */ public Label(){ } // ------------------------------------------------------------------------ // Methods to compute offsets and to manage forward references // ------------------------------------------------------------------------ /** * Puts a reference to this label in the bytecode of a method. If the position of the label is known, the offset is * computed and written directly. Otherwise, a null offset is written and a new forward reference is declared for * this label. * * @param owner the code writer that calls this method. * @param out the bytecode of the method. * @param source the position of first byte of the bytecode instruction that contains this label. * @param wideOffset true if the reference must be stored in 4 bytes, or false if it must be * stored with 2 bytes. * @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, boolean wideOffset) { if ((status & 2 /* RESOLVED */) == 0) { if (wideOffset) { addReference(source, out.length, FORWARD_REFERENCE_TYPE_WIDE); out.putInt(-1); } else { addReference(source, out.length, FORWARD_REFERENCE_TYPE_SHORT); out.putShort(-1); } } else { if (wideOffset) { out.putInt(position - source); } else { out.putShort(position - source); } } } /** * Adds a forward reference to this label. This method must be called only for a true forward reference, i.e. only * if this label is not resolved yet. For backward references, the offset of the reference can be, and must be, * computed and stored directly. * * @param sourcePosition the position of the referencing instruction. This position will be used to compute the * offset of this forward reference. * @param referencePosition the position where the offset for this forward reference must be stored. */ private void addReference(final int sourcePosition, final int referencePosition, final int referenceType) { if (srcAndRefPositions == null) { srcAndRefPositions = new int[6]; } if (referenceCount >= srcAndRefPositions.length) { int[] a = new int[srcAndRefPositions.length + 6]; System.arraycopy(srcAndRefPositions, 0, a, 0, srcAndRefPositions.length); srcAndRefPositions = a; } srcAndRefPositions[referenceCount++] = sourcePosition; srcAndRefPositions[referenceCount++] = referencePosition | referenceType; } /** * Resolves all forward references to this label. This method must be called when this label is added to the * bytecode of the method, i.e. when its position becomes known. This method fills in the blanks that where left in * the bytecode by each forward reference previously added to this label. * * @param owner the code writer that calls this method. * @param position the position of this label in the bytecode. * @param data the bytecode of the method. * @return true if a blank that was left for this label was to small to store the offset. In such a case * the corresponding jump instruction is replaced with a pseudo instruction (using unused opcodes) using an unsigned * two bytes offset. These pseudo instructions will need to be replaced with true instructions with wider offsets (4 * bytes instead of 2). This is done in {@link MethodWriter#resizeInstructions}. * @throws IllegalArgumentException if this label has already been resolved, or if it has not been created by the * given code writer. */ 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 handle = reference & FORWARD_REFERENCE_HANDLE_MASK; int offset = position - source; if ((reference & FORWARD_REFERENCE_TYPE_MASK) == FORWARD_REFERENCE_TYPE_SHORT) { data[handle++] = (byte) (offset >>> 8); data[handle] = (byte) offset; } else { data[handle++] = (byte) (offset >>> 24); data[handle++] = (byte) (offset >>> 16); data[handle++] = (byte) (offset >>> 8); data[handle] = (byte) offset; } } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/MethodCollector.java ================================================ 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 StringBuilder result; protected boolean debugInfoPresent; protected MethodCollector(int ignoreCount, int paramCount) { this.ignoreCount = ignoreCount; this.paramCount = paramCount; this.result = new StringBuilder(); 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) : ""; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/MethodVisitor.java ================================================ /*** * 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; /** * * @author Eric Bruneton */ public interface MethodVisitor { // ------------------------------------------------------------------------- // Annotations and non standard attributes // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Normal instructions // ------------------------------------------------------------------------- /** * Visits a zero operand instruction. * * @param opcode the opcode of the instruction to be visited. This opcode is either NOP, ACONST_NULL, ICONST_M1, * ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, ICONST_5, LCONST_0, LCONST_1, FCONST_0, FCONST_1, FCONST_2, * DCONST_0, DCONST_1, IALOAD, LALOAD, FALOAD, DALOAD, AALOAD, BALOAD, CALOAD, SALOAD, IASTORE, LASTORE, FASTORE, * DASTORE, AASTORE, BASTORE, CASTORE, SASTORE, POP, POP2, DUP, DUP_X1, DUP_X2, DUP2, DUP2_X1, DUP2_X2, SWAP, IADD, * LADD, FADD, DADD, ISUB, LSUB, FSUB, DSUB, IMUL, LMUL, FMUL, DMUL, IDIV, LDIV, FDIV, DDIV, IREM, LREM, FREM, DREM, * INEG, LNEG, FNEG, DNEG, ISHL, LSHL, ISHR, LSHR, IUSHR, LUSHR, IAND, LAND, IOR, LOR, IXOR, LXOR, I2L, I2F, I2D, * L2I, L2F, L2D, F2I, F2L, F2D, D2I, D2L, D2F, I2B, I2C, I2S, LCMP, FCMPL, FCMPG, DCMPL, DCMPG, IRETURN, LRETURN, * FRETURN, DRETURN, ARETURN, RETURN, ARRAYLENGTH, ATHROW, MONITORENTER, or MONITOREXIT. */ void visitInsn(int opcode); void visitIntInsn(int opcode, int operand); /** * Visits a local variable instruction. A local variable instruction is an instruction that loads or stores the * value of a local variable. * * @param opcode the opcode of the local variable instruction to be visited. This opcode is either ILOAD, LLOAD, * FLOAD, DLOAD, ALOAD, ISTORE, LSTORE, FSTORE, DSTORE, ASTORE or RET. * @param var the operand of the instruction to be visited. This operand is the index of a local variable. */ void visitVarInsn(int opcode, int var); /** * Visits a type instruction. A type instruction is an instruction that takes the internal name of a class as * parameter. * * @param opcode the opcode of the type instruction to be visited. This opcode is either NEW, ANEWARRAY, CHECKCAST * or INSTANCEOF. * @param type the operand of the instruction to be visited. This operand must be the internal name of an object or * array class (see {@link Type#getInternalName() getInternalName}). */ void visitTypeInsn(int opcode, String type); /** * Visits a field instruction. A field instruction is an instruction that loads or stores the value of a field of an * object. * * @param opcode the opcode of the type instruction to be visited. This opcode is either GETSTATIC, PUTSTATIC, * GETFIELD or PUTFIELD. * @param owner the internal name of the field's owner class (see {@link Type#getInternalName() getInternalName}). * @param name the field's name. * @param desc the field's descriptor (see {@link Type Type}). */ void visitFieldInsn(int opcode, String owner, String name, String desc); void visitMethodInsn(int opcode, String owner, String name, String desc); /** * Visits a jump instruction. A jump instruction is an instruction that may jump to another instruction. * * @param opcode the opcode of the type instruction to be visited. This opcode is either IFEQ, IFNE, IFLT, IFGE, * IFGT, IFLE, IF_ICMPEQ, IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ, IF_ACMPNE, GOTO, JSR, * IFNULL or IFNONNULL. * @param label the operand of the instruction to be visited. This operand is a label that designates the * instruction to which the jump instruction may jump. */ void visitJumpInsn(int opcode, Label label); /** * Visits a label. A label designates the instruction that will be visited just after it. * * @param label a {@link Label Label} object. */ void visitLabel(Label label); // ------------------------------------------------------------------------- // Special instructions // ------------------------------------------------------------------------- /** * Visits a LDC instruction. * * @param cst the constant to be loaded on the stack. This parameter must be a non null {@link Integer}, a * {@link Float}, a {@link Long}, a {@link Double} a {@link String} (or a {@link Type} for .class * constants, for classes whose version is 49.0 or more). */ void visitLdcInsn(Object cst); /** * Visits an IINC instruction. * * @param var index of the local variable to be incremented. * @param increment amount to increment the local variable by. */ void visitIincInsn(int var, int increment); // ------------------------------------------------------------------------- // Exceptions table entries, debug information, max stack and max locals // ------------------------------------------------------------------------- /** * Visits the maximum stack size and the maximum number of local variables of the method. * * @param maxStack maximum stack size of the method. * @param maxLocals maximum number of local variables for the method. */ void visitMaxs(int maxStack, int maxLocals); /** * Visits the end of the method. This method, which is the last one to be called, is used to inform the visitor that * all the annotations and attributes of the method have been visited. */ void visitEnd(); } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/MethodWriter.java ================================================ /*** * 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; /** * @author Eric Bruneton * @author Eugene Kuleshov */ public class MethodWriter implements MethodVisitor { /** * Next method writer (see {@link ClassWriter#firstMethod firstMethod}). */ MethodWriter next; /** * The class writer to which this method must be added. */ final ClassWriter cw; /** * Access flags of this method. */ private int access; /** * The index of the constant pool item that contains the name of this method. */ private final int name; /** * The index of the constant pool item that contains the descriptor of this method. */ private final int desc; /** * Number of exceptions that can be thrown by this method. */ int exceptionCount; /** * The exceptions that can be thrown by this method. More precisely, this array contains the indexes of the constant * pool items that contain the internal names of these exception classes. */ int[] exceptions; /** * The bytecode of this method. */ private ByteVector code = new ByteVector(); /** * Maximum stack size of this method. */ private int maxStack; /** * Maximum number of local variables for this method. */ private int maxLocals; // ------------------------------------------------------------------------ /* * Fields for the control flow graph analysis algorithm (used to compute the maximum stack size). A control flow * graph contains one node per "basic block", and one edge per "jump" from one basic block to another. Each node * (i.e., each basic block) is represented by the Label object that corresponds to the first instruction of this * basic block. Each node also stores the list of its successors in the graph, as a linked list of Edge objects. */ // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ 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 { cw.lastMethod.next = this; } cw.lastMethod = this; this.cw = cw; this.access = access; this.name = cw.newUTF8(name); this.desc = cw.newUTF8(desc); if (exceptions != null && exceptions.length > 0) { exceptionCount = exceptions.length; this.exceptions = new int[exceptionCount]; for (int i = 0; i < exceptionCount; ++i) { this.exceptions[i] = cw.newClassItem(exceptions[i]).index; } } } // ------------------------------------------------------------------------ // Implementation of the MethodVisitor interface // ------------------------------------------------------------------------ public void visitInsn(final int opcode) { // adds the instruction to the bytecode of the method code.putByte(opcode); // update currentBlock // Label currentBlock = this.currentBlock; } public void visitIntInsn(final int opcode, final int operand) { // Label currentBlock = this.currentBlock; // adds the instruction to the bytecode of the method // if (opcode == Opcodes.SIPUSH) { // code.put12(opcode, operand); // } else { // BIPUSH or NEWARRAY code.put11(opcode, operand); // } } public void visitVarInsn(final int opcode, final int var) { // Label currentBlock = this.currentBlock; // adds the instruction to the bytecode of the method if (var < 4 && opcode != Opcodes.RET) { int opt; if (opcode < Opcodes.ISTORE) { /* ILOAD_0 */ opt = 26 + ((opcode - Opcodes.ILOAD) << 2) + var; } else { /* ISTORE_0 */ opt = 59 + ((opcode - Opcodes.ISTORE) << 2) + var; } code.putByte(opt); } else if (var >= 256) { code.putByte(196 /* WIDE */).put12(opcode, var); } else { code.put11(opcode, var); } } public void visitTypeInsn(final int opcode, final String type) { Item i = cw.newClassItem(type); // Label currentBlock = this.currentBlock; // adds the instruction to the bytecode of the method code.put12(opcode, i.index); } public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { Item i = cw.newFieldItem(owner, name, desc); // Label currentBlock = this.currentBlock; // adds the instruction to the bytecode of the method code.put12(opcode, i.index); } public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) { boolean itf = opcode == Opcodes.INVOKEINTERFACE; Item i = cw.newMethodItem(owner, name, desc, itf); int argSize = i.intVal; // Label currentBlock = this.currentBlock; // adds the instruction to the bytecode of the method if (itf) { if (argSize == 0) { argSize = Type.getArgumentsAndReturnSizes(desc); i.intVal = argSize; } code.put12(Opcodes.INVOKEINTERFACE, i.index).put11(argSize >> 2, 0); } else { code.put12(opcode, i.index); } } 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 & 2 /* Label.RESOLVED */ ) != 0 && label.position - code.length < Short.MIN_VALUE) { throw new UnsupportedOperationException(); } else { /* * case of a backward jump with an offset >= -32768, or of a forward jump with, of course, an unknown * offset. In these cases we store the offset in 2 bytes (which will be increased in resizeInstructions, if * needed). */ code.putByte(opcode); // Currently, GOTO_W is the only supported wide reference label.put(this, code, code.length - 1, opcode == Opcodes.GOTO_W); } } public void visitLabel(final Label label) { // resolves previous forward references to label, if any label.resolve(this, code.length, code.data); } public void visitLdcInsn(final Object cst) { Item i = cw.newConstItem(cst); // Label currentBlock = this.currentBlock; // adds the instruction to the bytecode of the method int index = i.index; 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(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(132 /* Opcodes.IINC*/ ).put11(var, increment); // } } public void visitMaxs(final int maxStack, final int maxLocals) { this.maxStack = maxStack; this.maxLocals = maxLocals; } public void visitEnd() { } // ------------------------------------------------------------------------ // Utility methods: control flow analysis algorithm // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Utility methods: stack map frames // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Utility methods: dump bytecode array // ------------------------------------------------------------------------ /** * Returns the size of the bytecode of this method. * * @return the size of the bytecode of this method. */ final int getSize() { int size = 8; if (code.length > 0) { cw.newUTF8("Code"); size += 18 + code.length + 8 * 0; } if (exceptionCount > 0) { cw.newUTF8("Exceptions"); size += 8 + 2 * exceptionCount; } return size; } /** * Puts the bytecode of this method in the given byte vector. * * @param out the byte vector into which the bytecode of this method must be copied. */ final void put(final ByteVector out) { 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) { ++attributeCount; } if (exceptionCount > 0) { ++attributeCount; } out.putShort(attributeCount); if (code.length > 0) { int size = 12 + code.length + 8 * 0; // handlerCount out.putShort(cw.newUTF8("Code")).putInt(size); out.putShort(maxStack).putShort(maxLocals); out.putInt(code.length).putByteArray(code.data, 0, code.length); out.putShort(0); // handlerCount attributeCount = 0; out.putShort(attributeCount); } if (exceptionCount > 0) { out.putShort(cw.newUTF8("Exceptions")).putInt(2 * exceptionCount + 2); out.putShort(exceptionCount); for (int i = 0; i < exceptionCount; ++i) { out.putShort(exceptions[i]); } } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/Opcodes.java ================================================ /*** * 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; /** * Defines the JVM opcodes, access flags and array type codes. This interface does not define all the JVM opcodes * because some opcodes are automatically handled. For example, the xLOAD and xSTORE opcodes are automatically replaced * by xLOAD_n and xSTORE_n opcodes when possible. The xLOAD_n and xSTORE_n opcodes are therefore not defined in this * interface. Likewise for LDC, automatically replaced by LDC_W or LDC2_W when necessary, WIDE, GOTO_W and JSR_W. * * @author Eric Bruneton * @author Eugene Kuleshov */ public interface Opcodes { int T_INT = 10; // versions // int V1_1 = 3 << 16 | 45; // int V1_2 = 0 << 16 | 46; // int V1_3 = 0 << 16 | 47; // int V1_4 = 0 << 16 | 48; int V1_5 = 0 << 16 | 49; // int V1_6 = 0 << 16 | 50; // int V1_7 = 0 << 16 | 51; // access flags int ACC_PUBLIC = 0x0001; // class, field, method int ACC_SUPER = 0x0020; // class // opcodes // visit method (- = idem) int ACONST_NULL = 1; // - int ICONST_0 = 3; // - int ICONST_1 = 4; // - int LCONST_0 = 9; // - int LCONST_1 = 10; // - int FCONST_0 = 11; // - int DCONST_0 = 14; // - int BIPUSH = 16; // visitIntInsn // int SIPUSH = 17; // - // int LDC = 18; // visitLdcInsn // int LDC_W = 19; // - // int LDC2_W = 20; // - int ILOAD = 21; // visitVarInsn int LLOAD = 22; // - int FLOAD = 23; // - int DLOAD = 24; // - int ALOAD = 25; // - int ISTORE = 54; // visitVarInsn int LSTORE = 55; // - int FSTORE = 56; // - int DSTORE = 57; // - int ASTORE = 58; // - int IASTORE = 79; // visitInsn int POP = 87; // - // int POP2 = 88; // - int DUP = 89; // - int IADD = 96; // - // 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 DCMPL = 151; // - int IFEQ = 153; // visitJumpInsn int IFNE = 154; // - 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_ACMPEQ = 165; // - int IF_ACMPNE = 166; // - int GOTO = 167; // - int RET = 169; // visitVarInsn int ARETURN = 176; // - int RETURN = 177; // - int GETSTATIC = 178; // visitFieldInsn int GETFIELD = 180; // - int PUTFIELD = 181; // - int INVOKEVIRTUAL = 182; // visitMethodInsn int INVOKESPECIAL = 183; // - int INVOKESTATIC = 184; // - 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 CHECKCAST = 192; // visitTypeInsn int INSTANCEOF = 193; int IFNULL = 198; // visitJumpInsn int IFNONNULL = 199; // - int GOTO_W = 200; // visitJumpInsn // int JSR_W = 201; // - } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/Type.java ================================================ /*** * 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 Java type. This class can be used to make it easier to manipulate type and method descriptors. * * @author Eric Bruneton * @author Chris Nokleberg */ public class Type { /** * The void type. */ 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(1, null, ('Z' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The char type. */ 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(3, null, ('B' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The short type. */ 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(5, null, ('I' << 24) | (0 << 16) | (0 << 8) | 1, 1); /** * The float type. */ 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(7, null, ('J' << 24) | (1 << 16) | (1 << 8) | 2, 1); /** * The double type. */ public static final Type DOUBLE_TYPE = new Type(8, null, ('D' << 24) | (3 << 16) | (3 << 8) | 2, 1); // ------------------------------------------------------------------------ // Fields // ------------------------------------------------------------------------ /** * The sort of this Java type. */ protected final int sort; /** * A buffer containing the internal name of this Java type. This field is only used for reference types. */ private final char[] buf; /** * The offset of the internal name of this Java type in {@link #buf buf} or, for primitive types, the size, * descriptor and getOpcode offsets for this type (byte 0 contains the size, byte 1 the descriptor, byte 2 the * offset for IALOAD or IASTORE, byte 3 the offset for all other instructions). */ private final int off; /** * The length of the internal name of this Java type. */ private final int len; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ private Type(final int sort, final char[] buf, final int off, final int len){ this.sort = sort; this.buf = buf; this.off = off; this.len = len; } /** * Returns the Java type corresponding to the given type descriptor. * * @param typeDescriptor a type descriptor. * @return the Java type corresponding to the given type descriptor. */ public static Type getType(final String typeDescriptor) { return getType(typeDescriptor.toCharArray(), 0); } public static int getArgumentsAndReturnSizes(final String desc) { int n = 1; int c = 1; while (true) { char car = desc.charAt(c++); if (car == ')') { car = desc.charAt(c); return n << 2 | (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1)); } else if (car == 'L') { 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 == 'D' || car == 'J') { n += 2; } else { n += 1; } } } /** * Returns the Java type corresponding to the given type descriptor. * * @param buf a buffer containing a type descriptor. * @param off the offset of this descriptor in the previous buffer. * @return the Java type corresponding to the given type descriptor. */ private static Type getType(final char[] buf, final int off) { int len; switch (buf[off]) { case 'V': return VOID_TYPE; case 'Z': return BOOLEAN_TYPE; case 'C': return CHAR_TYPE; case 'B': return BYTE_TYPE; case 'S': return SHORT_TYPE; case 'I': return INT_TYPE; case 'F': return FLOAT_TYPE; case 'J': return LONG_TYPE; case 'D': return DOUBLE_TYPE; case '[': len = 1; while (buf[off + len] == '[') { ++len; } if (buf[off + len] == 'L') { ++len; while (buf[off + len] != ';') { ++len; } } return new Type(9 /*ARRAY*/, buf, off, len + 1); // case 'L': default: len = 1; while (buf[off + len] != ';') { ++len; } return new Type(10/*OBJECT*/, buf, off + 1, len - 1); } } public String getInternalName() { return new String(buf, off, len); } // ------------------------------------------------------------------------ // Conversion to type descriptors // ------------------------------------------------------------------------ /** * Returns the descriptor corresponding to this Java type. * * @return the descriptor corresponding to this Java type. */ String getDescriptor() { return new String(this.buf, off, len); } private int getDimensions() { int i = 1; while (buf[off + i] == '[') { ++i; } return i; } 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()); StringBuilder b = new StringBuilder(elementType.getClassName()); for (int i = getDimensions(); i > 0; --i) { b.append("[]"); } return b.toString(); // case OBJECT: default: return new String(buf, off, len).replace('/', '.'); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/asm/TypeCollector.java ================================================ package com.alibaba.fastjson.asm; import com.alibaba.fastjson.util.ASMUtils; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; public class TypeCollector { private static String JSONType = ASMUtils.desc(com.alibaba.fastjson.annotation.JSONType.class); 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; protected boolean jsonType; 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); } public void visitAnnotation(String desc) { if (JSONType.equals(desc)) { jsonType = true; } } private boolean correctTypeName(Type type, String paramTypeName) { String s = type.getClassName(); // array notation needs cleanup. StringBuilder braces = new StringBuilder(); while (s.endsWith("[]")) { braces.append('['); s = s.substring(0, s.length() - 2); } if (braces.length() != 0) { if (primitives.containsKey(s)) { s = braces.append(primitives.get(s)).toString(); } else { s = braces.append('L').append(s).append(';').toString(); } } return s.equals(paramTypeName); } public String[] getParameterNamesForMethod() { if (collector == null || !collector.debugInfoPresent) { return new String[0]; } return collector.getResult().split(","); } public boolean matched() { return collector != null; } public boolean hasJsonType() { return jsonType; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/DefaultExtJSONParser.java ================================================ /* * 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/DefaultJSONParser.java ================================================ /* * Copyright 1999-2019 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.*; import com.alibaba.fastjson.parser.deserializer.*; import com.alibaba.fastjson.serializer.*; import com.alibaba.fastjson.util.TypeUtils; 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 static com.alibaba.fastjson.parser.JSONLexer.EOI; import static com.alibaba.fastjson.parser.JSONToken.*; /** * @author wenshao[szujobs@hotmail.com] */ public class DefaultJSONParser implements Closeable { 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 int objectKeyLevel = 0; 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 }; primitiveClasses.addAll(Arrays.asList(classes)); } 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; } /** * @deprecated * @see setDateFormat */ public void setDateFomrat(DateFormat dateFormat) { this.setDateFormat(dateFormat); } public void setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } public DefaultJSONParser(String input){ this(input, ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE); } public DefaultJSONParser(final String input, final ParserConfig config){ this(input, new JSONScanner(input, JSON.DEFAULT_PARSER_FEATURE), config); } public DefaultJSONParser(final String input, final ParserConfig config, int features){ this(input, new JSONScanner(input, features), config); } public DefaultJSONParser(final char[] input, int length, final ParserConfig config, int features){ 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.lexer = lexer; this.input = input; this.config = config; this.symbolTable = config.symbolTable; 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 String getInput() { if (input instanceof char[]) { return new String((char[]) input); } return input.toString(); } @SuppressWarnings({ "unchecked", "rawtypes" }) 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; } 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 { boolean isJsonObjectMap = object instanceof JSONObject; Map map = isJsonObjectMap ? ((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) || isJsonObjectMap) { 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 == '[') { if (objectKeyLevel++ > 512) { throw new JSONException("object key level > 512"); } 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); } } if (!isObjectKey) { lexer.next(); lexer.skipWhitespace(); } ch = lexer.getCurrent(); lexer.resetStringPosition(); 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 if ("java.util.HashMap".equals(typeName)) { clazz = java.util.HashMap.class; } else if ("java.util.LinkedHashMap".equals(typeName)) { clazz = java.util.LinkedHashMap.class; } else { boolean allDigits = true; for (int i = 0; i < typeName.length(); ++i) { char c = typeName.charAt(i); if (c < '0' || c > '9') { allDigits = false; break; } } if (!allDigits) { 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) { instance = TypeUtils.cast(object, clazz, this.config); } if (instance == null) { if (clazz == Cloneable.class) { instance = new HashMap(); } else if ("java.util.Collections$EmptyMap".equals(typeName)) { instance = Collections.emptyMap(); } else if ("java.util.Collections$UnmodifiableMap".equals(typeName)) { instance = Collections.unmodifiableMap(new HashMap()); } 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.setResolveStatus(NONE); 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); } else if (deserializer instanceof MapDeserializer) { this.setResolveStatus(NONE); } Object obj = deserializer.deserialze(this, clazz, fieldName); return obj; } if (key == "$ref" && context != null && (object == null || object.size() == 0) && !lexer.isEnabled(Feature.DisableSpecialKeyDetect)) { lexer.nextToken(JSONToken.LITERAL_STRING); if (lexer.token() == JSONToken.LITERAL_STRING) { String ref = lexer.stringVal(); lexer.nextToken(JSONToken.RBRACE); if (lexer.token() == JSONToken.COMMA) { map.put(key, ref); continue; } 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 { JSONPath jsonpath = JSONPath.compile(ref); if (jsonpath.isRef()) { addResolveTask(new ResolveTask(context, ref)); setResolveStatus(DefaultJSONParser.NeedToResolve); } else { refValue = new JSONObject() .fluentPut("$ref", ref); } } if (lexer.token() != JSONToken.RBRACE) { throw new JSONException("syntax error, " + lexer.info()); } lexer.nextToken(JSONToken.COMMA); return refValue; } else { throw new JSONException("illegal ref, " + JSONToken.name(lexer.token())); } } 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 = (lexer.getFeatures() & Feature.OrderedField.mask) != 0 ? mapDeserializer.createMap(Map.class, lexer.getFeatures()) : mapDeserializer.createMap(Map.class); } else { input = new JSONObject(lexer.isEnabled(Feature.OrderedField)); } ParseContext ctxLocal = null; if (!parentIsArray) { ctxLocal = setContext(this.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); } } lexer.skipWhitespace(); ch = lexer.getCurrent(); 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 (T) TypeUtils.optionalEmpty(type); } 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(); } } ObjectDeserializer deserializer = config.getDeserializer(type); try { if (deserializer.getClass() == JavaBeanDeserializer.class) { if (lexer.token()!= JSONToken.LBRACE && lexer.token()!=JSONToken.LBRACKET) { throw new JSONException("syntax error,expect start with { or [,but actually start with "+ lexer.tokenName()); } return (T) ((JavaBeanDeserializer) deserializer).deserialze(this, type, fieldName, 0); } else { return (T) deserializer.deserialze(this, type, fieldName); } } 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, @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("field " + fieldName + " expect '[', 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; } } if (lexer.token() == JSONToken.RBRACKET) { break; } 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(); } } array.add(value); } else { Object val; if (lexer.token() == JSONToken.NULL) { lexer.nextToken(); val = null; } else { val = deserializer.deserialze(this, type, i); } array.add(val); checkListResolve(array); } if (lexer.token() == JSONToken.COMMA) { lexer.nextToken(deserializer.getFastMatchToken()); continue; } } } finally { this.setContext(context); } 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 { boolean isArray = false; Class componentType = null; if (i == types.length - 1) { if (type instanceof Class) { Class clazz = (Class) type; //如果最后一个type是字节数组,且当前token为字符串类型,不应该当作可变长参数进行处理 //而是作为一个整体的Base64字符串进行反序列化 if (!((clazz == byte[].class || clazz == char[].class) && lexer.token() == LITERAL_STRING)) { isArray = clazz.isArray(); componentType = clazz.getComponentType(); } } } // support varArgs if (isArray && lexer.token() != JSONToken.LBRACKET) { List varList = new ArrayList(); ObjectDeserializer deserializer = config.getDeserializer(componentType); int fastMatch = deserializer.getFastMatchToken(); if (lexer.token() != JSONToken.RBRACKET) { for (;;) { Object item = deserializer.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 deserializer = config.getDeserializer(type); value = deserializer.deserialze(this, type, i); } } } 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) { Class clazz = object.getClass(); JavaBeanDeserializer beanDeser = null; ObjectDeserializer deserializer = config.getDeserializer(clazz); if (deserializer instanceof JavaBeanDeserializer) { beanDeser = (JavaBeanDeserializer) deserializer; } 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 parsedObject = parseObject(object); if (parsedObject instanceof JSONObject) { return (JSONObject) parsedObject; } if (parsedObject == null) { return null; } return new JSONObject((Map) parsedObject); } @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); if (this.context != null && this.context.level > 512) { throw new JSONException("array level > 512"); } 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; } } } catch (ClassCastException e) { throw new JSONException("unkown error", e); } finally { this.setContext(context); } } public ParseContext getContext() { return context; } public ParseContext getOwnerContext() { return context.parent; } 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: Collection array = isEnabled(Feature.UseNativeJavaObject) ? new ArrayList() : new JSONArray(); parseArray(array, fieldName); if (lexer.isEnabled(Feature.UseObjectArray)) { return array.toArray(); } return array; case LBRACE: Map object = isEnabled(Feature.UseNativeJavaObject) ? lexer.isEnabled(Feature.OrderedField) ? new HashMap() : new LinkedHashMap() : 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 = 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 { JSONPath jsonpath = new JSONPath(ref, SerializeConfig.getGlobalInstance(), config, true); if (jsonpath.isRef()) { refValue = jsonpath.eval(value); } } 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; JSONPath jsonpath = JSONPath.compile(ref); if (jsonpath.isRef()) { refValue = jsonpath.eval(root); } } // workaround for bug if (fieldDeser.getOwnerClass() != null && (!fieldDeser.getOwnerClass().isInstance(object)) && task.ownerContext.parent != null ) { for (ParseContext ctx = task.ownerContext.parent;ctx != null;ctx = ctx.parent) { if (fieldDeser.getOwnerClass().isInstance(ctx.object)) { object = ctx.object; break; } } } 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); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/Feature.java ================================================ /* * 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] */ public enum Feature { /** * */ AutoCloseSource, /** * */ AllowComment, /** * */ AllowUnQuotedFieldNames, /** * */ AllowSingleQuotes, /** * */ InternFieldNames, /** * */ AllowISO8601DateFormat, /** * {"a":1,,,"b":2} */ AllowArbitraryCommas, /** * */ UseBigDecimal, /** * @since 1.1.2 */ 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 * */ 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, /** * @since 1.2.55 */ ErrorOnEnumNotMatch, /** * @since 1.2.68 */ SafeMode, /** * @since 1.2.72 */ TrimStringFieldValue, /** * @since 1.2.77 * use HashMap instead of JSONObject, ArrayList instead of JSONArray */ UseNativeJavaObject ; Feature(){ mask = (1 << ordinal()); } public final int mask; public final int getMask() { return mask; } public static boolean isEnabled(int features, Feature feature) { return (features & feature.mask) != 0; } public static int config(int features, Feature feature, boolean state) { if (state) { features |= feature.mask; } else { 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/JSONLexer.java ================================================ /* * Copyright 1999-2019 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.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 scanTypeName(SymbolTable symbolTable); 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(); void setFeatures(int features); } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/JSONLexerBase.java ================================================ /* * Copyright 1999-2019 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.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.util.IOUtils; import static com.alibaba.fastjson.parser.JSONToken.*; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_hashcode; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_prime; /** * @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; protected int nanos = 0; 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; eofPos = pos = bp; } 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; } if (ch == 'n') { scanNullOrNew(false); 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(), 10); } result *= 10; if (result < limit + digit) { return new BigInteger(numberString(), 10); } 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 JSONException("illegal number format : " + 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 = next(); char x2 = next(); boolean hex1 = (x1 >= '0' && x1 <= '9') || (x1 >= 'a' && x1 <= 'f') || (x1 >= 'A' && x1 <= 'F'); boolean hex2 = (x2 >= '0' && x2 <= '9') || (x2 >= 'a' && x2 <= 'f') || (x2 >= 'A' && x2 <= 'F'); if (!hex1 || !hex2) { throw new JSONException("invalid escape character \\x" + x1 + x2); } char x_char = (char) (digits[x1] * 16 + digits[x2]); putChar(x_char); break; case 'u': char u1 = next(); char u2 = next(); char u3 = next(); char u4 = 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'; } public String scanTypeName(SymbolTable symbolTable) { return null; } 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 int matchField(long fieldNameHash) { throw new UnsupportedOperationException(); } public boolean seekArrayToItem(int index) { throw new UnsupportedOperationException(); } public int seekObjectToField(long fieldNameHash, boolean deepScan) { throw new UnsupportedOperationException(); } public int seekObjectToField(long[] fieldNameHash) { throw new UnsupportedOperationException(); } public int seekObjectToFieldDeepScan(long fieldNameHash) { throw new UnsupportedOperationException(); } public void skipObject() { throw new UnsupportedOperationException(); } public void skipObject(boolean valid) { throw new UnsupportedOperationException(); } public void skipArray() { throw new UnsupportedOperationException(); } 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; token = JSONToken.COMMA; return strVal; } else if (isWhitespace(chLocal)) { chLocal = charAt(bp + (offset++)); continue; } else { if (chLocal == ']') { bp += offset; this.ch = charAt(bp); 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 = fnv1a_64_magic_hashcode; for (;;) { chLocal = charAt(bp + (offset++)); if (chLocal == '\"') { chLocal = charAt(bp + (offset++)); break; } hash ^= chLocal; hash *= fnv1a_64_magic_prime; 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; } public long scanEnumSymbol(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 = fnv1a_64_magic_hashcode; for (;;) { chLocal = charAt(bp + (offset++)); if (chLocal == '\"') { chLocal = charAt(bp + (offset++)); break; } hash ^= ((chLocal >= 'A' && chLocal <= 'Z') ? (chLocal + 32) : chLocal); hash *= fnv1a_64_magic_prime; 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)) { return new HashSet(); } else if (type.isAssignableFrom(ArrayList.class)) { return new ArrayList(); } else if (type.isAssignableFrom(LinkedList.class)) { return new LinkedList(); } else { try { return (Collection) type.newInstance(); } 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') { 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 < 17) { value = (float) (((double) 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) (((double) 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 < 17) { 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; } if (count > 65535) { throw new JSONException("decimal overflow"); } char[] chars = this.sub_chars(start, count); value = new BigDecimal(chars, 0, chars.length, MathContext.UNLIMITED); } 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; } } else { 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 < 17) { 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; } if (count > 65535) { throw new JSONException("scan decimal overflow"); } char[] chars = this.sub_chars(start, count); value = new BigDecimal(chars, 0, chars.length, MathContext.UNLIMITED); } 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'; boolean overflow = false; long temp; for (;;) { chLocal = charAt(bp + (offset++)); if (chLocal >= '0' && chLocal <= '9') { temp = intVal * 10 + (chLocal - '0'); if (temp < intVal) { overflow = true; break; } intVal = temp; 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 (!overflow && (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, ) if (count > 65535) { throw new JSONException("scanInteger overflow"); } String strVal = this.subString(start, count); value = new BigInteger(strVal, 10); } } 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() { scanNullOrNew(true); } public final void scanNullOrNew(boolean acceptColon) { 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 == ':' && acceptColon) || 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': char x1 = next(); char x2 = next(); boolean hex1 = (x1 >= '0' && x1 <= '9') || (x1 >= 'a' && x1 <= 'f') || (x1 >= 'A' && x1 <= 'F'); boolean hex2 = (x2 >= '0' && x2 <= '9') || (x2 >= 'a' && x2 <= 'f') || (x2 >= 'A' && x2 <= 'F'); if (!hex1 || !hex2) { throw new JSONException("invalid escape character \\x" + x1 + x2); } putChar((char) (digits[x1] * 16 + digits[x2])); 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) { int len = sbuf.length * 2; if (len < sp) { len = sp + 1; } char[] newsbuf = new char[len]; 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(); if (ch == '\'') { next(); token = JSONToken.HEX; return; } 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 (sp > 65535) { throw new JSONException("scanNumber overflow"); } 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; } public void setFeatures(int features) { this.features = features; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/JSONReaderScanner.java ================================================ /* * 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 java.math.MathContext; 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--; } if (sp > 65535) { throw new JSONException("decimal overflow"); } return new BigDecimal(buf, offset, sp, MathContext.UNLIMITED); } 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/JSONScanner.java ================================================ /* * 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; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.util.ASMUtils; import com.alibaba.fastjson.util.IOUtils; import java.math.BigDecimal; import java.math.MathContext; import java.util.*; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_hashcode; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_prime; //这个类,为了性能优化做了很多特别处理,一切都是为了性能!!! /** * @author wenshao[szujobs@hotmail.com] */ public final class JSONScanner extends JSONLexerBase { private final String text; private final int len; public JSONScanner(String input){ this(input, JSON.DEFAULT_PARSER_FEATURE); } public JSONScanner(String input, int features){ super(features); text = input; len = text.length(); bp = -1; next(); if (ch == 65279) { // utf-8 bom next(); } } public final char charAt(int index) { if (index >= len) { return EOI; } return text.charAt(index); } public final char next() { int index = ++bp; return ch = (index >= this.len ? // EOI // : text.charAt(index)); } public JSONScanner(char[] input, int inputLength){ this(input, inputLength, JSON.DEFAULT_PARSER_FEATURE); } public JSONScanner(char[] input, int inputLength, int features){ this(new String(input, 0, inputLength), features); } protected final void copyTo(int offset, int count, char[] dest) { text.getChars(offset, offset + count, dest, 0); } static boolean charArrayCompare(String src, int offset, char[] dest) { final int destLen = dest.length; if (destLen + offset > src.length()) { return false; } for (int i = 0; i < destLen; ++i) { if (dest[i] != src.charAt(offset + i)) { return false; } } return true; } public final boolean charArrayCompare(char[] chars) { return charArrayCompare(text, bp, chars); } public final int indexOf(char ch, int startIndex) { return text.indexOf(ch, startIndex); } public final String addSymbol(int offset, int len, int hash, final SymbolTable symbolTable) { return symbolTable.addSymbol(text, offset, len, hash); } public byte[] bytesValue() { if (token == JSONToken.HEX) { int start = np + 1, len = sp; if (len % 2 != 0) { throw new JSONException("illegal state. " + len); } 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); int b0 = c0 - (c0 <= 57 ? 48 : 55); int b1 = c1 - (c1 <= 57 ? 48 : 55); bytes[i] = (byte) ((b0 << 4) | b1); } return bytes; } if (!hasSpecial) { return IOUtils.decodeBase64(text, np + 1, sp); } else { String escapedText = new String(sbuf, 0, sp); return IOUtils.decodeBase64(escapedText); } } /** * 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 this.subString(np + 1, sp); } else { return new String(sbuf, 0, sp); } } 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 { 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[] 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 String numberString() { char chLocal = charAt(np + sp - 1); int sp = this.sp; if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { sp--; } return this.subString(np, sp); } public final BigDecimal decimalValue() { char chLocal = charAt(np + sp - 1); int sp = this.sp; if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { sp--; } if (sp > 65535) { throw new JSONException("decimal overflow"); } int offset = np, count = sp; if (count < sbuf.length) { text.getChars(offset, offset + count, sbuf, 0); return new BigDecimal(sbuf, 0, count, MathContext.UNLIMITED); } else { char[] chars = new char[count]; text.getChars(offset, offset + count, chars, 0); return new BigDecimal(chars, 0, chars.length, MathContext.UNLIMITED); } } public boolean scanISO8601DateIfMatch() { return scanISO8601DateIfMatch(true); } public boolean scanISO8601DateIfMatch(boolean strict) { int rest = len - bp; return scanISO8601DateIfMatch(strict, rest); } private boolean scanISO8601DateIfMatch(boolean strict, int rest) { if (rest < 8) { return false; } 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; } } if (plusIndex == -1) { return false; } int offset = bp + 6; String numberText = this.subString(offset, bp + plusIndex - offset); long millis = Long.parseLong(numberText); calendar = Calendar.getInstance(timeZone, locale); calendar.setTimeInMillis(millis); token = JSONToken.LITERAL_ISO8601_DATE; return true; } } char c10; if (rest == 8 || rest == 14 || (rest == 16 && ((c10 = charAt(bp + 10)) == 'T' || c10 == ' ')) || (rest == 17 && charAt(bp + 6) != '-')) { if (strict) { return false; } char y0, y1, y2, y3, M0, M1, d0, d1; char c8 = charAt(bp + 8); 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 if (c4 == '-' && c6 == '-') { y0 = c0; y1 = c1; y2 = c2; y3 = c3; M0 = '0'; M1 = c5; d0 = '0'; d1 = c7; } else { y0 = c0; y1 = c1; y2 = c2; y3 = c3; M0 = c4; M1 = c5; d0 = c6; d1 = c7; } if (!checkDate(y0, y1, y2, y3, M0, M1, d0, d1)) { return false; } setCalendar(y0, y1, y2, y3, M0, M1, d0, d1); 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); char h0, h1, m0, m1, s0, s1; 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 (!checkTime(h0, h1, m0, m1, s0, s1)) { return false; } 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; } if (S1 < '0' || S1 > '9') { return false; } if (S2 < '0' || S2 > '9') { return false; } 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; } calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, seconds); calendar.set(Calendar.MILLISECOND, millis); token = JSONToken.LITERAL_ISO8601_DATE; return true; } if (rest < 9) { return false; } 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; if (c9 == ' ') { d0 = '0'; d1 = c8; date_len = 9; } else { 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 (c8 == 'T') { y0 = c0; y1 = c1; y2 = c2; y3 = c3; M0 = c4; M1 = c5; d0 = c6; d1 = c7; date_len = 8; } 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 (!checkDate(y0, y1, y2, y3, M0, M1, d0, d1)) { return false; } setCalendar(y0, y1, y2, y3, M0, M1, d0, d1); char t = charAt(bp + date_len); if (t == 'T' && rest == 16 && date_len == 8 && charAt(bp + 15) == 'Z') { char h0 = charAt(bp + date_len + 1); char h1 = charAt(bp + date_len + 2); char m0 = charAt(bp + date_len + 3); char m1 = charAt(bp + date_len + 4); char s0 = charAt(bp + date_len + 5); char s1 = charAt(bp + date_len + 6); if (!checkTime(h0, h1, m0, m1, s0, s1)) { return false; } setTime(h0, h1, m0, m1, s0, s1); calendar.set(Calendar.MILLISECOND, 0); if (calendar.getTimeZone().getRawOffset() != 0) { String[] timeZoneIDs = TimeZone.getAvailableIDs(0); if (timeZoneIDs.length > 0) { TimeZone timeZone = TimeZone.getTimeZone(timeZoneIDs[0]); calendar.setTimeZone(timeZone); } } token = JSONToken.LITERAL_ISO8601_DATE; return true; } else 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); ch = charAt(bp += date_len); 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; } 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; } 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); if (!checkTime(h0, h1, m0, m1, s0, s1)) { return false; } setTime(h0, h1, m0, m1, s0, s1); char dot = charAt(bp + date_len + 9); int millisLen = -1; // 有可能没有毫秒区域,没有毫秒区域的时候下一个字符位置有可能是'Z'、'+'、'-' int millis = 0; if (dot == '.') { // 0000-00-00T00:00:00.000 if (rest < date_len + 11) { return false; } char S0 = charAt(bp + date_len + 10); if (S0 < '0' || S0 > '9') { return false; } millis = S0 - '0'; millisLen = 1; if (rest > date_len + 11) { char S1 = charAt(bp + date_len + 11); if (S1 >= '0' && S1 <= '9') { millis = millis * 10 + (S1 - '0'); millisLen = 2; } } if (millisLen == 2) { char S2 = charAt(bp + date_len + 12); if (S2 >= '0' && S2 <= '9') { millis = millis * 10 + (S2 - '0'); millisLen = 3; } } } calendar.set(Calendar.MILLISECOND, millis); int timzeZoneLength = 0; char timeZoneFlag = charAt(bp + date_len + 10 + millisLen); if (timeZoneFlag == ' ') { millisLen++; 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; } char t1 = charAt(bp + date_len + 10 + millisLen + 2); if (t1 < '0' || t1 > '9') { return false; } 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); t4 = charAt(bp + date_len + 10 + millisLen + 5); if(t3 == '4' && t4 == '5') { // handle some special timezones like xx:45 if (t0 == '1' && (t1 == '2' || t1 == '3')) { // NZ-CHAT => +12:45 // Pacific/Chatham => +12:45 // NZ-CHAT => +13:45 (DST) // Pacific/Chatham => +13:45 (DST) } else if (t0 == '0' && (t1 == '5' || t1 == '8')) { // Asia/Kathmandu => +05:45 // Asia/Katmandu => +05:45 // Australia/Eucla => +08:45 } else { return false; } } else { //handle normal timezone like xx:00 and xx:30 if (t3 != '0' && t3 != '3') { return false; } 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 if (t2 == '3' && charAt(bp + date_len + 10 + millisLen + 4) == '0') { t3 = '3'; t4 = '0'; timzeZoneLength = 5; } else if (t2 == '4' && charAt(bp + date_len + 10 + millisLen + 4) == '5') { t3 = '4'; t4 = '5'; timzeZoneLength = 5; } else { timzeZoneLength = 3; } setTimeZone(timeZoneFlag, t0, t1, t3, t4); } 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); } } } char end = charAt(bp + (date_len + 10 + millisLen + timzeZoneLength)); if (end != EOI && end != '"') { return false; } ch = charAt(bp += (date_len + 10 + millisLen + timzeZoneLength)); token = JSONToken.LITERAL_ISO8601_DATE; return true; } 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); } protected void setTimeZone(char timeZoneFlag, char t0, char t1) { setTimeZone(timeZoneFlag, t0, t1, '0', '0'); } protected void setTimeZone(char timeZoneFlag, char t0, char t1, char t3, char t4) { int timeZoneOffset = ((t0 - '0') * 10 + (t1 - '0')) * 3600 * 1000; timeZoneOffset += ((t3 - '0') * 10 + (t4 - '0')) * 60 * 1000; if (timeZoneFlag == '-') { timeZoneOffset = -timeZoneOffset; } if (calendar.getTimeZone().getRawOffset() != timeZoneOffset) { calendar.setTimeZone(new SimpleTimeZone(timeZoneOffset, Integer.toString(timeZoneOffset))); } } 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; } 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 (s0 >= '0' && s0 <= '5') { if (s1 < '0' || s1 > '9') { return false; } } else if (s0 == '6') { if (s1 != '0') { return false; } } else { return false; } return true; } 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); } static boolean checkDate(char y0, char y1, char y2, char y3, char M0, char M1, int d0, int d1) { if (y0 < '0' || y0 > '9') { 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; } 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; } return true; } @Override public boolean isEOF() { return bp == len || (ch == EOI && bp + 1 >= len); } public int scanFieldInt(char[] fieldName) { matchStat = UNKNOWN; int startPos = this.bp; char startChar = this.ch; if (!charArrayCompare(text, bp, fieldName)) { matchStat = NOT_MATCH_NAME; return 0; } int index = bp + fieldName.length; char ch = charAt(index++); final boolean quote = ch == '"'; if (quote) { ch = charAt(index++); } 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') { int value_10 = value * 10; if (value_10 < value) { matchStat = NOT_MATCH; return 0; } value = value_10 + (ch - '0'); } else if (ch == '.') { matchStat = NOT_MATCH; return 0; } else { break; } } if (value < 0) { matchStat = NOT_MATCH; 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 = charAt(++bp); matchStat = VALUE; 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; } return negative ? -value : value; } 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(); while (isWhitespace(ch)) { next(); } continue; } matchStat = NOT_MATCH_NAME; return stringDefaultValue(); } else { break; } } int index = bp + fieldName.length; int spaceCount = 0; char ch = charAt(index++); if (ch != '"') { while (isWhitespace(ch)) { spaceCount++; ch = charAt(index++); } if (ch != '"') { matchStat = NOT_MATCH; return stringDefaultValue(); } } final String strVal; { 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 - (bp + fieldName.length + 1 + spaceCount); char[] chars = sub_chars(bp + fieldName.length + 1 + spaceCount, chars_len); stringVal = readString(chars, chars_len); } if ((this.features & Feature.TrimStringFieldValue.mask) != 0) { stringVal = stringVal.trim(); } 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 = charAt(++bp); matchStat = VALUE; return strVal; } else { //condition ch == '}' is always 'true' ch = charAt(++bp); 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 { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return stringDefaultValue(); } matchStat = END; } return strVal; } public java.util.Date scanFieldDate(char[] fieldName) { matchStat = UNKNOWN; int startPos = this.bp; char startChar = this.ch; if (!charArrayCompare(text, bp, fieldName)) { matchStat = NOT_MATCH_NAME; return null; } int index = bp + fieldName.length; 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; 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 { matchStat = NOT_MATCH; return null; } } } else if (ch == '-' || (ch >= '0' && ch <= '9')) { long millis = 0; 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; } if (ch == ',') { this.ch = charAt(++bp); matchStat = VALUE; token = JSONToken.COMMA; return dateVal; } else { //condition ch == '}' is always 'true' ch = charAt(++bp); 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 { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return null; } matchStat = END; } return dateVal; } public long scanFieldSymbol(char[] fieldName) { matchStat = UNKNOWN; for (;;) { if (!charArrayCompare(text, bp, fieldName)) { if (isWhitespace(ch)) { next(); while (isWhitespace(ch)) { next(); } continue; } matchStat = NOT_MATCH_NAME; return 0; } else { break; } } int index = bp + fieldName.length; int spaceCount = 0; char ch = charAt(index++); if (ch != '"') { while (isWhitespace(ch)) { ch = charAt(index++); spaceCount++; } if (ch != '"') { matchStat = NOT_MATCH; return 0; } } long hash = fnv1a_64_magic_hashcode; 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 *= fnv1a_64_magic_prime; } 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; } @SuppressWarnings("unchecked") public Collection scanFieldStringArray(char[] fieldName, Class type) { matchStat = UNKNOWN; while (ch == '\n' || ch == ' ') { int index = ++bp; ch = (index >= this.len ? // EOI // : text.charAt(index)); } 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 startPos = this.bp; char startChar = this.ch; 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 { this.ch = startChar; bp = startPos; matchStat = NOT_MATCH; return null; } return list; } public long scanFieldLong(char[] fieldName) { matchStat = UNKNOWN; int startPos = this.bp; char startChar = this.ch; if (!charArrayCompare(text, bp, fieldName)) { matchStat = NOT_MATCH_NAME; return 0; } int index = bp + fieldName.length; char ch = charAt(index++); 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 = 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 { if (quote) { if (ch != '"') { matchStat = NOT_MATCH; return 0; } else { ch = charAt(index++); } } if (ch == ',' || ch == '}') { bp = index - 1; } break; } } 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; } for (;;) { if (ch == ',') { this.ch = charAt(++bp); matchStat = VALUE; token = JSONToken.COMMA; return negative ? -value : value; } 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; 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; } } return negative ? -value : value; } public boolean scanFieldBoolean(char[] fieldName) { matchStat = UNKNOWN; if (!charArrayCompare(text, bp, fieldName)) { matchStat = NOT_MATCH_NAME; return false; } int startPos = bp; int index = bp + fieldName.length; char ch = charAt(index++); final boolean quote = ch == '"'; if (quote) { ch = charAt(index++); } boolean value; if (ch == 't') { if (charAt(index++) != 'r') { matchStat = NOT_MATCH; return false; } if (charAt(index++) != 'u') { matchStat = NOT_MATCH; return false; } if (charAt(index++) != 'e') { matchStat = NOT_MATCH; return false; } if (quote && charAt(index++) != '"') { matchStat = NOT_MATCH; return false; } bp = index; ch = charAt(bp); value = true; } else if (ch == 'f') { 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 (charAt(index++) != 'e') { matchStat = NOT_MATCH; return false; } if (quote && charAt(index++) != '"') { matchStat = NOT_MATCH; return false; } 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 = charAt(bp); value = false; } else { matchStat = NOT_MATCH; return false; } for (;;) { if (ch == ',') { this.ch = charAt(++bp); matchStat = VALUE; token = JSONToken.COMMA; break; } else if (ch == '}') { 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; } } return value; } public final int scanInt(char expectNext) { matchStat = UNKNOWN; final int mark = bp; int offset = bp; char chLocal = charAt(offset++); while (isWhitespace(chLocal)) { chLocal = charAt(offset++); } final boolean quote = chLocal == '"'; if (quote) { chLocal = charAt(offset++); } final boolean negative = chLocal == '-'; if (negative) { chLocal = charAt(offset++); } int value; if (chLocal >= '0' && chLocal <= '9') { value = chLocal - '0'; for (;;) { chLocal = charAt(offset++); if (chLocal >= '0' && chLocal <= '9') { int value_10 = value * 10; if (value_10 < value) { throw new JSONException("parseInt error : " + subString(mark, offset - 1)); } 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; } } if (value < 0) { 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 (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; } 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 double scanDouble(char seperator) { matchStat = UNKNOWN; int offset = bp; char chLocal = charAt(offset++); final boolean quote = chLocal == '"'; if (quote) { chLocal = charAt(offset++); } boolean negative = chLocal == '-'; if (negative) { chLocal = charAt(offset++); } 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; } } 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; } } } else { matchStat = NOT_MATCH; return 0; } } 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 < 18) { 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 (chLocal == seperator) { bp = offset; this.ch = this.charAt(bp); matchStat = VALUE; token = JSONToken.COMMA; return value; } 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; } } 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; } 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; } matchStat = NOT_MATCH; return value; } } } public java.util.Date scanDate(char seperator) { matchStat = UNKNOWN; int startPos = this.bp; char startChar = this.ch; int index = bp; 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; 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) { 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 null; } if (ch == ',') { this.ch = charAt(++bp); matchStat = VALUE; return dateVal; } else { //condition ch == '}' is always 'true' ch = charAt(++bp); 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) { this.ch = EOI; token = JSONToken.EOF; } else { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return null; } matchStat = END; } return dateVal; } protected final void arrayCopy(int srcPos, char[] dest, int destPos, int length) { text.getChars(srcPos, srcPos + length, dest, destPos); } public String info() { StringBuilder buf = new StringBuilder(); // buf.append("pos ").append(bp); // return "pos " + bp // // + ", json : " // // + (text.length() < 65536 // // ? text // // : text.substring(0, 65536)); int line = 1; int column = 1; for (int i = 0; i < bp; ++i, column++) { char ch = text.charAt(i); if (ch == '\n') { column = 1; line++; } } buf.append("pos ").append(bp) .append(", line ").append(line) .append(", column ").append(column); if (text.length() < 65535) { buf.append(text); } else { buf.append(text.substring(0, 65535)); } return buf.toString(); } // for hsf support public String[] scanFieldStringArray(char[] fieldName, int argTypesCount, SymbolTable typeSymbolTable) { int startPos = bp; char starChar = ch; while (isWhitespace(ch)) { next(); } int offset; char ch; if (fieldName != null) { matchStat = UNKNOWN; if (!charArrayCompare(fieldName)) { matchStat = NOT_MATCH_NAME; return null; } offset = bp + fieldName.length; ch = text.charAt(offset++); while (isWhitespace(ch)) { ch = text.charAt(offset++); } if (ch == ':') { ch = text.charAt(offset++); } else { matchStat = NOT_MATCH; return null; } while (isWhitespace(ch)) { ch = text.charAt(offset++); } } else { offset = bp + 1; ch = this.ch; } 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; } String[] types = argTypesCount >= 0 ? new String[argTypesCount] : new String[4]; int typeIndex = 0; for (;;) { while (isWhitespace(this.ch)) { next(); } if (this.ch != '\"') { this.bp = startPos; this.ch = starChar; matchStat = NOT_MATCH; return null; } 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; } types[typeIndex++] = type; while (isWhitespace(this.ch)) { next(); } if (this.ch == ',') { next(); continue; } break; } if (types.length != typeIndex) { String[] array = new String[typeIndex]; System.arraycopy(types, 0, array, 0, typeIndex); types = array; } while (isWhitespace(this.ch)) { next(); } if (this.ch == ']') { next(); } else { this.bp = startPos; this.ch = starChar; matchStat = NOT_MATCH; return null; } return types; } public boolean matchField2(char[] fieldName) { while (isWhitespace(ch)) { next(); } if (!charArrayCompare(fieldName)) { matchStat = NOT_MATCH_NAME; return false; } int offset = bp + fieldName.length; char ch = text.charAt(offset++); while (isWhitespace(ch)) { ch = text.charAt(offset++); } if (ch == ':') { this.bp = offset; this.ch = charAt(bp); return true; } else { matchStat = NOT_MATCH_NAME; return false; } } public final void skipObject() { skipObject(false); } public final void skipObject(boolean valid) { boolean quote = false; int braceCnt = 0; int i = bp; for (; i < text.length(); ++i) { final char ch = text.charAt(i); if (ch == '\\') { if (i < len - 1) { ++i; continue; } else { this.ch = ch; this.bp = i; throw new JSONException("illegal str, " + info()); } } else if (ch == '"') { quote = !quote; } else if (ch == '{') { if (quote) { continue; } braceCnt++; } else if (ch == '}') { if (quote) { continue; } else { braceCnt--; } if (braceCnt == -1) { this.bp = i + 1; if (this.bp == text.length()) { this.ch = EOI; this.token = JSONToken.EOF; return; } this.ch = text.charAt(this.bp); if (this.ch == ',') { token = JSONToken.COMMA; int index = ++bp; this.ch = (index >= text.length() // ? EOI // : text.charAt(index)); return; } else if (this.ch == '}') { token = JSONToken.RBRACE; next(); return; } else if (this.ch == ']') { token = JSONToken.RBRACKET; next(); return; } else { nextToken(JSONToken.COMMA); } return; } } } for (int j = 0; j < bp; j++) { if (j < text.length() && text.charAt(j) == ' ') { i++; } } if (i == text.length()) { throw new JSONException("illegal str, " + info()); } } public final void skipArray() { skipArray(false); } public final void skipArray(boolean valid) { boolean quote = false; int bracketCnt = 0; int i = bp; for (; i < text.length(); ++i) { char ch = text.charAt(i); if (ch == '\\') { if (i < len - 1) { ++i; continue; } else { this.ch = ch; this.bp = i; throw new JSONException("illegal str, " + info()); } } else if (ch == '"') { quote = !quote; } else if (ch == '[') { if (quote) { continue; } bracketCnt++; } else if (ch == '{' && valid) { { int index = ++bp; this.ch = (index >= text.length() // ? EOI // : text.charAt(index)); } skipObject(valid); } else if (ch == ']') { if (quote) { continue; } else { bracketCnt--; } if (bracketCnt == -1) { this.bp = i + 1; if (this.bp == text.length()) { this.ch = EOI; token = JSONToken.EOF; return; } this.ch = text.charAt(this.bp); nextToken(JSONToken.COMMA); return; } } } if (i == text.length()) { throw new JSONException("illegal str, " + info()); } } public final void skipString() { if (ch == '"') { for (int i = bp + 1; i < text.length(); ++i) { char c = text.charAt(i); if (c == '\\') { if (i < len - 1) { ++i; continue; } } else if (c == '"') { this.ch = text.charAt(bp = i + 1); return; } } throw new JSONException("unclosed str"); } else { throw new UnsupportedOperationException(); } } public boolean seekArrayToItem(int index) { if (index < 0) { throw new IllegalArgumentException("index must > 0, but " + index); } if (token == JSONToken.EOF) { return false; } if (token != JSONToken.LBRACKET) { throw new UnsupportedOperationException(); } // nextToken(); for (int i = 0; i < index; ++i) { skipWhitespace(); if (ch == '"' || ch == '\'') { skipString(); if (ch == ',') { next(); continue; } else if (ch == ']') { next(); nextToken(JSONToken.COMMA); return false; } else { throw new JSONException("illegal json."); } } else if (ch == '{') { next(); token = JSONToken.LBRACE; skipObject(false); } else if (ch == '[') { next(); token = JSONToken.LBRACKET; skipArray(false); } else { boolean match = false; for (int j = bp + 1; j < text.length(); ++j) { char c = text.charAt(j); if (c == ',') { match = true; bp = j + 1; ch = charAt(bp); break; } else if (c == ']') { bp = j + 1; ch = charAt(bp); nextToken(); return false; } } if (!match) { throw new JSONException("illegal json."); } continue; } if (token == JSONToken.COMMA) { continue; } else if (token == JSONToken.RBRACKET) { return false; } else { throw new UnsupportedOperationException(); } } nextToken(); return true; } public int seekObjectToField(long fieldNameHash, boolean deepScan) { if (token == JSONToken.EOF) { return JSONLexer.NOT_MATCH; } if (token == JSONToken.RBRACE || token == JSONToken.RBRACKET) { nextToken(); return JSONLexer.NOT_MATCH; } if (token != JSONToken.LBRACE && token != JSONToken.COMMA) { throw new UnsupportedOperationException(JSONToken.name(token)); } for (;;) { if (ch == '}') { next(); nextToken(); return JSONLexer.NOT_MATCH; } if (ch == EOI) { return JSONLexer.NOT_MATCH; } if (ch != '"') { skipWhitespace(); } long hash; if (ch == '"') { hash = fnv1a_64_magic_hashcode; for (int i = bp + 1; i < text.length(); ++i) { char c = text.charAt(i); if (c == '\\') { ++i; if (i == text.length()) { throw new JSONException("unclosed str, " + info()); } c = text.charAt(i); } if (c == '"') { bp = i + 1; ch = (bp >= text.length() // ? EOI // : text.charAt(bp)); break; } hash ^= c; hash *= fnv1a_64_magic_prime; } } else { throw new UnsupportedOperationException(); } if (hash == fieldNameHash) { if (ch != ':') { skipWhitespace(); } if (ch == ':') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } if (ch == ',') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.COMMA; } else if (ch == ']') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.RBRACKET; } else if (ch == '}') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.RBRACE; } else if (ch >= '0' && ch <= '9') { sp = 0; pos = bp; scanNumber(); } else { nextToken(JSONToken.LITERAL_INT); } } return VALUE; } if (ch != ':') { skipWhitespace(); } if (ch == ':') { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } else { throw new JSONException("illegal json, " + info()); } if (ch != '"' && ch != '\'' && ch != '{' && ch != '[' && ch != '0' && ch != '1' && ch != '2' && ch != '3' && ch != '4' && ch != '5' && ch != '6' && ch != '7' && ch != '8' && ch != '9' && ch != '+' && ch != '-') { skipWhitespace(); } // skip fieldValues if (ch == '-' || ch == '+' || (ch >= '0' && ch <= '9')) { next(); while (ch >= '0' && ch <= '9') { next(); } // scale if (ch == '.') { next(); while (ch >= '0' && ch <= '9') { next(); } } // exp if (ch == 'E' || ch == 'e') { next(); if (ch == '-' || ch == '+') { next(); } while (ch >= '0' && ch <= '9') { next(); } } if (ch != ',') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == '"') { skipString(); if (ch != ',' && ch != '}') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == 't') { next(); if (ch == 'r') { next(); if (ch == 'u') { next(); if (ch == 'e') { next(); } } } if (ch != ',' && ch != '}') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == 'n') { next(); if (ch == 'u') { next(); if (ch == 'l') { next(); if (ch == 'l') { next(); } } } if (ch != ',' && ch != '}') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == 'f') { next(); if (ch == 'a') { next(); if (ch == 'l') { next(); if (ch == 's') { next(); if (ch == 'e') { next(); } } } } if (ch != ',' && ch != '}') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == '{') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } if (deepScan) { token = JSONToken.LBRACE; return OBJECT; } skipObject(false); if (token == JSONToken.RBRACE) { return JSONLexer.NOT_MATCH; } } else if (ch == '[') { next(); if (deepScan) { token = JSONToken.LBRACKET; return ARRAY; } skipArray(false); if (token == JSONToken.RBRACE) { return JSONLexer.NOT_MATCH; } } else { throw new UnsupportedOperationException(); } } } public int seekObjectToField(long[] fieldNameHash) { if (token != JSONToken.LBRACE && token != JSONToken.COMMA) { throw new UnsupportedOperationException(); } for (;;) { if (ch == '}') { next(); nextToken(); this.matchStat = JSONLexer.NOT_MATCH; return -1; } if (ch == EOI) { this.matchStat = JSONLexer.NOT_MATCH; return -1; } if (ch != '"') { skipWhitespace(); } long hash; if (ch == '"') { hash = fnv1a_64_magic_hashcode; for (int i = bp + 1; i < text.length(); ++i) { char c = text.charAt(i); if (c == '\\') { ++i; if (i == text.length()) { throw new JSONException("unclosed str, " + info()); } c = text.charAt(i); } if (c == '"') { bp = i + 1; ch = (bp >= text.length() // ? EOI // : text.charAt(bp)); break; } hash ^= c; hash *= fnv1a_64_magic_prime; } } else { throw new UnsupportedOperationException(); } int matchIndex = -1; for (int i = 0; i < fieldNameHash.length; i++) { if (hash == fieldNameHash[i]) { matchIndex = i; break; } } if (matchIndex != -1) { if (ch != ':') { skipWhitespace(); } if (ch == ':') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } if (ch == ',') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.COMMA; } else if (ch == ']') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.RBRACKET; } else if (ch == '}') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.RBRACE; } else if (ch >= '0' && ch <= '9') { sp = 0; pos = bp; scanNumber(); } else { nextToken(JSONToken.LITERAL_INT); } } matchStat = VALUE; return matchIndex; } if (ch != ':') { skipWhitespace(); } if (ch == ':') { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } else { throw new JSONException("illegal json, " + info()); } if (ch != '"' && ch != '\'' && ch != '{' && ch != '[' && ch != '0' && ch != '1' && ch != '2' && ch != '3' && ch != '4' && ch != '5' && ch != '6' && ch != '7' && ch != '8' && ch != '9' && ch != '+' && ch != '-') { skipWhitespace(); } // skip fieldValues if (ch == '-' || ch == '+' || (ch >= '0' && ch <= '9')) { next(); while (ch >= '0' && ch <= '9') { next(); } // scale if (ch == '.') { next(); while (ch >= '0' && ch <= '9') { next(); } } // exp if (ch == 'E' || ch == 'e') { next(); if (ch == '-' || ch == '+') { next(); } while (ch >= '0' && ch <= '9') { next(); } } if (ch != ',') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == '"') { skipString(); if (ch != ',' && ch != '}') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == '{') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } skipObject(false); } else if (ch == '[') { next(); skipArray(false); } else { throw new UnsupportedOperationException(); } } } public String scanTypeName(SymbolTable symbolTable) { if (text.startsWith("\"@type\":\"", bp)) { int p = text.indexOf('"', bp + 9); if (p != -1) { bp += 9; int h = 0; for (int i = bp; i < p; i++) { h = 31 * h + text.charAt(i); } String typeName = addSymbol(bp, p - bp, h, symbolTable); char separator = text.charAt(p + 1); if (separator != ',' && separator != ']') { return null; } bp = p + 2; ch = text.charAt(bp); return typeName; } } return null; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/JSONToken.java ================================================ /* * 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] */ public class JSONToken { // public final static int ERROR = 1; // public final static int LITERAL_INT = 2; // public final static int LITERAL_FLOAT = 3; // public final static int LITERAL_STRING = 4; // public final static int LITERAL_ISO8601_DATE = 5; public final static int TRUE = 6; // public final static int FALSE = 7; // public final static int NULL = 8; // public final static int NEW = 9; // public final static int LPAREN = 10; // ("("), // public final static int RPAREN = 11; // (")"), // public final static int LBRACE = 12; // ("{"), // public final static int RBRACE = 13; // ("}"), // public final static int LBRACKET = 14; // ("["), // public final static int RBRACKET = 15; // ("]"), // public final static int COMMA = 16; // (","), // public final static int COLON = 17; // (":"), // 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: return "error"; case LITERAL_INT: return "int"; case LITERAL_FLOAT: return "float"; case LITERAL_STRING: return "string"; case LITERAL_ISO8601_DATE: return "iso8601"; case TRUE: return "true"; case FALSE: return "false"; case NULL: return "null"; case NEW: return "new"; case LPAREN: return "("; case RPAREN: return ")"; case LBRACE: return "{"; case RBRACE: return "}"; case LBRACKET: return "["; case RBRACKET: return "]"; case COMMA: 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 "Unknown"; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/ParseContext.java ================================================ 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 final int level; public Type type; private transient String path; public ParseContext(ParseContext parent, Object object, Object fieldName){ this.parent = parent; this.object = object; this.fieldName = fieldName; this.level = parent == null ? 0 : parent.level + 1; } 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/ParserConfig.java ================================================ /* * 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.*; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.lang.reflect.*; 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.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; 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.JSONCreator; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.asm.ClassReader; import com.alibaba.fastjson.asm.TypeCollector; import com.alibaba.fastjson.parser.deserializer.*; import com.alibaba.fastjson.serializer.*; import com.alibaba.fastjson.spi.Module; import com.alibaba.fastjson.support.moneta.MonetaCodec; import com.alibaba.fastjson.util.*; import com.alibaba.fastjson.util.IdentityHashMap; import com.alibaba.fastjson.util.ServiceLoader; import javax.xml.datatype.XMLGregorianCalendar; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_hashcode; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_prime; /** * @author wenshao[szujobs@hotmail.com] */ public class ParserConfig { public static final String DENY_PROPERTY_INTERNAL = "fastjson.parser.deny.internal"; public static final String DENY_PROPERTY = "fastjson.parser.deny"; public static final String AUTOTYPE_ACCEPT = "fastjson.parser.autoTypeAccept"; public static final String AUTOTYPE_SUPPORT_PROPERTY = "fastjson.parser.autoTypeSupport"; public static final String SAFE_MODE_PROPERTY = "fastjson.parser.safeMode"; public static final String[] DENYS_INTERNAL; public static final String[] DENYS; private static final String[] AUTO_TYPE_ACCEPT_LIST; public static final boolean AUTO_SUPPORT; public static final boolean SAFE_MODE; private static final long[] INTERNAL_WHITELIST_HASHCODES; static { { String property = IOUtils.getStringProperty(DENY_PROPERTY_INTERNAL); DENYS_INTERNAL = splitItemsFormProperty(property); } { 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(SAFE_MODE_PROPERTY); SAFE_MODE = "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; } INTERNAL_WHITELIST_HASHCODES = new long[] { 0x9F2E20FB6049A371L, 0xA8AAA929446FFCE4L, 0xD45D6F8C9017FAL, 0x64DC636F343516DCL }; } public static ParserConfig getGlobalInstance() { return global; } public static ParserConfig global = new ParserConfig(); private final IdentityHashMap deserializers = new IdentityHashMap(); private final IdentityHashMap> mixInDeserializers = new IdentityHashMap>(16); private final ConcurrentMap> typeMapping = new ConcurrentHashMap>(16, 0.75f, 1); 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 static boolean jodaError = false; private static boolean guavaError = false; private boolean autoTypeSupport = AUTO_SUPPORT; private long[] internalDenyHashCodes; private long[] denyHashCodes; private long[] acceptHashCodes; public final boolean fieldBased; private boolean jacksonCompatible = false; public boolean compatibleWithJavaBean = TypeUtils.compatibleWithJavaBean; private List modules = new ArrayList(); private volatile List autoTypeCheckHandlers; private boolean safeMode = SAFE_MODE; { denyHashCodes = new long[]{ 0x80D0C70BCC2FEA02L, 0x868385095A22725FL, 0x86FC2BF9BEAF7AEFL, 0x87F52A1B07EA33A6L, 0x8872F29FD0B0B7A7L, 0x8BAAEE8F9BF77FA7L, 0x8EADD40CB2A94443L, 0x8F75F9FA0DF03F80L, 0x9172A53F157930AFL, 0x92122D710E364FB8L, 0x941866E73BEFF4C9L, 0x94305C26580F73C5L, 0x9437792831DF7D3FL, 0xA123A62F93178B20L, 0xA85882CE1044C450L, 0xAA3DAFFDB10C4937L, 0xAAA9E6B7C1E1C6A7L, 0xAAAA0826487A3737L, 0xAB82562F53E6E48FL, 0xAC6262F52C98AA39L, 0xAD937A449831E8A0L, 0xAE50DA1FAD60A096L, 0xAFF6FF23388E225AL, 0xAFFF4C95B99A334DL, 0xB40F341C746EC94FL, 0xB7E8ED757F5D13A2L, 0xB98B6B5396932FE9L, 0xBCDD9DC12766F0CEL, 0xBCE0DEE34E726499L, 0xBE4F13E96A6796D0L, 0xBEBA72FB1CCBA426L, 0xC00BE1DEBAF2808BL, 0xC1086AFAE32E6258L, 0xC2664D0958ECFE4CL, 0xC41FF7C9C87C7C05L, 0xC664B363BACA050AL, 0xC7599EBFE3E72406L, 0xC8D49E5601E661A9L, 0xC8F04B3A28909935L, 0xC963695082FD728EL, 0xCBF29CE484222325L, 0xD1EFCDF4B3316D34L, 0xD54B91CC77B239EDL, 0xD59EE91F0B09EA01L, 0xD66F68AB92E7FEF5L, 0xD8CA3D595E982BACL, 0xDCD8D615A6449E3EL, 0xDE23A0809A8B9BD6L, 0xDEFC208F237D4104L, 0xDF2DDFF310CDB375L, 0xE09AE4604842582FL, 0xE1919804D5BF468FL, 0xE2EB3AC7E56C467EL, 0xE603D6A51FAD692BL, 0xE704FD19052B2A34L, 0xE9184BE55B1D962AL, 0xE9F20BAD25F60807L, 0xED13653CB45C4BEDL, 0xF2983D099D29B477L, 0xF3702A4A5490B8E8L, 0xF474E44518F26736L, 0xF4D93F4FB3E3D991L, 0xF5D77DCF8E4D71E6L, 0xF6C0340E73A36A69L, 0xF7E96E74DFA58DBCL, 0xFC773AE20C827691L, 0xFCF3E78644B98BD8L, 0xFD5BFC610056D720L, 0xFFA15BF021F1E37CL, 0xFFDD1A80F1ED3405L, 0x10E067CD55C5E5L, 0x761619136CC13EL, 0x22BAA234C5BFB8AL, 0x3085068CB7201B8L, 0x45B11BC78A3ABA3L, 0x55CFCA0F2281C07L, 0xA555C74FE3A5155L, 0xB6E292FA5955ADEL, 0xBEF8514D0B79293L, 0xEE6511B66FD5EF0L, 0x100150A253996624L, 0x10B2BDCA849D9B3EL, 0x10DBC48446E0DAE5L, 0x119B5B1F10210AFCL, 0x144277B467723158L, 0x14DB2E6FEAD04AF0L, 0x154B6CB22D294CFAL, 0x17924CCA5227622AL, 0x193B2697EAAED41AL, 0x1CD6F11C6A358BB7L, 0x1E0A8C3358FF3DAEL, 0x24652CE717E713BBL, 0x24D2F6048FEF4E49L, 0x24EC99D5E7DC5571L, 0x25E962F1C28F71A2L, 0x275D0732B877AF29L, 0x28AC82E44E933606L, 0x2A71CE2CC40A710CL, 0x2AD1CE3A112F015DL, 0x2ADFEFBBFE29D931L, 0x2B3A37467A344CDFL, 0x2B6DD8B3229D6837L, 0x2D308DBBC851B0D8L, 0x2FE950D3EA52AE0DL, 0x313BB4ABD8D4554CL, 0x327C8ED7C8706905L, 0x332F0B5369A18310L, 0x339A3E0B6BEEBEE9L, 0x33C64B921F523F2FL, 0x33E7F3E02571B153L, 0x34A81EE78429FDF1L, 0x37317698DCFCE894L, 0x378307CB0111E878L, 0x3826F4B2380C8B9BL, 0x398F942E01920CF0L, 0x3A31412DBB05C7FFL, 0x3A7EE0635EB2BC33L, 0x3ADBA40367F73264L, 0x3B0B51ECBF6DB221L, 0x3BF14094A524F0E2L, 0x42D11A560FC9FBA9L, 0x43320DC9D2AE0892L, 0x440E89208F445FB9L, 0x46C808A4B5841F57L, 0x470FD3A18BB39414L, 0x49312BDAFB0077D9L, 0x4A3797B30328202CL, 0x4BA3E254E758D70DL, 0x4BF881E49D37F530L, 0x4CF54EEC05E3E818L, 0x4DA972745FEB30C1L, 0x4EF08C90FF16C675L, 0x4FD10DDC6D13821FL, 0x521B4F573376DF4AL, 0x527DB6B46CE3BCBCL, 0x535E552D6F9700C1L, 0x54855E265FE1DAD5L, 0x5728504A6D454FFCL, 0x599B5C1213A099ACL, 0x5A5BD85C072E5EFEL, 0x5AB0CB3071AB40D1L, 0x5B6149820275EA42L, 0x5D74D3E5B9370476L, 0x5D92E6DDDE40ED84L, 0x5E61093EF8CDDDBBL, 0x5F215622FB630753L, 0x61C5BDD721385107L, 0x62DB241274397C34L, 0x636ECCA2A131B235L, 0x63A220E60A17C7B9L, 0x647AB0224E149EBEL, 0x65F81B84C1D920CDL, 0x665C53C311193973L, 0x6749835432E0F0D2L, 0x69B6E0175084B377L, 0x6A47501EBB2AFDB2L, 0x6FCABF6FA54CAFFFL, 0x6FE92D83FC0A4628L, 0x746BD4A53EC195FBL, 0x74B50BB9260E31FFL, 0x75CC60F5871D0FD3L, 0x767A586A5107FEEFL, 0x78E5935826671397L, 0x793ADDDED7A967F5L, 0x7AA7EE3627A19CF3L, 0x7AFA070241B8CC4BL, 0x7ED9311D28BF1A65L, 0x7ED9481D28BF417AL, 0x7EE6C477DA20BBE3L }; 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); addItemsToDeny0(DENYS_INTERNAL); addItemsToAccept(AUTO_TYPE_ACCEPT_LIST); } private final Callable initDeserializersWithJavaSql = new Callable() { public Void call() { 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); return null; } }; private void initDeserializers() { deserializers.put(SimpleDateFormat.class, MiscCodec.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(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()); ModuleUtil.callWhenHasJavaSql(initDeserializersWithJavaSql); } 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 addItemsToDeny0(final String[] items){ if (items == null){ return; } for (int i = 0; i < items.length; ++i) { String item = items[i]; this.addDenyInternal(item); } } 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); } } /** * @since 1.2.68 */ public boolean isSafeMode() { return safeMode; } /** * @since 1.2.68 */ public void setSafeMode(boolean safeMode) { this.safeMode = safeMode; } 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; } /** * @deprecated */ public IdentityHashMap getDerializers() { return deserializers; } public IdentityHashMap getDeserializers() { return deserializers; } public ObjectDeserializer getDeserializer(Type type) { ObjectDeserializer deserializer = get(type); if (deserializer != null) { return deserializer; } 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 deserializer = get(type); if (deserializer == null && type instanceof ParameterizedTypeImpl) { Type innerType = TypeReference.intern((ParameterizedTypeImpl) type); deserializer = get(innerType); } if (deserializer != null) { return deserializer; } if (type == null) { type = clazz; } deserializer = get(type); if (deserializer != null) { return deserializer; } { 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) { deserializer = get(clazz); } if (deserializer != null) { return deserializer; } for (Module module : modules) { deserializer = module.createDeserializer(this, clazz); if (deserializer != null) { putDeserializer(type, deserializer); return deserializer; } } 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)) { putDeserializer(Class.forName(name), deserializer = AwtCodec.instance); return deserializer; } } } catch (Throwable e) { // skip awtError = true; } deserializer = 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)) { putDeserializer(Class.forName(name), deserializer = Jdk8DateCodec.instance); return deserializer; } } } 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)) { putDeserializer(Class.forName(name), deserializer = OptionalCodec.instance); return deserializer; } } } } catch (Throwable e) { // skip jdk8Error = true; } } if (!jodaError) { try { if (className.startsWith("org.joda.time.")) { String[] names = new String[] { "org.joda.time.DateTime", "org.joda.time.LocalDate", "org.joda.time.LocalDateTime", "org.joda.time.LocalTime", "org.joda.time.Instant", "org.joda.time.Period", "org.joda.time.Duration", "org.joda.time.DateTimeZone", "org.joda.time.format.DateTimeFormatter" }; for (String name : names) { if (name.equals(className)) { putDeserializer(Class.forName(name), deserializer = JodaCodec.instance); return deserializer; } } } } catch (Throwable e) { // skip jodaError = 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.LinkedHashMultimap", "com.google.common.collect.ArrayListMultimap", "com.google.common.collect.TreeMultimap" }; for (String name : names) { if (name.equals(className)) { putDeserializer(Class.forName(name), deserializer = GuavaCodec.instance); return deserializer; } } } catch (ClassNotFoundException e) { // skip guavaError = true; } } if (className.equals("java.nio.ByteBuffer")) { putDeserializer(clazz, deserializer = ByteBufferCodec.instance); } if (className.equals("java.nio.file.Path")) { putDeserializer(clazz, deserializer = MiscCodec.instance); } if (clazz == Map.Entry.class) { putDeserializer(clazz, deserializer = MiscCodec.instance); } if (className.equals("org.javamoney.moneta.Money")) { putDeserializer(clazz, deserializer = MonetaCodec.instance); } final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { for (AutowiredObjectDeserializer autowired : ServiceLoader.load(AutowiredObjectDeserializer.class, classLoader)) { for (Type forType : autowired.getAutowiredFor()) { putDeserializer(forType, autowired); } } } catch (Exception ex) { // skip } if (deserializer == null) { deserializer = get(type); } if (deserializer != null) { return deserializer; } if (clazz.isEnum()) { if (jacksonCompatible) { Method[] methods = clazz.getMethods(); for (Method method : methods) { if (TypeUtils.isJacksonCreator(method)) { deserializer = createJavaBeanDeserializer(clazz, type); putDeserializer(type, deserializer); return deserializer; } } } Class mixInType = (Class) JSON.getMixInAnnotations(clazz); Class deserClass = null; JSONType jsonType = TypeUtils.getAnnotation(mixInType != null ? mixInType : clazz, JSONType.class); if (jsonType != null) { deserClass = jsonType.deserializer(); try { deserializer = (ObjectDeserializer) deserClass.newInstance(); putDeserializer(clazz, deserializer); return deserializer; } catch (Throwable error) { // skip } } Method jsonCreatorMethod = null; if (mixInType != null) { Method mixedCreator = getEnumCreator(mixInType, clazz); if (mixedCreator != null) { try { jsonCreatorMethod = clazz.getMethod(mixedCreator.getName(), mixedCreator.getParameterTypes()); } catch (Exception e) { // skip } } } else { jsonCreatorMethod = getEnumCreator(clazz, clazz); } if (jsonCreatorMethod != null) { deserializer = new EnumCreatorDeserializer(jsonCreatorMethod); putDeserializer(clazz, deserializer); return deserializer; } deserializer = getEnumDeserializer(clazz); } else if (clazz.isArray()) { deserializer = ObjectArrayCodec.instance; } else if (clazz == Set.class || clazz == HashSet.class || clazz == Collection.class || clazz == List.class || clazz == ArrayList.class) { deserializer = CollectionCodec.instance; } else if (Collection.class.isAssignableFrom(clazz)) { deserializer = CollectionCodec.instance; } else if (Map.class.isAssignableFrom(clazz)) { deserializer = MapDeserializer.instance; } else if (Throwable.class.isAssignableFrom(clazz)) { deserializer = new ThrowableDeserializer(this, clazz); } else if (PropertyProcessable.class.isAssignableFrom(clazz)) { deserializer = new PropertyProcessableDeserializer((Class) clazz); } else if (clazz == InetAddress.class) { deserializer = MiscCodec.instance; } else { deserializer = createJavaBeanDeserializer(clazz, type); } putDeserializer(type, deserializer); return deserializer; } private static Method getEnumCreator(Class clazz, Class enumClass) { Method[] methods = clazz.getMethods(); Method jsonCreatorMethod = null; for (Method method : methods) { if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() == enumClass && method.getParameterTypes().length == 1 ) { JSONCreator jsonCreator = method.getAnnotation(JSONCreator.class); if (jsonCreator != null) { jsonCreatorMethod = method; break; } } } return jsonCreatorMethod; } /** * 可以通过重写这个方法,定义自己的枚举反序列化实现 * @param clazz 转换的类型 * @return 返回一个枚举的反序列化实现 * @author zhu.xiaojie * @time 2020-4-5 */ protected ObjectDeserializer getEnumDeserializer(Class clazz){ return new EnumDeserializer(clazz); } /** * * @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() && jsonType.parseFeatures().length == 0; } 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 ,false , TypeUtils.compatibleWithJavaBean , jacksonCompatible ); 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.parseFeatures().length != 0 // || 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) { if (TypeUtils.isXmlField(clazz)) { 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) { Type mixin = JSON.getMixInAnnotations(type); if (mixin != null) { IdentityHashMap mixInClasses = this.mixInDeserializers.get(type); if (mixInClasses == null) { //多线程下可能会重复创建,但不影响正确性 mixInClasses = new IdentityHashMap(4); this.mixInDeserializers.put(type, mixInClasses); } mixInClasses.put(mixin, deserializer); } else { this.deserializers.put(type, deserializer); } } public ObjectDeserializer get(Type type) { Type mixin = JSON.getMixInAnnotations(type); if (null == mixin) { return this.deserializers.get(type); } IdentityHashMap mixInClasses = this.mixInDeserializers.get(type); if (mixInClasses == null) { return null; } return mixInClasses.get(mixin); } public ObjectDeserializer getDeserializer(FieldInfo fieldInfo) { return getDeserializer(fieldInfo.fieldClass, fieldInfo.fieldType); } /** * @deprecated internal method, dont call */ public boolean isPrimitive(Class clazz) { return isPrimitive2(clazz); } private static Function, Boolean> isPrimitiveFuncation = new Function, Boolean>() { public Boolean apply(Class clazz) { return clazz == java.sql.Date.class // || clazz == java.sql.Time.class // || clazz == java.sql.Timestamp.class; } }; /** * @deprecated internal method, dont call */ public static boolean isPrimitive2(final Class clazz) { Boolean primitive = 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.isEnum() // ; if (!primitive) { primitive = ModuleUtil.callWhenHasJavaSql(isPrimitiveFuncation, clazz); } return primitive != null ? primitive : false; } /** * 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 (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 addDenyInternal(String name) { if (name == null || name.length() == 0) { return; } long hash = TypeUtils.fnv1a_64(name); if (internalDenyHashCodes == null) { this.internalDenyHashCodes = new long[] {hash}; return; } if (Arrays.binarySearch(this.internalDenyHashCodes, hash) >= 0) { return; } long[] hashCodes = new long[this.internalDenyHashCodes.length + 1]; hashCodes[hashCodes.length - 1] = hash; System.arraycopy(this.internalDenyHashCodes, 0, hashCodes, 0, this.internalDenyHashCodes.length); Arrays.sort(hashCodes); this.internalDenyHashCodes = hashCodes; } 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(Class type) { if (get(type) != null) { return type; } return checkAutoType(type.getName(), null, JSON.DEFAULT_PARSER_FEATURE); } 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 (autoTypeCheckHandlers != null) { for (AutoTypeCheckHandler h : autoTypeCheckHandlers) { Class type = h.handler(typeName, expectClass, features); if (type != null) { return type; } } } final int safeModeMask = Feature.SafeMode.mask; boolean safeMode = this.safeMode || (features & safeModeMask) != 0 || (JSON.DEFAULT_PARSER_FEATURE & safeModeMask) != 0; if (safeMode) { throw new JSONException("safeMode not support autoType : " + typeName); } final int mask = Feature.SupportAutoType.mask; boolean autoTypeSupport = this.autoTypeSupport || (features & mask) != 0 || (JSON.DEFAULT_PARSER_FEATURE & mask) != 0; if (typeName.length() >= 192 || typeName.length() < 3) { throw new JSONException("autoType is not support. " + typeName); } final boolean expectClassFlag; if (expectClass == null) { expectClassFlag = false; } else { long expectHash = TypeUtils.fnv1a_64(expectClass.getName()); if (expectHash == 0x90a25f5baa21529eL || expectHash == 0x2d10a5801b9d6136L || expectHash == 0xaf586a571e302c6bL || expectHash == 0xed007300a7b227c6L || expectHash == 0x295c4605fd1eaa95L || expectHash == 0x47ef269aadc650b4L || expectHash == 0x6439c4dff712ae8bL || expectHash == 0xe3dd9875a2dc5283L || expectHash == 0xe2a8ddba03e69e0dL || expectHash == 0xd734ceb4c3e9d1daL ) { expectClassFlag = false; } else { expectClassFlag = true; } } String className = typeName.replace('$', '.'); Class clazz; final long h1 = (fnv1a_64_magic_hashcode ^ className.charAt(0)) * fnv1a_64_magic_prime; if (h1 == 0xaf64164c86024f1aL) { // [ throw new JSONException("autoType is not support. " + typeName); } if ((h1 ^ className.charAt(className.length() - 1)) * fnv1a_64_magic_prime == 0x9198507b5af98f0L) { throw new JSONException("autoType is not support. " + typeName); } final long h3 = (((((fnv1a_64_magic_hashcode ^ className.charAt(0)) * fnv1a_64_magic_prime) ^ className.charAt(1)) * fnv1a_64_magic_prime) ^ className.charAt(2)) * fnv1a_64_magic_prime; long fullHash = TypeUtils.fnv1a_64(className); boolean internalWhite = Arrays.binarySearch(INTERNAL_WHITELIST_HASHCODES, fullHash) >= 0; if (internalDenyHashCodes != null) { long hash = h3; for (int i = 3; i < className.length(); ++i) { hash ^= className.charAt(i); hash *= fnv1a_64_magic_prime; if (Arrays.binarySearch(internalDenyHashCodes, hash) >= 0) { throw new JSONException("autoType is not support. " + typeName); } } } if ((!internalWhite) && (autoTypeSupport || expectClassFlag)) { long hash = h3; for (int i = 3; i < className.length(); ++i) { hash ^= className.charAt(i); hash *= fnv1a_64_magic_prime; if (Arrays.binarySearch(acceptHashCodes, hash) >= 0) { clazz = TypeUtils.loadClass(typeName, defaultClassLoader, true); if (clazz != null) { return clazz; } } if (Arrays.binarySearch(denyHashCodes, hash) >= 0 && TypeUtils.getClassFromMapping(typeName) == null) { if (Arrays.binarySearch(acceptHashCodes, fullHash) >= 0) { continue; } throw new JSONException("autoType is not support. " + typeName); } } } clazz = TypeUtils.getClassFromMapping(typeName); if (clazz == null) { clazz = deserializers.findClass(typeName); } if (expectClass == null && clazz != null && Throwable.class.isAssignableFrom(clazz) && !autoTypeSupport) { clazz = null; } if (clazz == null) { clazz = typeMapping.get(typeName); } if (internalWhite) { clazz = TypeUtils.loadClass(typeName, defaultClassLoader, true); } if (clazz != null) { if (expectClass != null && clazz != java.util.HashMap.class && clazz != java.util.LinkedHashMap.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 *= fnv1a_64_magic_prime; if (Arrays.binarySearch(denyHashCodes, hash) >= 0) { if (typeName.endsWith("Exception") || typeName.endsWith("Error")) { return null; } throw new JSONException("autoType is not support. " + typeName); } // white list if (Arrays.binarySearch(acceptHashCodes, hash) >= 0) { clazz = TypeUtils.loadClass(typeName, defaultClassLoader, true); if (clazz == null) { return expectClass; } if (expectClass != null && expectClass.isAssignableFrom(clazz)) { throw new JSONException("type not match. " + typeName + " -> " + expectClass.getName()); } return clazz; } } } boolean jsonType = false; InputStream is = null; try { String resource = typeName.replace('.', '/') + ".class"; if (defaultClassLoader != null) { is = defaultClassLoader.getResourceAsStream(resource); } else { is = ParserConfig.class.getClassLoader().getResourceAsStream(resource); } if (is != null) { ClassReader classReader = new ClassReader(is, true); TypeCollector visitor = new TypeCollector("", new Class[0]); classReader.accept(visitor); jsonType = visitor.hasJsonType(); } } catch (Exception e) { // skip } finally { IOUtils.close(is); } if (autoTypeSupport || jsonType || expectClassFlag) { boolean cacheClass = autoTypeSupport || jsonType; clazz = TypeUtils.loadClass(typeName, defaultClassLoader, cacheClass); } if (clazz != null) { if (jsonType) { if (autoTypeSupport) { TypeUtils.addMapping(typeName, clazz); } return clazz; } if (ClassLoader.class.isAssignableFrom(clazz) // classloader is danger || javax.sql.DataSource.class.isAssignableFrom(clazz) // dataSource can load jdbc driver || javax.sql.RowSet.class.isAssignableFrom(clazz) // ) { throw new JSONException("autoType is not support. " + typeName); } if (expectClass != null) { if (expectClass.isAssignableFrom(clazz)) { if (autoTypeSupport) { TypeUtils.addMapping(typeName, 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); } } if (!autoTypeSupport) { if (typeName.endsWith("Exception") || typeName.endsWith("Error")) { return null; } throw new JSONException("autoType is not support. " + typeName); } if (clazz != null) { if (autoTypeSupport) { TypeUtils.addMapping(typeName, clazz); } } return clazz; } public void clearDeserializers() { this.deserializers.clear(); this.initDeserializers(); } public boolean isJacksonCompatible() { return jacksonCompatible; } public void setJacksonCompatible(boolean jacksonCompatible) { this.jacksonCompatible = jacksonCompatible; } public void register(String typeName, Class type) { typeMapping.putIfAbsent(typeName, type); } public void register(Module module) { this.modules.add(module); } public void addAutoTypeCheckHandler(AutoTypeCheckHandler h) { List autoTypeCheckHandlers = this.autoTypeCheckHandlers; if (autoTypeCheckHandlers == null) { this.autoTypeCheckHandlers = autoTypeCheckHandlers = new CopyOnWriteArrayList(); } autoTypeCheckHandlers.add(h); } /** * @since 1.2.68 */ public interface AutoTypeCheckHandler { Class handler(String typeName, Class expectClass, int features); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/SymbolTable.java ================================================ /* * 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/ASMDeserializerFactory.java ================================================ package com.alibaba.fastjson.parser.deserializer; 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.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.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.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.util.*; public class ASMDeserializerFactory implements Opcodes { public final ASMClassLoader classLoader; protected final AtomicLong seed = new AtomicLong(); final static String DefaultJSONParser = type(DefaultJSONParser.class); final static String JSONLexerBase = type(JSONLexerBase.class); 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; } 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; } 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)); } 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); } 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); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getSymbolTable", "()" + desc(SymbolTable.class)); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanTypeName", "(" + desc(SymbolTable.class) + ")Ljava/lang/String;"); mw.visitVarInsn(ASTORE, context.var("typeName")); Label typeNameNotNull_ = new Label(); mw.visitVarInsn(ALOAD, context.var("typeName")); mw.visitJumpInsn(IFNULL, typeNameNotNull_); mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getConfig", "()" + desc(ParserConfig.class)); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, type(JavaBeanDeserializer.class), "beanInfo", desc(JavaBeanInfo.class)); mw.visitVarInsn(ALOAD, context.var("typeName")); mw.visitMethodInsn(INVOKESTATIC, type(JavaBeanDeserializer.class), "getSeeAlso" , "(" + desc(ParserConfig.class) + desc(JavaBeanInfo.class) + "Ljava/lang/String;)" + desc(JavaBeanDeserializer.class)); mw.visitVarInsn(ASTORE, context.var("userTypeDeser")); mw.visitVarInsn(ALOAD, context.var("userTypeDeser")); mw.visitTypeInsn(INSTANCEOF, type(JavaBeanDeserializer.class)); mw.visitJumpInsn(IFEQ, typeNameNotNull_); mw.visitVarInsn(ALOAD, context.var("userTypeDeser")); mw.visitVarInsn(ALOAD, Context.parser); mw.visitVarInsn(ALOAD, 2); mw.visitVarInsn(ALOAD, 3); mw.visitVarInsn(ALOAD, 4); mw.visitMethodInsn(INVOKEVIRTUAL, // type(JavaBeanDeserializer.class), // "deserialzeArrayMapping", // "(L" + DefaultJSONParser + ";Ljava/lang/reflect/Type;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); mw.visitInsn(ARETURN); mw.visitLabel(typeNameNotNull_); _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_asm(fieldInfo)); } 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_asm(fieldInfo)); 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_asm(fieldInfo)); 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_asm(fieldInfo)); 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_asm(fieldInfo)); 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_asm(fieldInfo)); 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_asm(fieldInfo)); 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_asm(fieldInfo, 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_asm(fieldInfo)); 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_asm(fieldInfo)); 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_asm(fieldInfo)); } 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_asm(fieldInfo)); } 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_asm(fieldInfo)); 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_asm(fieldInfo)); 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_asm(fieldInfo, 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_asm(fieldInfo)); 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_asm(fieldInfo)); 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_asm(fieldInfo)); } 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_asm(fieldInfo)); } 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_asm(fieldInfo)); } 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_asm(fieldInfo)); } 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_asm(fieldInfo)); } 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_asm(fieldInfo)); } 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_asm(fieldInfo)); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, context.var_asm(fieldInfo)); 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_asm(fieldInfo)); 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.visitLdcInsn(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_asm(fieldInfo)); _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_asm(fieldInfo)); } 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_asm(fieldInfo)); 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; } } _batchSet(context, mw, false); 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_); 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(quickElseIf_); mw.visitVarInsn(ILOAD, context.var("ch")); mw.visitVarInsn(BIPUSH, ']'); mw.visitJumpInsn(IF_ICMPNE, quickElseIfEOI_); 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(quickElseIfEOI_); mw.visitVarInsn(ILOAD, context.var("ch")); mw.visitVarInsn(BIPUSH, (char) JSONLexer.EOI); 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.EOF); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "setToken", "(I)V"); mw.visitJumpInsn(GOTO, quickEnd_); mw.visitLabel(quickElse_); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitLdcInsn(JSONToken.COMMA); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "nextToken", "(I)V"); mw.visitLabel(quickEnd_); mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitInsn(ARETURN); mw.visitMaxs(5, context.variantIndex); mw.visitEnd(); } private void _deserialze(ClassWriter cw, Context context) { if (context.fieldInfoList.length == 0) { return; } for (FieldInfo fieldInfo : context.fieldInfoList) { 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; } } } JavaBeanInfo beanInfo = context.beanInfo; context.fieldInfoList = beanInfo.sortedFields; 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(); 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.visitLdcInsn(Feature.SortFeidFastMatch.mask); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "isEnabled", "(I)Z"); Label continue_ = new Label(); mw.visitJumpInsn(IFNE, continue_); mw.visitJumpInsn(GOTO_W, super_); mw.visitLabel(continue_); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitLdcInsn(context.clazz.getName()); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanType", "(Ljava/lang/String;)I"); mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.NOT_MATCH); Label continue_2 = new Label(); mw.visitJumpInsn(IF_ICMPNE, continue_2); mw.visitJumpInsn(GOTO_W, super_); mw.visitLabel(continue_2); 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.visitFieldInsn(GETFIELD, JSONLexerBase, "matchStat", "I"); mw.visitLdcInsn(com.alibaba.fastjson.parser.JSONLexerBase.END); //mw.visitJumpInsn(IF_ICMPEQ, return_); Label continue_3 = new Label(); mw.visitJumpInsn(IF_ICMPNE, continue_3); mw.visitJumpInsn(GOTO_W, return_); mw.visitLabel(continue_3); 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.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_asm(fieldInfo)); } else if (fieldClass == long.class) { mw.visitInsn(LCONST_0); mw.visitVarInsn(LSTORE, context.var_asm(fieldInfo, 2)); } else if (fieldClass == float.class) { mw.visitInsn(FCONST_0); mw.visitVarInsn(FSTORE, context.var_asm(fieldInfo)); } else if (fieldClass == double.class) { mw.visitInsn(DCONST_0); mw.visitVarInsn(DSTORE, context.var_asm(fieldInfo, 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); } mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); } } 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, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldBoolean", "([C)Z"); mw.visitVarInsn(ISTORE, context.var_asm(fieldInfo)); } else if (fieldClass == byte.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); mw.visitVarInsn(ISTORE, context.var_asm(fieldInfo)); } else if (fieldClass == Byte.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); mw.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); 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_asm(fieldInfo)); mw.visitLabel(valueNullEnd_); } else if (fieldClass == short.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); mw.visitVarInsn(ISTORE, context.var_asm(fieldInfo)); } else if (fieldClass == Short.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); mw.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); 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_asm(fieldInfo)); mw.visitLabel(valueNullEnd_); } else if (fieldClass == int.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); mw.visitVarInsn(ISTORE, context.var_asm(fieldInfo)); } else if (fieldClass == Integer.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldInt", "([C)I"); mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); 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_asm(fieldInfo)); mw.visitLabel(valueNullEnd_); } else if (fieldClass == long.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldLong", "([C)J"); mw.visitVarInsn(LSTORE, context.var_asm(fieldInfo, 2)); } else if (fieldClass == Long.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldLong", "([C)J"); mw.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); 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_asm(fieldInfo)); mw.visitLabel(valueNullEnd_); } else if (fieldClass == float.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldFloat", "([C)F"); mw.visitVarInsn(FSTORE, context.var_asm(fieldInfo)); } else if (fieldClass == Float.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldFloat", "([C)F"); mw.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); 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_asm(fieldInfo)); mw.visitLabel(valueNullEnd_); } else if (fieldClass == double.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldDouble", "([C)D"); mw.visitVarInsn(DSTORE, context.var_asm(fieldInfo, 2)); } else if (fieldClass == Double.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldDouble", "([C)D"); mw.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); 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_asm(fieldInfo)); mw.visitLabel(valueNullEnd_); } else if (fieldClass == String.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldString", "([C)Ljava/lang/String;"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); } else if (fieldClass == java.util.Date.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldDate", "([C)Ljava/util/Date;"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); } else if (fieldClass == java.util.UUID.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldUUID", "([C)Ljava/util/UUID;"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); } else if (fieldClass == BigDecimal.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldDecimal", "([C)Ljava/math/BigDecimal;"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); } else if (fieldClass == BigInteger.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldBigInteger", "([C)Ljava/math/BigInteger;"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); } else if (fieldClass == int[].class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldIntArray", "([C)[I"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); } else if (fieldClass == float[].class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldFloatArray", "([C)[F"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); } else if (fieldClass == float[][].class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "scanFieldFloatArray2", "([C)[[F"); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); } else if (fieldClass.isEnum()) { mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[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_asm(fieldInfo)); // } else if (fieldClass.isEnum()) { // mw.visitVarInsn(ALOAD, context.var("lexer")); // mw.visitVarInsn(ALOAD, 0); // mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); // Label enumNull_ = new Label(); // mw.visitInsn(ACONST_NULL); // mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast // mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); // // 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_asm(fieldInfo)); // mw.visitLabel(enumNull_); } else if (Collection.class.isAssignableFrom(fieldClass)) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[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_asm(fieldInfo)); } else { _deserialze_list_obj(context, mw, reset_, fieldInfo, fieldClass, itemClass, i); if (i == fieldListSize - 1) { _deserialize_endCheck(context, mw, reset_); } continue; } } else { _deserialze_obj(context, mw, reset_, fieldInfo, fieldClass, i); if (i == fieldListSize - 1) { _deserialize_endCheck(context, mw, reset_); } continue; } mw.visitVarInsn(ALOAD, context.var("lexer")); 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_); 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, 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.visitLabel(return_); _setContext(context, mw); mw.visitVarInsn(ALOAD, context.var("instance")); Method buildMethod = context.beanInfo.buildMethod; if (buildMethod != null) { mw.visitMethodInsn(INVOKEVIRTUAL, type(context.getInstClass()), buildMethod.getName(), "()" + desc(buildMethod.getReturnType())); } mw.visitInsn(ARETURN); mw.visitLabel(reset_); _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.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.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"); } 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_asm(fieldInfo)); _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_asm(fieldInfo)); _set(context, mw, fieldInfo); } else if (fieldClass == long.class) { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(LLOAD, context.var_asm(fieldInfo, 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_asm(fieldInfo)); _set(context, mw, fieldInfo); } else if (fieldClass == double.class) { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(DLOAD, context.var_asm(fieldInfo, 2)); _set(context, mw, fieldInfo); } else if (fieldClass == String.class) { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(ALOAD, context.var_asm(fieldInfo)); _set(context, mw, fieldInfo); } else if (fieldClass.isEnum()) { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(ALOAD, context.var_asm(fieldInfo)); _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_asm(fieldInfo)); mw.visitTypeInsn(CHECKCAST, type(fieldClass)); // cast } else { mw.visitVarInsn(ALOAD, context.var_asm(fieldInfo)); } _set(context, mw, fieldInfo); } else { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(ALOAD, context.var_asm(fieldInfo)); _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, JSONLexerBase, "token", "()I"); mw.visitLdcInsn(JSONToken.RBRACE); mw.visitJumpInsn(IF_ICMPNE, reset_); // mw.visitLabel(nextToken_); _quickNextTokenComma(context, mw); } private void _deserialze_list_obj(Context context, MethodVisitor mw, Label reset_, FieldInfo fieldInfo, Class fieldClass, Class itemType, int i) { Label _end_if = new Label(); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "matchField", "([C)Z"); mw.visitJumpInsn(IFEQ, _end_if); _setFlag(mw, context, i); 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, context.var("lexer")); mw.visitLdcInsn(JSONToken.COMMA); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "nextToken", "(I)V"); mw.visitJumpInsn(GOTO, _end_if); // loop_end_ mw.visitLabel(valueNotNull_); 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, 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_); _newCollection(mw, fieldClass, i, false); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); _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.visitVarInsn(ALOAD, context.var_asm(fieldInfo)); 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_asm(fieldInfo)); 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_asm(fieldInfo)); 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_); 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.className, fieldInfo.name + "_asm_list_item_deser__", desc(ObjectDeserializer.class)); mw.visitVarInsn(ALOAD, 1); 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.visitIincInsn(context.var("i"), 1); mw.visitVarInsn(ALOAD, context.var_asm(fieldInfo)); 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.visitVarInsn(ALOAD, 1); mw.visitVarInsn(ALOAD, context.var_asm(fieldInfo)); mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "checkListResolve", "(Ljava/util/Collection;)V"); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "token", "()I"); mw.visitLdcInsn(JSONToken.COMMA); mw.visitJumpInsn(IF_ICMPNE, loop_); 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, JSONLexerBase, "token", "()I"); mw.visitLdcInsn(JSONToken.RBRACKET); mw.visitJumpInsn(IF_ICMPNE, reset_); _quickNextTokenComma(context, mw); // lexer.nextToken(JSONToken.COMMA); mw.visitLabel(_end_if); } 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.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, 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.className, fieldInfo.name + "_asm_list_item_deser__", desc(ObjectDeserializer.class)); mw.visitLabel(notNull_); mw.visitVarInsn(ALOAD, 0); 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 } 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(); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldName(fieldInfo), "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, JSONLexerBase, "matchField", "([C)Z"); mw.visitJumpInsn(IFNE, matched_); mw.visitInsn(ACONST_NULL); mw.visitVarInsn(ASTORE, context.var_asm(fieldInfo)); mw.visitJumpInsn(GOTO, _end_if); mw.visitLabel(matched_); _setFlag(mw, context, i); // increment matchedCount mw.visitVarInsn(ILOAD, context.var("matchedCount")); mw.visitInsn(ICONST_1); mw.visitInsn(IADD); mw.visitVarInsn(ISTORE, context.var("matchedCount")); _deserObject(context, mw, fieldInfo, fieldClass, i); 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.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getLastResolveTask", "()" + desc(ResolveTask.class)); mw.visitVarInsn(ASTORE, context.var("resolveTask")); 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.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.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); 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_asm(fieldInfo)); mw.visitJumpInsn(GOTO, instanceOfEnd_); mw.visitLabel(instanceOfElse_); } 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_asm(fieldInfo)); mw.visitLabel(instanceOfEnd_); } private void _getFieldDeser(Context context, MethodVisitor mw, FieldInfo fieldInfo) { Label notNull_ = new Label(); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldDeserName(fieldInfo), desc(ObjectDeserializer.class)); mw.visitJumpInsn(IFNONNULL, notNull_); mw.visitVarInsn(ALOAD, 0); 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)); mw.visitFieldInsn(PUTFIELD, context.className, context.fieldDeserName(fieldInfo), desc(ObjectDeserializer.class)); mw.visitLabel(notNull_); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.className, context.fieldDeserName(fieldInfo), desc(ObjectDeserializer.class)); } static class Context { static final int parser = 1; static final int type = 2; static final int fieldName = 3; private int variantIndex = -1; private final Map variants = new HashMap(); private final Class clazz; private final JavaBeanInfo beanInfo; private final String className; private FieldInfo[] fieldInfoList; public Context(String className, ParserConfig config, JavaBeanInfo beanInfo, int initVariantIndex){ this.className = className; this.clazz = beanInfo.clazz; this.variantIndex = initVariantIndex; this.beanInfo = beanInfo; fieldInfoList = beanInfo.fields; } public Class getInstClass() { Class instClass = beanInfo.builderClass; if (instClass == null) { instClass = clazz; } return instClass; } public int var(String name, int increment) { Integer i = variants.get(name); if (i == null) { variants.put(name, variantIndex); variantIndex += increment; } i = variants.get(name); return i.intValue(); } public int var(String name) { Integer i = variants.get(name); if (i == null) { variants.put(name, variantIndex++); } i = variants.get(name); return i.intValue(); } public int var_asm(FieldInfo fieldInfo) { return var(fieldInfo.name + "_asm"); } public int var_asm(FieldInfo fieldInfo, int increment) { return var(fieldInfo.name + "_asm", increment); } public String fieldName(FieldInfo fieldInfo) { return validIdent(fieldInfo.name) ? fieldInfo.name + "_asm_prefix__" : "asm_field_" + TypeUtils.fnv1a_64_extract(fieldInfo.name); } public String fieldDeserName(FieldInfo fieldInfo) { return validIdent(fieldInfo.name) ? fieldInfo.name + "_asm_deser__" : "_asm_deser__" + TypeUtils.fnv1a_64_extract(fieldInfo.name); } boolean validIdent(String name) { for (int i = 0; i < name.length(); ++i) { char ch = name.charAt(i); if (ch == 0) { if (!IOUtils.firstIdentifier(ch)) { return false; } } else { if (!IOUtils.isIdent(ch)) { return false; } } } return true; } } private void _init(ClassWriter cw, Context context) { for (int i = 0, size = context.fieldInfoList.length; i < size; ++i) { FieldInfo fieldInfo = context.fieldInfoList[i]; FieldWriter fw = new FieldWriter(cw, ACC_PUBLIC, context.fieldName(fieldInfo), "[C"); fw.visitEnd(); } 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 (Collection.class.isAssignableFrom(fieldClass)) { FieldWriter fw = new FieldWriter(cw, ACC_PUBLIC, fieldInfo.name + "_asm_list_item_deser__", desc(ObjectDeserializer.class)); fw.visitEnd(); } else { FieldWriter fw = new FieldWriter(cw, ACC_PUBLIC, context.fieldDeserName(fieldInfo), desc(ObjectDeserializer.class)); fw.visitEnd(); } } 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, type(JavaBeanDeserializer.class), "", "(" + desc(ParserConfig.class) + desc(JavaBeanInfo.class) + ")V"); // init fieldNamePrefix for (int i = 0, size = context.fieldInfoList.length; i < size; ++i) { FieldInfo fieldInfo = context.fieldInfoList[i]; mw.visitVarInsn(ALOAD, 0); mw.visitLdcInsn("\"" + fieldInfo.name + "\":"); // public char[] toCharArray() mw.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "toCharArray", "()[C"); mw.visitFieldInsn(PUTFIELD, context.className, context.fieldName(fieldInfo), "[C"); } mw.visitInsn(RETURN); mw.visitMaxs(4, 4); mw.visitEnd(); } private void _createInstance(ClassWriter cw, Context context) { 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, type(context.getInstClass()), "", "()V"); mw.visitInsn(ARETURN); mw.visitMaxs(3, 3); mw.visitEnd(); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/AbstractDateDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Locale; 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) { long millis = lexer.longValue(); lexer.nextToken(JSONToken.COMMA); if ("unixtime".equals(format)) { millis *= 1000; } val = millis; } else if (lexer.token() == JSONToken.LITERAL_STRING) { String strVal = lexer.stringVal(); if (format != null) { if ("yyyy-MM-dd HH:mm:ss.SSSSSSSSS".equals(format) && clazz instanceof Class && ((Class) clazz).getName().equals("java.sql.Timestamp")) { return (T) TypeUtils.castToTimestamp(strVal); } SimpleDateFormat simpleDateFormat = null; try { simpleDateFormat = new SimpleDateFormat(format, parser.lexer.getLocale()); } catch (IllegalArgumentException ex) { if (format.contains("T")) { String fromat2 = format.replaceAll("T", "'T'"); try { simpleDateFormat = new SimpleDateFormat(fromat2, parser.lexer.getLocale()); } catch (IllegalArgumentException e2) { throw ex; } } } if (JSON.defaultTimeZone != null) { simpleDateFormat.setTimeZone(parser.lexer.getTimeZone()); } try { val = simpleDateFormat.parse(strVal); } catch (ParseException ex) { val = null; // skip } if (val == null && JSON.defaultLocale == Locale.CHINA) { try { simpleDateFormat = new SimpleDateFormat(format, Locale.US); } catch (IllegalArgumentException ex) { if (format.contains("T")) { String fromat2 = format.replaceAll("T", "'T'"); try { simpleDateFormat = new SimpleDateFormat(fromat2, parser.lexer.getLocale()); } catch (IllegalArgumentException e2) { throw ex; } } } simpleDateFormat.setTimeZone(parser.lexer.getTimeZone()); try { val = simpleDateFormat.parse(strVal); } catch (ParseException ex) { val = null; // skip } } if (val == null) { if (format.equals("yyyy-MM-dd'T'HH:mm:ss.SSS") // && strVal.length() == 19) { try { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", JSON.defaultLocale); df.setTimeZone(JSON.defaultTimeZone); val = df.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); } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/ArrayListTypeFieldDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; 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.JSON; 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.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 { private final Type itemType; private int itemFastMatchToken; private ObjectDeserializer deserializer; public ArrayListTypeFieldDeserializer(ParserConfig mapping, Class clazz, FieldInfo fieldInfo){ super(clazz, fieldInfo); 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() { return JSONToken.LBRACKET; } @SuppressWarnings("rawtypes") @Override 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)) { if (object == null) { fieldValues.put(fieldInfo.name, null); } else { setValue(object, null); } return; } ArrayList list = new ArrayList(); ParseContext context = parser.getContext(); 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(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(); } 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) { 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 = TypeReference.intern( 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; } } } final JSONLexer lexer = parser.lexer; 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; } } lexer.nextToken(JSONToken.COMMA); } else if (token == JSONToken.LITERAL_STRING && fieldInfo.unwrapped) { String str = lexer.stringVal(); lexer.nextToken(); DefaultJSONParser valueParser = new DefaultJSONParser(str); valueParser.parseArray(array); } else { if (itemTypeDeser == null) { itemTypeDeser = deserializer = parser.getConfig().getDeserializer(itemType); } Object val = itemTypeDeser.deserialze(parser, itemType, 0); array.add(val); parser.checkListResolve(array); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/AutowiredObjectDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; import java.lang.reflect.Type; import java.util.Set; public interface AutowiredObjectDeserializer extends ObjectDeserializer{ Set getAutowiredFor(); } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/ContextObjectDeserializer.java ================================================ 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); } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/DefaultFieldDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; 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 { protected ObjectDeserializer fieldValueDeserilizer; protected boolean customDeserilizer = false; 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; } } public ObjectDeserializer getFieldValueDeserilizer(ParserConfig config) { if (fieldValueDeserilizer == null) { 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); if (fieldValueDeserilizer instanceof JavaObjectDeserializer) { fieldValueDeserilizer = parser.getConfig().getDeserializer(fieldType); } } } // 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 || this.fieldInfo.parserFeatures != 0) && 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 JSONToken.LITERAL_INT; } public void parseFieldUnwrapped(DefaultJSONParser parser, Object object, Type objectType, Map fieldValues) { throw new JSONException("TODO"); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/EnumCreatorDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.DefaultJSONParser; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; public class EnumCreatorDeserializer implements ObjectDeserializer { private final Method creator; private final Class paramType; public EnumCreatorDeserializer(Method creator) { this.creator = creator; paramType = creator.getParameterTypes()[0]; } public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { Object arg = parser.parseObject(paramType); try { return (T) creator.invoke(null, arg); } catch (IllegalAccessException e) { throw new JSONException("parse enum error", e); } catch (InvocationTargetException e) { throw new JSONException("parse enum error", e); } } public int getFastMatchToken() { return 0; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/EnumDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.*; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.annotation.JSONField; 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.util.TypeUtils; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_hashcode; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_prime; @SuppressWarnings("rawtypes") public class EnumDeserializer implements ObjectDeserializer { protected final Class enumClass; protected final Enum[] enums; protected final Enum[] ordinalEnums; protected long[] enumNameHashCodes; public EnumDeserializer(Class enumClass){ this.enumClass = enumClass; 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 = TypeUtils.getAnnotation(field, JSONField.class); if (jsonField != null) { String jsonFieldName = jsonField.name(); if (jsonFieldName != null && jsonFieldName.length() > 0) { name = jsonFieldName; } } } catch (Exception ex) { // skip } long hash = fnv1a_64_magic_hashcode; long hash_lower = fnv1a_64_magic_hashcode; 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 *= fnv1a_64_magic_prime; hash_lower *= fnv1a_64_magic_prime; } enumMap.put(hash, e); if (hash != hash_lower) { enumMap.put(hash_lower, e); } if (jsonField != null) { for (String alterName : jsonField.alternateNames()) { long alterNameHash = fnv1a_64_magic_hashcode; for (int j = 0; j < alterName.length(); ++j) { char ch = alterName.charAt(j); alterNameHash ^= ch; alterNameHash *= fnv1a_64_magic_prime; } if (alterNameHash != hash && alterNameHash != hash_lower) { enumMap.put(alterNameHash, e); } } } } 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(DefaultJSONParser parser, Type type, Object fieldName) { try { Object value; final JSONLexer lexer = parser.lexer; final int token = lexer.token(); if (token == JSONToken.LITERAL_INT) { int intValue = lexer.intValue(); lexer.nextToken(JSONToken.COMMA); if (intValue < 0 || intValue >= ordinalEnums.length) { throw new JSONException("parse enum " + enumClass.getName() + " error, value : " + intValue); } return (T) ordinalEnums[intValue]; } else if (token == JSONToken.LITERAL_STRING) { String name = lexer.stringVal(); lexer.nextToken(JSONToken.COMMA); if (name.length() == 0) { return (T) null; } long hash = fnv1a_64_magic_hashcode; long hash_lower = fnv1a_64_magic_hashcode; 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 *= fnv1a_64_magic_prime; hash_lower *= fnv1a_64_magic_prime; } Enum e = getEnumByHashCode(hash); if (e == null && hash_lower != hash) { e = getEnumByHashCode(hash_lower); } if (e == null && lexer.isEnabled(Feature.ErrorOnEnumNotMatch)) { throw new JSONException("not match enum value, " + enumClass.getName() + " : " + name); } return (T) e; } else if (token == JSONToken.NULL) { value = null; lexer.nextToken(JSONToken.COMMA); return null; } else { value = parser.parse(); } throw new JSONException("parse enum " + enumClass.getName() + " error, value : " + value); } catch (JSONException e) { throw e; } catch (Exception e) { throw new JSONException(e.getMessage(), e); } } public int getFastMatchToken() { return JSONToken.LITERAL_INT; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraProcessable.java ================================================ package com.alibaba.fastjson.parser.deserializer; /** * * @author wenshao[szujobs@hotmail.com] * @since 1.2.9 */ public interface ExtraProcessable { void processExtra(String key, Object value); } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraProcessor.java ================================================ 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); } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/ExtraTypeProvider.java ================================================ 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); } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/FieldDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.BeanContext; import com.alibaba.fastjson.util.FieldInfo; import com.alibaba.fastjson.util.TypeUtils; import java.lang.reflect.*; 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; public abstract class FieldDeserializer { public final FieldInfo fieldInfo; protected final Class clazz; protected BeanContext beanContext; public FieldDeserializer(Class clazz, FieldInfo fieldInfo) { this.clazz = clazz; this.fieldInfo = fieldInfo; } public Class getOwnerClass() { return clazz; } 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 { degradeValueAssignment(fieldInfo.field, method, object, value); } } else if (fieldInfo.fieldClass == AtomicLong.class) { AtomicLong atomic = (AtomicLong) method.invoke(object); if (atomic != null) { atomic.set(((AtomicLong) value).get()); } else { degradeValueAssignment(fieldInfo.field, method, object, value); } } else if (fieldInfo.fieldClass == AtomicBoolean.class) { AtomicBoolean atomic = (AtomicBoolean) method.invoke(object); if (atomic != null) { atomic.set(((AtomicBoolean) value).get()); } else { degradeValueAssignment(fieldInfo.field, method, object, value); } } else if (Map.class.isAssignableFrom(method.getReturnType())) { Map map = null; try { map = (Map) method.invoke(object); } catch (InvocationTargetException e) { degradeValueAssignment(fieldInfo.field, method, object, value); return; } if (map != null) { if (map == Collections.emptyMap()) { return; } if (map.isEmpty() && ((Map) value).isEmpty()) { return; } String mapClassName = map.getClass().getName(); if (mapClassName.equals("java.util.ImmutableCollections$Map1") || mapClassName.equals("java.util.ImmutableCollections$MapN") || mapClassName.startsWith("java.util.Collections$Unmodifiable")) { // skip return; } if (map.getClass().getName().equals("kotlin.collections.EmptyMap")) { degradeValueAssignment(fieldInfo.field, method, object, value); return; } map.putAll((Map) value); } else if (value != null) { degradeValueAssignment(fieldInfo.field, method, object, value); } } else { Collection collection = null; try { collection = (Collection) method.invoke(object); } catch (InvocationTargetException e) { degradeValueAssignment(fieldInfo.field, method, object, value); return; } if (collection != null && value != null) { String collectionClassName = collection.getClass().getName(); if (collection == Collections.emptySet() || collection == Collections.emptyList() || collectionClassName == "java.util.ImmutableCollections$ListN" || collectionClassName == "java.util.ImmutableCollections$List12" || collectionClassName.startsWith("java.util.Collections$Unmodifiable")) { // skip return; } if (!collection.isEmpty()) { collection.clear(); } else if (((Collection) value).isEmpty()) { return; //skip } if (collectionClassName.equals("kotlin.collections.EmptyList") || collectionClassName.equals("kotlin.collections.EmptySet")) { degradeValueAssignment(fieldInfo.field, method, object, value); return; } collection.addAll((Collection) value); } else if (collection == null && value != null) { degradeValueAssignment(fieldInfo.field, method, object, 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, " + clazz.getName() + "#" + fieldInfo.name, e); } } /** * kotlin代理类property的get方法会抛未初始化异常,用set方法直接赋值 */ private static boolean degradeValueAssignment( Field field, Method getMethod, Object object, Object value ) throws InvocationTargetException, IllegalAccessException { if (setFieldValue(field, object, value)) { return true; } try { Method setMethod = object .getClass() .getDeclaredMethod("set" + getMethod.getName().substring(3), getMethod.getReturnType()); setMethod.invoke(object, value); return true; } catch (InvocationTargetException ignored) { } catch (NoSuchMethodException ignored) { } catch (IllegalAccessException ignored) { } return false; } private static boolean setFieldValue(Field field, Object object, Object value) throws IllegalAccessException { if (field != null && !Modifier.isFinal(field.getModifiers())) { field.set(object, value); return true; } return false; } public void setWrappedValue(String key, Object value) { throw new JSONException("TODO"); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/FieldTypeResolver.java ================================================ package com.alibaba.fastjson.parser.deserializer; import java.lang.reflect.Type; public interface FieldTypeResolver extends ParseProcess { Type resolve(Object object, String fieldName); } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/JSONPDeserializer.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/JavaBeanDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONValidator; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.parser.*; import com.alibaba.fastjson.parser.DefaultJSONParser.ResolveTask; import com.alibaba.fastjson.util.FieldInfo; import com.alibaba.fastjson.util.JavaBeanInfo; import com.alibaba.fastjson.util.TypeUtils; 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 static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_hashcode; public class JavaBeanDeserializer implements ObjectDeserializer { private final FieldDeserializer[] fieldDeserializers; protected final FieldDeserializer[] sortedFieldDeserializers; protected final Class clazz; public final JavaBeanInfo beanInfo; private ConcurrentMap extraFieldDeserializers; private final Map alterNameFieldDeserializers; private Map fieldDeserializerMap; private transient long[] smartMatchHashArray; private transient short[] smartMatchHashArrayMapping; private transient long[] hashArray; private transient short[] hashArrayMapping; private final ParserConfig.AutoTypeCheckHandler autoTypeCheckHandler; public JavaBeanDeserializer(ParserConfig config, Class clazz) { this(config, clazz, clazz); } public JavaBeanDeserializer(ParserConfig config, Class clazz, Type type){ this(config // , JavaBeanInfo.build(clazz, type, config.propertyNamingStrategy, config.fieldBased, config.compatibleWithJavaBean, config.isJacksonCompatible()) ); } public JavaBeanDeserializer(ParserConfig config, JavaBeanInfo beanInfo){ this.clazz = beanInfo.clazz; this.beanInfo = beanInfo; ParserConfig.AutoTypeCheckHandler autoTypeCheckHandler = null; if (beanInfo.jsonType != null && beanInfo.jsonType.autoTypeCheckHandler() != ParserConfig.AutoTypeCheckHandler.class) { try { autoTypeCheckHandler = beanInfo.jsonType.autoTypeCheckHandler().newInstance(); } catch (Exception e) { // } } this.autoTypeCheckHandler = autoTypeCheckHandler; 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); sortedFieldDeserializers[i] = fieldDeserializer; if (size > 128) { if (fieldDeserializerMap == null) { fieldDeserializerMap = new HashMap(); } fieldDeserializerMap.put(fieldInfo.name, fieldDeserializer); } for (String name : fieldInfo.alternateNames) { if (alterNameFieldDeserializers == null) { alterNameFieldDeserializers = new HashMap(); } alterNameFieldDeserializers.put(name, fieldDeserializer); } } this.alterNameFieldDeserializers = alterNameFieldDeserializers; 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; } } public FieldDeserializer getFieldDeserializer(String key) { return getFieldDeserializer(key, null); } public FieldDeserializer getFieldDeserializer(String key, int[] setFlags) { if (key == null) { return null; } if (fieldDeserializerMap != null) { FieldDeserializer fieldDeserializer = fieldDeserializerMap.get(key); if (fieldDeserializer != null) { return fieldDeserializer; } } 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 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; } 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; } int flagIndex = i / 32; return flagIndex < setFlags.length && (setFlags[flagIndex] & (1 << i % 32)) != 0; } 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; } } if (beanInfo.defaultConstructor == null && beanInfo.factoryMethod == null) { return null; } if (beanInfo.factoryMethod != null && beanInfo.defaultConstructorParameterSize > 0) { return null; } 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."); } final String typeName; if (type instanceof Class) { typeName = ((Class) type).getName(); } else { throw new JSONException("can't create non-static inner class instance."); } final int lastIndex = typeName.lastIndexOf('$'); String parentClassName = typeName.substring(0, lastIndex); Object ctxObj = context.object; String parentName = ctxObj.getClass().getName(); 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; } } else { param = ctxObj; } if (param == null || param instanceof Collection && ((Collection)param).isEmpty()) { 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); } 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); } } } } return object; } public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { return deserialze(parser, type, fieldName, 0); } public T deserialze(DefaultJSONParser parser, Type type, Object fieldName, int features) { return deserialze(parser, type, fieldName, null, features, 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"); } String typeName = null; if ((typeName = lexer.scanTypeName(parser.symbolTable)) != null) { ObjectDeserializer deserializer = getSeeAlso(parser.getConfig(), this.beanInfo, typeName); Class userType = null; if (deserializer == null) { Class expectClass = TypeUtils.getClass(type); userType = parser.getConfig().checkAutoType(typeName, expectClass, lexer.getFeatures()); deserializer = parser.getConfig().getDeserializer(userType); } if (deserializer instanceof JavaBeanDeserializer) { return ((JavaBeanDeserializer) deserializer).deserialzeArrayMapping(parser, type, fieldName, object); } } object = createInstance(parser, type); 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 (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", "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(); int token = lexer.token(); if (token == JSONToken.NULL) { lexer.nextToken(JSONToken.COMMA); return null; } ParseContext context = parser.getContext(); if (object != null && context != null) { context = context.parent; } ParseContext childContext = null; 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 } } } } } if (token == JSONToken.LBRACKET && lexer.getCurrent() == ']') { lexer.next(); lexer.nextToken(); return null; } if (beanInfo.factoryMethod != null && beanInfo.fields.length == 1) { try { FieldInfo field = beanInfo.fields[0]; if (field.fieldClass == Integer.class) { if (token == JSONToken.LITERAL_INT) { int intValue = lexer.intValue(); lexer.nextToken(); return (T) createFactoryInstance(config, intValue); } } else if (field.fieldClass == String.class) { if (token == JSONToken.LITERAL_STRING) { String stringVal = lexer.stringVal(); lexer.nextToken(); return (T) createFactoryInstance(config, stringVal); } } } catch (Exception ex) { throw new JSONException(ex.getMessage(), ex); } } StringBuilder buf = (new StringBuilder()) // .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, notMatchCount = 0;; fieldIndex++) { String key = null; FieldDeserializer fieldDeserializer = null; FieldInfo fieldInfo = null; Class fieldClass = null; JSONField fieldAnnotation = null; boolean customDeserializer = false; if (fieldIndex < sortedFieldDeserializers.length && notMatchCount < 16) { fieldDeserializer = sortedFieldDeserializers[fieldIndex]; fieldInfo = fieldDeserializer.fieldInfo; fieldClass = fieldInfo.fieldClass; fieldAnnotation = fieldInfo.getAnnotation(); if (fieldAnnotation != null && fieldDeserializer instanceof DefaultFieldDeserializer) { customDeserializer = ((DefaultFieldDeserializer) fieldDeserializer).customDeserilizer; } } boolean matchField = false; boolean valueParsed = false; Object fieldValue = null; if (fieldDeserializer != null) { char[] name_chars = fieldInfo.name_chars; if (customDeserializer && lexer.matchField(name_chars)) { matchField = true; } else if (fieldClass == int.class || fieldClass == Integer.class) { int intVal = lexer.scanFieldInt(name_chars); if (intVal == 0 && lexer.matchStat == JSONLexer.VALUE_NULL) { fieldValue = null; } else { fieldValue = intVal; } if (lexer.matchStat > 0) { matchField = true; valueParsed = true; } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { notMatchCount++; continue; } } else if (fieldClass == long.class || fieldClass == Long.class) { long longVal = lexer.scanFieldLong(name_chars); if (longVal == 0 && lexer.matchStat == JSONLexer.VALUE_NULL) { fieldValue = null; } else { fieldValue = longVal; } if (lexer.matchStat > 0) { matchField = true; valueParsed = true; } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { notMatchCount++; 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) { notMatchCount++; 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) { notMatchCount++; continue; } } else if (fieldClass == BigDecimal.class) { fieldValue = lexer.scanFieldDecimal(name_chars); if (lexer.matchStat > 0) { matchField = true; valueParsed = true; } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { notMatchCount++; 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) { notMatchCount++; continue; } } else if (fieldClass == boolean.class || fieldClass == Boolean.class) { boolean booleanVal = lexer.scanFieldBoolean(name_chars); if (lexer.matchStat == JSONLexer.VALUE_NULL) { fieldValue = null; } else { fieldValue = booleanVal; } if (lexer.matchStat > 0) { matchField = true; valueParsed = true; } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { notMatchCount++; continue; } } else if (fieldClass == float.class || fieldClass == Float.class) { float floatVal = lexer.scanFieldFloat(name_chars); if (floatVal == 0 && lexer.matchStat == JSONLexer.VALUE_NULL) { fieldValue = null; } else { fieldValue = floatVal; } if (lexer.matchStat > 0) { matchField = true; valueParsed = true; } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { notMatchCount++; continue; } } else if (fieldClass == double.class || fieldClass == Double.class) { double doubleVal = lexer.scanFieldDouble(name_chars); if (doubleVal == 0 && lexer.matchStat == JSONLexer.VALUE_NULL) { fieldValue = null; } else { fieldValue = doubleVal; } if (lexer.matchStat > 0) { matchField = true; valueParsed = true; } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { notMatchCount++; continue; } } else if (fieldClass.isEnum() // && parser.getConfig().getDeserializer(fieldClass) instanceof EnumDeserializer && (fieldAnnotation == null || fieldAnnotation.deserializeUsing() == Void.class) ) { if (fieldDeserializer instanceof DefaultFieldDeserializer) { ObjectDeserializer fieldValueDeserilizer = ((DefaultFieldDeserializer) fieldDeserializer).fieldValueDeserilizer; fieldValue = this.scanEnum(lexer, name_chars, fieldValueDeserilizer); if (lexer.matchStat > 0) { matchField = true; valueParsed = true; } else if (lexer.matchStat == JSONLexer.NOT_MATCH_NAME) { notMatchCount++; 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) { notMatchCount++; 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) { notMatchCount++; 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) { notMatchCount++; 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); if (autoTypeCheckHandler != null) { userType = autoTypeCheckHandler.handler(typeName, expectClass, lexer.getFeatures()); } if (userType == null) { if (typeName.equals("java.util.HashMap") || typeName.equals("java.util.LinkedHashMap")) { if (lexer.token() == JSONToken.RBRACE) { lexer.nextToken(); break; } continue; } } if (userType == null) { 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); if (typeKeyFieldDeser != null) { 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) { fieldDeserializer.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 // ) { fieldDeserializer.setValue(object, fieldValue); } } else { if (fieldClass == String.class && ((features & Feature.TrimStringFieldValue.mask) != 0 || (beanInfo.parserFeatures & Feature.TrimStringFieldValue.mask) != 0 || (fieldInfo.parserFeatures & Feature.TrimStringFieldValue.mask) != 0)) { fieldValue = ((String) fieldValue).trim(); } fieldDeserializer.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 == null ? new HashMap(this.fieldDeserializers.length) : 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 (lexer.token() == JSONToken.RBRACE) { lexer.nextToken(JSONToken.COMMA); break; } if (lexer.token() == JSONToken.IDENTIFIER || lexer.token() == JSONToken.ERROR) { throw new JSONException("syntax error, unexpect token " + JSONToken.name(lexer.token())); } } if (object == null) { if (fieldValues == null) { object = createInstance(parser, type); if (childContext == null) { childContext = parser.setContext(context, object, fieldName); } return (T) object; } 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]; 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 = ""; } } else { if (beanInfo.creatorConstructorParameterTypes != null && i < beanInfo.creatorConstructorParameterTypes.length) { Type paramType = beanInfo.creatorConstructorParameterTypes[i]; if (paramType instanceof Class) { Class paramClass = (Class) paramType; if (!paramClass.isInstance(param)) { if (param instanceof List) { List list = (List) param; if (list.size() == 1) { Object first = list.get(0); if (paramClass.isInstance(first)) { param = list.get(0); } } } } } } } 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 (beanInfo.creatorConstructor != null) { boolean hasNull = false; if (beanInfo.kotlin) { for (int i = 0; i < params.length; i++) { if (params[i] == null && beanInfo.fields != null && i < beanInfo.fields.length) { FieldInfo fieldInfo = beanInfo.fields[i]; if (fieldInfo.fieldClass == String.class) { hasNull = true; } break; } } } try { if (hasNull && beanInfo.kotlinDefaultConstructor != null) { object = beanInfo.kotlinDefaultConstructor.newInstance(new Object[0]); for (int i = 0; i < params.length; i++) { final Object param = params[i]; if (param != null && beanInfo.fields != null && i < beanInfo.fields.length) { FieldInfo fieldInfo = beanInfo.fields[i]; fieldInfo.set(object, param); } } } else { 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); } } if (childContext != null) { childContext.object = object; } } Method buildMethod = beanInfo.buildMethod; if (buildMethod == null) { return (T) object; } 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; } if (enumDeserializer == null) { lexer.matchStat = JSONLexer.NOT_MATCH; return null; } long enumNameHashCode = lexer.scanEnumSymbol(name_chars); if (lexer.matchStat > 0) { Enum e = enumDeserializer.getEnumByHashCode(enumNameHashCode); if (e == null) { if (enumNameHashCode == fnv1a_64_magic_hashcode) { return null; } if (lexer.isEnabled(Feature.ErrorOnEnumNotMatch)) { throw new JSONException("not match enum value, " + enumDeserializer.enumClass); } } return e; } 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; final int initStringFieldAsEmpty = Feature.InitStringFieldAsEmpty.mask; FieldDeserializer fieldDeserializer; if (lexer.isEnabled(disableFieldSmartMatchMask) || (this.beanInfo.parserFeatures & disableFieldSmartMatchMask) != 0) { fieldDeserializer = getFieldDeserializer(key); } else if (lexer.isEnabled(initStringFieldAsEmpty) || (this.beanInfo.parserFeatures & initStringFieldAsEmpty) != 0) { fieldDeserializer = smartMatch(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; } JSONField jsonField = TypeUtils.getAnnotation(field, JSONField.class); if (jsonField != null) { String alteredFieldName = jsonField.name(); if (!"".equals(alteredFieldName)) { fieldName = alteredFieldName; } } extraFieldDeserializers.put(fieldName, field); } } this.extraFieldDeserializers = extraFieldDeserializers; } 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); } } } if (fieldDeserializer == null) { if (!lexer.isEnabled(Feature.IgnoreNotMatch)) { throw new JSONException("setter not found, class " + clazz.getName() + ", property " + key); } int fieldIndex = -1; for (int i = 0; i < this.sortedFieldDeserializers.length; i++) { FieldDeserializer fieldDeser = this.sortedFieldDeserializers[i]; 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); fieldIndex = i; } 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); } fieldIndex = i; } } 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); } fieldIndex = i; } } } if (fieldIndex != -1) { if (setFlags != null) { int flagIndex = fieldIndex / 32; int bitIndex = fieldIndex % 32; setFlags[flagIndex] |= (1 << bitIndex); } 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, objectType, fieldValues); if (setFlags != null) { int flagIndex = fieldIndex / 32; int bitIndex = fieldIndex % 32; setFlags[flagIndex] |= (1 << bitIndex); } 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) { if (this.smartMatchHashArray == null) { long[] hashArray = new long[sortedFieldDeserializers.length]; for (int i = 0; i < sortedFieldDeserializers.length; i++) { hashArray[i] = sortedFieldDeserializers[i].fieldInfo.nameHashCode; } Arrays.sort(hashArray); this.smartMatchHashArray = hashArray; } // smartMatchHashArrayMapping long smartKeyHash = TypeUtils.fnv1a_64_lower(key); int pos = Arrays.binarySearch(smartMatchHashArray, smartKeyHash); if (pos < 0) { long smartKeyHash1 = TypeUtils.fnv1a_64_extract(key); pos = Arrays.binarySearch(smartMatchHashArray, smartKeyHash1); } boolean is = false; if (pos < 0 && (is = key.startsWith("is"))) { smartKeyHash = TypeUtils.fnv1a_64_extract(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, sortedFieldDeserializers[i].fieldInfo.nameHashCode); 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; } private Object createFactoryInstance(ParserConfig config, Object value) // throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { return beanInfo.factoryMethod.invoke(null, value); } 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; Field field = fieldDeser.fieldInfo.field; Type paramType = fieldInfo.fieldType; Class fieldClass = fieldInfo.fieldClass; JSONField fieldAnnation = fieldInfo.getAnnotation(); if (fieldInfo.declaringClass != null && ((!fieldClass.isInstance(value)) || (fieldAnnation != null && fieldAnnation.deserializeUsing() != Void.class)) ) { String input; if (value instanceof String && JSONValidator.from(((String) value)) .validate()) { input = (String) value; } else { input = JSON.toJSONString(value); } DefaultJSONParser parser = new DefaultJSONParser(input); fieldDeser.parseField(parser, object, paramType, null); continue; } if (field != null && fieldInfo.method == null) { Class fieldType = field.getType(); if (fieldType == boolean.class) { if (value == Boolean.FALSE) { field.setBoolean(object, false); continue; } if (value == Boolean.TRUE) { field.setBoolean(object, true); continue; } } else if (fieldType == int.class) { if (value instanceof Number) { field.setInt(object, ((Number) value).intValue()); continue; } } else if (fieldType == long.class) { if (value instanceof Number) { field.setLong(object, ((Number) value).longValue()); continue; } } else if (fieldType == float.class) { if (value instanceof Number) { field.setFloat(object, ((Number) value).floatValue()); continue; } else if (value instanceof String) { String strVal = (String) value; float floatValue; if (strVal.length() <= 10) { floatValue = TypeUtils.parseFloat(strVal); } else { floatValue = Float.parseFloat(strVal); } field.setFloat(object, floatValue); continue; } } else if (fieldType == double.class) { if (value instanceof Number) { field.setDouble(object, ((Number) value).doubleValue()); continue; } else if (value instanceof String) { String strVal = (String) value; double doubleValue; if (strVal.length() <= 10) { doubleValue = TypeUtils.parseDouble(strVal); } else { doubleValue = Double.parseDouble(strVal); } field.setDouble(object, doubleValue); continue; } } else if (value != null && paramType == value.getClass()) { field.set(object, value); continue; } } String format = fieldInfo.format; if (format != null && paramType == Date.class) { value = TypeUtils.castToDate(value, format); } else if (format != null && (paramType instanceof Class) && (((Class) paramType).getName().equals("java.time.LocalDateTime"))) { value = Jdk8DateCodec.castToLocalDateTime(value, format); } else { if (paramType instanceof ParameterizedType) { value = TypeUtils.cast(value, (ParameterizedType) paramType, config); } 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) { boolean hasNull = false; if (beanInfo.kotlin) { for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { if (beanInfo.fields != null && i < beanInfo.fields.length) { FieldInfo fieldInfo = beanInfo.fields[i]; if (fieldInfo.fieldClass == String.class) { hasNull = true; } } } else if (param.getClass() != beanInfo.fields[i].fieldClass){ params[i] = TypeUtils.cast(param, beanInfo.fields[i].fieldClass, config); } } } if (hasNull && beanInfo.kotlinDefaultConstructor != null) { try { object = beanInfo.kotlinDefaultConstructor.newInstance(); for (int i = 0; i < params.length; i++) { final Object param = params[i]; if (param != null && beanInfo.fields != null && i < beanInfo.fields.length) { FieldInfo fieldInfo = beanInfo.fields[i]; fieldInfo.set(object, param); } } } catch (Exception e) { throw new JSONException("create instance error, " + beanInfo.creatorConstructor.toGenericString(), e); } } else { 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 static 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/JavaObjectDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; import java.io.Closeable; 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.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.util.TypeUtils; public class JavaObjectDeserializer implements ObjectDeserializer { public final static JavaObjectDeserializer instance = new JavaObjectDeserializer(); @SuppressWarnings("unchecked") 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 = TypeUtils.getRawClass(componentType); Object[] array = (Object[]) Array.newInstance(componentClass, list.size()); list.toArray(array); return (T) array; } if (type instanceof Class && type != Object.class && type != Serializable.class && type != Cloneable.class && type != Closeable.class && type != Comparable.class) { return (T) parser.parseObject(type); } return (T) parser.parse(fieldName); } public int getFastMatchToken() { return JSONToken.LBRACE; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/Jdk8DateCodec.java ================================================ 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.chrono.ChronoZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONLexer; import com.alibaba.fastjson.parser.JSONScanner; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.serializer.*; import com.alibaba.fastjson.util.TypeUtils; 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 defaultFormatter_23 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); 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 String formatter_iso8601_pattern_23 = "yyyy-MM-dd'T'HH:mm:ss.SSS"; private final static String formatter_iso8601_pattern_29 = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS"; 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 localTime; if (text.length() == 23) { LocalDateTime localDateTime = LocalDateTime.parse(text); localTime = LocalTime.of(localDateTime.getHour(), localDateTime.getMinute(), localDateTime.getSecond(), localDateTime.getNano()); } else { boolean digit = true; for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (ch < '0' || ch > '9') { digit = false; break; } } if (digit && text.length() > 8 && text.length() < 19) { long epochMillis = Long.parseLong(text); localTime = LocalDateTime .ofInstant( Instant.ofEpochMilli(epochMillis), JSON.defaultTimeZone.toZoneId()) .toLocalTime(); } else { localTime = LocalTime.parse(text); } } return (T) localTime; } else if (type == ZonedDateTime.class) { if (formatter == defaultFormatter) { formatter = ISO_FIXED_FORMAT; } if (formatter == null) { if (text.length() <= 19) { JSONScanner s = new JSONScanner(text); TimeZone timeZone = parser.lexer.getTimeZone(); s.setTimeZone(timeZone); boolean match = s.scanISO8601DateIfMatch(false); if (match) { Date date = s.getCalendar().getTime(); return (T) ZonedDateTime.ofInstant(date.toInstant(), timeZone.toZoneId()); } } } 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) { boolean digit = true; for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (ch < '0' || ch > '9') { digit = false; break; } } if (digit && text.length() > 8 && text.length() < 19) { long epochMillis = Long.parseLong(text); return (T) Instant.ofEpochMilli(epochMillis); } Instant instant = Instant.parse(text); return (T) instant; } } else if (lexer.token() == JSONToken.LITERAL_INT) { long millis = lexer.longValue(); lexer.nextToken(); if ("unixtime".equals(format)) { millis *= 1000; } else if ("yyyyMMddHHmmss".equals(format)) { int yyyy = (int) (millis / 10000000000L); int MM = (int) ((millis / 100000000L) % 100); int dd = (int) ((millis / 1000000L) % 100); int HH = (int) ((millis / 10000L) % 100); int mm = (int) ((millis / 100L) % 100); int ss = (int) (millis % 100); if (type == LocalDateTime.class) { return (T) LocalDateTime.of(yyyy, MM, dd, HH, mm, ss); } } 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(); } if (type == ZonedDateTime.class) { return (T) ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis), JSON.defaultTimeZone.toZoneId()); } if (type == Instant.class) { return (T) Instant.ofEpochMilli(millis); } throw new UnsupportedOperationException(); } else if (lexer.token() == JSONToken.LBRACE) { JSONObject object = parser.parseObject(); if (type == Instant.class) { Object epochSecond = object.get("epochSecond"); Object nano = object.get("nano"); if (epochSecond instanceof Number && nano instanceof Number) { return (T) Instant.ofEpochSecond( TypeUtils.longExtractValue((Number) epochSecond) , TypeUtils.longExtractValue((Number) nano)); } if (epochSecond instanceof Number) { return (T) Instant.ofEpochSecond( TypeUtils.longExtractValue((Number) epochSecond)); } } else if (type == Duration.class) { Long seconds = object.getLong("seconds"); if (seconds != null) { long nanos = object.getLongValue("nano"); return (T) Duration.ofSeconds(seconds, nanos); } } } 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 == '/') { // 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; } } } } else if (text.length() == 23) { 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); char c19 = text.charAt(19); if (c13 == ':' && c16 == ':' && c4 == '-' && c7 == '-' && c10 == ' ' && c19 == '.' ) { formatter = defaultFormatter_23; } } 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; } } } if (formatter == null) { JSONScanner dateScanner = new JSONScanner(text); if (dateScanner.scanISO8601DateIfMatch(false)) { Instant instant = dateScanner.getCalendar().toInstant(); return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); } boolean digit = true; for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (ch < '0' || ch > '9') { digit = false; break; } } if (digit && text.length() > 8 && text.length() < 19) { long epochMillis = Long.parseLong(text); return LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMillis), JSON.defaultTimeZone.toZoneId()); } } 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; } } boolean digit = true; for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (ch < '0' || ch > '9') { digit = false; break; } } if (digit && text.length() > 8 && text.length() < 19) { long epochMillis = Long.parseLong(text); return LocalDateTime .ofInstant( Instant.ofEpochMilli(epochMillis), JSON.defaultTimeZone.toZoneId()) .toLocalDate(); } } 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 == '/') { // 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; } } boolean digit = true; for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (ch < '0' || ch > '9') { digit = false; break; } } if (digit && text.length() > 8 && text.length() < 19) { long epochMillis = Long.parseLong(text); return ZonedDateTime.ofInstant(Instant.ofEpochMilli(epochMillis), JSON.defaultTimeZone.toZoneId()); } } 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) { if ((features & mask) != 0 || serializer.isEnabled(SerializerFeature.UseISO8601DateFormat)) { format = formatter_iso8601_pattern; } else if (serializer.isEnabled(SerializerFeature.WriteDateUseDateFormat)) { if (serializer.getFastJsonConfigDateFormatPattern() != null && serializer.getFastJsonConfigDateFormatPattern().length() > 0){ format = serializer.getFastJsonConfigDateFormatPattern(); }else{ format = JSON.DEFFAULT_DATE_FORMAT; } } else { int nano = dateTime.getNano(); if (nano == 0) { format = formatter_iso8601_pattern; } else if (nano % 1000000 == 0) { format = formatter_iso8601_pattern_23; } else { format = formatter_iso8601_pattern_29; } } } if (format != null) { write(out, dateTime, 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 ("unixtime".equals(format)) { Instant instant = null; if (object instanceof ChronoZonedDateTime) { long seconds = ((ChronoZonedDateTime) object).toEpochSecond(); out.writeInt((int) seconds); return; } if (object instanceof LocalDateTime) { long seconds = ((LocalDateTime) object).atZone(JSON.defaultTimeZone.toZoneId()).toEpochSecond(); out.writeInt((int) seconds); return; } } if ("millis".equals(format)) { Instant instant = null; if (object instanceof ChronoZonedDateTime) { instant = ((ChronoZonedDateTime) object).toInstant(); } else if (object instanceof LocalDateTime) { instant = ((LocalDateTime) object).atZone(JSON.defaultTimeZone.toZoneId()).toInstant(); } if (instant != null) { long millis = instant.toEpochMilli(); out.writeLong(millis); return; } } if (format == formatter_iso8601_pattern) { formatter = formatter_iso8601; } else { formatter = DateTimeFormatter.ofPattern(format); } String text = formatter.format((TemporalAccessor) object); out.writeString(text); } public static Object castToLocalDateTime(Object value, String format) { if (value == null) { return null; } if (format == null) { format = "yyyy-MM-dd HH:mm:ss"; } DateTimeFormatter df = DateTimeFormatter.ofPattern(format); return LocalDateTime.parse(value.toString(), df); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/MapDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; 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; public class MapDeserializer extends ContextObjectDeserializer implements ObjectDeserializer { public static MapDeserializer instance = new MapDeserializer(); @SuppressWarnings("unchecked") public T deserialze(DefaultJSONParser parser, Type type, Object fieldName, String format, int features) { 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; } boolean unmodifiableMap = type instanceof Class && "java.util.Collections$UnmodifiableMap".equals(((Class) type).getName()); Map map = (lexer.getFeatures() & Feature.OrderedField.mask) != 0 ? createMap(type, lexer.getFeatures()) : createMap(type); ParseContext context = parser.getContext(); try { parser.setContext(context, map, fieldName); T t = (T) deserialze(parser, type, fieldName, map, features); if (unmodifiableMap) { t = (T) Collections.unmodifiableMap((Map) t); } return t; } finally { parser.setContext(context); } } protected Object deserialze(DefaultJSONParser parser, Type type, Object fieldName, Map map) { return deserialze(parser, type, fieldName, map, 0); } @SuppressWarnings({ "rawtypes", "unchecked" }) protected Object deserialze(DefaultJSONParser parser, Type type, Object fieldName, Map map, int features) { 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, features); } else { return parseMap(parser, map, keyType, valueType, fieldName); } } else { return parser.parseObject(map, fieldName); } } public static Map parseMap(DefaultJSONParser parser, Map map, Type valueType, Object fieldName) { return parseMap(parser, map, valueType, fieldName, 0); } @SuppressWarnings("rawtypes") public static Map parseMap(DefaultJSONParser parser, Map map, Type valueType, Object fieldName, int features) { JSONLexer lexer = parser.lexer; int token = lexer.token(); if (token != JSONToken.LBRACE) { if (token == JSONToken.LITERAL_STRING) { String stringVal = lexer.stringVal(); if (stringVal.length() == 0 || stringVal.equals("null")) { return null; } } 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) && !Feature.isEnabled(features, Feature.DisableSpecialKeyDetect) ) { String typeName = lexer.scanSymbol(parser.getSymbolTable(), '"'); final ParserConfig config = parser.getConfig(); Class clazz; if (typeName.equals("java.util.HashMap")) { clazz = java.util.HashMap.class; } else if (typeName.equals("java.util.LinkedHashMap")) { clazz = java.util.LinkedHashMap.class; } else if (config.isSafeMode()) { clazz = java.util.HashMap.class; } else { try { clazz = config.checkAutoType(typeName, null, lexer.getFeatures()); } catch (JSONException ex) { // skip clazz = java.util.HashMap.class; } } 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; if (lexer.token() == JSONToken.LITERAL_STRING && keyDeserializer instanceof JavaBeanDeserializer ) { String keyStrValue = lexer.stringVal(); lexer.nextToken(); DefaultJSONParser keyParser = new DefaultJSONParser(keyStrValue, parser.getConfig(), parser.getLexer().getFeatures()); keyParser.setDateFormat(parser.getDateFomartPattern()); key = keyDeserializer.deserialze(keyParser, keyType, null); } else { 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; } public Map createMap(Type type) { return createMap(type, JSON.DEFAULT_GENERATE_FEATURE); } @SuppressWarnings({ "unchecked", "rawtypes" }) public Map createMap(Type type, int featrues) { 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) { return (featrues & Feature.OrderedField.mask) != 0 ? new LinkedHashMap() : new HashMap(); } if (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, featrues); } Class clazz = (Class) type; if (clazz.isInterface()) { throw new JSONException("unsupport type " + type); } if ("java.util.Collections$UnmodifiableMap".equals(clazz.getName())) { return new HashMap(); } try { return (Map) clazz.newInstance(); } catch (Exception e) { throw new JSONException("unsupport type " + type, e); } } public int getFastMatchToken() { return JSONToken.LBRACE; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/NumberDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; 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.Feature; import com.alibaba.fastjson.parser.JSONLexer; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.util.TypeUtils; public class NumberDeserializer implements ObjectDeserializer { public final static NumberDeserializer instance = new NumberDeserializer(); @SuppressWarnings("unchecked") 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) 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)); } if (clazz == short.class || clazz == Short.class) { BigDecimal val = lexer.decimalValue(); lexer.nextToken(JSONToken.COMMA); short shortValue = TypeUtils.shortValue(val); return (T) Short.valueOf(shortValue); } if (clazz == byte.class || clazz == Byte.class) { BigDecimal val = lexer.decimalValue(); lexer.nextToken(JSONToken.COMMA); byte byteValue = TypeUtils.byteValue(val); return (T) Byte.valueOf(byteValue); } BigDecimal val = lexer.decimalValue(); lexer.nextToken(JSONToken.COMMA); if (lexer.isEnabled(Feature.UseBigDecimal)) { return (T) val; } else { return (T) Double.valueOf(val.doubleValue()); } } 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); } public int getFastMatchToken() { return JSONToken.LITERAL_INT; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/ObjectDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; import java.lang.reflect.Type; 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 { /** * 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(); } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/OptionalCodec.java ================================================ 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()); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/ParseProcess.java ================================================ package com.alibaba.fastjson.parser.deserializer; public interface ParseProcess { } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/PropertyProcessable.java ================================================ 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); } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/PropertyProcessableDeserializer.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/ResolveFieldDeserializer.java ================================================ 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) { } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/SqlDateDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; import java.lang.reflect.Type; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; 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.util.TypeUtils; 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") 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 BigDecimal) { val = (T) new java.sql.Date(TypeUtils.longValue((BigDecimal) val)); } else if (val instanceof Number) { val = (T) new java.sql.Date(((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); 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); } 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 BigDecimal) { return (T) new java.sql.Timestamp(TypeUtils.longValue((BigDecimal) val)); } 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 (strVal.length() > 19 && strVal.charAt(4) == '-' && strVal.charAt(7) == '-' && strVal.charAt(10) == ' ' && strVal.charAt(13) == ':' && strVal.charAt(16) == ':' && strVal.charAt(19) == '.') { String dateFomartPattern = parser.getDateFomartPattern(); if (dateFomartPattern.length() != strVal.length() && dateFomartPattern == JSON.DEFFAULT_DATE_FORMAT) { return (T) java.sql.Timestamp.valueOf(strVal); } } if (dateLexer.scanISO8601DateIfMatch(false)) { 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/StackTraceElementDeserializer.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/ThrowableDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; import java.lang.reflect.Constructor; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; 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.util.FieldInfo; import com.alibaba.fastjson.util.TypeUtils; public class ThrowableDeserializer extends JavaBeanDeserializer { public ThrowableDeserializer(ParserConfig mapping, Class clazz){ super(mapping, clazz, clazz); } @SuppressWarnings("unchecked") 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) { FieldInfo fieldInfo = fieldDeserializer.fieldInfo; if (!fieldInfo.fieldClass.isInstance(value)) { value = TypeUtils.cast(value, fieldInfo.fieldType, parser.getConfig()); } 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() { return JSONToken.LBRACE; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/parser/deserializer/TimeDeserializer.java ================================================ package com.alibaba.fastjson.parser.deserializer; 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.JSONScanner; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.util.TypeUtils; 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 BigDecimal) { return (T) new java.sql.Time(TypeUtils.longValue((BigDecimal) 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ASMSerializerFactory.java ================================================ package com.alibaba.fastjson.serializer; 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.io.Serializable; import java.lang.reflect.*; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import static com.alibaba.fastjson.util.ASMUtils.desc; import static com.alibaba.fastjson.util.ASMUtils.type; public class ASMSerializerFactory implements Opcodes { protected final ASMClassLoader classLoader = new ASMClassLoader(); private final AtomicLong seed = new AtomicLong(); 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 { 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) { Integer i = variants.get(name); if (i == null) { variants.put(name, variantIndex++); } i = variants.get(name); return i.intValue(); } public int var(String name, int increment) { Integer i = variants.get(name); if (i == null) { variants.put(name, variantIndex); variantIndex += 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 JavaBeanSerializer createJavaBeanSerializer(SerializeBeanInfo beanInfo) throws Exception { Class clazz = beanInfo.beanType; if (clazz.isPrimitive()) { throw new JSONException("unsupportd class " + clazz.getName()); } 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; } ClassWriter cw = new ClassWriter(); 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 = new MethodWriter(cw, ACC_PUBLIC, "", "(" + desc(SerializeBeanInfo.class) + ")V", null, null); mw.visitVarInsn(ALOAD, 0); 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(4, 4); mw.visitEnd(); boolean DisableCircularReferenceDetect = false; if (jsonType != null) { for (SerializerFeature featrues : jsonType.serialzeFeatures()) { if (featrues == SerializerFeature.DisableCircularReferenceDetect) { DisableCircularReferenceDetect = true; break; } } } // 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"; } 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); mw.visitFieldInsn(GETFIELD, JSONSerializer, "out", SerializeWriter_desc); mw.visitVarInsn(ASTORE, context.var("out")); if ((!nativeSorted) // && !context.writeDirect) { if (jsonType == null || jsonType.alphabetic()) { Label _else = new Label(); mw.visitVarInsn(ALOAD, context.var("out")); mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isSortField", "()Z"); 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); 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(7, context.variantIndex + 2); mw.visitEnd(); } if (!nativeSorted) { // sortField support Context context = new Context(getters, beanInfo, classNameType, false, DisableCircularReferenceDetect); 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.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 generateWriteMethod(clazz, mw, unsortedGetters, context); mw.visitInsn(RETURN); 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 serializerClass = classLoader.defineClassPublic(classNameFull, code, 0, code.length); Constructor constructor = serializerClass.getConstructor(SerializeBeanInfo.class); Object instance = constructor.newInstance(beanInfo); return (JavaBeanSerializer) instance; } private void generateWriteAsArray(Class clazz, MethodVisitor mw, FieldInfo[] getters, Context context) throws Exception { 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.visitVarInsn(BIPUSH, ']'); mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); return; } 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; break; } } 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[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) { _float(clazz, mw, property, context); } else if (propertyClass == double.class) { _double(clazz, mw, property, context); } else if (propertyClass == boolean.class) { _int(clazz, mw, property, context, context.var("boolean"), 'Z'); } else if (propertyClass == char.class) { _int(clazz, mw, property, context, context.var("char"), 'C'); } else if (propertyClass == String.class) { _string(clazz, mw, property, context); } else if (propertyClass == BigDecimal.class) { _decimal(clazz, mw, property, context); } else if (List.class.isAssignableFrom(propertyClass)) { _list(clazz, mw, property, context); } else if (propertyClass.isEnum()) { _enum(clazz, mw, property, context); } else { _object(clazz, mw, property, context); } } if (!context.writeDirect) { _after(mw, context); } Label _else = new Label(); Label _end_if = new Label(); mw.visitVarInsn(ILOAD, context.var("seperator")); mw.visitIntInsn(BIPUSH, '{'); mw.visitJumpInsn(IF_ICMPNE, _else); mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(BIPUSH, '{'); mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); mw.visitLabel(_else); mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(BIPUSH, '}'); mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); mw.visitLabel(_end_if); mw.visitLabel(end); if (!context.nonContext) { mw.visitVarInsn(ALOAD, Context.serializer); mw.visitVarInsn(ALOAD, context.var("parent")); mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "setContext", "(" + SerialContext_desc + ")V"); } } private void _object(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { Label _end = new Label(); _nameApply(mw, property, context, _end); _get(mw, context, property); mw.visitVarInsn(ASTORE, context.var("object")); _filters(mw, property, context, _end); _writeObject(mw, property, context, _end); mw.visitLabel(_end); } 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(); _nameApply(mw, fieldInfo, context, _end); _get(mw, context, fieldInfo); mw.visitTypeInsn(CHECKCAST, "java/lang/Enum"); // cast mw.visitVarInsn(ASTORE, context.var("enum")); _filters(mw, fieldInfo, context, _end); mw.visitVarInsn(ALOAD, context.var("enum")); mw.visitJumpInsn(IFNONNULL, _not_null); _if_write_null(mw, fieldInfo, context); mw.visitJumpInsn(GOTO, _end_if); mw.visitLabel(_not_null); 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(); _nameApply(mw, property, context, end_); _get(mw, context, property); mw.visitVarInsn(ISTORE, var); _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, var); mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValue", "(CLjava/lang/String;" + type + ")V"); _seperator(mw, context); mw.visitLabel(end_); } private void _long(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { Label end_ = new Label(); _nameApply(mw, property, context, end_); _get(mw, context, property); 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", 2)); mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValue", "(CLjava/lang/String;J)V"); _seperator(mw, context); mw.visitLabel(end_); } private void _float(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { Label end_ = new Label(); _nameApply(mw, property, context, end_); _get(mw, context, property); 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, SerializeWriter, "writeFieldValue", "(CLjava/lang/String;F)V"); _seperator(mw, context); mw.visitLabel(end_); } private void _double(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { Label end_ = new Label(); _nameApply(mw, property, context, end_); _get(mw, context, property); mw.visitVarInsn(DSTORE, context.var("double", 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(DLOAD, context.var("double", 2)); mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValue", "(CLjava/lang/String;D)V"); _seperator(mw, context); 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) { Label end_ = new Label(); _nameApply(mw, property, context, end_); _get(mw, context, property); mw.visitVarInsn(ASTORE, context.var("decimal")); _filters(mw, property, context, end_); Label if_ = new Label(); Label else_ = new Label(); Label endIf_ = new Label(); mw.visitLabel(if_); // if (decimalValue == null) { mw.visitVarInsn(ALOAD, context.var("decimal")); mw.visitJumpInsn(IFNONNULL, else_); _if_write_null(mw, property, context); 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("decimal")); mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeFieldValue", "(CLjava/lang/String;Ljava/math/BigDecimal;)V"); _seperator(mw, context); mw.visitJumpInsn(GOTO, endIf_); mw.visitLabel(endIf_); mw.visitLabel(end_); } private void _string(Class clazz, MethodVisitor mw, FieldInfo property, Context context) { 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_); } _nameApply(mw, property, context, end_); _get(mw, context, property); mw.visitVarInsn(ASTORE, context.var("string")); _filters(mw, property, context, end_); Label else_ = new Label(); Label endIf_ = new Label(); // if (value == null) { mw.visitVarInsn(ALOAD, context.var("string")); mw.visitJumpInsn(IFNONNULL, else_); _if_write_null(mw, property, context); mw.visitJumpInsn(GOTO, endIf_); mw.visitLabel(else_); // else { out.writeFieldValue(seperator, fieldName, fieldValue) 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")); } 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); mw.visitLabel(endIf_); mw.visitLabel(end_); } private void _list(Class clazz, MethodVisitor mw, FieldInfo fieldInfo, Context context) { Type propertyType = fieldInfo.fieldType; Type elementType = TypeUtils.getCollectionItemType(propertyType); Class elementClass = null; if (elementType instanceof Class) { elementClass = (Class) elementType; } if (elementClass == Object.class // || elementClass == Serializable.class) { elementClass = null; } Label end_ = new Label(), else_ = new Label(), endIf_ = new Label(); _nameApply(mw, fieldInfo, context, end_); _get(mw, context, fieldInfo); mw.visitTypeInsn(CHECKCAST, "java/util/List"); // cast mw.visitVarInsn(ASTORE, context.var("list")); _filters(mw, fieldInfo, context, end_); mw.visitVarInsn(ALOAD, context.var("list")); mw.visitJumpInsn(IFNONNULL, else_); _if_write_null(mw, fieldInfo, context); mw.visitJumpInsn(GOTO, endIf_); mw.visitLabel(else_); // else { mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(ILOAD, context.var("seperator")); mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)V"); _writeFieldName(mw, context); // mw.visitVarInsn(ALOAD, context.var("list")); mw.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "size", "()I"); mw.visitVarInsn(ISTORE, context.var("size")); Label _else_3 = new Label(); Label _end_if_3 = new Label(); mw.visitVarInsn(ILOAD, context.var("size")); mw.visitInsn(ICONST_0); mw.visitJumpInsn(IF_ICMPNE, _else_3); mw.visitVarInsn(ALOAD, context.var("out")); mw.visitLdcInsn("[]"); 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, 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.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(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.visitVarInsn(ALOAD, Context.serializer); mw.visitMethodInsn(INVOKEVIRTUAL, JSONSerializer, "popContext", "()V"); } mw.visitLabel(_end_if_3); _seperator(mw, context); mw.visitLabel(endIf_); mw.visitLabel(end_); } private void _filters(MethodVisitor mw, FieldInfo property, Context context, Label _end) { 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); } _notWriteDefault(mw, property, context, _end); if (context.writeDirect) { return; } _apply(mw, property, context); mw.visitJumpInsn(IFEQ, _end); _processKey(mw, property, context); _processValue(mw, property, context, _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); } 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 = fieldInfo.getFormat(); Class fieldClass = fieldInfo.fieldClass; Label notNull_ = new Label(); // if (obj == null) if (context.writeDirect) { mw.visitVarInsn(ALOAD, context.var("object")); } else { mw.visitVarInsn(ALOAD, Context.processValue); } 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(notNull_); mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(ILOAD, context.var("seperator")); mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "write", "(I)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_); 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, 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 { 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) { Class propertyClass = property.fieldClass; 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, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); } else if (propertyClass == short.class) { mw.visitVarInsn(ILOAD, context.var("short")); 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, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); } else if (propertyClass == char.class) { mw.visitVarInsn(ILOAD, context.var("char")); mw.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;"); } else if (propertyClass == long.class) { 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, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); } else if (propertyClass == double.class) { 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, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"); } else if (propertyClass == BigDecimal.class) { mw.visitVarInsn(ALOAD, context.var("decimal")); } else if (propertyClass == String.class) { mw.visitVarInsn(ALOAD, context.var("string")); } else if (propertyClass.isEnum()) { mw.visitVarInsn(ALOAD, context.var("enum")); } else if (List.class.isAssignableFrom(propertyClass)) { mw.visitVarInsn(ALOAD, context.var("list")); } else { mw.visitVarInsn(ALOAD, context.var("object")); } mw.visitMethodInsn(INVOKEVIRTUAL, JavaBeanSerializer, "apply", "(L" + JSONSerializer + ";Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Z"); } private void _processValue(MethodVisitor mw, FieldInfo fieldInfo, Context context, Label _end) { Label processKeyElse_ = new Label(); Class fieldClass = fieldInfo.fieldClass; 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, "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, "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, "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, "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, "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, "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")); mw.visitVarInsn(ASTORE, Context.original); mw.visitVarInsn(ALOAD, Context.original); } else if (fieldClass == String.class) { mw.visitVarInsn(ALOAD, context.var("string")); mw.visitVarInsn(ASTORE, Context.original); mw.visitVarInsn(ALOAD, Context.original); } else if (fieldClass.isEnum()) { mw.visitVarInsn(ALOAD, context.var("enum")); 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.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.visitVarInsn(ALOAD, Context.original); mw.visitVarInsn(ALOAD, Context.processValue); mw.visitJumpInsn(IF_ACMPEQ, processKeyElse_); _writeObject(mw, fieldInfo, context, _end); mw.visitJumpInsn(GOTO, _end); mw.visitLabel(processKeyElse_); } private void _processKey(MethodVisitor mw, FieldInfo property, Context context) { Label _else_processKey = new Label(); mw.visitVarInsn(ILOAD, context.var("hasNameFilters")); mw.visitJumpInsn(IFEQ, _else_processKey); Class propertyClass = property.fieldClass; 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, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); } else if (propertyClass == short.class) { mw.visitVarInsn(ILOAD, context.var("short")); 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, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); } else if (propertyClass == char.class) { mw.visitVarInsn(ILOAD, context.var("char")); mw.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;"); } else if (propertyClass == long.class) { 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, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); } else if (propertyClass == double.class) { 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, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"); } else if (propertyClass == BigDecimal.class) { mw.visitVarInsn(ALOAD, context.var("decimal")); } else if (propertyClass == String.class) { mw.visitVarInsn(ALOAD, context.var("string")); } else if (propertyClass.isEnum()) { mw.visitVarInsn(ALOAD, context.var("enum")); } else if (List.class.isAssignableFrom(propertyClass)) { mw.visitVarInsn(ALOAD, context.var("list")); } else { mw.visitVarInsn(ALOAD, context.var("object")); } 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) { Class propertyClass = fieldInfo.fieldClass; Label _if = new Label(); Label _else = new Label(); Label _write_null = new Label(); Label _end_if = new Label(); mw.visitLabel(_if); JSONField annotation = fieldInfo.getAnnotation(); int features = 0; if (annotation != null) { features = SerializerFeature.of(annotation.serialzeFeatures()); } 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.WRITE_MAP_NULL_FEATURES; } if ((features & writeNullFeatures) == 0) { mw.visitVarInsn(ALOAD, context.var("out")); mw.visitLdcInsn(writeNullFeatures); mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "isEnabled", "(I)Z"); mw.visitJumpInsn(IFEQ, _else); } mw.visitLabel(_write_null); mw.visitVarInsn(ALOAD, context.var("out")); mw.visitVarInsn(ILOAD, context.var("seperator")); 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.visitLdcInsn(SerializerFeature.WriteNullStringAsEmpty.mask); } else if (Number.class.isAssignableFrom(propertyClass)) { mw.visitLdcInsn(SerializerFeature.WriteNullNumberAsZero.mask); } else if (propertyClass == Boolean.class) { mw.visitLdcInsn(SerializerFeature.WriteNullBooleanAsFalse.mask); } else if (Collection.class.isAssignableFrom(propertyClass) || propertyClass.isArray()) { mw.visitLdcInsn(SerializerFeature.WriteNullListAsEmpty.mask); } else { mw.visitLdcInsn(0); } mw.visitMethodInsn(INVOKEVIRTUAL, SerializeWriter, "writeNull", "(II)V"); // seperator = ','; _seperator(mw, context); mw.visitJumpInsn(GOTO, _end_if); mw.visitLabel(_else); 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/AdderSerializer.java ================================================ 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('}'); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/AfterFilter.java ================================================ 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) { JSONSerializer last = serializerLocal.get(); serializerLocal.set(serializer); seperatorLocal.set(seperator); writeAfter(object); serializerLocal.set(last); return seperatorLocal.get(); } protected final void writeKeyValue(String key, Object value) { JSONSerializer serializer = serializerLocal.get(); char seperator = seperatorLocal.get(); boolean ref = serializer.containsReference(value); serializer.writeKeyValue(seperator, key, value); if (!ref && serializer.references != null) { serializer.references.remove(value); } if (seperator != ',') { seperatorLocal.set(COMMA); } } public abstract void writeAfter(Object object); } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/AnnotationSerializer.java ================================================ package com.alibaba.fastjson.serializer; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; 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 { private static volatile Class sun_AnnotationType = null; private static volatile boolean sun_AnnotationType_error = false; private static volatile Method sun_AnnotationType_getInstance = null; private static volatile Method sun_AnnotationType_members = null; 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]; if (sun_AnnotationType == null && !sun_AnnotationType_error) { try { sun_AnnotationType = Class.forName("sun.reflect.annotation.AnnotationType"); } catch (Throwable ex) { sun_AnnotationType_error = true; throw new JSONException("not support Type Annotation.", ex); } } if (sun_AnnotationType == null) { throw new JSONException("not support Type Annotation."); } if (sun_AnnotationType_getInstance == null && !sun_AnnotationType_error) { try { sun_AnnotationType_getInstance = sun_AnnotationType.getMethod("getInstance", Class.class); } catch (Throwable ex) { sun_AnnotationType_error = true; throw new JSONException("not support Type Annotation.", ex); } } if (sun_AnnotationType_members == null && !sun_AnnotationType_error) { try { sun_AnnotationType_members = sun_AnnotationType.getMethod("members"); } catch (Throwable ex) { sun_AnnotationType_error = true; throw new JSONException("not support Type Annotation.", ex); } } if (sun_AnnotationType_getInstance == null || sun_AnnotationType_error) { throw new JSONException("not support Type Annotation."); } Object type; try { type = sun_AnnotationType_getInstance.invoke(null, annotationClass); } catch (Throwable ex) { sun_AnnotationType_error = true; throw new JSONException("not support Type Annotation.", ex); } Map members; try { members = (Map) sun_AnnotationType_members.invoke(type); } catch (Throwable ex) { sun_AnnotationType_error = true; throw new JSONException("not support Type Annotation.", ex); } 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; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/AppendableSerializer.java ================================================ 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, Object fieldName, Type fieldType, int features) throws IOException { if (object == null) { SerializeWriter out = serializer.out; out.writeNull(SerializerFeature.WriteNullStringAsEmpty); return; } serializer.write(object.toString()); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ArraySerializer.java ================================================ /* * 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 ArraySerializer implements ObjectSerializer { private final Class componentType; private final ObjectSerializer compObjectSerializer; public ArraySerializer(Class componentType, ObjectSerializer compObjectSerializer){ this.componentType = componentType; this.compObjectSerializer = compObjectSerializer; } 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; } Object[] array = (Object[]) object; int size = array.length; SerialContext context = serializer.context; serializer.setContext(context, object, fieldName, 0); try { out.append('['); for (int i = 0; i < size; ++i) { if (i != 0) { out.append(','); } Object item = array[i]; 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); } } out.append(']'); } finally { serializer.context = context; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/AtomicCodec.java ================================================ /* * 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/AutowiredObjectSerializer.java ================================================ /* * 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.lang.reflect.Type; import java.util.Set; /** * @author wenshao[szujobs@hotmail.com] */ public interface AutowiredObjectSerializer extends ObjectSerializer { Set getAutowiredFor(); } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/AwtCodec.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/BeanContext.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/BeforeFilter.java ================================================ 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) { JSONSerializer last = serializerLocal.get(); serializerLocal.set(serializer); seperatorLocal.set(seperator); writeBefore(object); serializerLocal.set(last); return seperatorLocal.get(); } protected final void writeKeyValue(String key, Object value) { JSONSerializer serializer = serializerLocal.get(); char seperator = seperatorLocal.get(); boolean ref = serializer.references.containsKey(value); serializer.writeKeyValue(seperator, key, value); if (!ref) { serializer.references.remove(value); } if (seperator != ',') { seperatorLocal.set(COMMA); } } public abstract void writeBefore(Object object); } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/BigDecimalCodec.java ================================================ /* * 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 { final static BigDecimal LOW = BigDecimal.valueOf(-9007199254740991L); final static BigDecimal HIGH = BigDecimal.valueOf(9007199254740991L); 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; int scale = val.scale(); String outText; if (SerializerFeature.isEnabled(features, out.features, SerializerFeature.WriteBigDecimalAsPlain) && scale >= -100 && scale < 100) { outText = val.toPlainString(); } else { outText = val.toString(); } if (scale == 0) { if (outText.length() >= 16 && SerializerFeature.isEnabled(features, out.features, SerializerFeature.BrowserCompatible) && (val.compareTo(LOW) < 0 || val.compareTo(HIGH) > 0)) { out.writeString(outText); return; } } 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/BigIntegerCodec.java ================================================ /* * 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.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 BigIntegerCodec implements ObjectSerializer, ObjectDeserializer { private final static BigInteger LOW = BigInteger.valueOf(-9007199254740991L); private final static BigInteger HIGH = BigInteger.valueOf(9007199254740991L); 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; String str = val.toString(); if (str.length() >= 16 && SerializerFeature.isEnabled(features, out.features, SerializerFeature.BrowserCompatible) && (val.compareTo(LOW) < 0 || val.compareTo(HIGH) > 0)) { out.writeString(str); return; } out.write(str); } @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); if (val.length() > 65535) { throw new JSONException("decimal overflow"); } return (T) new BigInteger(val); } Object value = parser.parse(); return value == null // ? null // : (T) TypeUtils.castToBigInteger(value); } public int getFastMatchToken() { return JSONToken.LITERAL_INT; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/BooleanCodec.java ================================================ /* * 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ByteBufferCodec.java ================================================ package com.alibaba.fastjson.serializer; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import java.io.IOException; import java.lang.reflect.Type; import java.nio.ByteBuffer; public class ByteBufferCodec implements ObjectSerializer, ObjectDeserializer { public final static ByteBufferCodec instance = new ByteBufferCodec(); @Override public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { ByteBufferBean bean = parser.parseObject(ByteBufferBean.class); return (T) bean.byteBuffer(); } @Override public int getFastMatchToken() { return JSONToken.LBRACKET; } @Override public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { ByteBuffer byteBuf = (ByteBuffer) object; byte[] array = byteBuf.array(); SerializeWriter out = serializer.out; out.write('{'); out.writeFieldName("array"); out.writeByteArray(array); out.writeFieldValue(',', "limit", byteBuf.limit()); out.writeFieldValue(',', "position", byteBuf.position()); out.write('}'); } public static class ByteBufferBean { public byte[] array; public int limit; public int position; public ByteBuffer byteBuffer() { ByteBuffer buf = ByteBuffer.wrap(array); buf.limit(limit); buf.position(position); return buf; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/CalendarCodec.java ================================================ package com.alibaba.fastjson.serializer; import java.io.IOException; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; 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.parser.deserializer.ContextObjectDeserializer; 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 extends ContextObjectDeserializer implements ObjectSerializer, ObjectDeserializer, ContextObjectSerializer { public final static CalendarCodec instance = new CalendarCodec(); private DatatypeFactory dateFactory; public void write(JSONSerializer serializer, Object object, BeanContext context) throws IOException { SerializeWriter out = serializer.out; String format = context.getFormat(); Calendar calendar = (Calendar) object; if (format.equals("unixtime")) { long seconds = calendar.getTimeInMillis() / 1000L; out.writeInt((int) seconds); return; } DateFormat dateFormat = new SimpleDateFormat(format); if (dateFormat == null) { dateFormat = new SimpleDateFormat(JSON.DEFFAULT_DATE_FORMAT, serializer.locale); } dateFormat.setTimeZone(serializer.timeZone); String text = dateFormat.format(calendar.getTime()); out.writeString(text); } 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); float timeZoneF = calendar.getTimeZone().getOffset(calendar.getTimeInMillis()) / (3600.0f * 1000); int timeZone = (int)timeZoneF; if (timeZone == 0.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.write(':'); // handles uneven timeZones 30 mins, 45 mins // this would always be less than 60 int offSet = (int)((timeZoneF - timeZone) * 60); out.append(String.format("%02d", offSet)); } out.append(quote); } else { Date date = calendar.getTime(); serializer.write(date); } } 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 type, Object fieldName, String format, int features) { Object value = DateCodec.instance.deserialze(parser, type, fieldName, format, features); 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/CharArrayCodec.java ================================================ package com.alibaba.fastjson.serializer; import java.lang.reflect.Type; import java.util.Collection; 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/CharacterCodec.java ================================================ /* * 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ClobSerializer.java ================================================ 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 ClobSerializer implements ObjectSerializer { public final static ClobSerializer instance = new ClobSerializer(); 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); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/CollectionCodec.java ================================================ /* * 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.Collection; import java.util.HashSet; 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.isAssignableFrom(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; if (parser.lexer.token() == JSONToken.SET) { parser.lexer.nextToken(); list = TypeUtils.createSet(type); } else { list = TypeUtils.createCollection(type); } Type itemType = TypeUtils.getCollectionItemType(type); parser.parseArray(itemType, list, fieldName); return (T) list; } public int getFastMatchToken() { return JSONToken.LBRACKET; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ContextObjectSerializer.java ================================================ package com.alibaba.fastjson.serializer; import java.io.IOException; public interface ContextObjectSerializer extends ObjectSerializer { void write(JSONSerializer serializer, // Object object, // BeanContext context) throws IOException; } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ContextValueFilter.java ================================================ package com.alibaba.fastjson.serializer; /** * @since 1.2.9 * */ public interface ContextValueFilter extends SerializeFilter { Object process(BeanContext context, Object object, String name, Object value); } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/DateCodec.java ================================================ /* * 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.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; } Class clazz = object.getClass(); if (clazz == java.sql.Date.class && !out.isEnabled(SerializerFeature.WriteDateUseDateFormat)) { long millis = ((java.sql.Date) object).getTime(); TimeZone timeZone = serializer.timeZone; int offset = timeZone.getOffset(millis); // if ((millis + offset) % (24 * 1000 * 3600) == 0 && !SerializerFeature.isEnabled(out.features, features, SerializerFeature.WriteClassName)) { out.writeString(object.toString()); return; } } if (clazz == java.sql.Time.class) { long millis = ((java.sql.Time) object).getTime(); if ("unixtime".equals(serializer.getDateFormatPattern())) { long seconds = millis / 1000; out.writeLong(seconds); return; } if ("millis".equals(serializer.getDateFormatPattern())) { long seconds = millis; out.writeLong(millis); return; } if (millis < 24L * 60L * 60L * 1000L) { out.writeString(object.toString()); return; } } int nanos = 0; if (clazz == java.sql.Timestamp.class) { java.sql.Timestamp ts = (java.sql.Timestamp) object; nanos = ts.getNanos(); } Date date; if (object instanceof Date) { date = (Date) object; } else { date = TypeUtils.castToDate(object); } if ("unixtime".equals(serializer.getDateFormatPattern())) { long seconds = date.getTime() / 1000; out.writeLong(seconds); return; } if ("millis".equals(serializer.getDateFormatPattern())) { long millis = date.getTime(); out.writeLong(millis); return; } if (out.isEnabled(SerializerFeature.WriteDateUseDateFormat)) { DateFormat format = serializer.getDateFormat(); if (format == null) { // 如果是通过FastJsonConfig进行设置,优先从FastJsonConfig获取 String dateFormatPattern = serializer.getFastJsonConfigDateFormatPattern(); if(dateFormatPattern == null) { dateFormatPattern = JSON.DEFFAULT_DATE_FORMAT; } format = new SimpleDateFormat(dateFormatPattern, serializer.locale); format.setTimeZone(serializer.timeZone); } String text = format.format(date); out.writeString(text); return; } if (out.isEnabled(SerializerFeature.WriteClassName)) { if (clazz != fieldType) { if (clazz == 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(clazz.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 (nanos > 0) { buf = "0000-00-00 00:00:00.000000000".toCharArray(); IOUtils.getChars(nanos, 29, 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 (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); } } if (nanos > 0) { // java.sql.Timestamp int i = 0; for (; i < 9; ++i) { int off = buf.length - i - 1; if (buf[off] != '0') { break; } } out.write(buf, 0, buf.length - i); out.write(quote); return; } out.write(buf); float timeZoneF = calendar.getTimeZone().getOffset(calendar.getTimeInMillis()) / (3600.0f * 1000); int timeZone = (int)timeZoneF; if (timeZone == 0.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.write(':'); // handles uneven timeZones 30 mins, 45 mins // this would always be less than 60 int offSet = (int)(Math.abs(timeZoneF - timeZone) * 60); out.append(String.format("%02d", offSet)); } 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 BigDecimal) { return (T) new java.util.Date(TypeUtils.longValue((BigDecimal) 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; } if (strVal.length() == 23 && strVal.endsWith(" 000")) { strVal = strVal.substring(0, 19); } { 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(); } } String dateFomartPattern = parser.getDateFomartPattern(); boolean formatMatch = strVal.length() == dateFomartPattern.length() || (strVal.length() == 22 && dateFomartPattern.equals("yyyyMMddHHmmssSSSZ")) || (strVal.indexOf('T') != -1 && dateFomartPattern.contains("'T'") && strVal.length() + 2 == dateFomartPattern.length()) ; if (formatMatch) { 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/DoubleSerializer.java ================================================ /* * 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; /** * @author wenshao[szujobs@hotmail.com] */ public class DoubleSerializer implements ObjectSerializer { public final static DoubleSerializer instance = new DoubleSerializer(); 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) { out.writeNull(SerializerFeature.WriteNullNumberAsZero); return; } double doubleValue = ((Double) object).doubleValue(); if (Double.isNaN(doubleValue) // || Double.isInfinite(doubleValue)) { out.writeNull(); } else { if (decimalFormat == null) { out.writeDouble(doubleValue, true); } else { String doubleText = decimalFormat.format(doubleValue); out.write(doubleText); } } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/EnumSerializer.java ================================================ /* * 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.JSONException; import java.io.IOException; import java.lang.reflect.*; /** * @author wenshao[szujobs@hotmail.com] */ public class EnumSerializer implements ObjectSerializer { private final Member member; public EnumSerializer() { this.member = null; } public EnumSerializer(Member member) { this.member = member; } public final static EnumSerializer instance = new EnumSerializer(); public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { if (member == null) { SerializeWriter out = serializer.out; out.writeEnum((Enum) object); return; } Object fieldValue = null; try { if (member instanceof Field) { fieldValue = ((Field) member).get(object); } else { fieldValue = ((Method) member).invoke(object); } } catch (Exception e) { throw new JSONException("getEnumValue error", e); } serializer.write(fieldValue); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/EnumerationSerializer.java ================================================ 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; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/FieldSerializer.java ================================================ /* * 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.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; /** * @author wenshao[szujobs@hotmail.com] */ public class FieldSerializer implements Comparable { public final FieldInfo fieldInfo; protected final boolean writeNull; protected int features; private final String double_quoted_fieldPrefix; private String single_quoted_fieldPrefix; private String un_quoted_fieldPrefix; 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); if (beanType != null) { 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){ features |= SerializerFeature.BrowserCompatible.mask; browserCompatible = true; } else if (feature == SerializerFeature.WriteMapNullValue) { features |= SerializerFeature.WriteMapNullValue.mask; } } } } fieldInfo.setAccessible(); this.double_quoted_fieldPrefix = '"' + fieldInfo.name + "\":"; boolean writeNull = false; JSONField annotation = fieldInfo.getAnnotation(); if (annotation != null) { for (SerializerFeature feature : annotation.serialzeFeatures()) { if ((feature.getMask() & SerializerFeature.WRITE_MAP_NULL_FEATURES) != 0) { writeNull = true; break; } } format = annotation.format(); if (format.trim().length() == 0) { format = null; } 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; persistenceXToMany = TypeUtils.isAnnotationPresentOneToMany(fieldInfo.method) || TypeUtils.isAnnotationPresentManyToMany(fieldInfo.method); } public void writePrefix(JSONSerializer serializer) throws IOException { SerializeWriter out = serializer.out; if (out.quoteFieldNames) { boolean useSingleQuotes = SerializerFeature.isEnabled(out.features, fieldInfo.serialzeFeatures, SerializerFeature.UseSingleQuotes); if (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 == java.util.Date.class || fieldInfo.fieldClass == java.sql.Date.class) { SimpleDateFormat dateFormat = new SimpleDateFormat(format, JSON.defaultLocale); dateFormat.setTimeZone(JSON.defaultTimeZone); return dateFormat.format(propertyValue); } } return propertyValue; } public int compareTo(FieldSerializer o) { 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; if (runtimeFieldClass == byte.class) { runtimeFieldClass = Byte.class; } else if (runtimeFieldClass == short.class) { runtimeFieldClass = Short.class; } else if (runtimeFieldClass == int.class) { runtimeFieldClass = Integer.class; } else if (runtimeFieldClass == long.class) { runtimeFieldClass = Long.class; } else if (runtimeFieldClass == float.class) { runtimeFieldClass = Float.class; } else if (runtimeFieldClass == double.class) { runtimeFieldClass = Double.class; } else if (runtimeFieldClass == boolean.class) { runtimeFieldClass = Boolean.class; } } 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); } } 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.mask) : fieldInfo.serialzeFeatures) | features; if (propertyValue == null) { SerializeWriter out = serializer.out; if (fieldInfo.fieldClass == Object.class && out.isEnabled(SerializerFeature.WRITE_MAP_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) || runtimeFieldClass.isArray()) { out.writeNull(features, SerializerFeature.WriteNullListAsEmpty.mask); return; } ObjectSerializer fieldSerializer = runtimeInfo.fieldSerializer; if ((out.isEnabled(SerializerFeature.WRITE_MAP_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 && valueSerializer instanceof JavaBeanSerializer) { ((JavaBeanSerializer) valueSerializer).write(serializer, propertyValue, fieldInfo.name, fieldInfo.fieldType, fieldFeatures, false); return; } if (browserCompatible && (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); } static class RuntimeSerializerInfo { final ObjectSerializer fieldSerializer; final Class runtimeFieldClass; public RuntimeSerializerInfo(ObjectSerializer fieldSerializer, Class runtimeFieldClass){ this.fieldSerializer = fieldSerializer; this.runtimeFieldClass = runtimeFieldClass; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/FloatCodec.java ================================================ /* * 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/GuavaCodec.java ================================================ package com.alibaba.fastjson.serializer; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import java.io.IOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.List; import java.util.Map; /** * Created by wenshao on 15/01/2017. */ public class GuavaCodec implements ObjectSerializer, ObjectDeserializer { 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()); } } public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { Type rawType = type; if (type instanceof ParameterizedType) { rawType = ((ParameterizedType) type).getRawType(); } if (rawType == ArrayListMultimap.class) { ArrayListMultimap multimap = ArrayListMultimap.create(); JSONObject object = parser.parseObject(); for (Map.Entry entry : object.entrySet()) { Object value = entry.getValue(); if (value instanceof Collection) { multimap.putAll(entry.getKey(), (List) value); } else { multimap.put(entry.getKey(), value); } } return (T) multimap; } return null; } public int getFastMatchToken() { return 0; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/IntegerCodec.java ================================================ /* * 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.concurrent.atomic.AtomicInteger; 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 number = lexer.decimalValue(); intObj = TypeUtils.intValue(number); lexer.nextToken(JSONToken.COMMA); } 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) { String message = "parseInt error"; if (fieldName != null) { message += (", field : " + fieldName); } throw new JSONException(message, ex); } if (clazz == AtomicInteger.class) { return (T) new AtomicInteger(intObj.intValue()); } return (T) intObj; } public int getFastMatchToken() { return JSONToken.LITERAL_INT; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/JSONAwareSerializer.java ================================================ /* * 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.JSONAware; /** * @author wenshao[szujobs@hotmail.com] */ public class JSONAwareSerializer implements ObjectSerializer { public static JSONAwareSerializer instance = new JSONAwareSerializer(); 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()); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/JSONLibDataFormatSerializer.java ================================================ package com.alibaba.fastjson.serializer; import java.io.IOException; import java.lang.reflect.Type; import java.util.Date; import com.alibaba.fastjson.JSONObject; public class JSONLibDataFormatSerializer implements ObjectSerializer { public JSONLibDataFormatSerializer(){ } @SuppressWarnings("deprecation") public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { if (object == null) { serializer.out.writeNull(); return; } Date date = (Date) object; JSONObject json = new JSONObject(); json.put("date", date.getDate()); json.put("day", date.getDay()); json.put("hours", date.getHours()); json.put("minutes", date.getMinutes()); json.put("month", date.getMonth()); json.put("seconds", date.getSeconds()); json.put("time", date.getTime()); json.put("timezoneOffset", date.getTimezoneOffset()); json.put("year", date.getYear()); serializer.write(json); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/JSONObjectCodec.java ================================================ package com.alibaba.fastjson.serializer; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.Type; public class JSONObjectCodec implements ObjectSerializer { public final static JSONObjectCodec instance = new JSONObjectCodec(); public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { SerializeWriter out = serializer.out; MapSerializer mapSerializer = MapSerializer.instance; try { Field mapField = object.getClass().getDeclaredField("map"); if (Modifier.isPrivate(mapField.getModifiers())) { mapField.setAccessible(true); } Object map = mapField.get(object); mapSerializer.write(serializer, map, fieldName, fieldType, features); } catch (Exception e) { out.writeNull(); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/JSONSerializable.java ================================================ /* * 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; } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/JSONSerializableSerializer.java ================================================ /* * 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); if (jsonSerializable == null) { serializer.writeNull(); return; } jsonSerializable.write(serializer, fieldName, fieldType, features); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/JSONSerializer.java ================================================ /* * 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.ByteArrayOutputStream; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.GZIPOutputStream; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.util.IOUtils; /** * @author wenshao[szujobs@hotmail.com] */ public class JSONSerializer extends SerializeFilterable { protected final SerializeConfig config; public final SerializeWriter out; private int indentCount = 0; private String indent = "\t"; /** * #1868 为了区分全局配置(FastJsonConfig)的日期格式配置以及toJSONString传入的日期格式配置 * 建议使用以下调整: * 1. dateFormatPattern、dateFormat只作为toJSONString传入配置使用; * 2. 新增fastJsonConfigDateFormatPattern,用于存储通过(FastJsonConfig)配置的日期格式 */ private String dateFormatPattern; private DateFormat dateFormat; private String fastJsonConfigDateFormatPattern; protected IdentityHashMap references = null; protected SerialContext context; protected TimeZone timeZone = JSON.defaultTimeZone; protected Locale locale = JSON.defaultLocale; public JSONSerializer(){ this(new SerializeWriter(), SerializeConfig.getGlobalInstance()); } 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; } public DateFormat getDateFormat() { if (dateFormat == null) { if (dateFormatPattern != null) { dateFormat = this.generateDateFormat( dateFormatPattern ); } } return dateFormat; } private DateFormat generateDateFormat(String dateFormatPattern) { DateFormat dateFormat = new SimpleDateFormat(dateFormatPattern, locale); dateFormat.setTimeZone(timeZone); return dateFormat; } public void setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; if (dateFormatPattern != null) { dateFormatPattern = null; } } public void setDateFormat(String dateFormat) { this.dateFormatPattern = dateFormat; if (this.dateFormat != null) { this.dateFormat = null; } } /** * Set global date format pattern in FastJsonConfig * * @param dateFormatPattern global date format pattern */ public void setFastJsonConfigDateFormatPattern(String dateFormatPattern) { this.fastJsonConfigDateFormatPattern = dateFormatPattern; } public String getFastJsonConfigDateFormatPattern() { return this.fastJsonConfigDateFormatPattern; } public SerialContext getContext() { return context; } public void setContext(SerialContext context) { this.context = context; } 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 void popContext() { if (context != null) { this.context = this.context.parent; } } 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 boolean containsReference(Object value) { if (references == null) { return false; } SerialContext refContext = references.get(value); if (refContext == null) { return false; } if (value == Collections.emptyMap()) { return false; } Object fieldName = refContext.fieldName; return fieldName == null || fieldName instanceof Integer || fieldName instanceof String; } 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; } } 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 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 boolean hasPropertyFilters(SerializeFilterable filterable) { return (propertyFilters != null && propertyFilters.size() > 0) // || (filterable.propertyFilters != null && filterable.propertyFilters.size() > 0); } public int getIndentCount() { return indentCount; } public void incrementIndent() { indentCount++; } public void decrementIdent() { indentCount--; } public void println() { out.write('\n'); for (int i = 0; i < indentCount; ++i) { out.write(indent); } } public SerializeWriter getWriter() { return out; } public String toString() { return out.toString(); } public void config(SerializerFeature feature, boolean state) { out.config(feature, state); } public boolean isEnabled(SerializerFeature feature) { return out.isEnabled(feature); } public void writeNull() { this.out.writeNull(); } public SerializeConfig getMapping() { return config; } public static void write(Writer out, Object object) { SerializeWriter writer = new SerializeWriter(); try { JSONSerializer serializer = new JSONSerializer(writer); serializer.write(object); writer.writeTo(out); } catch (IOException ex) { throw new JSONException(ex.getMessage(), ex); } finally { writer.close(); } } 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); } } /** * @since 1.2.57 * */ public final void writeAs(Object object, Class type) { if (object == null) { out.writeNull(); return; } ObjectSerializer writer = getObjectWriter(type); 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(); return; } Class clazz = object.getClass(); ObjectSerializer writer = getObjectWriter(clazz); writer.write(this, object, fieldName, fieldType, fieldFeatures); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } } public final void writeWithFormat(Object object, String format) { if (object instanceof Date) { if ("unixtime".equals(format)) { long seconds = ((Date) object).getTime() / 1000L; out.writeInt((int) seconds); return; } if ("millis".equals(format)) { out.writeLong(((Date) object).getTime()); return; } DateFormat dateFormat = this.getDateFormat(); if (dateFormat == null) { if (format != null) { try { dateFormat = this.generateDateFormat(format); } catch (IllegalArgumentException e) { String format2 = format.replaceAll("T", "'T'"); dateFormat = this.generateDateFormat(format2); } } else if (fastJsonConfigDateFormatPattern != null) { dateFormat = this.generateDateFormat(fastJsonConfigDateFormatPattern); } else { dateFormat = this.generateDateFormat(JSON.DEFFAULT_DATE_FORMAT); } } 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) { StringCodec.instance.write(this, text); } public ObjectSerializer getObjectWriter(Class clazz) { return config.getObjectWriter(clazz); } public void close() { this.out.close(); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/JSONSerializerMap.java ================================================ package com.alibaba.fastjson.serializer; @Deprecated public class JSONSerializerMap extends SerializeConfig { public final boolean put(Class clazz, ObjectSerializer serializer) { return super.put(clazz, serializer); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java ================================================ /* * 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.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; 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.Map; import java.util.Set; 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.annotation.JSONType; import com.alibaba.fastjson.util.FieldInfo; import com.alibaba.fastjson.util.TypeUtils; /** * @author wenshao[szujobs@hotmail.com] */ public class JavaBeanSerializer extends SerializeFilterable implements ObjectSerializer { // serializers protected final FieldSerializer[] getters; protected final FieldSerializer[] sortedGetters; protected final SerializeBeanInfo beanInfo; private transient volatile long[] hashArray; private transient volatile short[] hashArrayMapping; public JavaBeanSerializer(Class beanType){ this(beanType, (Map) null); } public JavaBeanSerializer(Class beanType, String... aliasList){ this(beanType, createAliasMap(aliasList)); } static Map createAliasMap(String... aliasList) { Map aliasMap = new HashMap(); for (String alias : aliasList) { aliasMap.put(alias, alias); } return aliasMap; } public JSONType getJSONType() { return beanInfo.jsonType; } /** * @since 1.2.42 */ public Class getType() { return beanInfo.beanType; } 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]; boolean hashNotMatch = false; for (int i = 0; i < getters.length; ++i) { FieldSerializer fieldSerializer = getFieldSerializer(beanInfo.fields[i].name); if (fieldSerializer == null) { hashNotMatch = true; break; } getters[i] = fieldSerializer; } if (hashNotMatch) { System.arraycopy(sortedGetters, 0, getters, 0, sortedGetters.length); } } if (beanInfo.jsonType != null) { for (Class filterClass : beanInfo.jsonType.serialzeFilters()) { try { SerializeFilter filter = filterClass.getConstructor().newInstance(); this.addFilter(filter); } catch (Exception e) { // skip } } } } 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); } public void write(JSONSerializer serializer, // Object object, // Object fieldName, // Type fieldType, // int features) throws IOException { write(serializer, object, fieldName, fieldType, features, false); } 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; } if (writeReference(serializer, object, features)) { return; } final FieldSerializer[] getters; if (out.sortField) { getters = this.sortedGetters; } else { getters = this.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); FieldSerializer errorFieldSerializer = null; try { 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 ((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 writeClassName = out.isEnabled(SerializerFeature.WriteClassName); 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]; Field field = fieldSerializer.fieldInfo.field; FieldInfo fieldInfo = fieldSerializer.fieldInfo; String fieldInfoName = fieldInfo.name; Class fieldClass = fieldInfo.fieldClass; final boolean fieldUseSingleQuotes = SerializerFeature.isEnabled(out.features, fieldInfo.serialzeFeatures, SerializerFeature.UseSingleQuotes); final boolean directWritePrefix = out.quoteFieldNames && !fieldUseSingleQuotes; if (skipTransient) { if (fieldInfo.fieldTransient) { continue; } } if (ignoreNonFieldGetter) { if (field == null) { continue; } } boolean notApply = false; if ((!this.applyName(serializer, object, fieldInfoName)) // || !this.applyLabel(serializer, fieldInfo.label)) { if (writeAsArray) { notApply = true; } else { continue; } } if (fieldInfoName.equals(beanInfo.typeKey) && serializer.isWriteClassName(fieldType, object)) { continue; } Object propertyValue; if (notApply) { propertyValue = null; } else { try { propertyValue = fieldSerializer.getPropertyValueDirect(object); } catch (InvocationTargetException ex) { errorFieldSerializer = fieldSerializer; if (out.isEnabled(SerializerFeature.IgnoreErrorGetter)) { propertyValue = null; } else { throw ex; } } } if (!this.apply(serializer, object, fieldInfoName, propertyValue)) { continue; } 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 = this.processValue(serializer, fieldSerializer.fieldContext, object, fieldInfoName, propertyValue, features); if (propertyValue == null) { int serialzeFeatures = fieldInfo.serialzeFeatures; JSONField jsonField = fieldInfo.getAnnotation(); if (beanInfo.jsonType != null) { serialzeFeatures |= SerializerFeature.of(beanInfo.jsonType.serialzeFeatures()); } // beanInfo.jsonType if (jsonField != null && !"".equals(jsonField.defaultValue())) { propertyValue = jsonField.defaultValue(); } else 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) { propertyValue = false; } else if ((out.features & defaultMask) != 0 && (serialzeFeatures & SerializerFeature.WriteMapNullValue.mask) == 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) { propertyValue = ""; } else if ((out.features & defaultMask) != 0 && (serialzeFeatures & SerializerFeature.WriteMapNullValue.mask) == 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) { propertyValue = 0; } else if ((out.features & defaultMask) != 0 && (serialzeFeatures & SerializerFeature.WriteMapNullValue.mask) == 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) { propertyValue = Collections.emptyList(); } else if ((out.features & defaultMask) != 0 && (serialzeFeatures & SerializerFeature.WriteMapNullValue.mask) == 0) { propertyValue = Collections.emptyList(); } } else if ((!writeAsArray) && (!fieldSerializer.writeNull) && !out.isEnabled(SerializerFeature.WriteMapNullValue.mask) && (serialzeFeatures & SerializerFeature.WriteMapNullValue.mask) == 0) { 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) { if (fieldInfo.unwrapped && propertyValue instanceof Map && ((Map) propertyValue).size() == 0) { continue; } out.write(','); if (out.isEnabled(SerializerFeature.PrettyFormat)) { serializer.println(); } } if (key != fieldInfoName) { if (!writeAsArray) { out.writeFieldName(key, true); } serializer.write(propertyValue); } else if (originalValue != propertyValue) { if (!writeAsArray) { fieldSerializer.writePrefix(serializer); } serializer.write(propertyValue); } else { if (!writeAsArray) { boolean isMap = Map.class.isAssignableFrom(fieldClass); boolean isJavaBean = !fieldClass.isPrimitive() && !fieldClass.getName().startsWith("java.") || fieldClass == Object.class; if (writeClassName || !fieldInfo.unwrapped || !(isMap || isJavaBean)) { 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) { int serialzeFeatures = fieldSerializer.features; if (beanInfo.jsonType != null) { serialzeFeatures |= SerializerFeature.of(beanInfo.jsonType.serialzeFeatures()); } if ((out.features & SerializerFeature.WriteNullStringAsEmpty.mask) != 0 && (serialzeFeatures & SerializerFeature.WriteMapNullValue.mask) == 0) { out.writeString(""); } else if ((serialzeFeatures & SerializerFeature.WriteNullStringAsEmpty.mask) != 0) { out.writeString(""); } else { out.writeNull(); } } else { String propertyValueString = (String) propertyValue; if (fieldUseSingleQuotes) { 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); } } 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(); } if (!unwrapped) { out.append(endSeperator); } } catch (Exception e) { String errorMessage = "write javaBean error, fastjson version " + JSON.VERSION; if (object != null) { errorMessage += ", class " + object.getClass().getName(); } if (fieldName != null) { errorMessage += ", fieldName : " + fieldName; } else if (errorFieldSerializer != null && errorFieldSerializer.fieldInfo != null) { FieldInfo fieldInfo = errorFieldSerializer.fieldInfo; if (fieldInfo.method != null) { errorMessage += ", method : " + fieldInfo.method.getName(); } else { errorMessage += ", fieldName : " + errorFieldSerializer.fieldInfo.name; } } if (e.getMessage() != null) { errorMessage += (", " + e.getMessage()); } Throwable cause = null; if (e instanceof InvocationTargetException) { cause = e.getCause(); } if (cause == null) { cause = e; } throw new JSONException(errorMessage, cause); } finally { serializer.context = parent; } } 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(); if (TypeUtils.isProxy(clazz)) { clazz = clazz.getSuperclass(); } typeName = clazz.getName(); } serializer.write(typeName); } 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; } 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); } 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); } } 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; } 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); } } public FieldSerializer getFieldSerializer(String key) { if (key == null) { return null; } int low = 0; int high = sortedGetters.length - 1; while (low <= high) { int mid = (low + high) >>> 1; String fieldName = sortedGetters[mid].fieldInfo.name; int cmp = fieldName.compareTo(key); if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { return sortedGetters[mid]; // key found } } return null; // key not found. } public FieldSerializer getFieldSerializer(long hash) { PropertyNamingStrategy[] namingStrategies = null; if (this.hashArray == null) { namingStrategies = PropertyNamingStrategy.values(); 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); this.hashArray = new long[index]; System.arraycopy(hashArray, 0, this.hashArray, 0, index); } int pos = Arrays.binarySearch(hashArray, hash); if (pos < 0) { return null; } if (hashArrayMapping == null) { if (namingStrategies == null) { namingStrategies = PropertyNamingStrategy.values(); } 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; } for (int j = 0; j < namingStrategies.length; j++) { String name_t = namingStrategies[j].translate(name); if (name.equals(name_t)) { continue; } int p_t = Arrays.binarySearch(hashArray , TypeUtils.fnv1a_64(name_t)); if (p_t >= 0) { mapping[p_t] = (short) i; } } } hashArrayMapping = mapping; } int getterIndex = hashArrayMapping[pos]; if (getterIndex != -1) { return sortedGetters[getterIndex]; } return null; // key not found. } public List getFieldValues(Object object) throws Exception { List fieldValues = new ArrayList(sortedGetters.length); for (FieldSerializer getter : sortedGetters) { fieldValues.add(getter.getPropertyValue(object)); } return fieldValues; } // 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)); } 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; } /** * Get field names of not null fields. Keep the same logic as getSize. * * @param object the object to be checked * @return field name set * @throws Exception * @see #getSize(Object) */ public Set getFieldNames(Object object) throws Exception { Set fieldNames = new HashSet(); for (FieldSerializer getter : sortedGetters) { Object value = getter.getPropertyValueDirect(object); if (value != null) { fieldNames.add(getter.fieldInfo.name); } } return fieldNames; } public Map getFieldValuesMap(Object object) throws Exception { Map map = new LinkedHashMap(sortedGetters.length); boolean skipTransient = true; FieldInfo fieldInfo = null; for (FieldSerializer getter : sortedGetters) { skipTransient = SerializerFeature.isEnabled(getter.features, SerializerFeature.SkipTransientField); fieldInfo = getter.fieldInfo; if (skipTransient && fieldInfo != null && fieldInfo.fieldTransient) { continue; } if (getter.fieldInfo.unwrapped) { Object unwrappedValue = getter.getPropertyValue(object); Object map1 = JSON.toJSON(unwrappedValue); if (map1 instanceof Map) { map.putAll((Map) map1); } else { map.put(getter.fieldInfo.name, getter.getPropertyValue(object)); } } else { map.put(getter.fieldInfo.name, getter.getPropertyValue(object)); } } return map; } 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; } } } if (this.labelFilters != null) { for (LabelFilter propertyFilter : this.labelFilters) { if (!propertyFilter.apply(label)) { return false; } } } return true; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/JodaCodec.java ================================================ package com.alibaba.fastjson.serializer; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONLexer; import com.alibaba.fastjson.parser.JSONToken; import java.io.IOException; import java.lang.reflect.Type; import java.util.Locale; import java.util.TimeZone; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.alibaba.fastjson.util.TypeUtils; import org.joda.time.*; import org.joda.time.format.*; public class JodaCodec implements ObjectSerializer, ContextObjectSerializer, ObjectDeserializer { public final static JodaCodec instance = new JodaCodec(); private final static String defaultPatttern = "yyyy-MM-dd HH:mm:ss"; private final static DateTimeFormatter defaultFormatter = DateTimeFormat.forPattern(defaultPatttern); private final static DateTimeFormatter defaultFormatter_23 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS"); private final static DateTimeFormatter formatter_dt19_tw = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_cn = DateTimeFormat.forPattern("yyyy年M月d日 HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_cn_1 = DateTimeFormat.forPattern("yyyy年M月d日 H时m分s秒"); private final static DateTimeFormatter formatter_dt19_kr = DateTimeFormat.forPattern("yyyy년M월d일 HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_us = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_eur = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_de = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_in = DateTimeFormat.forPattern("dd-MM-yyyy HH:mm:ss"); private final static DateTimeFormatter formatter_d8 = DateTimeFormat.forPattern("yyyyMMdd"); private final static DateTimeFormatter formatter_d10_tw = DateTimeFormat.forPattern("yyyy/MM/dd"); private final static DateTimeFormatter formatter_d10_cn = DateTimeFormat.forPattern("yyyy年M月d日"); private final static DateTimeFormatter formatter_d10_kr = DateTimeFormat.forPattern("yyyy년M월d일"); private final static DateTimeFormatter formatter_d10_us = DateTimeFormat.forPattern("MM/dd/yyyy"); private final static DateTimeFormatter formatter_d10_eur = DateTimeFormat.forPattern("dd/MM/yyyy"); private final static DateTimeFormatter formatter_d10_de = DateTimeFormat.forPattern("dd.MM.yyyy"); private final static DateTimeFormatter formatter_d10_in = DateTimeFormat.forPattern("dd-MM-yyyy"); private final static DateTimeFormatter ISO_FIXED_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.getDefault()); private final static String formatter_iso8601_pattern = "yyyy-MM-dd'T'HH:mm:ss"; private final static String formatter_iso8601_pattern_23 = "yyyy-MM-dd'T'HH:mm:ss.SSS"; private final static String formatter_iso8601_pattern_29 = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS"; private final static DateTimeFormatter formatter_iso8601 = DateTimeFormat.forPattern(formatter_iso8601_pattern); public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { return deserialze(parser, type, fieldName, null, 0); } 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 = DateTimeFormat.forPattern(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 = localDate.toLocalDateTime(LocalTime.MIDNIGHT); } 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 = localDateTime.toLocalDate(); } 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 = localDateTime.toLocalTime(); } else { localDate = LocalTime.parse(text); } return (T) localDate; } else if (type == DateTime.class) { if (formatter == defaultFormatter) { formatter = ISO_FIXED_FORMAT; } DateTime zonedDateTime = parseZonedDateTime(text, formatter); return (T) zonedDateTime; } else if (type == DateTimeZone.class) { DateTimeZone offsetTime = DateTimeZone.forID(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) { boolean digit = true; for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (ch < '0' || ch > '9') { digit = false; break; } } if (digit && text.length() > 8 && text.length() < 19) { long epochMillis = Long.parseLong(text); return (T) new Instant(epochMillis); } Instant instant = Instant.parse(text); return (T) instant; } else if (type == DateTimeFormatter.class) { return (T) DateTimeFormat.forPattern(text); } } else if (lexer.token() == JSONToken.LITERAL_INT) { long millis = lexer.longValue(); lexer.nextToken(); TimeZone timeZone = JSON.defaultTimeZone; if (timeZone == null) { timeZone = TimeZone.getDefault(); } if (type == DateTime.class) { return (T) new DateTime(millis, DateTimeZone.forTimeZone(timeZone)); } LocalDateTime localDateTime = new LocalDateTime(millis, DateTimeZone.forTimeZone(timeZone)); if (type == LocalDateTime.class) { return (T) localDateTime; } if (type == LocalDate.class) { return (T) localDateTime.toLocalDate(); } if (type == LocalTime.class) { return (T) localDateTime.toLocalTime(); } if (type == Instant.class) { Instant instant = new Instant(millis); return (T) instant; } throw new UnsupportedOperationException(); } else if (lexer.token() == JSONToken.LBRACE) { JSONObject object = parser.parseObject(); if (type == Instant.class) { Object epochSecond = object.get("epochSecond"); if (epochSecond instanceof Number) { return (T) Instant.ofEpochSecond( TypeUtils.longExtractValue((Number) epochSecond)); } Object millis = object.get("millis"); if (millis instanceof Number) { return (T) Instant.ofEpochMilli( TypeUtils.longExtractValue((Number) millis)); } } } 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 == '-') { // yyyy-MM-dd or yyyy-MM-dd'T' if (c10 == 'T') { formatter = formatter_iso8601; } else if (c10 == ' ') { 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; } } } } else if (text.length() == 23) { 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); char c19 = text.charAt(19); if (c13 == ':' && c16 == ':' && c4 == '-' && c7 == '-' && c10 == ' ' && c19 == '.' ) { formatter = defaultFormatter_23; } } 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; } } boolean digit = true; for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (ch < '0' || ch > '9') { digit = false; break; } } if (digit && text.length() > 8 && text.length() < 19) { long epochMillis = Long.parseLong(text); return new LocalDateTime(epochMillis, DateTimeZone.forTimeZone(JSON.defaultTimeZone)); } } 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; } } boolean digit = true; for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); if (ch < '0' || ch > '9') { digit = false; break; } } if (digit && text.length() > 8 && text.length() < 19) { long epochMillis = Long.parseLong(text); return new LocalDateTime(epochMillis, DateTimeZone.forTimeZone(JSON.defaultTimeZone)) .toLocalDate(); } } return formatter == null ? // LocalDate.parse(text) // : LocalDate.parse(text, formatter); } protected DateTime 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 == '-') { // yyyy-MM-dd or yyyy-MM-dd'T' if (c10 == 'T') { formatter = formatter_iso8601; } else if (c10 == ' ') { 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 ? // DateTime.parse(text) // : DateTime.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) { if ((features & mask) != 0 || serializer.isEnabled(SerializerFeature.UseISO8601DateFormat)) { format = formatter_iso8601_pattern; } else if (serializer.isEnabled(SerializerFeature.WriteDateUseDateFormat)) { format = JSON.DEFFAULT_DATE_FORMAT; } else { int millis = dateTime.getMillisOfSecond(); if (millis == 0) { format = formatter_iso8601_pattern_23; } else { format = formatter_iso8601_pattern_29; } } } if (format != null) { write(out, dateTime, format); } else { out.writeLong(dateTime.toDateTime(DateTimeZone.forTimeZone(JSON.defaultTimeZone)).toInstant().getMillis()); } } 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, (ReadablePartial) object, format); } private void write(SerializeWriter out, ReadablePartial object, String format) { DateTimeFormatter formatter; if (format.equals(formatter_iso8601_pattern)) { formatter = formatter_iso8601; } else { formatter = DateTimeFormat.forPattern(format); } String text = formatter.print(object); out.writeString(text); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/LabelFilter.java ================================================ /* * 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); } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/Labels.java ================================================ /* * 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) < 0; } 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ListSerializer.java ================================================ /* * 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.util.TypeUtils; import java.io.IOException; import java.lang.reflect.Type; import java.util.List; /** * @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, 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) { out.writeNull(SerializerFeature.WriteNullListAsEmpty); return; } List list = (List) object; if (list.size() == 0) { out.append("[]"); return; } SerialContext context = serializer.context; serializer.setContext(context, object, fieldName, 0); ObjectSerializer itemSerializer = null; try { if (out.isEnabled(SerializerFeature.PrettyFormat)) { out.append('['); serializer.incrementIndent(); 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; } 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 (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 (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; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/LongCodec.java ================================================ /* * 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.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.LITERAL_FLOAT) { BigDecimal number = lexer.decimalValue(); longObject = TypeUtils.longValue(number); lexer.nextToken(JSONToken.COMMA); } 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/MapSerializer.java ================================================ /* * 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, features); } else { boolean objectOrArray = entryKey instanceof Map || entryKey instanceof Collection; if (!objectOrArray) { String strKey = JSON.toJSONString(entryKey); value = this.processValue(serializer, null, object, strKey, value, features); } } } if (value == null) { if (!SerializerFeature.isEnabled(out.features, features, 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) || SerializerFeature.isEnabled(features, SerializerFeature.WriteNonStringKeyAsString)) && !(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('}'); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/MiscCodec.java ================================================ /* * 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.io.StringWriter; 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; import org.w3c.dom.Node; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /** * @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 if (object instanceof org.w3c.dom.Node) { strVal = toString((Node) object); } else { throw new JSONException("not support class : " + objClass); } out.writeString(strVal); } private static String toString(org.w3c.dom.Node node) { try { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource domSource = new DOMSource(node); StringWriter out = new StringWriter(); transformer.transform(domSource, new StreamResult(out)); return out.toString(); } catch (TransformerException e) { throw new JSONException("xml node to string error", e); } } 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(), false); } 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/NameFilter.java ================================================ /* * 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 extends SerializeFilter { String process(Object object, String name, Object value); } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ObjectArrayCodec.java ================================================ /* * 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.writeWithFieldName(array[i], Integer.valueOf(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, i, null, 0); } else { preClazz = clazz; preWriter = serializer.getObjectWriter(clazz); preWriter.write(serializer, item, i, 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ObjectSerializer.java ================================================ /* * 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; /** * 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 { /** * 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; } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/PascalNameFilter.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/PrimitiveArraySerializer.java ================================================ /* * 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/PropertyFilter.java ================================================ /* * 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); } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/PropertyPreFilter.java ================================================ /* * 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); } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ReferenceCodec.java ================================================ /* * 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/SerialContext.java ================================================ 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 >= '0' && ch <='9') || (ch >= 'A' && ch <='Z') || (ch >= 'a' && ch <='z') || ch > 128) { continue; } special = true; break; } if (special) { for (int i = 0; i < fieldName.length(); ++i) { char ch = fieldName.charAt(i); if (ch == '\\') { buf.append('\\'); buf.append('\\'); buf.append('\\'); } else if ((ch >= '0' && ch <='9') || (ch >= 'A' && ch <='Z') || (ch >= 'a' && ch <='z') || ch > 128) { buf.append(ch); continue; } else if(ch == '\"'){ buf.append('\\'); buf.append('\\'); buf.append('\\'); } else { 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(); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/SerializeBeanInfo.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/SerializeConfig.java ================================================ /* * 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.spi.Module; import com.alibaba.fastjson.support.moneta.MonetaCodec; 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.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 jodaError = 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 IdentityHashMap> mixInSerializers; private final boolean fieldBased; private long[] denyClasses = { 4165360493669296979L, 4446674157046724083L }; private List modules = new ArrayList(); 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) { String className = clazz.getName(); long hashCode64 = TypeUtils.fnv1a_64(className); if (Arrays.binarySearch(denyClasses, hashCode64) >= 0) { throw new JSONException("not support class : " + className); } 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; } if (asm) { for (SerializerFeature feature : jsonType.serialzeFeatures()) { if (SerializerFeature.WriteNonStringValueAsString == feature // || SerializerFeature.WriteEnumUsingToString == feature // || SerializerFeature.NotWriteDefaultValue == feature || SerializerFeature.BrowserCompatible == feature) { asm = false; break; } } } if (asm) { final Class[] filterClasses = jsonType.serialzeFilters(); if (filterClasses.length != 0) { asm = false; } } } 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; } if (fieldInfo.fieldClass.isEnum() && get(fieldInfo.fieldClass) != EnumSerializer.instance) { 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 = false; break; } if (annotation.defaultValue() != null && !"".equals(annotation.defaultValue())) { asm = false; 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 (OutOfMemoryError e) { if (e.getMessage().indexOf("Metaspace") != -1) { throw e; } // skip } catch (Throwable e) { throw new JSONException("create asm serializer error, verson " + JSON.VERSION + ", 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); this.mixInSerializers = new IdentityHashMap>(16); 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); } public ObjectSerializer getObjectWriter(Class clazz, boolean create) { ObjectSerializer writer = get(clazz); if (writer != null) { return writer; } 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 = 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 = get(clazz); } } for (Module module : modules) { writer = module.createSerializer(this, clazz); if (writer != null) { put(clazz, writer); return writer; } } 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()) { Class mixedInType = (Class) JSON.getMixInAnnotations(clazz); JSONType jsonType; if (mixedInType != null) { jsonType = TypeUtils.getAnnotation(mixedInType, JSONType.class); } else { jsonType = TypeUtils.getAnnotation(clazz, JSONType.class); } if (jsonType != null && jsonType.serializeEnumAsJavaBean()) { put(clazz, writer = createJavaBeanSerializer(clazz)); } else { Member member = null; if (mixedInType != null) { Member mixedInMember = getEnumValueField(mixedInType); if (mixedInMember != null) { try { if (mixedInMember instanceof Method) { Method mixedInMethod = (Method) mixedInMember; member = clazz.getMethod(mixedInMethod.getName(), mixedInMethod.getParameterTypes()); } } catch (Exception e) { // skip } } } else { member = getEnumValueField(clazz); } if (member != null) { put(clazz, writer = new EnumSerializer(member)); } else { put(clazz, writer = getEnumSerializer()); } } } 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 = getEnumSerializer()); } } 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 (TypeUtils.isClob(clazz)) { put(clazz, writer = ClobSerializer.instance); } else if (TypeUtils.isPath(clazz)) { put(clazz, writer = ToStringSerializer.instance); } else if (Iterator.class.isAssignableFrom(clazz)) { put(clazz, writer = MiscCodec.instance); } else if (org.w3c.dom.Node.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.LinkedHashMultimap", "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 (className.equals("net.sf.json.JSONNull")) { put(clazz, writer = MiscCodec.instance); return writer; } if (className.equals("org.json.JSONObject")) { put(clazz, writer = JSONObjectCodec.instance); return writer; } if ((!jodaError) && className.startsWith("org.joda.")) { try { String[] names = new String[] { "org.joda.time.LocalDate", "org.joda.time.LocalDateTime", "org.joda.time.LocalTime", "org.joda.time.Instant", "org.joda.time.DateTime", "org.joda.time.Period", "org.joda.time.Duration", "org.joda.time.DateTimeZone", "org.joda.time.UTCDateTimeZone", "org.joda.time.tz.CachedDateTimeZone", "org.joda.time.tz.FixedDateTimeZone", }; for (String name : names) { if (name.equals(className)) { put(Class.forName(name), writer = JodaCodec.instance); return writer; } } } catch (ClassNotFoundException e) { // skip jodaError = true; } } if ("java.nio.HeapByteBuffer".equals(className)) { put(clazz, writer = ByteBufferCodec.instance); return writer; } if ("org.javamoney.moneta.Money".equals(className)) { put(clazz, writer = MonetaCodec.instance); return writer; } if ("com.google.protobuf.Descriptors$FieldDescriptor".equals(className)) { put(clazz, writer = ToStringSerializer.instance); return writer; } Class[] interfaces = clazz.getInterfaces(); if (interfaces.length == 1 && interfaces[0].isAnnotation()) { put(clazz, AnnotationSerializer.instance); 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 = get(clazz); } } return writer; } private static Member getEnumValueField(Class clazz) { Member member = null; Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.getReturnType() == Void.class) { continue; } JSONField jsonField = method.getAnnotation(JSONField.class); if (jsonField != null) { if (member != null) { return null; } member = method; } } for (Field field : clazz.getFields()) { JSONField jsonField = field.getAnnotation(JSONField.class); if (jsonField != null) { if (member != null) { return null; } member = field; } } return member; } /** * 可以通过重写这个方法,定义自己的枚举序列化实现 * @return 返回一个枚举的反序列化实现 * @author zhu.xiaojie * @time 2020-4-5 */ protected ObjectSerializer getEnumSerializer(){ return EnumSerializer.instance; } public final ObjectSerializer get(Type type) { Type mixin = JSON.getMixInAnnotations(type); if (null == mixin) { return this.serializers.get(type); } IdentityHashMap mixInClasses = this.mixInSerializers.get(type); if (mixInClasses == null) { return null; } return mixInClasses.get(mixin); } public boolean put(Object type, Object value) { return put((Type)type, (ObjectSerializer)value); } public boolean put(Type type, ObjectSerializer value) { Type mixin = JSON.getMixInAnnotations(type); if (mixin != null) { IdentityHashMap mixInClasses = this.mixInSerializers.get(type); if (mixInClasses == null) { //多线程下可能会重复创建,但不影响正确性 mixInClasses = new IdentityHashMap(4); mixInSerializers.put(type, mixInClasses); } return mixInClasses.put(mixin, 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(); } public void register(Module module) { this.modules.add(module); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/SerializeFilter.java ================================================ package com.alibaba.fastjson.serializer; public interface SerializeFilter { } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/SerializeFilterable.java ================================================ package com.alibaba.fastjson.serializer; import java.text.DecimalFormat; 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) { return processValue(jsonBeanDeser, beanContext, object, key, propertyValue, 0); } protected Object processValue(JSONSerializer jsonBeanDeser, // BeanContext beanContext, Object object, // String key, // Object propertyValue, // int features) { if (propertyValue != null) { if ((SerializerFeature.isEnabled(jsonBeanDeser.out.features, features, SerializerFeature.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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/SerializeWriter.java ================================================ /* * 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.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.util.IOUtils; import com.alibaba.fastjson.util.RyuDouble; import com.alibaba.fastjson.util.RyuFloat; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.math.BigDecimal; import java.nio.charset.Charset; import java.util.List; import static com.alibaba.fastjson.util.IOUtils.replaceChars; /** * @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(); private static final char[] VALUE_TRUE = ":true".toCharArray(); private static final char[] VALUE_FALSE = ":false".toCharArray(); private static int BUFFER_THRESHOLD = 1024 * 128; static { try { String prop = IOUtils.getStringProperty("fastjson.serializer_buffer_threshold"); if (prop != null && prop.length() > 0) { int serializer_buffer_threshold = Integer.parseInt(prop); if (serializer_buffer_threshold >= 64 && serializer_buffer_threshold <= 1024 * 64) { BUFFER_THRESHOLD = serializer_buffer_threshold * 1024; } } } catch (Throwable error) { // skip } } 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); if (buf.length < BUFFER_THRESHOLD) { char[] charsLocal = bufLocal.get(); if (charsLocal == null || charsLocal.length < buf.length) { bufLocal.set(buf); } } 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); } byte[] bytesLocal = bytes; if (bytes.length < bytesLength) { bytes = new byte[bytesLength]; } int position = IOUtils.encodeUTF8(buf, 0, count, bytes); out.write(bytes, 0, position); if (bytes != bytesLocal && bytes.length <= BUFFER_THRESHOLD) { bytesBufLocal.set(bytes); } 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); } byte[] bytesLocal = 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); if (bytes != bytesLocal && bytes.length <= BUFFER_THRESHOLD) { bytesBufLocal.set(bytes); } 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 <= BUFFER_THRESHOLD) { 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; // base64 algorithm author Mikael Grev 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) { 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 (value != value || value == Float.POSITIVE_INFINITY || value == Float.NEGATIVE_INFINITY) { writeNull(); } else { int newcount = count + 15; if (newcount > buf.length) { if (writer == null) { expandCapacity(newcount); } else { String str = RyuFloat.toString(value); write(str, 0, str.length()); if (checkWriteClassName && isEnabled(SerializerFeature.WriteClassName)) { write('F'); } return; } } int len = RyuFloat.toString(value, buf, count); count += len; if (checkWriteClassName && isEnabled(SerializerFeature.WriteClassName)) { write('F'); } } } public void writeDouble(double value, boolean checkWriteClassName) { if (Double.isNaN(value) || Double.isInfinite(value)) { writeNull(); return; } int newcount = count + 24; if (newcount > buf.length) { if (writer == null) { expandCapacity(newcount); } else { String str = RyuDouble.toString(value); write(str, 0, str.length()); if (checkWriteClassName && isEnabled(SerializerFeature.WriteClassName)) { write('D'); } return; } } int len = RyuDouble.toString(value, buf, count); count += len; 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()); } } /** * @deprecated */ public void writeLongAndChar(long i, char c) throws IOException { writeLong(i); write(c); } 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 ((beanFeatures & SerializerFeature.WriteMapNullValue.mask) != 0 && (beanFeatures & ~SerializerFeature.WriteMapNullValue.mask & SerializerFeature.WRITE_MAP_NULL_FEATURES) == 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(VALUE_TRUE, 0, buf, nameEnd + 2, 5); } else { System.arraycopy(VALUE_FALSE, 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 || isEnabled(SerializerFeature.BrowserCompatible.mask) ) { 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 { int scale = value.scale(); write(isEnabled(SerializerFeature.WriteBigDecimalAsPlain) && scale >= -100 && scale < 100 ? value.toPlainString() : 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; } /** * @deprecated */ public void reset() { count = 0; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/SerializerFeature.java ================================================ /* * 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 featuresB, SerializerFeature feature) { int mask = feature.mask; return (features & mask) != 0 || (featuresB & 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]; public static final int WRITE_MAP_NULL_FEATURES = WriteMapNullValue.getMask() | WriteNullBooleanAsFalse.getMask() | WriteNullListAsEmpty.getMask() | WriteNullNumberAsZero.getMask() | WriteNullStringAsEmpty.getMask() ; } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/SimpleDateFormatSerializer.java ================================================ package com.alibaba.fastjson.serializer; import java.io.IOException; import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.Date; public class SimpleDateFormatSerializer implements ObjectSerializer { private final String pattern; public SimpleDateFormatSerializer(String pattern){ this.pattern = pattern; } public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { if (object == null) { serializer.out.writeNull(); return; } Date date = (Date) object; SimpleDateFormat format = new SimpleDateFormat(pattern, serializer.locale); format.setTimeZone(serializer.timeZone); String text = format.format(date); serializer.write(text); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/SimplePropertyPreFilter.java ================================================ 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; } } return includes.size() == 0 || includes.contains(name); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/StringCodec.java ================================================ /* * 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ToStringSerializer.java ================================================ 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/serializer/ValueFilter.java ================================================ /* * 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 extends SerializeFilter { Object process(Object object, String name, Object value); } ================================================ FILE: src/main/java/com/alibaba/fastjson/spi/Module.java ================================================ package com.alibaba.fastjson.spi; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.alibaba.fastjson.serializer.ObjectSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; public interface Module { ObjectDeserializer createDeserializer(ParserConfig config, Class type); ObjectSerializer createSerializer(SerializeConfig config, Class type); } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/config/FastJsonConfig.java ================================================ package com.alibaba.fastjson.support.config; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.ParseProcess; 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 ParseProcess * @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; /** * parseProcess */ private ParseProcess parseProcess; /** * 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; /** * The Write content length. */ private boolean writeContentLength; /** * init param. */ public FastJsonConfig() { this.charset = IOUtils.UTF8; this.serializeConfig = SerializeConfig.getGlobalInstance(); this.parserConfig = ParserConfig.getGlobalInstance(); this.serializerFeatures = new SerializerFeature[] { SerializerFeature.BrowserSecure }; this.serializeFilters = new SerializeFilter[0]; this.features = new Feature[0]; this.writeContentLength = true; } /** * @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; } /** * Is write content length boolean. * * @return the boolean */ public boolean isWriteContentLength() { return writeContentLength; } /** * Sets write content length. * * @param writeContentLength the write content length */ public void setWriteContentLength(boolean writeContentLength) { this.writeContentLength = writeContentLength; } /** * Gets parse process. * * @return the parse process */ public ParseProcess getParseProcess() { return parseProcess; } /** * Sets parse process. * * @param parseProcess the parse process */ public void setParseProcess(ParseProcess parseProcess) { this.parseProcess = parseProcess; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/geo/Feature.java ================================================ package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONType; import java.util.LinkedHashMap; import java.util.Map; /** * @since 1.2.68 */ @JSONType(typeName = "Feature", orders = {"type", "id", "bbox", "coordinates", "properties"}) public class Feature extends Geometry { private String id; private Geometry geometry; private Map properties = new LinkedHashMap(); public Feature() { super("Feature"); } public Geometry getGeometry() { return geometry; } public void setGeometry(Geometry geometry) { this.geometry = geometry; } public Map getProperties() { return properties; } public void setProperties(Map properties) { this.properties = properties; } public String getId() { return id; } public void setId(String id) { this.id = id; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/geo/FeatureCollection.java ================================================ package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONType; import java.util.ArrayList; import java.util.List; /** * @since 1.2.68 */ @JSONType(typeName = "FeatureCollection", orders = {"type", "bbox", "coordinates"}) public class FeatureCollection extends Geometry { private List features = new ArrayList(); public FeatureCollection() { super("FeatureCollection"); } public List getFeatures() { return features; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/geo/Geometry.java ================================================ package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONType; /** * @since 1.2.68 */ @JSONType(seeAlso = {GeometryCollection.class , LineString.class , MultiLineString.class , Point.class , MultiPoint.class , Polygon.class , MultiPolygon.class , Feature.class , FeatureCollection.class} , typeKey = "type") public abstract class Geometry { private final String type; private double[] bbox; protected Geometry(String type) { this.type = type; } public String getType() { return type; } public double[] getBbox() { return bbox; } public void setBbox(double[] bbox) { this.bbox = bbox; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/geo/GeometryCollection.java ================================================ package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONType; import java.util.ArrayList; import java.util.List; /** * @since 1.2.68 */ @JSONType(typeName = "GeometryCollection", orders = {"type", "bbox", "geometries"}) public class GeometryCollection extends Geometry { private List geometries = new ArrayList(); public GeometryCollection() { super("GeometryCollection"); } public List getGeometries() { return geometries; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/geo/LineString.java ================================================ package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONType; /** * @since 1.2.68 */ @JSONType(typeName = "LineString", orders = {"type", "bbox", "coordinates"}) public class LineString extends Geometry { private double[][] coordinates; public LineString() { super("LineString"); } public double[][] getCoordinates() { return coordinates; } public void setCoordinates(double[][] coordinates) { this.coordinates = coordinates; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/geo/MultiLineString.java ================================================ package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONType; /** * @since 1.2.68 */ @JSONType(typeName = "MultiLineString", orders = {"type", "bbox", "coordinates"}) public class MultiLineString extends Geometry { private double[][][] coordinates; public MultiLineString() { super("MultiLineString"); } public double[][][] getCoordinates() { return coordinates; } public void setCoordinates(double[][][] coordinates) { this.coordinates = coordinates; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/geo/MultiPoint.java ================================================ package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONType; /** * @since 1.2.68 */ @JSONType(typeName = "MultiPoint", orders = {"type", "bbox", "coordinates"}) public class MultiPoint extends Geometry { private double[][] coordinates; public MultiPoint() { super("MultiPoint"); } public double[][] getCoordinates() { return coordinates; } public void setCoordinates(double[][] coordinates) { this.coordinates = coordinates; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/geo/MultiPolygon.java ================================================ package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONType; /** * @since 1.2.68 */ @JSONType(typeName = "MultiPolygon", orders = {"type", "bbox", "coordinates"}) public class MultiPolygon extends Geometry { private double[][][][] coordinates; public MultiPolygon() { super("MultiPolygon"); } public double[][][][] getCoordinates() { return coordinates; } public void setCoordinates(double[][][][] coordinates) { this.coordinates = coordinates; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/geo/Point.java ================================================ package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; /** * @since 1.2.68 */ @JSONType(typeName = "Point", orders = {"type", "bbox", "coordinates"}) public class Point extends Geometry { private double longitude; private double latitude; public Point() { super("Point"); } public double[] getCoordinates() { return new double[] {longitude, latitude}; } public void setCoordinates(double[] coordinates) { if (coordinates == null || coordinates.length == 0) { this.longitude = 0; this.latitude = 0; return; } if (coordinates.length == 1) { this.longitude = coordinates[0]; return; } this.longitude = coordinates[0]; this.latitude = coordinates[1]; } @JSONField(serialize = false) public double getLongitude() { return longitude; } @JSONField(serialize = false) public double getLatitude() { return latitude; } @JSONField(deserialize = false) public void setLongitude(double longitude) { this.longitude = longitude; } @JSONField(deserialize = false) public void setLatitude(double latitude) { this.latitude = latitude; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/geo/Polygon.java ================================================ package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONType; /** * @since 1.2.68 */ @JSONType(typeName = "Polygon", orders = {"type", "bbox", "coordinates"}) public class Polygon extends Geometry { private double[][][] coordinates; public Polygon() { super("Polygon"); } public double[][][] getCoordinates() { return coordinates; } public void setCoordinates(double[][][] coordinates) { this.coordinates = coordinates; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/hsf/HSFJSONUtils.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/hsf/MethodLocator.java ================================================ package com.alibaba.fastjson.support.hsf; import java.lang.reflect.Method; public interface MethodLocator { Method findMethod(String[] types); } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonAutoDiscoverable.java ================================================ 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 static final String FASTJSON_AUTO_DISCOVERABLE = "fastjson.auto.discoverable"; public volatile static boolean autoDiscover = true; static { try { autoDiscover = Boolean.parseBoolean( System.getProperty(FASTJSON_AUTO_DISCOVERABLE, String.valueOf(autoDiscover))); } catch (Throwable ex) { //skip } } public void configure(final FeatureContext context) { final Configuration config = context.getConfiguration(); // Register FastJson. if (!config.isRegistered(FastJsonFeature.class) && autoDiscover) { context.register(FastJsonFeature.class); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonFeature.java ================================================ 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) { try { 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); } } catch (NoSuchMethodError e) { // skip } return true; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonProvider.java ================================================ package com.alibaba.fastjson.support.jaxrs; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.Feature; 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; } /** * Instantiates a new Fast json provider. * * @param charset the charset * @see FastJsonConfig#setCharset(Charset) * @deprecated */ @Deprecated public FastJsonProvider(String charset) { this.fastJsonConfig.setCharset(Charset.forName(charset)); } /** * Gets charset. * * @return the charset * @see FastJsonConfig#getCharset() * @deprecated */ @Deprecated public Charset getCharset() { return this.fastJsonConfig.getCharset(); } /** * Sets charset. * * @param charset the charset * @see FastJsonConfig#setCharset(Charset) * @deprecated */ @Deprecated public void setCharset(Charset charset) { this.fastJsonConfig.setCharset(charset); } /** * Gets date format. * * @return the date format * @see FastJsonConfig#getDateFormat() * @deprecated */ @Deprecated public String getDateFormat() { return this.fastJsonConfig.getDateFormat(); } /** * Sets date format. * * @param dateFormat the date format * @see FastJsonConfig#setDateFormat(String) * @deprecated */ @Deprecated public void setDateFormat(String dateFormat) { this.fastJsonConfig.setDateFormat(dateFormat); } /** * Get features serializer feature []. * * @return the serializer feature [] * @see FastJsonConfig#getFeatures() * @deprecated */ @Deprecated public SerializerFeature[] getFeatures() { return this.fastJsonConfig.getSerializerFeatures(); } /** * Sets features. * * @param features the features * @see FastJsonConfig#setFeatures(Feature...) * @deprecated */ @Deprecated public void setFeatures(SerializerFeature... features) { this.fastJsonConfig.setSerializerFeatures(features); } /** * Get filters serialize filter []. * * @return the serialize filter [] * @see FastJsonConfig#getSerializeFilters() * @deprecated */ @Deprecated public SerializeFilter[] getFilters() { return this.fastJsonConfig.getSerializeFilters(); } /** * Sets filters. * * @param filters the filters * @see FastJsonConfig#setSerializeFilters(SerializeFilter...) * @deprecated */ @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; } /** * 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 { JSON.writeJSONStringWithFastJsonConfig(entityStream, // fastJsonConfig.getCharset(), // obj, // fastJsonConfig.getSerializeConfig(), // fastJsonConfig.getSerializeFilters(), // fastJsonConfig.getDateFormat(), // JSON.DEFAULT_GENERATE_FEATURE, // fastJsonConfig.getSerializerFeatures()); entityStream.flush(); } catch (JSONException ex) { throw new WebApplicationException(ex); } } /** * 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.getParserConfig(), fastJsonConfig.getParseProcess(), JSON.DEFAULT_PARSER_FEATURE, fastJsonConfig.getFeatures()); } catch (JSONException ex) { throw new WebApplicationException(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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/moneta/MonetaCodec.java ================================================ package com.alibaba.fastjson.support.moneta; import com.alibaba.fastjson.JSONObject; 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 com.alibaba.fastjson.serializer.SerializeWriter; import org.javamoney.moneta.Money; import javax.money.Monetary; import java.io.IOException; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; public class MonetaCodec implements ObjectSerializer, ObjectDeserializer { public static final MonetaCodec instance = new MonetaCodec(); public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { Money money = (Money) object; if (money == null) { serializer.writeNull(); return; } SerializeWriter out = serializer.out; out.writeFieldValue('{', "numberStripped", money.getNumberStripped()); out.writeFieldValue(',', "currency", money.getCurrency().getCurrencyCode()); out.write('}'); } public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { JSONObject object = parser.parseObject(); Object currency = object.get("currency"); String currencyCode = null; if (currency instanceof JSONObject) { currencyCode = ((JSONObject) currency).getString("currencyCode"); } else if (currency instanceof String) { currencyCode = (String) currency; } Object numberStripped = object.get("numberStripped"); if (numberStripped instanceof BigDecimal || numberStripped instanceof Integer || numberStripped instanceof BigInteger) { return (T) Money.of((Number) numberStripped, Monetary.getCurrency(currencyCode)); } throw new UnsupportedOperationException(); } public int getFastMatchToken() { return 0; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/retrofit/Retrofit2ConverterFactory.java ================================================ 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 com.alibaba.fastjson.support.config.FastJsonConfig; 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 * @author Victor.Zxy */ public class Retrofit2ConverterFactory extends Converter.Factory { private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8"); private FastJsonConfig fastJsonConfig; @Deprecated private static final Feature[] EMPTY_SERIALIZER_FEATURES = new Feature[0]; @Deprecated private ParserConfig parserConfig = ParserConfig.getGlobalInstance(); @Deprecated private int featureValues = JSON.DEFAULT_PARSER_FEATURE; @Deprecated private Feature[] features; @Deprecated private SerializeConfig serializeConfig; @Deprecated private SerializerFeature[] serializerFeatures; public Retrofit2ConverterFactory() { this.fastJsonConfig = new FastJsonConfig(); } public Retrofit2ConverterFactory(FastJsonConfig fastJsonConfig) { this.fastJsonConfig = fastJsonConfig; } public static Retrofit2ConverterFactory create() { return create(new FastJsonConfig()); } public static Retrofit2ConverterFactory create(FastJsonConfig fastJsonConfig) { if (fastJsonConfig == null) throw new NullPointerException("fastJsonConfig == null"); return new Retrofit2ConverterFactory(fastJsonConfig); } @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 FastJsonConfig getFastJsonConfig() { return fastJsonConfig; } public Retrofit2ConverterFactory setFastJsonConfig(FastJsonConfig fastJsonConfig) { this.fastJsonConfig = fastJsonConfig; return this; } /** * Gets parser config. * * @return the parser config * @see FastJsonConfig#getParserConfig() * @deprecated */ @Deprecated public ParserConfig getParserConfig() { return fastJsonConfig.getParserConfig(); } /** * Sets parser config. * * @param config the config * @return the parser config * @see FastJsonConfig#setParserConfig(ParserConfig) * @deprecated */ @Deprecated public Retrofit2ConverterFactory setParserConfig(ParserConfig config) { fastJsonConfig.setParserConfig(config); return this; } /** * Gets parser feature values. * * @return the parser feature values * @see JSON#DEFAULT_PARSER_FEATURE * @deprecated */ @Deprecated public int getParserFeatureValues() { return JSON.DEFAULT_PARSER_FEATURE; } /** * Sets parser feature values. * * @param featureValues the feature values * @return the parser feature values * @see JSON#DEFAULT_PARSER_FEATURE * @deprecated */ @Deprecated public Retrofit2ConverterFactory setParserFeatureValues(int featureValues) { return this; } /** * Get parser features feature []. * * @return the feature [] * @see FastJsonConfig#getFeatures() * @deprecated */ @Deprecated public Feature[] getParserFeatures() { return fastJsonConfig.getFeatures(); } /** * Sets parser features. * * @param features the features * @return the parser features * @see FastJsonConfig#setFeatures(Feature...) * @deprecated */ @Deprecated public Retrofit2ConverterFactory setParserFeatures(Feature[] features) { fastJsonConfig.setFeatures(features); return this; } /** * Gets serialize config. * * @return the serialize config * @see FastJsonConfig#getSerializeConfig() * @deprecated */ @Deprecated public SerializeConfig getSerializeConfig() { return fastJsonConfig.getSerializeConfig(); } /** * Sets serialize config. * * @param serializeConfig the serialize config * @return the serialize config * @see FastJsonConfig#setSerializeConfig(SerializeConfig) * @deprecated */ @Deprecated public Retrofit2ConverterFactory setSerializeConfig(SerializeConfig serializeConfig) { fastJsonConfig.setSerializeConfig(serializeConfig); return this; } /** * Get serializer features serializer feature []. * * @return the serializer feature [] * @see FastJsonConfig#getSerializerFeatures() * @deprecated */ @Deprecated public SerializerFeature[] getSerializerFeatures() { return fastJsonConfig.getSerializerFeatures(); } /** * Sets serializer features. * * @param features the features * @return the serializer features * @see FastJsonConfig#setSerializerFeatures(SerializerFeature...) * @deprecated */ @Deprecated public Retrofit2ConverterFactory setSerializerFeatures(SerializerFeature[] features) { fastJsonConfig.setSerializerFeatures(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.bytes() , fastJsonConfig.getCharset() , type , fastJsonConfig.getParserConfig() , fastJsonConfig.getParseProcess() , JSON.DEFAULT_PARSER_FEATURE , fastJsonConfig.getFeatures() ); } catch (Exception e) { throw new IOException("JSON parse error: " + e.getMessage(), e); } finally { value.close(); } } } final class RequestBodyConverter implements Converter { RequestBodyConverter() { } public RequestBody convert(T value) throws IOException { try { byte[] content = JSON.toJSONBytesWithFastJsonConfig(fastJsonConfig.getCharset() , value , fastJsonConfig.getSerializeConfig() , fastJsonConfig.getSerializeFilters() , fastJsonConfig.getDateFormat() , JSON.DEFAULT_GENERATE_FEATURE , fastJsonConfig.getSerializerFeatures() ); return RequestBody.create(MEDIA_TYPE, content); } catch (Exception e) { throw new IOException("Could not write JSON: " + e.getMessage(), e); } } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/FastJsonContainer.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/FastJsonHttpMessageConverter.java ================================================ 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.ParameterizedTypeImpl; 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"); @Deprecated protected SerializerFeature[] features = new SerializerFeature[0]; @Deprecated protected SerializeFilter[] filters = new SerializeFilter[0]; @Deprecated protected String dateFormat; private boolean setLengthError = false; /** * 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); } /** * Gets charset. * * @return the charset * @see FastJsonConfig#getCharset() * @deprecated */ @Deprecated public Charset getCharset() { return this.fastJsonConfig.getCharset(); } /** * Sets charset. * * @param charset the charset * @see FastJsonConfig#setCharset(Charset) * @deprecated */ @Deprecated public void setCharset(Charset charset) { this.fastJsonConfig.setCharset(charset); } /** * Gets date format. * * @return the date format * @see FastJsonConfig#getDateFormat() * @deprecated */ @Deprecated public String getDateFormat() { return this.fastJsonConfig.getDateFormat(); } /** * Sets date format. * * @param dateFormat the date format * @see FastJsonConfig#setDateFormat(String) * @deprecated */ @Deprecated public void setDateFormat(String dateFormat) { this.fastJsonConfig.setDateFormat(dateFormat); } /** * Get features serializer feature []. * * @return the serializer feature [] * @see FastJsonConfig#getSerializerFeatures() * @deprecated */ @Deprecated public SerializerFeature[] getFeatures() { return this.fastJsonConfig.getSerializerFeatures(); } /** * Sets features. * * @param features the features * @see FastJsonConfig#setSerializerFeatures(SerializerFeature...) * @deprecated */ @Deprecated public void setFeatures(SerializerFeature... features) { this.fastJsonConfig.setSerializerFeatures(features); } /** * Get filters serialize filter []. * * @return the serialize filter [] * @see FastJsonConfig#getSerializeFilters() * @deprecated */ @Deprecated public SerializeFilter[] getFilters() { return this.fastJsonConfig.getSerializeFilters(); } /** * Sets filters. * * @param filters the filters * @see FastJsonConfig#setSerializeFilters(SerializeFilter...) * @deprecated */ @Deprecated public void setFilters(SerializeFilter... filters) { this.fastJsonConfig.setSerializeFilters(filters); } /** * Add serialize filter. * * @param filter the filter * @see FastJsonConfig#setSerializeFilters(SerializeFilter...) * @deprecated */ @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) { try { InputStream in = inputMessage.getBody(); return JSON.parseObject(in, fastJsonConfig.getCharset(), type, fastJsonConfig.getParserConfig(), fastJsonConfig.getParseProcess(), JSON.DEFAULT_PARSER_FEATURE, 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.writeJSONStringWithFastJsonConfig(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() && !setLengthError) { try { headers.setContentLength(len); } catch (UnsupportedOperationException ex) { // skip setLengthError = true; } } 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); } /** * 如果type的实例不是com.alibaba.fastjson.util.ParameterizedTypeImpl,则需进行转换。 * 避免触发fastjson中因无法命中泛型缓存导致不断生成反序列化器引起的fullgc问题 */ if (type instanceof ParameterizedType && !(type instanceof ParameterizedTypeImpl)) { type = handlerParameterizedType((ParameterizedType) type); } return type; } private Type handlerParameterizedType(ParameterizedType type) { Type ownerType = type.getOwnerType(); Type rawType = type.getRawType(); Type[] argTypes = type.getActualTypeArguments(); for(int i = 0; i < argTypes.length; ++i) { if (argTypes[i] instanceof ParameterizedType) { argTypes[i] = handlerParameterizedType((ParameterizedType)argTypes[i]); } } Type key = new ParameterizedTypeImpl(argTypes, ownerType, rawType); return key; } 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; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/FastJsonHttpMessageConverter4.java ================================================ 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/FastJsonJsonView.java ================================================ 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.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.HashMap; import java.util.Map; import java.util.Set; 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; } /** * Sets serializer feature. * * @param features the features * @see FastJsonConfig#setSerializerFeatures(SerializerFeature...) * @deprecated */ @Deprecated public void setSerializerFeature(SerializerFeature... features) { this.fastJsonConfig.setSerializerFeatures(features); } /** * Gets charset. * * @return the charset * @see FastJsonConfig#getCharset() * @deprecated */ @Deprecated public Charset getCharset() { return this.fastJsonConfig.getCharset(); } /** * Sets charset. * * @param charset the charset * @see FastJsonConfig#setCharset(Charset) * @deprecated */ @Deprecated public void setCharset(Charset charset) { this.fastJsonConfig.setCharset(charset); } /** * Gets date format. * * @return the date format * @see FastJsonConfig#getDateFormat() * @deprecated */ @Deprecated public String getDateFormat() { return this.fastJsonConfig.getDateFormat(); } /** * Sets date format. * * @param dateFormat the date format * @see FastJsonConfig#setDateFormat(String) * @deprecated */ @Deprecated public void setDateFormat(String dateFormat) { this.fastJsonConfig.setDateFormat(dateFormat); } /** * Get features serializer feature []. * * @return the serializer feature [] * @see FastJsonConfig#getSerializerFeatures() * @deprecated */ @Deprecated public SerializerFeature[] getFeatures() { return this.fastJsonConfig.getSerializerFeatures(); } /** * Sets features. * * @param features the features * @see FastJsonConfig#setSerializerFeatures(SerializerFeature...) * @deprecated */ @Deprecated public void setFeatures(SerializerFeature... features) { this.fastJsonConfig.setSerializerFeatures(features); } /** * Get filters serialize filter []. * * @return the serialize filter [] * @see FastJsonConfig#getSerializeFilters() * @deprecated */ @Deprecated public SerializeFilter[] getFilters() { return this.fastJsonConfig.getSerializeFilters(); } /** * Sets filters. * * @param filters the filters * @see FastJsonConfig#setSerializeFilters(SerializeFilter...) * @deprecated */ @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". * * @see JSONP Wikipedia article * @since 4.1 */ 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.writeJSONStringWithFastJsonConfig(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); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/FastJsonRedisSerializer.java ================================================ 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 * @author Victor.Zxy * @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.toJSONBytesWithFastJsonConfig( fastJsonConfig.getCharset(), t, fastJsonConfig.getSerializeConfig(), fastJsonConfig.getSerializeFilters(), fastJsonConfig.getDateFormat(), JSON.DEFAULT_GENERATE_FEATURE, 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, fastJsonConfig.getCharset(), type, fastJsonConfig.getParserConfig(), fastJsonConfig.getParseProcess(), JSON.DEFAULT_PARSER_FEATURE, fastJsonConfig.getFeatures() ); } catch (Exception ex) { throw new SerializationException("Could not deserialize: " + ex.getMessage(), ex); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/FastJsonViewResponseBodyAdvice.java ================================================ 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/FastJsonpHttpMessageConverter4.java ================================================ 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/FastJsonpResponseBodyAdvice.java ================================================ 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"); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/FastjsonSockJsMessageCodec.java ================================================ 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(); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/GenericFastJsonRedisSerializer.java ================================================ 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); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/JSONPResponseBodyAdvice.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/MappingFastJsonValue.java ================================================ 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(')'); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/PropertyPreFilters.java ================================================ 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; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonFilter.java ================================================ 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(); } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonView.java ================================================ 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 {}; } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/annotation/ResponseJSONP.java ================================================ 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"; } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/spring/messaging/MappingFastJsonMessageConverter.java ================================================ 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 * @author Victor.Zxy * @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, fastJsonConfig.getCharset(), targetClass, fastJsonConfig.getParserConfig(), fastJsonConfig.getParseProcess(), JSON.DEFAULT_PARSER_FEATURE, fastJsonConfig.getFeatures()); } else if (payload instanceof String) { obj = JSON.parseObject((String) payload, targetClass, fastJsonConfig.getParserConfig(), fastJsonConfig.getParseProcess(), JSON.DEFAULT_PARSER_FEATURE, fastJsonConfig.getFeatures()); } return obj; } @Override protected Object convertToInternal(Object payload, MessageHeaders headers, Object conversionHint) { // encode payload to json string or byte[] Object obj; if (byte[].class == getSerializedPayloadClass()) { if (payload instanceof String && JSON.isValid((String) payload)) { obj = ((String) payload).getBytes(fastJsonConfig.getCharset()); } else { obj = JSON.toJSONBytesWithFastJsonConfig(fastJsonConfig.getCharset(), payload, fastJsonConfig.getSerializeConfig(), fastJsonConfig.getSerializeFilters(), fastJsonConfig.getDateFormat(), JSON.DEFAULT_GENERATE_FEATURE, fastJsonConfig.getSerializerFeatures()); } } else { if (payload instanceof String && JSON.isValid((String) payload)) { obj = payload; } else { obj = JSON.toJSONString(payload, fastJsonConfig.getSerializeConfig(), fastJsonConfig.getSerializeFilters(), fastJsonConfig.getDateFormat(), JSON.DEFAULT_GENERATE_FEATURE, fastJsonConfig.getSerializerFeatures()); } } return obj; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/support/springfox/SwaggerJsonSerializer.java ================================================ 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); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/ASMClassLoader.java ================================================ 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(getParentClassLoader()); } public ASMClassLoader(ClassLoader parent){ super (parent); } 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(); } protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { Class mappingClass = classMapping.get(name); if (mappingClass != null) { return mappingClass; } try { return super.loadClass(name, resolve); } catch (ClassNotFoundException e) { 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/ASMUtils.java ================================================ 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 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(desc(types[i])); } buf.append(')'); buf.append(desc(method.getReturnType())); return buf.toString(); } public static String desc(Class returnType) { if (returnType.isPrimitive()) { return getPrimitiveLetter(returnType); } else if (returnType.isArray()) { return "[" + desc(returnType.getComponentType()); } else { return "L" + type(returnType) + ";"; } } public static String type(Class parameterType) { if (parameterType.isArray()) { return "[" + desc(parameterType.getComponentType()); } else { if (!parameterType.isPrimitive()) { String clsName = parameterType.getName(); return clsName.replace('.', '/'); // 直接基于字符串替换,不使用正则替换 } else { return getPrimitiveLetter(parameterType); } } } public static String getPrimitiveLetter(Class type) { if (Integer.TYPE == type) { return "I"; } else if (Void.TYPE == type) { return "V"; } else if (Boolean.TYPE == type) { return "Z"; } else if (Character.TYPE == type) { return "C"; } else if (Byte.TYPE == type) { return "B"; } else if (Short.TYPE == type) { return "S"; } else if (Float.TYPE == type) { return "F"; } else if (Long.TYPE == type) { return "J"; } 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 = TypeUtils.getParameterAnnotations(method); } else { Constructor constructor = (Constructor) methodOrCtor; types = constructor.getParameterTypes(); declaringClass = constructor.getDeclaringClass(); name = ""; parameterAnnotations = TypeUtils.getParameterAnnotations(constructor); } 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, false); 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); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/AntiCollisionHashMap.java ================================================ 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; 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; 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; 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; 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(); return (v1 == v2 || (v1 != null && v1.equals(v2))); } return false; } public final int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public final String toString() { return getKey() + "=" + getValue(); } } /** * 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); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/Base64.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/BiFunction.java ================================================ package com.alibaba.fastjson.util; public interface BiFunction { /** * Applies this function to the given arguments. * * @param t the first function argument * @param u the second function argument * @return the function result */ R apply(T t, U u); } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/FieldInfo.java ================================================ 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.Map; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.annotation.JSONField; public class FieldInfo implements Comparable { 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 final long nameHashCode; public FieldInfo(String name, // Class declaringClass, // Class fieldClass, // Type fieldType, // Field field, // int ordinal, // int serialzeFeatures, // int parserFeatures){ if (ordinal < 0) { ordinal = 0; } 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(); if (field != null) { TypeUtils.setAccessible(field); } this.label = ""; fieldAnnotation = field == null ? null : TypeUtils.getAnnotation(field, JSONField.class); methodAnnotation = null; this.getOnly = false; this.jsonDirect = false; this.unwrapped = false; this.format = null; this.alternateNames = new String[0]; nameHashCode = nameHashCode64(name, fieldAnnotation); } public FieldInfo(String name, // Method method, // Field field, // Class clazz, // Type type, // int ordinal, // int serialzeFeatures, // int parserFeatures, // JSONField fieldAnnotation, // JSONField methodAnnotation, // String label){ this(name, method, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, fieldAnnotation, methodAnnotation, label, null); } public FieldInfo(String name, // Method method, // Field field, // Class clazz, // Type type, // int ordinal, // int serialzeFeatures, // int parserFeatures, // JSONField fieldAnnotation, // JSONField methodAnnotation, // String label, Map genericInfo){ if (field != null) { String fieldName = field.getName(); if (fieldName.equals(name)) { name = fieldName; } } if (ordinal < 0) { ordinal = 0; } 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 = TypeUtils.isTransient(method); } if (label != null && label.length() > 0) { this.label = label; } else { this.label = ""; } String format = null; JSONField annotation = getAnnotation(); nameHashCode = nameHashCode64(name, annotation); 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 { 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, genericInfo); if (genericFieldType != fieldType) { if (genericFieldType instanceof ParameterizedType) { fieldClass = TypeUtils.getClass(genericFieldType); } else if (genericFieldType instanceof Class) { fieldClass = TypeUtils.getClass(genericFieldType); } } } this.fieldType = genericFieldType; this.fieldClass = fieldClass; isEnum = fieldClass.isEnum(); } private long nameHashCode64(String name, JSONField annotation) { if (annotation != null && annotation.name().length() != 0) { return TypeUtils.fnv1a_64_lower(name); } return TypeUtils.fnv1a_64_extract(name); } 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 = TypeUtils.getAnnotation(method, annotationClass); } if (annotatition == null && field != null) { annotatition = TypeUtils.getAnnotation(field, annotationClass); } return annotatition; } public static Type getFieldType(final Class clazz, final Type type, Type fieldType){ return getFieldType(clazz, type, fieldType, null); } public static Type getFieldType(final Class clazz, final Type type, Type fieldType, Map genericInfo) { 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, genericInfo); 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; boolean changed = getArgument(arguments, genericInfo); //if genericInfo is not working use the old path; if(!changed){ 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(); } changed = getArgument(arguments, typeVariables, paramType.getActualTypeArguments()); } if (changed) { fieldType = TypeReference.intern( new ParameterizedTypeImpl(arguments, parameterizedFieldType.getOwnerType(), parameterizedFieldType.getRawType()) ); return fieldType; } } return fieldType; } private static boolean getArgument(Type[] typeArgs, Map genericInfo){ if(genericInfo == null || genericInfo.size() == 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, genericInfo); if (p_changed) { typeArgs[i] = TypeReference.intern( new ParameterizedTypeImpl(p_typeArg_args, p_typeArg.getOwnerType(), p_typeArg.getRawType()) ); changed = true; } } else if (typeArg instanceof TypeVariable) { if (genericInfo.containsKey(typeArg)) { typeArgs[i] = genericInfo.get(typeArg); changed = true; } } } return changed; } 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] = TypeReference.intern( 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; } 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 String toString() { return this.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 int compareTo(FieldInfo o) { // Deal extend bridge if (o.method != null && this.method != null && o.method.isBridge() && !this.method.isBridge() && o.method.getName().equals(this.method.getName())) { return 1; } if (this.ordinal < o.ordinal) { return -1; } 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; } TypeUtils.setAccessible(field); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/Function.java ================================================ package com.alibaba.fastjson.util; public interface Function { /** * Computes a result * * @return computed result */ V apply(ARG arg); } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/GenericArrayTypeImpl.java ================================================ package com.alibaba.fastjson.util; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Type; public class GenericArrayTypeImpl implements GenericArrayType { private final Type genericComponentType; public GenericArrayTypeImpl(Type genericComponentType) { assert genericComponentType != null; this.genericComponentType = genericComponentType; } @Override public Type getGenericComponentType() { return this.genericComponentType; } @Override public String toString() { Type genericComponentType = this.getGenericComponentType(); StringBuilder builder = new StringBuilder(); if (genericComponentType instanceof Class) { builder.append(((Class) genericComponentType).getName()); } else { builder.append(genericComponentType.toString()); } builder.append("[]"); return builder.toString(); } @Override public boolean equals(Object obj) { if (obj instanceof GenericArrayType) { GenericArrayType that = (GenericArrayType) obj; return this.genericComponentType.equals(that.getGenericComponentType()); } return false; } @Override public int hashCode() { return this.genericComponentType.hashCode(); } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/IOUtils.java ================================================ /* * 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 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[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]; public final static boolean[] identifierFlags = 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; } } 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; } } 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) { long p = 10; for (int i = 1; i < 19; i++) { if (x < p) return i; p = 10 * p; } return 19; } public static void getChars(long i, int index, char[] buf) { long q; int r; int charPos = index; char sign = 0; if (i < 0) { sign = '-'; i = -i; } // Get 2 digits/iteration using longs until quotient fits into an int while (i > Integer.MAX_VALUE) { q = i / 100; // really: r = i - (q * 100); r = (int) (i - ((q << 6) + (q << 5) + (q << 2))); i = q; buf[--charPos] = DigitOnes[r]; buf[--charPos] = DigitTens[r]; } // Get 2 digits/iteration using ints int q2; int i2 = (int) i; while (i2 >= 65536) { q2 = i2 / 100; // really: r = i2 - (q * 100); r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2)); i2 = q2; buf[--charPos] = DigitOnes[r]; buf[--charPos] = DigitTens[r]; } // Fall thru to fast mode for smaller numbers // assert(i2 <= 65536, i2); for (;;) { q2 = (i2 * 52429) >>> (16 + 3); r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ... buf[--charPos] = digits[r]; i2 = q2; if (i2 == 0) break; } if (sign != 0) { buf[--charPos] = sign; } } /** * Places characters representing the integer i into the character array buf. The characters are placed into the * buffer backwards starting with the least significant digit at the specified index (exclusive), and working * backwards from there. Will fail if i == Integer.MIN_VALUE */ public static void getChars(int i, int index, char[] buf) { int q, r, p = index; char sign = 0; if (i < 0) { sign = '-'; i = -i; } while (i >= 65536) { q = i / 100; // really: r = i - (q * 100); r = i - ((q << 6) + (q << 5) + (q << 2)); i = q; buf[--p] = DigitOnes[r]; buf[--p] = DigitTens[r]; } // Fall thru to fast mode for smaller numbers // assert(i <= 65536, i); for (;;) { q = (i * 52429) >>> (16 + 3); r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... buf[--p] = digits[r]; i = q; if (i == 0) break; } if (sign != 0) { buf[--p] = sign; } } public static void getChars(byte b, int index, char[] buf) { int i = b; int q, r; int charPos = index; char sign = 0; if (i < 0) { sign = '-'; i = -i; } // Fall thru to fast mode for smaller numbers // assert(i <= 65536, i); for (;;) { q = (i * 52429) >>> (16 + 3); r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... buf[--charPos] = digits[r]; i = q; if (i == 0) break; } if (sign != 0) { buf[--charPos] = sign; } } /** * 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[] 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 int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE }; // Requires positive x public static int stringSize(int x) { for (int i = 0;; i++) { if (x <= sizeTable[i]) { return i + 1; } } } public static void decode(CharsetDecoder charsetDecoder, ByteBuffer byteBuf, CharBuffer charByte) { try { CoderResult cr = charsetDecoder.decode(byteBuf, charByte, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = charsetDecoder.flush(charByte); if (!cr.isUnderflow()) { cr.throwException(); } } catch (CharacterCodingException x) { // Substitution is always enabled, // so this shouldn't happen 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.
* * @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11 * @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; } /** * @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11 */ 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.
* * @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11 * @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 (c >= '\uD800' && c < ('\uDBFF' + 1)) { // Character.isHighSurrogate(c) if (sl - ip < 2) { uc = -1; } else { char d = chars[ip + 1]; // d >= '\uDC00' && d < ('\uDFFF' + 1) if (d >= '\uDC00' && d < ('\uDFFF' + 1)) { // Character.isLowSurrogate(d) uc = ((c << 10) + d) + (0x010000 - ('\uD800' << 10) - '\uDC00'); // Character.toCodePoint(c, d) } else { // throw new JSONException("encodeUTF8 error", new MalformedInputException(1)); bytes[dp++] = (byte) '?'; continue; } } } else { // if (c >= '\uDC00' && c < ('\uDFFF' + 1)) { // Character.isLowSurrogate(c) bytes[dp++] = (byte) '?'; continue; // 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 >= '\uD800' && c < ('\uDFFF' + 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 !(uc >= 0x010000 && uc < 0X10FFFF + 1) // !Character.isSupplementaryCodePoint(uc) ) { return -1; } else { da[dp++] = (char) ((uc >>> 10) + ('\uD800' - (0x010000 >>> 10))); // Character.highSurrogate(uc); da[dp++] = (char) ((uc & 0x3ff) + '\uDC00'); // 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/IdentityHashMap.java ================================================ /* * 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 java.util.Arrays; /** * for concurrent IdentityHashMap * * @author wenshao[szujobs@hotmail.com] */ @SuppressWarnings("unchecked") public class IdentityHashMap { private final Entry[] buckets; private final int indexMask; public final static int DEFAULT_SIZE = 8192; public IdentityHashMap(){ this(DEFAULT_SIZE); } public IdentityHashMap(int tableSize){ this.indexMask = tableSize - 1; this.buckets = new Entry[tableSize]; } public final V get(K key) { 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) { return (V) entry.value; } } return null; } 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; } } Entry entry = new Entry(key, value, hash, buckets[bucket]); buckets[bucket] = entry; // 并发是处理时会可能导致缓存丢失,但不影响正确性 return false; } protected static final class Entry { public final int hashCode; public final K key; public V value; public final Entry next; public Entry(K key, V value, int hash, Entry next){ this.key = key; this.value = value; this.next = next; this.hashCode = hash; } } public void clear() { Arrays.fill(this.buckets, null); } public int size() { int count = 0; for (Entry bucket : this.buckets) { for (; bucket != null; bucket = bucket.next) { count++; } } return count; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/JavaBeanInfo.java ================================================ package com.alibaba.fastjson.util; import java.lang.annotation.Annotation; import java.lang.reflect.*; 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.JSON; 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 boolean kotlin; public Constructor kotlinDefaultConstructor; 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(); kotlin = TypeUtils.isKotlin(clazz); if (kotlin) { this.creatorConstructorParameters = TypeUtils.getKoltinConstructorParameters(clazz); try { this.kotlinDefaultConstructor = clazz.getConstructor(); } catch (Throwable ex) { // skip } Annotation[][] paramAnnotationArrays = TypeUtils.getParameterAnnotations(creatorConstructor); 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.set(i, field); return true; } int result = item.compareTo(field); if (result < 0) { fieldList.set(i, field); return true; } 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, false); } private static Map buildGenericInfo(Class clazz) { Class childClass = clazz; Class currentClass = clazz.getSuperclass(); if (currentClass == null) { return null; } Map typeVarMap = null; //analyse the whole generic info from the class inheritance for (; currentClass != null && currentClass != Object.class; childClass = currentClass, currentClass = currentClass.getSuperclass()) { if (childClass.getGenericSuperclass() instanceof ParameterizedType) { Type[] childGenericParentActualTypeArgs = ((ParameterizedType) childClass.getGenericSuperclass()).getActualTypeArguments(); TypeVariable[] currentTypeParameters = currentClass.getTypeParameters(); for (int i = 0; i < childGenericParentActualTypeArgs.length; i++) { //if the child class's generic super class actual args is defined in the child class type parameters if (typeVarMap == null) { typeVarMap = new HashMap(); } if (typeVarMap.containsKey(childGenericParentActualTypeArgs[i])) { Type actualArg = typeVarMap.get(childGenericParentActualTypeArgs[i]); typeVarMap.put(currentTypeParameters[i], actualArg); } else { typeVarMap.put(currentTypeParameters[i], childGenericParentActualTypeArgs[i]); } } } } return typeVarMap; } public static JavaBeanInfo build(Class clazz // , Type type // , PropertyNamingStrategy propertyNamingStrategy // , boolean fieldBased // , boolean compatibleWithJavaBean ) { return build(clazz, type, propertyNamingStrategy, fieldBased, compatibleWithJavaBean, false); } public static JavaBeanInfo build(Class clazz // , Type type // , PropertyNamingStrategy propertyNamingStrategy // , boolean fieldBased // , boolean compatibleWithJavaBean , boolean jacksonCompatible ) { 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(); Map genericInfo = buildGenericInfo(clazz); 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); } if (defaultConstructor != null) { TypeUtils.setAccessible(defaultConstructor); } 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) { Type mixInType = JSON.getMixInAnnotations(clazz); if (mixInType instanceof Class) { Constructor[] mixInConstructors = ((Class) mixInType).getConstructors(); Constructor mixInCreator = getCreatorConstructor(mixInConstructors); if (mixInCreator != null) { try { creatorConstructor = clazz.getConstructor(mixInCreator.getParameterTypes()); } catch (NoSuchMethodException e) { // skip } } } if (creatorConstructor == null) { creatorConstructor = getCreatorConstructor(constructors); } if (creatorConstructor != null && !isInterfaceOrAbstract) { // 基于标记 JSONCreator 注解的构造方法 TypeUtils.setAccessible(creatorConstructor); Class[] types = creatorConstructor.getParameterTypes(); String[] lookupParameterNames = null; if (types.length > 0) { Annotation[][] paramAnnotationArrays = TypeUtils.getParameterAnnotations(creatorConstructor); for (int i = 0; i < types.length && i < paramAnnotationArrays.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]; } if (field == null) { if (lookupParameterNames == null) { if (kotlin) { lookupParameterNames = TypeUtils.getKoltinConstructorParameters(clazz); } else { lookupParameterNames = ASMUtils.lookupParameterNames(creatorConstructor); } } if (lookupParameterNames.length > i) { String parameterName = lookupParameterNames[i]; field = TypeUtils.getField(clazz, parameterName, declaredFields); } } 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, jacksonCompatible)) != null) { TypeUtils.setAccessible(factoryMethod); String[] lookupParameterNames = null; Class[] types = factoryMethod.getParameterTypes(); if (types.length > 0) { Annotation[][] paramAnnotationArrays = TypeUtils.getParameterAnnotations(factoryMethod); 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 && !(jacksonCompatible && TypeUtils.isJacksonCreator(factoryMethod))) { throw new JSONException("illegal json creator"); } String fieldName = null; int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; if (fieldAnnotation != null) { fieldName = fieldAnnotation.name(); ordinal = fieldAnnotation.ordinal(); serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); } if (fieldName == null || fieldName.length() == 0) { if (lookupParameterNames == null) { lookupParameterNames = ASMUtils.lookupParameterNames(factoryMethod); } fieldName = lookupParameterNames[i]; } Class fieldClass = types[i]; Type fieldType = factoryMethod.getGenericParameterTypes()[i]; Field field = TypeUtils.getField(clazz, fieldName, declaredFields); FieldInfo fieldInfo = new FieldInfo(fieldName, 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.getKotlinConstructor(constructors, paramNames); 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; } else { continue; } } 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; } else { continue; } } if (className.equals("org.springframework.security.core.authority.SimpleGrantedAuthority")) { if (parameterTypes.length == 1 && parameterTypes[0] == String.class) { creatorConstructor = constructor; paramNames = new String[] {"authority"}; break; } else { continue; } } // 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 = TypeUtils.getParameterAnnotations(creatorConstructor); 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 = TypeUtils.getAnnotation(field, 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 = TypeUtils.getAnnotation(builderClass, JSONPOJOBuilder.class); if (builderAnno != null) { withPrefix = builderAnno.withPrefix(); } if (withPrefix == null) { 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 = TypeUtils.getAnnotation(method, 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, genericInfo)); continue; } } String methodName = method.getName(); StringBuilder properNameBuilder; if (methodName.startsWith("set") && methodName.length() > 3) { properNameBuilder = new StringBuilder(methodName.substring(3)); } else { if (withPrefix.length() == 0){ properNameBuilder = new StringBuilder(methodName); } 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 (withPrefix.length() != 0 && !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, genericInfo)); } if (builderClass != null) { JSONPOJOBuilder builderAnnotation = TypeUtils.getAnnotation(builderClass, 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 = TypeUtils.getAnnotation(method, 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, genericInfo)); 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, genericInfo)); continue; } } if (annotation == null && !methodName.startsWith("set") || builderClass != null) { // TODO "set"的判断放在 JSONField 注解后面,意思是允许非 setter 方法标记 JSONField 注解? continue; } char c3 = methodName.charAt(3); String propertyName; Field field = null; // 用于存储KotlinBean中所有的get方法, 方便后续判断 List getMethodNameList = null; if (kotlin) { getMethodNameList = new ArrayList(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().startsWith("get")) { getMethodNameList.add(methods[i].getName()); } } } if (Character.isUpperCase(c3) // || c3 > 512 // for unicode method name ) { // 这里本身的逻辑是通过setAbc这类方法名解析出成员变量名为abc或者Abc, 但是在kotlin中, isAbc, abc成员变量的set方法都是setAbc // 因此如果是kotlin的话还需要进行不一样的判断, 判断的方式是通过get方法进行判断, isAbc的get方法名为isAbc(), abc的get方法名为getAbc() if (kotlin) { String getMethodName = "g" + methodName.substring(1); propertyName = TypeUtils.getPropertyNameByMethodName(getMethodName); } else { if (TypeUtils.compatibleWithJavaBean) { propertyName = TypeUtils.decapitalize(methodName.substring(3)); } else { propertyName = TypeUtils.getPropertyNameByMethodName(methodName); } } } else if (c3 == '_') { // 这里本身的逻辑是通过set_abc这类方法名解析出成员变量名为abc, 但是在kotlin中, is_abc和_abc成员变量的set方法都是set_abc // 因此如果是kotlin的话还需要进行不一样的判断, 判断的方式是通过get方法进行判断, is_abc的get方法名为is_abc(), _abc的get方法名为get_abc() if (kotlin) { String getMethodName = "g" + methodName.substring(1); if (getMethodNameList.contains(getMethodName)) { propertyName = methodName.substring(3); } else { propertyName = "is" + methodName.substring(3); } field = TypeUtils.getField(clazz, propertyName, declaredFields); } else { propertyName = methodName.substring(4); field = TypeUtils.getField(clazz, propertyName, declaredFields); if (field == null) { String temp = propertyName; propertyName = methodName.substring(3); field = TypeUtils.getField(clazz, propertyName, declaredFields); if (field == null) { propertyName = temp; //减少修改代码带来的影响 } } } } 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 { propertyName = methodName.substring(3); field = TypeUtils.getField(clazz, propertyName, declaredFields); if (field == null) { continue; } } if (field == null) { 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 = TypeUtils.getAnnotation(field, 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, genericInfo)); continue; } } } if (propertyNamingStrategy != null) { propertyName = propertyNamingStrategy.translate(propertyName); } add(fieldList, new FieldInfo(propertyName, method, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, fieldAnnotation, null, genericInfo)); } 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; Field collectionField = null; JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class); if (annotation != null && annotation.deserialize()) { continue; } if (annotation != null && annotation.name().length() > 0) { propertyName = annotation.name(); } else { propertyName = TypeUtils.getPropertyNameByMethodName(methodName); Field field = TypeUtils.getField(clazz, propertyName, declaredFields); if (field != null) { JSONField fieldAnnotation = TypeUtils.getAnnotation(field, JSONField.class); if (fieldAnnotation != null && !fieldAnnotation.deserialize()) { continue; } if (Collection.class.isAssignableFrom(method.getReturnType()) || Map.class.isAssignableFrom(method.getReturnType())) { collectionField = field; } } } if (propertyNamingStrategy != null) { propertyName = propertyNamingStrategy.translate(propertyName); } FieldInfo fieldInfo = getField(fieldList, propertyName); if (fieldInfo != null) { continue; } add(fieldList, new FieldInfo(propertyName, method, collectionField, clazz, type, 0, 0, 0, annotation, null, null, genericInfo)); } } } if (fieldList.size() == 0) { if (TypeUtils.isXmlField(clazz)) { fieldBased = true; } if (fieldBased) { for (Class currentClass = clazz; currentClass != null; currentClass = currentClass.getSuperclass()) { computeFields(clazz, type, propertyNamingStrategy, fieldList, declaredFields); } } } 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) { Map genericInfo = buildGenericInfo(clazz); 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 = TypeUtils.getAnnotation(field, 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, genericInfo)); } } 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 = TypeUtils.getParameterAnnotations(constructor); 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; } } return creatorConstructor; } private static Method getFactoryMethod(Class clazz, Method[] methods, boolean jacksonCompatible) { Method factoryMethod = null; for (Method method : methods) { if (!Modifier.isStatic(method.getModifiers())) { continue; } if (!clazz.isAssignableFrom(method.getReturnType())) { continue; } JSONCreator annotation = TypeUtils.getAnnotation(method, JSONCreator.class); if (annotation != null) { if (factoryMethod != null) { throw new JSONException("multi-JSONCreator"); } factoryMethod = method; // 不应该break,否则多个静态工厂方法上存在 JSONCreator 注解时,并不会触发上述异常抛出 } } if (factoryMethod == null && jacksonCompatible) { for (Method method : methods) { if (TypeUtils.isJacksonCreator(method)) { factoryMethod = method; break; } } } return factoryMethod; } /** * @deprecated */ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/ModuleUtil.java ================================================ package com.alibaba.fastjson.util; import java.util.concurrent.Callable; public class ModuleUtil { private static boolean hasJavaSql = false; static { try { Class.forName("java.sql.Time"); hasJavaSql = true; } catch (Throwable e) { hasJavaSql = false; } } public static T callWhenHasJavaSql(Callable callable) { if (hasJavaSql) { try { return callable.call(); } catch (Exception e) { throw new RuntimeException(e); } } return null; } public static T callWhenHasJavaSql(Function callable, ARG arg) { if (hasJavaSql) { return callable.apply(arg); } return null; } public static R callWhenHasJavaSql(BiFunction callable, T t, U u) { if (hasJavaSql) { return callable.apply(t, u); } return null; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/ParameterizedTypeImpl.java ================================================ 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/RyuDouble.java ================================================ // Copyright 2018 Ulf Adams // // 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.math.BigInteger; /** * An implementation of Ryu for double. */ public final class RyuDouble { private static final int[][] POW5_SPLIT = new int[326][4]; private static final int[][] POW5_INV_SPLIT = new int[291][4]; static { BigInteger mask = BigInteger.ONE.shiftLeft(31).subtract(BigInteger.ONE); BigInteger invMask = BigInteger.ONE.shiftLeft(31).subtract(BigInteger.ONE); for (int i = 0; i < 326; i++) { BigInteger pow = BigInteger.valueOf(5).pow(i); int pow5len = pow.bitLength(); int expectedPow5Bits = i == 0 ? 1 : (int) ((i * 23219280L + 10000000L - 1) / 10000000L); if (expectedPow5Bits != pow5len) { throw new IllegalStateException(pow5len + " != " + expectedPow5Bits); } if (i < POW5_SPLIT.length) { for (int j = 0; j < 4; j++) { POW5_SPLIT[i][j] = pow .shiftRight(pow5len - 121 + (3 - j) * 31) .and(mask) .intValue(); } } if (i < POW5_INV_SPLIT.length) { // We want floor(log_2 5^q) here, which is pow5len - 1. int j = pow5len + 121; BigInteger inv = BigInteger.ONE .shiftLeft(j) .divide(pow) .add(BigInteger.ONE); for (int k = 0; k < 4; k++) { if (k == 0) { POW5_INV_SPLIT[i][k] = inv .shiftRight((3 - k) * 31) .intValue(); } else { POW5_INV_SPLIT[i][k] = inv .shiftRight((3 - k) * 31) .and(invMask) .intValue(); } } } } } public static String toString(double value) { char[] result = new char[24]; int len = toString(value, result, 0); return new String(result, 0, len); } public static int toString(double value, char[] result, int off) { final long DOUBLE_MANTISSA_MASK = 4503599627370495L; // (1L << 52) - 1; final int DOUBLE_EXPONENT_MASK = 2047; // (1 << 11) - 1; final int DOUBLE_EXPONENT_BIAS = 1023; // (1 << (11 - 1)) - 1; final long LOG10_5_NUMERATOR = 6989700L; // (long) (10000000L * Math.log10(5)); final long LOG10_2_NUMERATOR = 3010299L; // (long) (10000000L * Math.log10(2)); // Step 1: Decode the floating point number, and unify normalized and subnormal cases. // First, handle all the trivial cases. int index = off; if (Double.isNaN(value)) { result[index++] = 'N'; result[index++] = 'a'; result[index++] = 'N'; return index - off; } if (value == Double.POSITIVE_INFINITY) { result[index++] = 'I'; result[index++] = 'n'; result[index++] = 'f'; result[index++] = 'i'; result[index++] = 'n'; result[index++] = 'i'; result[index++] = 't'; result[index++] = 'y'; return index - off; } if (value == Double.NEGATIVE_INFINITY) { result[index++] = '-'; result[index++] = 'I'; result[index++] = 'n'; result[index++] = 'f'; result[index++] = 'i'; result[index++] = 'n'; result[index++] = 'i'; result[index++] = 't'; result[index++] = 'y'; return index - off; } long bits = Double.doubleToLongBits(value); if (bits == 0) { result[index++] = '0'; result[index++] = '.'; result[index++] = '0'; return index - off; } if (bits == 0x8000000000000000L) { result[index++] = '-'; result[index++] = '0'; result[index++] = '.'; result[index++] = '0'; return index - off; } final int DOUBLE_MANTISSA_BITS = 52; // Otherwise extract the mantissa and exponent bits and run the full algorithm. int ieeeExponent = (int) ((bits >>> DOUBLE_MANTISSA_BITS) & DOUBLE_EXPONENT_MASK); long ieeeMantissa = bits & DOUBLE_MANTISSA_MASK; int e2; long m2; if (ieeeExponent == 0) { // Denormal number - no implicit leading 1, and the exponent is 1, not 0. e2 = 1 - DOUBLE_EXPONENT_BIAS - DOUBLE_MANTISSA_BITS; m2 = ieeeMantissa; } else { // Add implicit leading 1. e2 = ieeeExponent - DOUBLE_EXPONENT_BIAS - DOUBLE_MANTISSA_BITS; m2 = ieeeMantissa | (1L << DOUBLE_MANTISSA_BITS); } boolean sign = bits < 0; // Step 2: Determine the interval of legal decimal representations. boolean even = (m2 & 1) == 0; final long mv = 4 * m2; final long mp = 4 * m2 + 2; final int mmShift = ((m2 != (1L << DOUBLE_MANTISSA_BITS)) || (ieeeExponent <= 1)) ? 1 : 0; final long mm = 4 * m2 - 1 - mmShift; e2 -= 2; // Step 3: Convert to a decimal power base using 128-bit arithmetic. // -1077 = 1 - 1023 - 53 - 2 <= e_2 - 2 <= 2046 - 1023 - 53 - 2 = 968 long dv, dp, dm; final int e10; boolean dmIsTrailingZeros = false, dvIsTrailingZeros = false; if (e2 >= 0) { final int q = Math.max(0, (int) (e2 * LOG10_2_NUMERATOR / 10000000L) - 1); // k = constant + floor(log_2(5^q)) // q == 0 ? 1 : (int) ((q * 23219280L + 10000000L - 1) / 10000000L) final int k = 122 + (q == 0 ? 1 : (int) ((q * 23219280L + 10000000L - 1) / 10000000L)) - 1; final int i = -e2 + q + k; int actualShift = i - 3 * 31 - 21; if (actualShift < 0) { throw new IllegalArgumentException("" + actualShift); } final int[] ints = POW5_INV_SPLIT[q]; { long mHigh = mv >>> 31; long mLow = mv & 0x7fffffff; long bits13 = mHigh * ints[0]; long bits03 = mLow * ints[0]; long bits12 = mHigh * ints[1]; long bits02 = mLow * ints[1]; long bits11 = mHigh * ints[2]; long bits01 = mLow * ints[2]; long bits10 = mHigh * ints[3]; long bits00 = mLow * ints[3]; dv = (((((( ((bits00 >>> 31) + bits01 + bits10) >>> 31) + bits02 + bits11) >>> 31) + bits03 + bits12) >>> 21) + (bits13 << 10)) >>> actualShift; } { long mHigh = mp >>> 31; long mLow = mp & 0x7fffffff; long bits13 = mHigh * ints[0]; long bits03 = mLow * ints[0]; long bits12 = mHigh * ints[1]; long bits02 = mLow * ints[1]; long bits11 = mHigh * ints[2]; long bits01 = mLow * ints[2]; long bits10 = mHigh * ints[3]; long bits00 = mLow * ints[3]; dp = (((((( ((bits00 >>> 31) + bits01 + bits10) >>> 31) + bits02 + bits11) >>> 31) + bits03 + bits12) >>> 21) + (bits13 << 10)) >>> actualShift; } { long mHigh = mm >>> 31; long mLow = mm & 0x7fffffff; long bits13 = mHigh * ints[0]; long bits03 = mLow * ints[0]; long bits12 = mHigh * ints[1]; long bits02 = mLow * ints[1]; long bits11 = mHigh * ints[2]; long bits01 = mLow * ints[2]; long bits10 = mHigh * ints[3]; long bits00 = mLow * ints[3]; dm = (((((( ((bits00 >>> 31) + bits01 + bits10) >>> 31) + bits02 + bits11) >>> 31) + bits03 + bits12) >>> 21) + (bits13 << 10)) >>> actualShift; } e10 = q; if (q <= 21) { if (mv % 5 == 0) { int pow5Factor_mv; { long v = mv; if ((v % 5) != 0) { pow5Factor_mv = 0; } else if ((v % 25) != 0) { pow5Factor_mv = 1; } else if ((v % 125) != 0) { pow5Factor_mv = 2; } else if ((v % 625) != 0) { pow5Factor_mv = 3; } else { pow5Factor_mv = 4; v /= 625; while (v > 0) { if (v % 5 != 0) { break; } v /= 5; pow5Factor_mv++; } } } dvIsTrailingZeros = pow5Factor_mv >= q; } else if (even) { int pow5Factor_mm; { long v = mm; if ((v % 5) != 0) { pow5Factor_mm = 0; } else if ((v % 25) != 0) { pow5Factor_mm = 1; } else if ((v % 125) != 0) { pow5Factor_mm = 2; } else if ((v % 625) != 0) { pow5Factor_mm = 3; } else { pow5Factor_mm = 4; v /= 625; while (v > 0) { if (v % 5 != 0) { break; } v /= 5; pow5Factor_mm++; } } } dmIsTrailingZeros = pow5Factor_mm >= q; // } else { int pow5Factor_mp; { long v = mp; if ((v % 5) != 0) { pow5Factor_mp = 0; } else if ((v % 25) != 0) { pow5Factor_mp = 1; } else if ((v % 125) != 0) { pow5Factor_mp = 2; } else if ((v % 625) != 0) { pow5Factor_mp = 3; } else { pow5Factor_mp = 4; v /= 625; while (v > 0) { if (v % 5 != 0) { break; } v /= 5; pow5Factor_mp++; } } } if (pow5Factor_mp >= q) { dp--; } } } } else { final int q = Math.max(0, (int) (-e2 * LOG10_5_NUMERATOR / 10000000L) - 1); final int i = -e2 - q; final int k = (i == 0 ? 1 : (int) ((i * 23219280L + 10000000L - 1) / 10000000L)) - 121; final int j = q - k; int actualShift = j - 3 * 31 - 21; if (actualShift < 0) { throw new IllegalArgumentException("" + actualShift); } int[] ints = POW5_SPLIT[i]; { long mHigh = mv >>> 31; long mLow = mv & 0x7fffffff; long bits13 = mHigh * ints[0]; // 124 long bits03 = mLow * ints[0]; // 93 long bits12 = mHigh * ints[1]; // 93 long bits02 = mLow * ints[1]; // 62 long bits11 = mHigh * ints[2]; // 62 long bits01 = mLow * ints[2]; // 31 long bits10 = mHigh * ints[3]; // 31 long bits00 = mLow * ints[3]; // 0 dv = (((((( ((bits00 >>> 31) + bits01 + bits10) >>> 31) + bits02 + bits11) >>> 31) + bits03 + bits12) >>> 21) + (bits13 << 10)) >>> actualShift; } { long mHigh = mp >>> 31; long mLow = mp & 0x7fffffff; long bits13 = mHigh * ints[0]; // 124 long bits03 = mLow * ints[0]; // 93 long bits12 = mHigh * ints[1]; // 93 long bits02 = mLow * ints[1]; // 62 long bits11 = mHigh * ints[2]; // 62 long bits01 = mLow * ints[2]; // 31 long bits10 = mHigh * ints[3]; // 31 long bits00 = mLow * ints[3]; // 0 dp = (((((( ((bits00 >>> 31) + bits01 + bits10) >>> 31) + bits02 + bits11) >>> 31) + bits03 + bits12) >>> 21) + (bits13 << 10)) >>> actualShift; } { long mHigh = mm >>> 31; long mLow = mm & 0x7fffffff; long bits13 = mHigh * ints[0]; // 124 long bits03 = mLow * ints[0]; // 93 long bits12 = mHigh * ints[1]; // 93 long bits02 = mLow * ints[1]; // 62 long bits11 = mHigh * ints[2]; // 62 long bits01 = mLow * ints[2]; // 31 long bits10 = mHigh * ints[3]; // 31 long bits00 = mLow * ints[3]; // 0 dm = (((((( ((bits00 >>> 31) + bits01 + bits10) >>> 31) + bits02 + bits11) >>> 31) + bits03 + bits12) >>> 21) + (bits13 << 10)) >>> actualShift; } e10 = q + e2; if (q <= 1) { dvIsTrailingZeros = true; if (even) { dmIsTrailingZeros = mmShift == 1; } else { dp--; } } else if (q < 63) { dvIsTrailingZeros = (mv & ((1L << (q - 1)) - 1)) == 0; } } // Step 4: Find the shortest decimal representation in the interval of legal representations. // // We do some extra work here in order to follow Float/Double.toString semantics. In particular, // that requires printing in scientific format if and only if the exponent is between -3 and 7, // and it requires printing at least two decimal digits. // // Above, we moved the decimal dot all the way to the right, so now we need to count digits to // figure out the correct exponent for scientific notation. final int vplength; // = decimalLength(dp); if (dp >= 1000000000000000000L) { vplength= 19; } else if (dp >= 100000000000000000L) { vplength= 18; } else if (dp >= 10000000000000000L) { vplength = 17; } else if (dp >= 1000000000000000L) { vplength = 16; } else if (dp >= 100000000000000L) { vplength = 15; } else if (dp >= 10000000000000L) { vplength = 14; } else if (dp >= 1000000000000L) { vplength = 13; } else if (dp >= 100000000000L) { vplength = 12; } else if (dp >= 10000000000L) { vplength = 11; } else if (dp >= 1000000000L) { vplength = 10; } else if (dp >= 100000000L) { vplength = 9; } else if (dp >= 10000000L) { vplength = 8; } else if (dp >= 1000000L) { vplength = 7; } else if (dp >= 100000L) { vplength = 6; } else if (dp >= 10000L) { vplength = 5; } else if (dp >= 1000L) { vplength = 4; } else if (dp >= 100L) { vplength = 3; } else if (dp >= 10L) { vplength = 2; } else { vplength = 1; } int exp = e10 + vplength - 1; // Double.toString semantics requires using scientific notation if and only if outside this range. boolean scientificNotation = !((exp >= -3) && (exp < 7)); int removed = 0; int lastRemovedDigit = 0; long output; if (dmIsTrailingZeros || dvIsTrailingZeros) { while (dp / 10 > dm / 10) { if ((dp < 100) && scientificNotation) { // Double.toString semantics requires printing at least two digits. break; } dmIsTrailingZeros &= dm % 10 == 0; dvIsTrailingZeros &= lastRemovedDigit == 0; lastRemovedDigit = (int) (dv % 10); dp /= 10; dv /= 10; dm /= 10; removed++; } if (dmIsTrailingZeros && even) { while (dm % 10 == 0) { if ((dp < 100) && scientificNotation) { // Double.toString semantics requires printing at least two digits. break; } dvIsTrailingZeros &= lastRemovedDigit == 0; lastRemovedDigit = (int) (dv % 10); dp /= 10; dv /= 10; dm /= 10; removed++; } } if (dvIsTrailingZeros && (lastRemovedDigit == 5) && (dv % 2 == 0)) { // Round even if the exact numbers is .....50..0. lastRemovedDigit = 4; } output = dv + ((dv == dm && !(dmIsTrailingZeros && even)) || (lastRemovedDigit >= 5) ? 1 : 0); } else { while (dp / 10 > dm / 10) { if ((dp < 100) && scientificNotation) { // Double.toString semantics requires printing at least two digits. break; } lastRemovedDigit = (int) (dv % 10); dp /= 10; dv /= 10; dm /= 10; removed++; } output = dv + ((dv == dm || (lastRemovedDigit >= 5)) ? 1 : 0); } int olength = vplength - removed; // Step 5: Print the decimal representation. // We follow Double.toString semantics here. if (sign) { result[index++] = '-'; } // Values in the interval [1E-3, 1E7) are special. if (scientificNotation) { // Print in the format x.xxxxxE-yy. for (int i = 0; i < olength - 1; i++) { int c = (int) (output % 10); output /= 10; result[index + olength - i] = (char) ('0' + c); } result[index] = (char) ('0' + output % 10); result[index + 1] = '.'; index += olength + 1; if (olength == 1) { result[index++] = '0'; } // Print 'E', the exponent sign, and the exponent, which has at most three digits. result[index++] = 'E'; if (exp < 0) { result[index++] = '-'; exp = -exp; } if (exp >= 100) { result[index++] = (char) ('0' + exp / 100); exp %= 100; result[index++] = (char) ('0' + exp / 10); } else if (exp >= 10) { result[index++] = (char) ('0' + exp / 10); } result[index++] = (char) ('0' + exp % 10); return index - off; } else { // Otherwise follow the Java spec for values in the interval [1E-3, 1E7). if (exp < 0) { // Decimal dot is before any of the digits. result[index++] = '0'; result[index++] = '.'; for (int i = -1; i > exp; i--) { result[index++] = '0'; } int current = index; for (int i = 0; i < olength; i++) { result[current + olength - i - 1] = (char) ('0' + output % 10); output /= 10; index++; } } else if (exp + 1 >= olength) { // Decimal dot is after any of the digits. for (int i = 0; i < olength; i++) { result[index + olength - i - 1] = (char) ('0' + output % 10); output /= 10; } index += olength; for (int i = olength; i < exp + 1; i++) { result[index++] = '0'; } result[index++] = '.'; result[index++] = '0'; } else { // Decimal dot is somewhere between the digits. int current = index + 1; for (int i = 0; i < olength; i++) { if (olength - i - 1 == exp) { result[current + olength - i - 1] = '.'; current--; } result[current + olength - i - 1] = (char) ('0' + output % 10); output /= 10; } index += olength + 1; } return index - off; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/RyuFloat.java ================================================ // Copyright 2018 Ulf Adams // // 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; /** * An implementation of Ryu for float. */ public final class RyuFloat { private static final int[][] POW5_SPLIT = { {536870912, 0}, {671088640, 0}, {838860800, 0}, {1048576000, 0}, {655360000, 0}, {819200000, 0}, {1024000000, 0}, {640000000, 0}, {800000000, 0}, {1000000000, 0}, {625000000, 0}, {781250000, 0}, {976562500, 0}, {610351562, 1073741824}, {762939453, 268435456}, {953674316, 872415232}, {596046447, 1619001344}, {745058059, 1486880768}, {931322574, 1321730048}, {582076609, 289210368}, {727595761, 898383872}, {909494701, 1659850752}, {568434188, 1305842176}, {710542735, 1632302720}, {888178419, 1503507488}, {555111512, 671256724}, {693889390, 839070905}, {867361737, 2122580455}, {542101086, 521306416}, {677626357, 1725374844}, {847032947, 546105819}, {1058791184, 145761362}, {661744490, 91100851}, {827180612, 1187617888}, {1033975765, 1484522360}, {646234853, 1196261931}, {807793566, 2032198326}, {1009741958, 1466506084}, {631088724, 379695390}, {788860905, 474619238}, {986076131, 1130144959}, {616297582, 437905143}, {770371977, 1621123253}, {962964972, 415791331}, {601853107, 1333611405}, {752316384, 1130143345}, {940395480, 1412679181}, }; private static final int[][] POW5_INV_SPLIT = { {268435456, 1}, {214748364, 1717986919}, {171798691, 1803886265}, {137438953, 1013612282}, {219902325, 1192282922}, {175921860, 953826338}, {140737488, 763061070}, {225179981, 791400982}, {180143985, 203624056}, {144115188, 162899245}, {230584300, 1978625710}, {184467440, 1582900568}, {147573952, 1266320455}, {236118324, 308125809}, {188894659, 675997377}, {151115727, 970294631}, {241785163, 1981968139}, {193428131, 297084323}, {154742504, 1955654377}, {247588007, 1840556814}, {198070406, 613451992}, {158456325, 61264864}, {253530120, 98023782}, {202824096, 78419026}, {162259276, 1780722139}, {259614842, 1990161963}, {207691874, 733136111}, {166153499, 1016005619}, {265845599, 337118801}, {212676479, 699191770}, {170141183, 988850146}, }; public static String toString(float value) { char[] result = new char[15]; int len = toString(value, result, 0); return new String(result, 0, len); } public static int toString(float value, char[] result, int off) { final int FLOAT_MANTISSA_MASK = 8388607; // (1 << 23) - 1; final int FLOAT_EXPONENT_MASK = 255; // (1 << 8) - 1; final int FLOAT_EXPONENT_BIAS = 127; // (1 << (8 - 1)) - 1; final long LOG10_2_NUMERATOR = 3010299; // (long) (10000000L * Math.log10(2)); final long LOG10_5_DENOMINATOR = 10000000L; final long LOG10_5_NUMERATOR = 6989700L; // (long) (LOG10_5_DENOMINATOR * Math.log10(5)); // Step 1: Decode the floating point number, and unify normalized and subnormal cases. // First, handle all the trivial cases. int index = off; if (Float.isNaN(value)) { result[index++] = 'N'; result[index++] = 'a'; result[index++] = 'N'; return index - off; } if (value == Float.POSITIVE_INFINITY) { result[index++] = 'I'; result[index++] = 'n'; result[index++] = 'f'; result[index++] = 'i'; result[index++] = 'n'; result[index++] = 'i'; result[index++] = 't'; result[index++] = 'y'; return index - off; } if (value == Float.NEGATIVE_INFINITY) { result[index++] = '-'; result[index++] = 'I'; result[index++] = 'n'; result[index++] = 'f'; result[index++] = 'i'; result[index++] = 'n'; result[index++] = 'i'; result[index++] = 't'; result[index++] = 'y'; return index - off; } int bits = Float.floatToIntBits(value); if (bits == 0) { result[index++] = '0'; result[index++] = '.'; result[index++] = '0'; return index - off; } if (bits == 0x80000000) { result[index++] = '-'; result[index++] = '0'; result[index++] = '.'; result[index++] = '0'; return index - off; } // Otherwise extract the mantissa and exponent bits and run the full algorithm. int ieeeExponent = (bits >> 23) & FLOAT_EXPONENT_MASK; int ieeeMantissa = bits & FLOAT_MANTISSA_MASK; // By default, the correct mantissa starts with a 1, except for denormal numbers. int e2; int m2; if (ieeeExponent == 0) { e2 = 1 - FLOAT_EXPONENT_BIAS - 23; m2 = ieeeMantissa; } else { e2 = ieeeExponent - FLOAT_EXPONENT_BIAS - 23; m2 = ieeeMantissa | (1 << 23); } boolean sign = bits < 0; // Step 2: Determine the interval of legal decimal representations. boolean even = (m2 & 1) == 0; int mv = 4 * m2; int mp = 4 * m2 + 2; int mm = 4 * m2 - ((m2 != (1L << 23)) || (ieeeExponent <= 1) ? 2 : 1); e2 -= 2; // Step 3: Convert to a decimal power base using 128-bit arithmetic. // -151 = 1 - 127 - 23 - 2 <= e_2 - 2 <= 254 - 127 - 23 - 2 = 102 int dp, dv, dm; int e10; boolean dpIsTrailingZeros, dvIsTrailingZeros, dmIsTrailingZeros; int lastRemovedDigit = 0; if (e2 >= 0) { // Compute m * 2^e_2 / 10^q = m * 2^(e_2 - q) / 5^q int q = (int) (e2 * LOG10_2_NUMERATOR / 10000000L); int k = 59 + (q == 0 ? 1 : (int) ((q * 23219280L + 10000000L - 1) / 10000000L)) - 1; int i = -e2 + q + k; long pis0 = (long) POW5_INV_SPLIT[q][0]; long pis1 = (long) POW5_INV_SPLIT[q][1]; dv = (int) ((mv * pis0 + ((mv * pis1) >> 31)) >> (i - 31)); dp = (int) ((mp * pis0 + ((mp * pis1) >> 31)) >> (i - 31)); dm = (int) ((mm * pis0 + ((mm * pis1) >> 31)) >> (i - 31)); if (q != 0 && ((dp - 1) / 10 <= dm / 10)) { // We need to know one removed digit even if we are not going to loop below. We could use // q = X - 1 above, except that would require 33 bits for the result, and we've found that // 32-bit arithmetic is faster even on 64-bit machines. int e = q - 1; int l = 59 + (e == 0 ? 1 : (int) ((e * 23219280L + 10000000L - 1) / 10000000L)) - 1; int qx = q - 1, ii = -e2 + q - 1 + l; long mulPow5InvDivPow2 = (mv * (long) POW5_INV_SPLIT[qx][0] + ((mv * (long) POW5_INV_SPLIT[qx][1]) >> 31)) >> (ii - 31); lastRemovedDigit = (int) (mulPow5InvDivPow2 % 10); } e10 = q; int pow5Factor_mp = 0; { int v = mp; while (v > 0) { if (v % 5 != 0) { break; } v /= 5; pow5Factor_mp++; } } int pow5Factor_mv = 0; { int v = mv; while (v > 0) { if (v % 5 != 0) { break; } v /= 5; pow5Factor_mv++; } } int pow5Factor_mm = 0; { int v = mm; while (v > 0) { if (v % 5 != 0) { break; } v /= 5; pow5Factor_mm++; } } dpIsTrailingZeros = pow5Factor_mp >= q; dvIsTrailingZeros = pow5Factor_mv >= q; dmIsTrailingZeros = pow5Factor_mm >= q; } else { // Compute m * 5^(-e_2) / 10^q = m * 5^(-e_2 - q) / 2^q int q = (int) (-e2 * LOG10_5_NUMERATOR / LOG10_5_DENOMINATOR); int i = -e2 - q; int k = (i == 0 ? 1 : (int) ((i * 23219280L + 10000000L - 1) / 10000000L)) - 61; int j = q - k; long ps0 = POW5_SPLIT[i][0]; long ps1 = POW5_SPLIT[i][1]; int j31 = j - 31; dv = (int) ((mv * ps0 + ((mv * ps1) >> 31)) >> j31); dp = (int) ((mp * ps0 + ((mp * ps1) >> 31)) >> j31); dm = (int) ((mm * ps0 + ((mm * ps1) >> 31)) >> j31); if (q != 0 && ((dp - 1) / 10 <= dm / 10)) { int e = i + 1; j = q - 1 - ((e == 0 ? 1 : (int) ((e * 23219280L + 10000000L - 1) / 10000000L)) - 61); int ix = i + 1; long mulPow5divPow2 = (mv * (long) POW5_SPLIT[ix][0] + ((mv * (long) POW5_SPLIT[ix][1]) >> 31)) >> (j - 31); lastRemovedDigit = (int) (mulPow5divPow2 % 10); } e10 = q + e2; // Note: e2 and e10 are both negative here. dpIsTrailingZeros = 1 >= q; dvIsTrailingZeros = (q < 23) && (mv & ((1 << (q - 1)) - 1)) == 0; dmIsTrailingZeros = (mm % 2 == 1 ? 0 : 1) >= q; } // Step 4: Find the shortest decimal representation in the interval of legal representations. // // We do some extra work here in order to follow Float/Double.toString semantics. In particular, // that requires printing in scientific format if and only if the exponent is between -3 and 7, // and it requires printing at least two decimal digits. // // Above, we moved the decimal dot all the way to the right, so now we need to count digits to // figure out the correct exponent for scientific notation. int dplength = 10; int factor = 1000000000; for (; dplength > 0; dplength--) { if (dp >= factor) { break; } factor /= 10; } int exp = e10 + dplength - 1; // Float.toString semantics requires using scientific notation if and only if outside this range. boolean scientificNotation = !((exp >= -3) && (exp < 7)); int removed = 0; if (dpIsTrailingZeros && !even) { dp--; } while (dp / 10 > dm / 10) { if ((dp < 100) && scientificNotation) { // We print at least two digits, so we might as well stop now. break; } dmIsTrailingZeros &= dm % 10 == 0; dp /= 10; lastRemovedDigit = dv % 10; dv /= 10; dm /= 10; removed++; } if (dmIsTrailingZeros && even) { while (dm % 10 == 0) { if ((dp < 100) && scientificNotation) { // We print at least two digits, so we might as well stop now. break; } dp /= 10; lastRemovedDigit = dv % 10; dv /= 10; dm /= 10; removed++; } } if (dvIsTrailingZeros && (lastRemovedDigit == 5) && (dv % 2 == 0)) { // Round down not up if the number ends in X50000 and the number is even. lastRemovedDigit = 4; } int output = dv + ((dv == dm && !(dmIsTrailingZeros && even)) || (lastRemovedDigit >= 5) ? 1 : 0); int olength = dplength - removed; // Step 5: Print the decimal representation. // We follow Float.toString semantics here. if (sign) { result[index++] = '-'; } if (scientificNotation) { // Print in the format x.xxxxxE-yy. for (int i = 0; i < olength - 1; i++) { int c = output % 10; output /= 10; result[index + olength - i] = (char) ('0' + c); } result[index] = (char) ('0' + output % 10); result[index + 1] = '.'; index += olength + 1; if (olength == 1) { result[index++] = '0'; } // Print 'E', the exponent sign, and the exponent, which has at most two digits. result[index++] = 'E'; if (exp < 0) { result[index++] = '-'; exp = -exp; } if (exp >= 10) { result[index++] = (char) ('0' + exp / 10); } result[index++] = (char) ('0' + exp % 10); } else { // Otherwise follow the Java spec for values in the interval [1E-3, 1E7). if (exp < 0) { // Decimal dot is before any of the digits. result[index++] = '0'; result[index++] = '.'; for (int i = -1; i > exp; i--) { result[index++] = '0'; } int current = index; for (int i = 0; i < olength; i++) { result[current + olength - i - 1] = (char) ('0' + output % 10); output /= 10; index++; } } else if (exp + 1 >= olength) { // Decimal dot is after any of the digits. for (int i = 0; i < olength; i++) { result[index + olength - i - 1] = (char) ('0' + output % 10); output /= 10; } index += olength; for (int i = olength; i < exp + 1; i++) { result[index++] = '0'; } result[index++] = '.'; result[index++] = '0'; } else { // Decimal dot is somewhere between the digits. int current = index + 1; for (int i = 0; i < olength; i++) { if (olength - i - 1 == exp) { result[current + olength - i - 1] = '.'; current--; } result[current + olength - i - 1] = (char) ('0' + output % 10); output /= 10; } index += olength + 1; } } return index - off; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/ServiceLoader.java ================================================ package com.alibaba.fastjson.util; import java.io.BufferedReader; 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 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(); String path = PREFIX + className; Set serviceNames = new HashSet(); try { 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 (Throwable ex) { // skip } for (String serviceName : serviceNames) { try { Class serviceClass = classLoader.loadClass(serviceName); T service = (T) serviceClass.newInstance(); services.add(service); } catch (Exception e) { // skip } } return services; } public static void load(URL url, Set set) throws IOException { InputStream is = null; BufferedReader reader = null; try { is = url.openStream(); reader = new BufferedReader(new InputStreamReader(is, "utf-8")); for (;;) { String line = reader.readLine(); if (line == null) { break; } int ci = line.indexOf('#'); if (ci >= 0) { line = line.substring(0, ci); } line = line.trim(); if (line.length() == 0) { continue; } set.add(line); } } finally { IOUtils.close(reader); IOUtils.close(is); } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/ThreadLocalCache.java ================================================ 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, 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) { SoftReference ref = charsBufLocal.get(); if (ref == null) { return allocate(length); } char[] chars = ref.get(); if (chars == null) { return allocate(length); } if (chars.length < length) { chars = allocate(length); } return chars; } private static char[] allocate(int length) { if(length> CHARS_CACH_MAX_SIZE) { 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 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 1 << 32 - Integer.numberOfLeadingZeros(length-1); } // ///////// 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) { SoftReference ref = bytesBufLocal.get(); if (ref == null) { return allocateBytes(length); } byte[] bytes = ref.get(); if (bytes == null) { return allocateBytes(length); } if (bytes.length < length) { bytes = allocateBytes(length); } return bytes; } private static byte[] allocateBytes(int length) { if(length > BYTES_CACH_MAX_SIZE) { 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; } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/TypeUtils.java ================================================ /* * 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.io.InputStream; import java.io.Reader; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Clob; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author wenshao[szujobs@hotmail.com] */ public class TypeUtils { private static final Pattern NUMBER_WITH_TRAILING_ZEROS_PATTERN = Pattern.compile("\\.0*$"); 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>(256, 0.75f, 1); private static Class pathClass; private static boolean pathClass_error = false; private static Class class_JacksonCreator = null; private static boolean class_JacksonCreator_error = false; private static volatile Class class_XmlAccessType = null; private static volatile Class class_XmlAccessorType = null; private static volatile boolean classXmlAccessorType_error = false; private static volatile Method method_XmlAccessorType_value = null; private static volatile Field field_XmlAccessType_FIELD = null; private static volatile Object field_XmlAccessType_FIELD_VALUE = null; private static Class class_deque = null; static { try { TypeUtils.compatibleWithJavaBean = "true".equals(IOUtils.getStringProperty(IOUtils.FASTJSON_COMPATIBLEWITHJAVABEAN)); TypeUtils.compatibleWithFieldName = "true".equals(IOUtils.getStringProperty(IOUtils.FASTJSON_COMPATIBLEWITHFIELDNAME)); } catch (Throwable e) { // skip } try { class_deque = Class.forName("java.util.Deque"); } catch (Throwable e) { // skip } } public static boolean isXmlField(Class clazz) { if (class_XmlAccessorType == null && !classXmlAccessorType_error) { try { class_XmlAccessorType = Class.forName("javax.xml.bind.annotation.XmlAccessorType"); } catch (Throwable ex) { classXmlAccessorType_error = true; } } if (class_XmlAccessorType == null) { return false; } Annotation annotation = TypeUtils.getAnnotation(clazz, class_XmlAccessorType); if (annotation == null) { return false; } if (method_XmlAccessorType_value == null && !classXmlAccessorType_error) { try { method_XmlAccessorType_value = class_XmlAccessorType.getMethod("value"); } catch (Throwable ex) { classXmlAccessorType_error = true; } } if (method_XmlAccessorType_value == null) { return false; } Object value = null; if (!classXmlAccessorType_error) { try { value = method_XmlAccessorType_value.invoke(annotation); } catch (Throwable ex) { classXmlAccessorType_error = true; } } if (value == null) { return false; } if (class_XmlAccessType == null && !classXmlAccessorType_error) { try { class_XmlAccessType = Class.forName("javax.xml.bind.annotation.XmlAccessType"); field_XmlAccessType_FIELD = class_XmlAccessType.getField("FIELD"); field_XmlAccessType_FIELD_VALUE = field_XmlAccessType_FIELD.get(null); } catch (Throwable ex) { classXmlAccessorType_error = true; } } return value == field_XmlAccessType_FIELD_VALUE; } public static Annotation getXmlAccessorType(Class clazz) { if (class_XmlAccessorType == null && !classXmlAccessorType_error) { try { class_XmlAccessorType = Class.forName("javax.xml.bind.annotation.XmlAccessorType"); } catch (Throwable ex) { classXmlAccessorType_error = true; } } if (class_XmlAccessorType == null) { return null; } return TypeUtils.getAnnotation(clazz, class_XmlAccessorType); } // // public static boolean isXmlAccessType(Class clazz) { // if (class_XmlAccessType == null && !class_XmlAccessType_error) { // // try{ // class_XmlAccessType = Class.forName("javax.xml.bind.annotation.XmlAccessType"); // } catch(Throwable ex){ // class_XmlAccessType_error = true; // } // } // // if (class_XmlAccessType == null) { // return false; // } // // return class_XmlAccessType.isAssignableFrom(clazz); // } private static Function isClobFunction = new Function() { public Boolean apply(Class clazz) { return Clob.class.isAssignableFrom(clazz); } }; public static boolean isClob(final Class clazz) { Boolean isClob = ModuleUtil.callWhenHasJavaSql(isClobFunction, clazz); return isClob != null ? isClob : false; } 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 BigDecimal) { return byteValue((BigDecimal) value); } 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); } if (value instanceof Boolean) { return (Boolean) value ? (byte) 1 : (byte) 0; } 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 BigDecimal) { return shortValue((BigDecimal) value); } 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); } if (value instanceof Boolean) { return ((Boolean) value).booleanValue() ? (short) 1 : (short) 0; } throw new JSONException("can not cast to short, value : " + value); } public static BigDecimal castToBigDecimal(Object value) { if (value == null) { return null; } if (value instanceof Float) { if (Float.isNaN((Float) value) || Float.isInfinite((Float) value)) { return null; } } else if (value instanceof Double) { if (Double.isNaN((Double) value) || Double.isInfinite((Double) value)) { return null; } } else if (value instanceof BigDecimal) { return (BigDecimal) value; } else if (value instanceof BigInteger) { return new BigDecimal((BigInteger) value); } else if (value instanceof Map && ((Map) value).size() == 0) { return null; } String strVal = value.toString(); if (strVal.length() == 0 || strVal.equalsIgnoreCase("null")) { return null; } if (strVal.length() > 65535) { throw new JSONException("decimal overflow"); } return new BigDecimal(strVal); } public static BigInteger castToBigInteger(Object value) { if (value == null) { return null; } if (value instanceof Float) { Float floatValue = (Float) value; if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { return null; } return BigInteger.valueOf(floatValue.longValue()); } else if (value instanceof Double) { Double doubleValue = (Double) value; if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) { return null; } return BigInteger.valueOf(doubleValue.longValue()); } else if (value instanceof BigInteger) { return (BigInteger) value; } else if (value instanceof BigDecimal) { BigDecimal decimal = (BigDecimal) value; int scale = decimal.scale(); if (scale > -1000 && scale < 1000) { return ((BigDecimal) value).toBigInteger(); } } String strVal = value.toString(); if (strVal.length() == 0 || strVal.equalsIgnoreCase("null")) { return null; } if (strVal.length() > 65535) { throw new JSONException("decimal overflow"); } 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(',') != -1) { strVal = strVal.replaceAll(",", ""); } return Float.parseFloat(strVal); } if (value instanceof Boolean) { return (Boolean) value ? 1F : 0F; } 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(',') != -1) { strVal = strVal.replaceAll(",", ""); } return Double.parseDouble(strVal); } if (value instanceof Boolean) { return (Boolean) value ? 1D : 0D; } 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 BigDecimal) { longValue = longValue((BigDecimal) value); return new Date(longValue); } if (value instanceof Number) { longValue = ((Number) value).longValue(); if ("unixtime".equals(format)) { longValue *= 1000; } 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('-') > 0 || strVal.indexOf('+') > 0 || format != null) { if (format == null) { final int len = strVal.length(); if (len == JSON.DEFFAULT_DATE_FORMAT.length() || (len == 22 && JSON.DEFFAULT_DATE_FORMAT.equals("yyyyMMddHHmmssSSSZ"))) { format = JSON.DEFFAULT_DATE_FORMAT; } else if (len == 10) { format = "yyyy-MM-dd"; } else if (len == "yyyy-MM-dd HH:mm:ss".length()) { format = "yyyy-MM-dd HH:mm:ss"; } else if (len == 29 && strVal.charAt(26) == ':' && strVal.charAt(28) == '0') { format = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; } else if (len == 23 && strVal.charAt(19) == ',') { format = "yyyy-MM-dd HH:mm:ss,SSS"; } 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 == -1) { 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); } private static Function castToSqlDateFunction = new Function() { public Object apply(Object value) { if (value == null) { return null; } if (value instanceof java.sql.Date) { return (java.sql.Date) value; } if (value instanceof Date) { return new java.sql.Date(((Date) value).getTime()); } if (value instanceof Calendar) { return new java.sql.Date(((Calendar) value).getTimeInMillis()); } long longValue = 0; if (value instanceof BigDecimal) { longValue = longValue((BigDecimal) value); } else 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 Object castToSqlDate(final Object value) { return ModuleUtil.callWhenHasJavaSql(castToSqlDateFunction, value); } public static long longExtractValue(Number number) { if (number instanceof BigDecimal) { return ((BigDecimal) number).longValueExact(); } return number.longValue(); } private static Function castToSqlTimeFunction = new Function() { public Object apply(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 BigDecimal) { longValue = longValue((BigDecimal) value); } else 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 { if (strVal.length() == 8 && strVal.charAt(2) == ':' && strVal.charAt(5) == ':') { return java.sql.Time.valueOf(strVal); } 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 Object castToSqlTime(final Object value) { return ModuleUtil.callWhenHasJavaSql(castToSqlTimeFunction, value); } public static Function castToTimestampFunction = new Function() { public Object apply(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 BigDecimal) { longValue = longValue((BigDecimal) value); } else 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 (strVal.length() == 29 && strVal.charAt(4) == '-' && strVal.charAt(7) == '-' && strVal.charAt(10) == ' ' && strVal.charAt(13) == ':' && strVal.charAt(16) == ':' && strVal.charAt(19) == '.') { int year = num( strVal.charAt(0), strVal.charAt(1), strVal.charAt(2), strVal.charAt(3)); int month = num( strVal.charAt(5), strVal.charAt(6)); int day = num( strVal.charAt(8), strVal.charAt(9)); int hour = num( strVal.charAt(11), strVal.charAt(12)); int minute = num( strVal.charAt(14), strVal.charAt(15)); int second = num( strVal.charAt(17), strVal.charAt(18)); int nanos = num( strVal.charAt(20), strVal.charAt(21), strVal.charAt(22), strVal.charAt(23), strVal.charAt(24), strVal.charAt(25), strVal.charAt(26), strVal.charAt(27), strVal.charAt(28)); return new java.sql.Timestamp(year - 1900, month - 1, day, hour, minute, second, nanos); } 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); } } } return new java.sql.Timestamp(longValue); } }; public static Object castToTimestamp(final Object value) { return ModuleUtil.callWhenHasJavaSql(castToTimestampFunction, value); } static int num(char c0, char c1) { if (c0 >= '0' && c0 <= '9' && c1 >= '0' && c1 <= '9' ) { return (c0 - '0') * 10 + (c1 - '0'); } return -1; } static int num(char c0, char c1, char c2, char c3) { if (c0 >= '0' && c0 <= '9' && c1 >= '0' && c1 <= '9' && c2 >= '0' && c2 <= '9' && c3 >= '0' && c3 <= '9' ) { return (c0 - '0') * 1000 + (c1 - '0') * 100 + (c2 - '0') * 10 + (c3 - '0'); } return -1; } static int num(char c0, char c1, char c2, char c3, char c4, char c5, char c6, char c7, char c8) { if (c0 >= '0' && c0 <= '9' && c1 >= '0' && c1 <= '9' && c2 >= '0' && c2 <= '9' && c3 >= '0' && c3 <= '9' && c4 >= '0' && c4 <= '9' && c5 >= '0' && c5 <= '9' && c6 >= '0' && c6 <= '9' && c7 >= '0' && c7 <= '9' && c8 >= '0' && c8 <= '9' ) { return (c0 - '0') * 100000000 + (c1 - '0') * 10000000 + (c2 - '0') * 1000000 + (c3 - '0') * 100000 + (c4 - '0') * 10000 + (c5 - '0') * 1000 + (c6 - '0') * 100 + (c7 - '0') * 10 + (c8 - '0'); } return -1; } 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 BigDecimal) { return longValue((BigDecimal) value); } 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(',') != -1) { 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); } } if (value instanceof Boolean) { return (Boolean) value ? 1L : 0L; } throw new JSONException("can not cast to long, value : " + value); } public static byte byteValue(BigDecimal decimal) { if (decimal == null) { return 0; } int scale = decimal.scale(); if (scale >= -100 && scale <= 100) { return decimal.byteValue(); } return decimal.byteValueExact(); } public static short shortValue(BigDecimal decimal) { if (decimal == null) { return 0; } int scale = decimal.scale(); if (scale >= -100 && scale <= 100) { return decimal.shortValue(); } return decimal.shortValueExact(); } public static int intValue(BigDecimal decimal) { if (decimal == null) { return 0; } int scale = decimal.scale(); if (scale >= -100 && scale <= 100) { return decimal.intValue(); } return decimal.intValueExact(); } public static long longValue(BigDecimal decimal) { if (decimal == null) { return 0; } int scale = decimal.scale(); if (scale >= -100 && scale <= 100) { return decimal.longValue(); } return decimal.longValueExact(); } public static Integer castToInt(Object value) { if (value == null) { return null; } if (value instanceof Integer) { return (Integer) value; } if (value instanceof BigDecimal) { return intValue((BigDecimal) 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(',') != -1) { strVal = strVal.replaceAll(",", ""); } Matcher matcher = NUMBER_WITH_TRAILING_ZEROS_PATTERN.matcher(strVal); if (matcher.find()) { strVal = matcher.replaceAll(""); } return Integer.parseInt(strVal); } if (value instanceof Boolean) { return (Boolean) value ? 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 byte[], value : " + value); } public static Boolean castToBoolean(Object value) { if (value == null) { return null; } if (value instanceof Boolean) { return (Boolean) value; } if (value instanceof BigDecimal) { return intValue((BigDecimal) value) == 1; } 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()); } private static BiFunction castFunction = new BiFunction() { public Object apply(Object obj, Class clazz) { if (clazz == java.sql.Date.class) { return castToSqlDate(obj); } if (clazz == java.sql.Time.class) { return castToSqlTime(obj); } if (clazz == java.sql.Timestamp.class) { return castToTimestamp(obj); } return null; } }; @SuppressWarnings({"unchecked", "rawtypes"}) public static T cast(final Object obj, final 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); } T retObj = (T) ModuleUtil.callWhenHasJavaSql(castFunction, obj, clazz); if (retObj != null) { return retObj; } if (clazz.isEnum()) { return 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); } } final ObjectDeserializer objectDeserializer = config.get(clazz); if (objectDeserializer != null) { String str = JSON.toJSONString(obj); return JSON.parseObject(str, 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 deserializer = mapping.getDeserializer(clazz); if (deserializer instanceof EnumDeserializer) { EnumDeserializer enumDeserializer = (EnumDeserializer) deserializer; return (T) enumDeserializer.getEnumByHashCode(TypeUtils.fnv1a_64(name)); } return (T) Enum.valueOf((Class) clazz, name); } if (obj instanceof BigDecimal) { int ordinal = intValue((BigDecimal) obj); Object[] values = clazz.getEnumConstants(); if (ordinal < values.length) { return (T) values[ordinal]; } } 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 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 == List.class || rawTye == ArrayList.class) { Type itemType = type.getActualTypeArguments()[0]; if (obj instanceof List) { List listObj = (List) obj; List arrayList = new ArrayList(listObj.size()); for (Object item : listObj) { Object itemValue; if (itemType instanceof Class) { if (item != null && item.getClass() == JSONObject.class) { itemValue = ((JSONObject) item).toJavaObject((Class) itemType, mapping, 0); } else { itemValue = cast(item, (Class) itemType, mapping); } } else { itemValue = cast(item, itemType, mapping); } arrayList.add(itemValue); } return (T) arrayList; } } 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 (Object item : (Iterable) obj) { Object itemValue; if (itemType instanceof Class) { if (item != null && item.getClass() == JSONObject.class) { itemValue = ((JSONObject) item).toJavaObject((Class) itemType, mapping, 0); } else { itemValue = cast(item, (Class) itemType, mapping); } } else { itemValue = cast(item, itemType, mapping); } collection.add(itemValue); } 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; } } Type[] actualTypeArguments = type.getActualTypeArguments(); if (actualTypeArguments.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(); Object entryValue = entry.getValue(); if (actualTypeArguments.length == 2 && entryValue instanceof Map) { Type valueType = actualTypeArguments[1]; entry.setValue( cast(entryValue, valueType, mapping) ); } 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 if (value instanceof BigDecimal) { lineNumber = ((BigDecimal) value).intValueExact(); } 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.get(clazz); if (deserializer != null) { String json = JSON.toJSONString(object); return 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 == JSON.class && map instanceof JSONObject) { return (T) map; } if (clazz == LinkedHashMap.class && map instanceof JSONObject) { JSONObject jsonObject = (JSONObject) map; Map innerMap = jsonObject.getInnerMap(); if (innerMap instanceof LinkedHashMap) { return (T) innerMap; } } if (clazz.isInstance(map)) { return (T) map; } if (clazz == JSONObject.class) { return (T) new JSONObject(map); } if (config == null) { config = ParserConfig.getGlobalInstance(); } JavaBeanDeserializer javaBeanDeser = null; ObjectDeserializer deserializer = config.getDeserializer(clazz); if (deserializer instanceof JavaBeanDeserializer) { javaBeanDeser = (JavaBeanDeserializer) deserializer; } 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 Function>, Void> addBaseClassMappingsFunction = new Function>, Void>() { public Void apply(Map> mappings) { Class[] classes = new Class[]{ java.sql.Time.class, java.sql.Date.class, java.sql.Timestamp.class }; for (Class clazz : classes) { if (clazz == null) { continue; } mappings.put(clazz.getName(), clazz); } return null; } }; static { addBaseClassMappings(); } 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.LinkedHashMap.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.ArrayList.class, java.util.concurrent.TimeUnit.class, java.util.concurrent.ConcurrentHashMap.class, java.util.concurrent.atomic.AtomicInteger.class, java.util.concurrent.atomic.AtomicLong.class, java.util.Collections.EMPTY_MAP.getClass(), java.lang.Boolean.class, java.lang.Character.class, java.lang.Byte.class, java.lang.Short.class, java.lang.Integer.class, java.lang.Long.class, java.lang.Float.class, java.lang.Double.class, java.lang.Number.class, java.lang.String.class, java.math.BigDecimal.class, java.math.BigInteger.class, java.util.BitSet.class, java.util.Calendar.class, java.util.Date.class, java.util.Locale.class, java.util.UUID.class, java.text.SimpleDateFormat.class, com.alibaba.fastjson.JSONObject.class, com.alibaba.fastjson.JSONPObject.class, com.alibaba.fastjson.JSONArray.class, }; for (Class clazz : classes) { if (clazz == null) { continue; } mappings.put(clazz.getName(), clazz); } ModuleUtil.callWhenHasJavaSql(addBaseClassMappingsFunction, mappings); } public static void clearClassMapping() { mappings.clear(); addBaseClassMappings(); } public static void addMapping(String className, Class clazz) { mappings.put(className, clazz); } 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, false); } public static Class loadClass(String className, ClassLoader classLoader, boolean cache) { if (className == null || className.length() == 0) { return null; } if (className.length() > 198) { throw new JSONException("illegal className : " + className); } 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); if (cache) { 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.NeverUseThisValueExceptDefaultValue) { 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(); try { Arrays.sort(methods, new MethodInheritanceComparator()); } catch (Throwable ignored) { } for (Method method : methods) { String methodName = method.getName(); int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; String label = null; if (Modifier.isStatic(method.getModifiers())) { continue; } Class returnType = method.getReturnType(); if (returnType.equals(Void.TYPE)) { continue; } if (method.getParameterTypes().length != 0) { continue; } if (returnType == ClassLoader.class || returnType == InputStream.class || returnType == Reader.class) { continue; } if (methodName.equals("getMetaClass") && returnType.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 = TypeUtils.getAnnotation(method, JSONField.class); if (annotation == null) { annotation = getSuperMethodAnnotation(clazz, method); } if (annotation == null && kotlin) { if (constructors == null) { constructors = clazz.getDeclaredConstructors(); Constructor creatorConstructor = TypeUtils.getKotlinConstructor(constructors); if (creatorConstructor != null) { paramAnnotationArrays = TypeUtils.getParameterAnnotations(creatorConstructor); 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 = TypeUtils.getAnnotation(field, 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; Field field = null; if (Character.isUpperCase(c3) // || c3 > 512 // for unicode method name ) { if (compatibleWithJavaBean) { propertyName = decapitalize(methodName.substring(3)); } else { propertyName = TypeUtils.getPropertyNameByMethodName(methodName); } propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 3); } else if (c3 == '_') { propertyName = methodName.substring(3); field = fieldCacheMap.get(propertyName); if (field == null) { String temp = propertyName; propertyName = methodName.substring(4); field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null) { propertyName = temp; //减少修改代码带来的影响 } } } else if (c3 == 'f') { propertyName = methodName.substring(3); } else if (methodName.length() >= 5 && Character.isUpperCase(methodName.charAt(4))) { propertyName = decapitalize(methodName.substring(3)); } else { propertyName = methodName.substring(3); field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null) { continue; } } boolean ignore = isJSONTypeIgnore(clazz, propertyName); if (ignore) { continue; } if (field == null) { // 假如bean的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 = TypeUtils.getAnnotation(field, 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 (returnType != Boolean.TYPE && returnType != Boolean.class) { continue; } char c2 = methodName.charAt(2); String propertyName; Field field = null; 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); field = fieldCacheMap.get(propertyName); if (field == null) { String temp = propertyName; propertyName = methodName.substring(2); field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null) { propertyName = temp; } } } else if (c2 == 'f') { propertyName = methodName.substring(2); } else { propertyName = methodName.substring(2); field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null) { continue; } } boolean ignore = isJSONTypeIgnore(clazz, propertyName); if (ignore) { continue; } if (field == null) { field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); } if (field == null) { field = ParserConfig.getFieldFromCache(methodName, fieldCacheMap); } JSONField fieldAnnotation = null; if (field != null) { fieldAnnotation = TypeUtils.getAnnotation(field, 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(fieldInfoMap.size()); for (FieldInfo field : fieldInfoMap.values()) { map.put(field.name, field); } for (String item : orders) { FieldInfo field = map.get(item); if (field != null) { fieldInfoList.add(field); map.remove(item); } } fieldInfoList.addAll(map.values()); } else { fieldInfoList.addAll(fieldInfoMap.values()); 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 = TypeUtils.getAnnotation(field, 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 = TypeUtils.getAnnotation(interfaceMethod, 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 = TypeUtils.getAnnotation(interfaceMethod, 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 (String field : fields) { if (propertyName.equals(field)) { return false; } } return true; } else { fields = jsonType.ignores(); for (String field : fields) { if (propertyName.equals(field)) { return true; } } } } if (clazz.getSuperclass() != Object.class && clazz.getSuperclass() != null) { return isJSONTypeIgnore(clazz.getSuperclass(), propertyName); } 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]; if (boundType instanceof Class) { return (Class) boundType; } return getClass(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; } /** * @deprecated */ 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); } /** * resolve property name from get/set method name * * @param methodName get/set method name * @return property name */ public static String getPropertyNameByMethodName(String methodName) { return Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); } static void setAccessible(AccessibleObject obj) { if (!setAccessibleEnable) { return; } if (obj.isAccessible()) { return; } try { obj.setAccessible(true); } catch (Throwable error) { setAccessibleEnable = false; } } public static Type getCollectionItemType(Type fieldType) { if (fieldType instanceof ParameterizedType) { return getCollectionItemType((ParameterizedType) fieldType); } if (fieldType instanceof Class) { return getCollectionItemType((Class) fieldType); } return Object.class; } private static Type getCollectionItemType(Class clazz) { return clazz.getName().startsWith("java.") ? Object.class : getCollectionItemType(getCollectionSuperType(clazz)); } private static Type getCollectionItemType(ParameterizedType parameterizedType) { Type rawType = parameterizedType.getRawType(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (rawType == Collection.class) { return getWildcardTypeUpperBounds(actualTypeArguments[0]); } Class rawClass = (Class) rawType; Map actualTypeMap = createActualTypeMap(rawClass.getTypeParameters(), actualTypeArguments); Type superType = getCollectionSuperType(rawClass); if (superType instanceof ParameterizedType) { Class superClass = getRawClass(superType); Type[] superClassTypeParameters = ((ParameterizedType) superType).getActualTypeArguments(); return superClassTypeParameters.length > 0 ? getCollectionItemType(makeParameterizedType(superClass, superClassTypeParameters, actualTypeMap)) : getCollectionItemType(superClass); } return getCollectionItemType((Class) superType); } private static Type getCollectionSuperType(Class clazz) { Type assignable = null; for (Type type : clazz.getGenericInterfaces()) { Class rawClass = getRawClass(type); if (rawClass == Collection.class) { return type; } if (Collection.class.isAssignableFrom(rawClass)) { assignable = type; } } return assignable == null ? clazz.getGenericSuperclass() : assignable; } private static Map createActualTypeMap(TypeVariable[] typeParameters, Type[] actualTypeArguments) { int length = typeParameters.length; Map actualTypeMap = new HashMap(length); for (int i = 0; i < length; i++) { actualTypeMap.put(typeParameters[i], actualTypeArguments[i]); } return actualTypeMap; } private static ParameterizedType makeParameterizedType(Class rawClass, Type[] typeParameters, Map actualTypeMap) { int length = typeParameters.length; Type[] actualTypeArguments = new Type[length]; for (int i = 0; i < length; i++) { actualTypeArguments[i] = getActualType(typeParameters[i], actualTypeMap); } return new ParameterizedTypeImpl(actualTypeArguments, null, rawClass); } private static Type getActualType(Type typeParameter, Map actualTypeMap) { if (typeParameter instanceof TypeVariable) { return actualTypeMap.get(typeParameter); } else if (typeParameter instanceof ParameterizedType) { return makeParameterizedType(getRawClass(typeParameter), ((ParameterizedType) typeParameter).getActualTypeArguments(), actualTypeMap); } else if (typeParameter instanceof GenericArrayType) { return new GenericArrayTypeImpl(getActualType(((GenericArrayType) typeParameter).getGenericComponentType(), actualTypeMap)); } return typeParameter; } private static Type getWildcardTypeUpperBounds(Type type) { if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; Type[] upperBounds = wildcardType.getUpperBounds(); return upperBounds.length > 0 ? upperBounds[0] : Object.class; } return type; } 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; } private static final Map primitiveTypeMap = new HashMap(8) {{ put(boolean.class, "Z"); put(char.class, "C"); put(byte.class, "B"); put(short.class, "S"); put(int.class, "I"); put(long.class, "J"); put(float.class, "F"); put(double.class, "D"); }}; 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 { String postfix = (String) primitiveTypeMap.get(ck); if (postfix != null) { clz = Class.forName(prefix + postfix); } } catch (ClassNotFoundException ignored) { } } } return clz; } public static Set createSet(Type type) { Class rawClass = getRawClass(type); Set set; if (rawClass == AbstractCollection.class // || rawClass == Collection.class) { set = new HashSet(); } else if (rawClass.isAssignableFrom(HashSet.class)) { set = new HashSet(); } else if (rawClass.isAssignableFrom(LinkedHashSet.class)) { set = new LinkedHashSet(); } else if (rawClass.isAssignableFrom(TreeSet.class)) { set = new TreeSet(); } else if (rawClass.isAssignableFrom(EnumSet.class)) { Type itemType; if (type instanceof ParameterizedType) { itemType = ((ParameterizedType) type).getActualTypeArguments()[0]; } else { itemType = Object.class; } set = EnumSet.noneOf((Class) itemType); } else { try { set = (Set) rawClass.newInstance(); } catch (Exception e) { throw new JSONException("create instance error, class " + rawClass.getName()); } } return set; } @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 if (rawClass.isAssignableFrom(Queue.class) || (class_deque != null && rawClass.isAssignableFrom(class_deque))) { list = new LinkedList(); } 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 if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; Type[] upperBounds = wildcardType.getUpperBounds(); if (upperBounds.length == 1) { return getRawClass(upperBounds[0]); } else { throw new JSONException("TODO"); } } else { throw new JSONException("TODO"); } } private static final Set isProxyClassNames = new HashSet(6) {{ add("net.sf.cglib.proxy.Factory"); add("org.springframework.cglib.proxy.Factory"); add("javassist.util.proxy.ProxyObject"); add("org.apache.ibatis.javassist.util.proxy.ProxyObject"); add("org.hibernate.proxy.HibernateProxy"); add("org.springframework.context.annotation.ConfigurationClassEnhancer$EnhancedConfiguration"); }}; public static boolean isProxy(Class clazz) { for (Class item : clazz.getInterfaces()) { String interfaceName = item.getName(); if (isProxyClassNames.contains(interfaceName)) { 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 = TypeUtils.getAnnotation(method, 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; } catch (Throwable e) { // skip } } return true; } public static double parseDouble(String str) { final int len = str.length(); if (len > 10) { return Double.parseDouble(str); } boolean negative = false; long longValue = 0; int scale = 0; for (int i = 0; i < len; ++i) { char ch = str.charAt(i); if (ch == '-' && i == 0) { negative = true; continue; } if (ch == '.') { if (scale != 0) { return Double.parseDouble(str); } scale = len - i - 1; continue; } if (ch >= '0' && ch <= '9') { int digit = ch - '0'; longValue = longValue * 10 + digit; } else { return Double.parseDouble(str); } } if (negative) { longValue = -longValue; } switch (scale) { case 0: return (double) longValue; case 1: return ((double) longValue) / 10; case 2: return ((double) longValue) / 100; case 3: return ((double) longValue) / 1000; case 4: return ((double) longValue) / 10000; case 5: return ((double) longValue) / 100000; case 6: return ((double) longValue) / 1000000; case 7: return ((double) longValue) / 10000000; case 8: return ((double) longValue) / 100000000; case 9: return ((double) longValue) / 1000000000; } return Double.parseDouble(str); } public static float parseFloat(String str) { final int len = str.length(); if (len >= 10) { return Float.parseFloat(str); } boolean negative = false; long longValue = 0; int scale = 0; for (int i = 0; i < len; ++i) { char ch = str.charAt(i); if (ch == '-' && i == 0) { negative = true; continue; } if (ch == '.') { if (scale != 0) { return Float.parseFloat(str); } scale = len - i - 1; continue; } if (ch >= '0' && ch <= '9') { int digit = ch - '0'; longValue = longValue * 10 + digit; } else { return Float.parseFloat(str); } } if (negative) { longValue = -longValue; } switch (scale) { case 0: return (float) longValue; case 1: return ((float) longValue) / 10; case 2: return ((float) longValue) / 100; case 3: return ((float) longValue) / 1000; case 4: return ((float) longValue) / 10000; case 5: return ((float) longValue) / 100000; case 6: return ((float) longValue) / 1000000; case 7: return ((float) longValue) / 10000000; case 8: return ((float) longValue) / 100000000; case 9: return ((float) longValue) / 1000000000; } return Float.parseFloat(str); } public static final long fnv1a_64_magic_hashcode = 0xcbf29ce484222325L; public static final long fnv1a_64_magic_prime = 0x100000001b3L; public static long fnv1a_64_extract(String key) { long hashCode = fnv1a_64_magic_hashcode; 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 *= fnv1a_64_magic_prime; } return hashCode; } public static long fnv1a_64_lower(String key) { long hashCode = fnv1a_64_magic_hashcode; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= fnv1a_64_magic_prime; } return hashCode; } public static long fnv1a_64(String key) { long hashCode = fnv1a_64_magic_hashcode; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); hashCode ^= ch; hashCode *= fnv1a_64_magic_prime; } 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 getKotlinConstructor(Constructor[] constructors) { return getKotlinConstructor(constructors, null); } public static Constructor getKotlinConstructor(Constructor[] constructors, String[] paramNames) { Constructor creatorConstructor = null; for (Constructor constructor : constructors) { Class[] parameterTypes = constructor.getParameterTypes(); if (paramNames != null && parameterTypes.length != paramNames.length) { continue; } 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; } if (constructor == null) { return null; } 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 targetClass, Class annotationClass) { A targetAnnotation = targetClass.getAnnotation(annotationClass); Class mixInClass = null; Type type = JSON.getMixInAnnotations(targetClass); if (type instanceof Class) { mixInClass = (Class) type; } if (mixInClass != null) { A mixInAnnotation = mixInClass.getAnnotation(annotationClass); Annotation[] annotations = mixInClass.getAnnotations(); if (mixInAnnotation == null && annotations.length > 0) { for (Annotation annotation : annotations) { mixInAnnotation = annotation.annotationType().getAnnotation(annotationClass); if (mixInAnnotation != null) { break; } } } if (mixInAnnotation != null) { return mixInAnnotation; } } Annotation[] targetClassAnnotations = targetClass.getAnnotations(); if (targetAnnotation == null && targetClassAnnotations.length > 0) { for (Annotation annotation : targetClassAnnotations) { targetAnnotation = annotation.annotationType().getAnnotation(annotationClass); if (targetAnnotation != null) { break; } } } return targetAnnotation; } public static A getAnnotation(Field field, Class annotationClass) { A targetAnnotation = field.getAnnotation(annotationClass); Class clazz = field.getDeclaringClass(); A mixInAnnotation; Class mixInClass = null; Type type = JSON.getMixInAnnotations(clazz); if (type instanceof Class) { mixInClass = (Class) type; } if (mixInClass != null) { Field mixInField = null; String fieldName = field.getName(); // 递归从MixIn类的父类中查找注解(如果有父类的话) for (Class currClass = mixInClass; currClass != null && currClass != Object.class; currClass = currClass.getSuperclass()) { try { mixInField = currClass.getDeclaredField(fieldName); break; } catch (NoSuchFieldException e) { // skip } } if (mixInField == null) { return targetAnnotation; } mixInAnnotation = mixInField.getAnnotation(annotationClass); if (mixInAnnotation != null) { return mixInAnnotation; } } return targetAnnotation; } public static A getAnnotation(Method method, Class annotationClass) { A targetAnnotation = method.getAnnotation(annotationClass); Class clazz = method.getDeclaringClass(); A mixInAnnotation; Class mixInClass = null; Type type = JSON.getMixInAnnotations(clazz); if (type instanceof Class) { mixInClass = (Class) type; } if (mixInClass != null) { Method mixInMethod = null; String methodName = method.getName(); Class[] parameterTypes = method.getParameterTypes(); // 递归从MixIn类的父类中查找注解(如果有父类的话) for (Class currClass = mixInClass; currClass != null && currClass != Object.class; currClass = currClass.getSuperclass()) { try { mixInMethod = currClass.getDeclaredMethod(methodName, parameterTypes); break; } catch (NoSuchMethodException e) { // skip } } if (mixInMethod == null) { return targetAnnotation; } mixInAnnotation = mixInMethod.getAnnotation(annotationClass); if (mixInAnnotation != null) { return mixInAnnotation; } } return targetAnnotation; } public static Annotation[][] getParameterAnnotations(Method method) { Annotation[][] targetAnnotations = method.getParameterAnnotations(); Class clazz = method.getDeclaringClass(); Annotation[][] mixInAnnotations; Class mixInClass = null; Type type = JSON.getMixInAnnotations(clazz); if (type instanceof Class) { mixInClass = (Class) type; } if (mixInClass != null) { Method mixInMethod = null; String methodName = method.getName(); Class[] parameterTypes = method.getParameterTypes(); // 递归从MixIn类的父类中查找注解(如果有父类的话) for (Class currClass = mixInClass; currClass != null && currClass != Object.class; currClass = currClass.getSuperclass()) { try { mixInMethod = currClass.getDeclaredMethod(methodName, parameterTypes); break; } catch (NoSuchMethodException e) { continue; } } if (mixInMethod == null) { return targetAnnotations; } mixInAnnotations = mixInMethod.getParameterAnnotations(); if (mixInAnnotations != null) { return mixInAnnotations; } } return targetAnnotations; } public static Annotation[][] getParameterAnnotations(Constructor constructor) { Annotation[][] targetAnnotations = constructor.getParameterAnnotations(); Class clazz = constructor.getDeclaringClass(); Annotation[][] mixInAnnotations; Class mixInClass = null; Type type = JSON.getMixInAnnotations(clazz); if (type instanceof Class) { mixInClass = (Class) type; } if (mixInClass != null) { Constructor mixInConstructor = null; Class[] parameterTypes = constructor.getParameterTypes(); // 构建参数列表,因为内部类的构造函数需要传入外部类的引用 List> enclosingClasses = new ArrayList>(2); for (Class enclosingClass = mixInClass.getEnclosingClass(); enclosingClass != null; enclosingClass = enclosingClass.getEnclosingClass()) { enclosingClasses.add(enclosingClass); } int level = enclosingClasses.size(); // 递归从MixIn类的父类中查找注解(如果有父类的话) for (Class currClass = mixInClass; currClass != null && currClass != Object.class; currClass = currClass.getSuperclass()) { try { if (level != 0) { Class[] outerClassAndParameterTypes = new Class[level + parameterTypes.length]; System.arraycopy(parameterTypes, 0, outerClassAndParameterTypes, level, parameterTypes.length); for (int i = level; i > 0; i--) { outerClassAndParameterTypes[i - 1] = enclosingClasses.get(i - 1); } mixInConstructor = mixInClass.getDeclaredConstructor(outerClassAndParameterTypes); } else { mixInConstructor = mixInClass.getDeclaredConstructor(parameterTypes); } break; } catch (NoSuchMethodException e) { level--; } } if (mixInConstructor == null) { return targetAnnotations; } mixInAnnotations = mixInConstructor.getParameterAnnotations(); if (mixInAnnotations != null) { return mixInAnnotations; } } return targetAnnotations; } public static boolean isJacksonCreator(Method method) { if (method == null) { return false; } if (class_JacksonCreator == null && !class_JacksonCreator_error) { try { class_JacksonCreator = (Class) Class.forName("com.fasterxml.jackson.annotation.JsonCreator"); } catch (Throwable e) { // skip class_JacksonCreator_error = true; } } return class_JacksonCreator != null && method.isAnnotationPresent(class_JacksonCreator); } private static Object OPTIONAL_EMPTY; private static boolean OPTIONAL_ERROR = false; public static Object optionalEmpty(Type type) { if (OPTIONAL_ERROR) { return null; } Class clazz = getClass(type); if (clazz == null) { return null; } String className = clazz.getName(); if ("java.util.Optional".equals(className)) { if (OPTIONAL_EMPTY == null) { try { Method empty = Class.forName(className).getMethod("empty"); OPTIONAL_EMPTY = empty.invoke(null); } catch (Throwable e) { OPTIONAL_ERROR = true; } } return OPTIONAL_EMPTY; } return null; } public static class MethodInheritanceComparator implements Comparator { public int compare(Method m1, Method m2) { int cmp = m1.getName().compareTo(m2.getName()); if (cmp != 0) { return cmp; } Class class1 = m1.getReturnType(); Class class2 = m2.getReturnType(); if (class1.equals(class2)) { return 0; } if (class1.isAssignableFrom(class2)) { return -1; } if (class2.isAssignableFrom(class1)) { return 1; } return 0; } } } ================================================ FILE: src/main/java/com/alibaba/fastjson/util/UTF8Decoder.java ================================================ package com.alibaba.fastjson.util; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; /* Legal UTF-8 Byte Sequences * * # Code Points Bits Bit/Byte pattern * 1 7 0xxxxxxx * U+0000..U+007F 00..7F * * 2 11 110xxxxx 10xxxxxx * U+0080..U+07FF C2..DF 80..BF * * 3 16 1110xxxx 10xxxxxx 10xxxxxx * U+0800..U+0FFF E0 A0..BF 80..BF * U+1000..U+FFFF E1..EF 80..BF 80..BF * * 4 21 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * U+10000..U+3FFFF F0 90..BF 80..BF 80..BF * U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF * U+100000..U10FFFF F4 80..8F 80..BF 80..BF * */ /** * @deprecated */ public class UTF8Decoder extends CharsetDecoder { private final static Charset charset = Charset.forName("UTF-8"); public UTF8Decoder(){ super(charset, 1.0f, 1.0f); } private static boolean isNotContinuation(int b) { return (b & 0xc0) != 0x80; } // [C2..DF] [80..BF] private static boolean isMalformed2(int b1, int b2) { return (b1 & 0x1e) == 0x0 || (b2 & 0xc0) != 0x80; } // [E0] [A0..BF] [80..BF] // [E1..EF] [80..BF] [80..BF] private static boolean isMalformed3(int b1, int b2, int b3) { return (b1 == (byte) 0xe0 && (b2 & 0xe0) == 0x80) || (b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80; } // [F0] [90..BF] [80..BF] [80..BF] // [F1..F3] [80..BF] [80..BF] [80..BF] // [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 boolean isMalformed4(int b2, int b3, int b4) { return (b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 || (b4 & 0xc0) != 0x80; } private static CoderResult lookupN(ByteBuffer src, int n) { for (int i = 1; i < n; i++) { if (isNotContinuation(src.get())) return CoderResult.malformedForLength(i); } return CoderResult.malformedForLength(n); } public static CoderResult malformedN(ByteBuffer src, int nb) { switch (nb) { case 1: int b1 = src.get(); if ((b1 >> 2) == -2) { // 5 bytes 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx if (src.remaining() < 4) return CoderResult.UNDERFLOW; return lookupN(src, 5); } if ((b1 >> 1) == -2) { // 6 bytes 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx if (src.remaining() < 5) { return CoderResult.UNDERFLOW; } return lookupN(src, 6); } return CoderResult.malformedForLength(1); case 2: // always 1 return CoderResult.malformedForLength(1); case 3: b1 = src.get(); int b2 = src.get(); // no need to lookup b3 return CoderResult.malformedForLength(((b1 == (byte) 0xe0 && (b2 & 0xe0) == 0x80) || isNotContinuation(b2)) ? 1 : 2); case 4: // we don't care the speed here b1 = src.get() & 0xff; b2 = src.get() & 0xff; if (b1 > 0xf4 || (b1 == 0xf0 && (b2 < 0x90 || b2 > 0xbf)) || (b1 == 0xf4 && (b2 & 0xf0) != 0x80) || isNotContinuation(b2)) return CoderResult.malformedForLength(1); if (isNotContinuation(src.get())) return CoderResult.malformedForLength(2); return CoderResult.malformedForLength(3); default: throw new IllegalStateException(); } } private static CoderResult malformed(ByteBuffer src, int sp, CharBuffer dst, int dp, int nb) { src.position(sp - src.arrayOffset()); CoderResult cr = malformedN(src, nb); src.position(sp); dst.position(dp); return cr; } private static CoderResult xflow(Buffer src, int sp, int sl, Buffer dst, int dp, int nb) { src.position(sp); dst.position(dp); return (nb == 0 || sl - sp < nb) ? CoderResult.UNDERFLOW : CoderResult.OVERFLOW; } private CoderResult decodeArrayLoop(ByteBuffer src, CharBuffer dst) { // This method is optimized for ASCII input. byte[] srcArray = src.array(); int srcPosition = src.arrayOffset() + src.position(); int srcLength = src.arrayOffset() + src.limit(); char[] destArray = dst.array(); int destPosition = dst.arrayOffset() + dst.position(); int destLength = dst.arrayOffset() + dst.limit(); int destLengthASCII = destPosition + Math.min(srcLength - srcPosition, destLength - destPosition); // ASCII only loop while (destPosition < destLengthASCII && srcArray[srcPosition] >= 0) { destArray[destPosition++] = (char) srcArray[srcPosition++]; } while (srcPosition < srcLength) { int b1 = srcArray[srcPosition]; if (b1 >= 0) { // 1 byte, 7 bits: 0xxxxxxx if (destPosition >= destLength) { return xflow(src, srcPosition, srcLength, dst, destPosition, 1); } destArray[destPosition++] = (char) b1; srcPosition++; } else if ((b1 >> 5) == -2) { // 2 bytes, 11 bits: 110xxxxx 10xxxxxx if (srcLength - srcPosition < 2 || destPosition >= destLength) { return xflow(src, srcPosition, srcLength, dst, destPosition, 2); } int b2 = srcArray[srcPosition + 1]; if (isMalformed2(b1, b2)) { return malformed(src, srcPosition, dst, destPosition, 2); } destArray[destPosition++] = (char) (((b1 << 6) ^ b2) ^ 0x0f80); srcPosition += 2; } else if ((b1 >> 4) == -2) { // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx if (srcLength - srcPosition < 3 || destPosition >= destLength) { return xflow(src, srcPosition, srcLength, dst, destPosition, 3); } int b2 = srcArray[srcPosition + 1]; int b3 = srcArray[srcPosition + 2]; if (isMalformed3(b1, b2, b3)) { return malformed(src, srcPosition, dst, destPosition, 3); } destArray[destPosition++] = (char) (((b1 << 12) ^ (b2 << 6) ^ b3) ^ 0x1f80); srcPosition += 3; } else if ((b1 >> 3) == -2) { // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx if (srcLength - srcPosition < 4 || destLength - destPosition < 2) { return xflow(src, srcPosition, srcLength, dst, destPosition, 4); } int b2 = srcArray[srcPosition + 1]; int b3 = srcArray[srcPosition + 2]; int b4 = srcArray[srcPosition + 3]; int uc = ((b1 & 0x07) << 18) | ((b2 & 0x3f) << 12) | ((b3 & 0x3f) << 06) | (b4 & 0x3f); if (isMalformed4(b2, b3, b4) || !((uc >= 0x10000) && (uc <= 1114111))) { return malformed(src, srcPosition, dst, destPosition, 4); } destArray[destPosition++] = (char) (0xd800 | (((uc - 0x10000) >> 10) & 0x3ff)); destArray[destPosition++] = (char) (0xdc00 | ((uc - 0x10000) & 0x3ff)); srcPosition += 4; } else { return malformed(src, srcPosition, dst, destPosition, 1); } } return xflow(src, srcPosition, srcLength, dst, destPosition, 0); } protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) { return decodeArrayLoop(src, dst); } } ================================================ FILE: src/main/resources/META-INF/LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ================================================ FILE: src/main/resources/META-INF/NOTICE.txt ================================================ /* * 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. */ ================================================ FILE: src/main/resources/META-INF/services/javax.ws.rs.ext.MessageBodyReader ================================================ com.alibaba.fastjson.support.jaxrs.FastJsonProvider ================================================ FILE: src/main/resources/META-INF/services/javax.ws.rs.ext.MessageBodyWriter ================================================ com.alibaba.fastjson.support.jaxrs.FastJsonProvider ================================================ FILE: src/main/resources/META-INF/services/javax.ws.rs.ext.Providers ================================================ com.alibaba.fastjson.support.jaxrs.FastJsonProvider ================================================ FILE: src/main/resources/META-INF/services/org.glassfish.jersey.internal.spi.AutoDiscoverable ================================================ com.alibaba.fastjson.support.jaxrs.FastJsonAutoDiscoverable ================================================ FILE: src/test/java/cn/com/tx/domain/notifyDetail/NotifyDetail.java ================================================ 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(); } } ================================================ FILE: src/test/java/cn/com/tx/domain/pagination/Pagination.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/china/bolt/biz/daili/merchants/vo/MerchantsVO.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/JSONPathTest.java ================================================ /* * Copyright 2018 Diffblue Limited * * 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 com.alibaba.fastjson.JSONPath; import com.diffblue.deeptestutils.Reflector; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class JSONPathTest { @Rule public ExpectedException thrown = ExpectedException.none(); /* testedClasses: JSONPath */ /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 2547 branch to line 2551 * - conditional line 2551 branch to line 2551 * - conditional line 2551 branch to line 2552 */ @Test public void eq1() throws Throwable { // Arrange Object a = -1; Object b = null; // Act Class c = Reflector.forName("com.alibaba.fastjson.JSONPath"); Method m = c.getDeclaredMethod("eq", Reflector.forName("java.lang.Object"), Reflector.forName("java.lang.Object")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, a, b); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 2547 branch to line 2548 */ @Test public void eq2() throws Throwable { // Arrange Object a = null; Object b = null; // Act Class c = Reflector.forName("com.alibaba.fastjson.JSONPath"); Method m = c.getDeclaredMethod("eq", Reflector.forName("java.lang.Object"), Reflector.forName("java.lang.Object")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, a, b); // Assert result Assert.assertEquals(true, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 1434 branch to line 1434 */ @Test public void isDigitFirst1() throws Throwable { // Arrange char ch = '2'; // Act Class c = Reflector.forName("com.alibaba.fastjson.JSONPath$JSONPathParser"); Method m = c.getDeclaredMethod("isDigitFirst", Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, ch); // Assert result Assert.assertEquals(true, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 1434 branch to line 1434 */ @Test public void isDigitFirst2() throws Throwable { // Arrange char ch = ':'; // Act Class c = Reflector.forName("com.alibaba.fastjson.JSONPath$JSONPathParser"); Method m = c.getDeclaredMethod("isDigitFirst", Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, ch); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 1434 branch to line 1434 */ @Test public void isDigitFirst3() throws Throwable { // Arrange char ch = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.JSONPath$JSONPathParser"); Method m = c.getDeclaredMethod("isDigitFirst", Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, ch); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 674 branch to line 674 */ @Test public void isEOF1() throws Throwable { // Arrange Object objectUnderTest = Reflector.getInstance("com.alibaba.fastjson.JSONPath$JSONPathParser"); Reflector.setField(objectUnderTest, "path", ""); Reflector.setField(objectUnderTest, "pos", -2147483647); Reflector.setField(objectUnderTest, "level", 0); Reflector.setField(objectUnderTest, "ch", '\u0000'); // Act Class c = Reflector.forName("com.alibaba.fastjson.JSONPath$JSONPathParser"); Method m = c.getDeclaredMethod("isEOF"); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 674 branch to line 674 */ @Test public void isEOF2() throws Throwable { // Arrange Object objectUnderTest = Reflector.getInstance("com.alibaba.fastjson.JSONPath$JSONPathParser"); Reflector.setField(objectUnderTest, "path", "!"); Reflector.setField(objectUnderTest, "pos", 1); Reflector.setField(objectUnderTest, "level", 0); Reflector.setField(objectUnderTest, "ch", '\u0000'); // Act Class c = Reflector.forName("com.alibaba.fastjson.JSONPath$JSONPathParser"); Method m = c.getDeclaredMethod("isEOF"); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest); // Assert result Assert.assertEquals(true, retval); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/codegen/ClassGen.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/codegen/DeserializerGen.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/IgnoreTypeDeserializer.java ================================================ package com.alibaba.fastjson.deserializer; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Created by jiangyu on 2017-03-03 11:33. */ public class IgnoreTypeDeserializer { @Before public void before() { ParserConfig.global.setAutoTypeSupport(true); } @After public void after() { ParserConfig.global.setAutoTypeSupport(false); } @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()); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/TestISO8601Date.java ================================================ package com.alibaba.fastjson.deserializer; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.Feature; import org.junit.*; import java.util.*; /** * Issue #1884 Test Case * * @author cnzgray@qq.com * @since 2018-05-31 17:15 */ public class TestISO8601Date { @Before public void init() { JSON.DEFAULT_PARSER_FEATURE |= Feature.AllowISO8601DateFormat.mask; } @Test public void testBug1884() { Calendar cale = Calendar.getInstance(); cale.clear(); cale.setTimeZone( TimeZone.getTimeZone( "GMT+7" ) ); cale.set( 2018, Calendar.MAY, 31, 19, 13, 42 ); Date date = cale.getTime(); String s1 = "{date: \"2018-05-31T19:13:42+07:00\"}"; // 错误的 String s2 = "{date: \"2018-05-31T19:13:42.000+07:00\"}"; // 正确的 Date date1 = JSON.parseObject( s1, JSONObject.class ).getDate( "date" ); Date date2 = JSON.parseObject( s2, JSONObject.class ).getDate( "date" ); assertEquals(date1, date2); assertEquals(date, date1); assertEquals(date, date2); } @Test public void testBug376() { Calendar cale = Calendar.getInstance(); cale.clear(); cale.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); cale.set( 2018, Calendar.MAY, 31, 19, 13, 42 ); Date date = cale.getTime(); String s1 = "{date: \"2018-05-31T19:13:42Z\"}"; String s2 = "{date: \"2018-05-31T19:13:42.000Z\"}"; Date date1 = JSON.parseObject( s1, JSONObject.class ).getDate( "date" ); Date date2 = JSON.parseObject( s2, JSONObject.class ).getDate( "date" ); assertEquals( date1, date2 ); assertEquals( date, date1 ); assertEquals( date, date2 ); } private void assertEquals( Date expected, Date actual ) { Assert.assertEquals( 0, expected.compareTo( actual ) ); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/ValueBean.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue1463/TestIssue1463.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue1463/beans/Person.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue2358/TestJson.java ================================================ package com.alibaba.fastjson.deserializer.issue2358; import com.alibaba.fastjson.JSONObject; import java.util.List; /** * Created by liangchuyi on 2019/4/8. */ public class TestJson { private String test1; private String test2; public String getTest1() { return test1; } public void setTest1(String test1) { this.test1 = test1; } public String getTest2() { return test2; } public void setTest2(String test2) { this.test2 = test2; } class TestJson2 { private String test1; private String test2; public String getTest1() { return test1; } public void setTest1(String test1) { this.test1 = test1; } public String getTest2() { return test2; } public void setTest2(String test2) { this.test2 = test2; } } public static void main(String args[]) { String str = "[{\n" + " \"test1\":\"1\",\n" + " \"test2\":\"2\"\n" + "},\n" + " {\n" + " \"test1\":\"1\",\n" + " \"test2\":\"2\"\n" + " }]"; List testJsons = JSONObject.parseArray(str, TestJson2.class); System.out.println(testJsons); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue2638/Person.java ================================================ package com.alibaba.fastjson.deserializer.issue2638; 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; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue2638/TestIssue2638.java ================================================ package com.alibaba.fastjson.deserializer.issue2638; import com.alibaba.fastjson.JSON; import org.junit.Test; /** * @Author:JacceYang chaoyang_sjtu@126.com * @Description: * @Data:Initialized in 7:54 PM 2019/8/17 **/ public class TestIssue2638 { @Test public void testBug2638() { String str="}"; JSON.parseObject(str,Person.class); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue2711/PageRequest.java ================================================ package com.alibaba.fastjson.deserializer.issue2711; import com.alibaba.fastjson.annotation.JSONField; public class PageRequest { @JSONField(unwrapped = true) T data; int from = 0; int size = 10; public T getData() { return data; } public void setData(T data) { this.data = data; } public int getFrom() { return from; } public void setFrom(int from) { this.from = from; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue2711/TestIssue.java ================================================ package com.alibaba.fastjson.deserializer.issue2711; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import org.junit.Assert; import org.junit.Test; public class TestIssue { @Test public void testDeserializeGenericsUnwrapped() { PageRequest req = new PageRequest(); req.setData(new User(1L, "jack")); req.setFrom(10); req.setSize(20); String s = JSON.toJSONString(req); System.out.println(s); PageRequest newReq = JSON.parseObject(s, new TypeReference>() {}); Assert.assertNotNull(newReq); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue2711/User.java ================================================ package com.alibaba.fastjson.deserializer.issue2711; public class User { Long id; String name; public User(Long id, String name) { this.id = id; this.name = 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 "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue2779/Issue2779Test.java ================================================ package com.alibaba.fastjson.deserializer.issue2779; import com.alibaba.fastjson.JSON; import org.junit.Test; // https://github.com/alibaba/fastjson/issues/2779 public class Issue2779Test { @Test public void canDeserializeLargeJavaBean() { JSON.parseObject("{}", LargeJavaBean.class); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue2779/LargeJavaBean.java ================================================ package com.alibaba.fastjson.deserializer.issue2779; import java.util.List; public class LargeJavaBean { public List getList100() { return list100; } public void setList100(List list100) { this.list100 = list100; } public List getList101() { return list101; } public void setList101(List list101) { this.list101 = list101; } public List getList102() { return list102; } public void setList102(List list102) { this.list102 = list102; } public List getList103() { return list103; } public void setList103(List list103) { this.list103 = list103; } public List getList104() { return list104; } public void setList104(List list104) { this.list104 = list104; } public List getList105() { return list105; } public void setList105(List list105) { this.list105 = list105; } public List getList106() { return list106; } public void setList106(List list106) { this.list106 = list106; } public List getList107() { return list107; } public void setList107(List list107) { this.list107 = list107; } public List getList108() { return list108; } public void setList108(List list108) { this.list108 = list108; } public List getList109() { return list109; } public void setList109(List list109) { this.list109 = list109; } public List getList110() { return list110; } public void setList110(List list110) { this.list110 = list110; } public List getList111() { return list111; } public void setList111(List list111) { this.list111 = list111; } public List getList112() { return list112; } public void setList112(List list112) { this.list112 = list112; } public List getList113() { return list113; } public void setList113(List list113) { this.list113 = list113; } public List getList114() { return list114; } public void setList114(List list114) { this.list114 = list114; } public List getList115() { return list115; } public void setList115(List list115) { this.list115 = list115; } public List getList116() { return list116; } public void setList116(List list116) { this.list116 = list116; } public List getList117() { return list117; } public void setList117(List list117) { this.list117 = list117; } public List getList118() { return list118; } public void setList118(List list118) { this.list118 = list118; } public List getList119() { return list119; } public void setList119(List list119) { this.list119 = list119; } public List getList120() { return list120; } public void setList120(List list120) { this.list120 = list120; } public List getList121() { return list121; } public void setList121(List list121) { this.list121 = list121; } public List getList122() { return list122; } public void setList122(List list122) { this.list122 = list122; } public List getList123() { return list123; } public void setList123(List list123) { this.list123 = list123; } public List getList124() { return list124; } public void setList124(List list124) { this.list124 = list124; } public List getList125() { return list125; } public void setList125(List list125) { this.list125 = list125; } public List getList126() { return list126; } public void setList126(List list126) { this.list126 = list126; } public List getList127() { return list127; } public void setList127(List list127) { this.list127 = list127; } public List getList128() { return list128; } public void setList128(List list128) { this.list128 = list128; } public List getList129() { return list129; } public void setList129(List list129) { this.list129 = list129; } public List getList130() { return list130; } public void setList130(List list130) { this.list130 = list130; } public List getList131() { return list131; } public void setList131(List list131) { this.list131 = list131; } public List getList132() { return list132; } public void setList132(List list132) { this.list132 = list132; } public List getList133() { return list133; } public void setList133(List list133) { this.list133 = list133; } public List getList134() { return list134; } public void setList134(List list134) { this.list134 = list134; } public List getList135() { return list135; } public void setList135(List list135) { this.list135 = list135; } public List getList136() { return list136; } public void setList136(List list136) { this.list136 = list136; } public List getList137() { return list137; } public void setList137(List list137) { this.list137 = list137; } public List getList138() { return list138; } public void setList138(List list138) { this.list138 = list138; } public List getList139() { return list139; } public void setList139(List list139) { this.list139 = list139; } public List getList140() { return list140; } public void setList140(List list140) { this.list140 = list140; } public List getList141() { return list141; } public void setList141(List list141) { this.list141 = list141; } public List getList142() { return list142; } public void setList142(List list142) { this.list142 = list142; } public List getList143() { return list143; } public void setList143(List list143) { this.list143 = list143; } public List getList144() { return list144; } public void setList144(List list144) { this.list144 = list144; } public List getList145() { return list145; } public void setList145(List list145) { this.list145 = list145; } public List getList146() { return list146; } public void setList146(List list146) { this.list146 = list146; } public List getList147() { return list147; } public void setList147(List list147) { this.list147 = list147; } public List getList148() { return list148; } public void setList148(List list148) { this.list148 = list148; } public List getList149() { return list149; } public void setList149(List list149) { this.list149 = list149; } public List getList150() { return list150; } public void setList150(List list150) { this.list150 = list150; } public List getList151() { return list151; } public void setList151(List list151) { this.list151 = list151; } public List getList152() { return list152; } public void setList152(List list152) { this.list152 = list152; } public List getList153() { return list153; } public void setList153(List list153) { this.list153 = list153; } public List getList154() { return list154; } public void setList154(List list154) { this.list154 = list154; } public List getList155() { return list155; } public void setList155(List list155) { this.list155 = list155; } public List getList156() { return list156; } public void setList156(List list156) { this.list156 = list156; } public List getList157() { return list157; } public void setList157(List list157) { this.list157 = list157; } public List getList158() { return list158; } public void setList158(List list158) { this.list158 = list158; } public List getList159() { return list159; } public void setList159(List list159) { this.list159 = list159; } public List getList160() { return list160; } public void setList160(List list160) { this.list160 = list160; } public List getList161() { return list161; } public void setList161(List list161) { this.list161 = list161; } public List getList162() { return list162; } public void setList162(List list162) { this.list162 = list162; } public List getList163() { return list163; } public void setList163(List list163) { this.list163 = list163; } // provide by zhaiyao, for fastjson test private List list100; private List list101; private List list102; private List list103; private List list104; private List list105; private List list106; private List list107; private List list108; private List list109; private List list110; private List list111; private List list112; private List list113; private List list114; private List list115; private List list116; private List list117; private List list118; private List list119; private List list120; private List list121; private List list122; private List list123; private List list124; private List list125; private List list126; private List list127; private List list128; private List list129; private List list130; private List list131; private List list132; private List list133; private List list134; private List list135; private List list136; private List list137; private List list138; private List list139; private List list140; private List list141; private List list142; private List list143; private List list144; private List list145; private List list146; private List list147; private List list148; private List list149; private List list150; private List list151; private List list152; private List list153; private List list154; private List list155; private List list156; private List list157; private List list158; private List list159; private List list160; private List list161; private List list162; private List list163; public static class Alphabet { // provide by zhaiyao, for fastjson test private List a; private List b; private List c; private List d; private List e; private List f; private List g; private List h; private List i; private List j; private List k; private List l; private List m; private List n; private List o; private List p; private List q; private List r; private List s; private List t; private List u; private List v; private List w; private List x; private List y; private List z; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue2898/TestIssue2898.java ================================================ package com.alibaba.fastjson.deserializer.issue2898; import java.io.IOException; import java.io.InputStream; import com.alibaba.fastjson.JSON; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Test; public class TestIssue2898 { @Test public void testDeserialzeComplexGenericType() throws Exception { String s = "{\"props\": {\"test\": [{\"foo\": \"bar\"}]}}"; ExtClassLoader classLoader = new ExtClassLoader(); Class clazz = classLoader.loadClass("DataClassPropsGeneric"); Object d = JSON.parseObject(s, clazz); System.out.println(d); Assert.assertNotNull(d); } public static class ExtClassLoader extends ClassLoader { public ExtClassLoader() throws IOException { super(Thread.currentThread().getContextClassLoader()); { byte[] bytes; InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( "kotlin/DataClassPropsGeneric.clazz"); bytes = IOUtils.toByteArray(is); is.close(); super.defineClass("DataClassPropsGeneric", bytes, 0, bytes.length); } } } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue2951/TestIssue2951.java ================================================ package com.alibaba.fastjson.deserializer.issue2951; import com.alibaba.fastjson.JSON; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; public class TestIssue2951 { @Test public void test() { String data = "{\"field1\": null, \"field2\": null, \"field3\": \"1\", \"field4\": null}"; Model model; model = JSON.parseObject(data, Model.class); Assert.assertEquals(model.field1, 0); Assert.assertEquals(model.field2, 0F, 0); Assert.assertEquals(model.field3, "1"); Assert.assertNull(model.field4); String data1 = "{\"field1\": null, \"field2\": null, \"field3\": \"1\", \"field4\": \"null\"}"; model = JSON.parseObject(data1, Model.class); Assert.assertEquals(model.field1, 0); Assert.assertEquals(model.field2, 0F, 0); Assert.assertEquals(model.field3, "1"); List actualField4 = new ArrayList(); actualField4.add("null"); Assert.assertEquals(model.field4, actualField4); } public static class Model { public final int field1; public final float field2; public final String field3; public final List field4; public Model(int field1, float field2, String field3, List field4) { this.field1 = field1; this.field2 = field2; this.field3 = field3; this.field4 = field4; } } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue3050/TestIssue3050.java ================================================ package com.alibaba.fastjson.deserializer.issue3050; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.deserializer.issue3050.beans.Person; import com.alibaba.fastjson.parser.Feature; import org.junit.Assert; import org.junit.Test; /** * https://github.com/alibaba/fastjson/issues/3050 * * @author yangy * @since 2020年05月03日 */ public class TestIssue3050 { @Test public void testIssue3050() { String jsonStr = "{\"name\":5, \"address\":\"beijing\", \"id\":\"100\", \"age\":10}"; Person person = JSON.parseObject(jsonStr, Person.class, Feature.InitStringFieldAsEmpty); Assert.assertEquals("5", person.getName()); Assert.assertEquals("beijing", person.getAddress()); Assert.assertEquals("100", person.getId()); Assert.assertEquals(10, person.getAge()); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue3050/beans/Person.java ================================================ package com.alibaba.fastjson.deserializer.issue3050.beans; /** * issue3050 * * @author yangy * @since 2020年05月03日 */ public class Person { private String name; private String address; private String id; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", address='" + address + '\'' + ", id='" + id + '\'' + ", age=" + age + '}'; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue3248/TestIssue3248.kt ================================================ package com.alibaba.fastjson.deserializer.issue3248 import com.alibaba.fastjson.JSON import com.alibaba.fastjson.annotation.JSONField import org.junit.Assert import org.junit.Test /** * https://github.com/alibaba/fastjson/issues/3248 * @author 佐井 * @since 2020-06-10 09:19 */ class TestIssue3248 { @JSONField(name = "namex") var name = "" var isTest: Boolean = false @Test fun test() { val test = TestIssue3248().also { it.name = "my name" it.isTest = true } val raw = JSON.toJSONString(test) val parsed = JSON.parseObject(raw, TestIssue3248::class.java) Assert.assertEquals(test.name, parsed.name) Assert.assertEquals(test.isTest, parsed.isTest) } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issue3804/TestIssue3804.java ================================================ package com.alibaba.fastjson.deserializer.issue3804; import com.alibaba.fastjson.JSONValidator; import org.junit.Test; public class TestIssue3804 { @Test public void testIssue3804() { //String textResponse="{\"error\":false,\"code\":0}"; String textResponse="{\"error\":false,\"code"; JSONValidator validator = JSONValidator.from(textResponse); if (validator.validate() && validator.getType() == JSONValidator.Type.Object) { System.out.println("Yes, it is Object"); } else { System.out.println("No, it is not Object"); } } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3671/TestIssue3671.java ================================================ package com.alibaba.fastjson.deserializer.issues3671; import com.alibaba.fastjson.JSONValidator; import org.junit.Assert; import org.junit.Test; /** * https://github.com/alibaba/fastjson/issues/3671 * * @author ryc * @date 2021/03/12 15:40 */ public class TestIssue3671 { @Test public void testIssue3671() { String json = "[{\n" + " \"filters\": [],\n" + " \"id\": \"baidu_route2\",\n" + " \"order\": 0,\n" + " \"predicates\": [{\n" + " \"args\": {\n" + " \"pattern\": \"/baidu/**\"\n" + " },\n" + " \"name\": \"Path\"\n" + " }],\n" + " \"uri\": \"https://www.baidu.com\"\n" + "}]\n "; Assert.assertTrue(JSONValidator.from(json).validate()); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/TestIssues3796.java ================================================ package com.alibaba.fastjson.deserializer.issues3796; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.deserializer.issues3796.bean.LargeJavaBean; import org.junit.Test; /** * @author kurisu9az * @description 修复issues3796 * @date 2021/6/2 18:48 **/ public class TestIssues3796 { @Test public void testIssues3796() { JSON.parseObject("{}", LargeJavaBean.class); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/CommonObject.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class CommonObject { private int a; private int b; private int c; public CommonObject() { } public CommonObject(int a, int b) { this.a = a; this.b = b; } public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/CommonObject2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class CommonObject2 { private int a; private long b; public int getA() { return a; } public void setA(int a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/CommonObject3.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class CommonObject3 { private long a; private long b; private int c; public long getA() { return a; } public void setA(long a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/LargeJavaBean.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import com.alibaba.fastjson.annotation.JSONField; import java.util.List; public class LargeJavaBean { public static final String testName = "testName"; @JSONField(name = "_id") private long id; private String a = "null"; private String b = "null"; private String c = "null"; private int d = -1; private String e = "null"; private String f = "null"; private String g = "null"; @JSONField(serialize = false) private ObjectA h = new ObjectA(); private int i; private int j; private String k; private String l; private ObjectB m = new ObjectB(); private int n; private String o; private int p; private long q; private long r; private long s; private long t; private long u; private long v; private int w = 0; private int x = 0; private boolean y = false; private List z; private List a1; private List b1; private List c1; private List d1; @JSONField(serialize = false) private List e1; private long f1; private long g1; private List h1; private List j1; private ObjectI k1; private List l1; private List m1; private ObjectL n1; private List o1; private ObjectN p1; private int q1; private long r1; private long[] s1; @JSONField(serialize = false) private ObjectO t1; @JSONField(serialize = false) private ObjectP u1; private List v1; private List w1; private List x1; private List y1; private List z1; private ObjectT a2 = new ObjectT(); private List b2; private ObjectV c2 = new ObjectV(); private List d2; private List e2; private ObjectX f2; private ObjectY g2; private ObjectZ h2; private int i2 = 0; private ObjectA1 j2; private List k2; private ObjectB1 l2; private List m2; private int n2; private ObjectD1 o2; private int p2; long q2; long r2; int s2; int t2; int u2; int v2; int w2; private List x2; private List y2; ObjectF1 z2 = new ObjectF1(); private List a3; private List b3; private List c3; private ObjectH1 d3; private List e3; private ObjectI1 f3; private ObjectJ1 g3; private ObjectK1 h3; ObjectL1 i3 = new ObjectL1(); private ObjectM1 j3; private ObjectN1 k3; private List l3; private List m3; private ObjectP1 n3; private List o3; private ObjectR1 p3; private ObjectS1 q3; private List r3; private List s3; private ObjectV1 t3; private List u3; private int v3; private ObjectW1 w3; private List x3; private List y3; private List z3; private int a4; private List b4; private ObjectZ1 c4; private List d4; private ObjectB2 e4; private List f4; private List g4 ; private List h4; private ObjectF2 i4; private ObjectG2 j4; private ObjectH2 k4; private ObjectI2 l4; private int m4; private ObjectJ2 n4; private List o4; private int p4; private int q4; private List r4; private List s4; private int t4; private boolean u4 = false; private List v4; private int w4; private ObjectM2 x4; private ObjectM2 y4; private List z4; private List a5; private boolean[] b5; private ObjectO2 c5; public static String getTestName() { return testName; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getA() { return a; } public void setA(String a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } public String getC() { return c; } public void setC(String c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public String getE() { return e; } public void setE(String e) { this.e = e; } public String getF() { return f; } public void setF(String f) { this.f = f; } public String getG() { return g; } public void setG(String g) { this.g = g; } public ObjectA getH() { return h; } public void setH(ObjectA h) { this.h = h; } public int getI() { return i; } public void setI(int i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public String getK() { return k; } public void setK(String k) { this.k = k; } public String getL() { return l; } public void setL(String l) { this.l = l; } public ObjectB getM() { return m; } public void setM(ObjectB m) { this.m = m; } public int getN() { return n; } public void setN(int n) { this.n = n; } public String getO() { return o; } public void setO(String o) { this.o = o; } public int getP() { return p; } public void setP(int p) { this.p = p; } public long getQ() { return q; } public void setQ(long q) { this.q = q; } public long getR() { return r; } public void setR(long r) { this.r = r; } public long getS() { return s; } public void setS(long s) { this.s = s; } public long getT() { return t; } public void setT(long t) { this.t = t; } public long getU() { return u; } public void setU(long u) { this.u = u; } public long getV() { return v; } public void setV(long v) { this.v = v; } public int getW() { return w; } public void setW(int w) { this.w = w; } public int getX() { return x; } public void setX(int x) { this.x = x; } public boolean isY() { return y; } public void setY(boolean y) { this.y = y; } public List getZ() { return z; } public void setZ(List z) { this.z = z; } public List getA1() { return a1; } public void setA1(List a1) { this.a1 = a1; } public List getB1() { return b1; } public void setB1(List b1) { this.b1 = b1; } public List getC1() { return c1; } public void setC1(List c1) { this.c1 = c1; } public List getD1() { return d1; } public void setD1(List d1) { this.d1 = d1; } public List getE1() { return e1; } public void setE1(List e1) { this.e1 = e1; } public long getF1() { return f1; } public void setF1(long f1) { this.f1 = f1; } public long getG1() { return g1; } public void setG1(long g1) { this.g1 = g1; } public List getH1() { return h1; } public void setH1(List h1) { this.h1 = h1; } public List getJ1() { return j1; } public void setJ1(List j1) { this.j1 = j1; } public ObjectI getK1() { return k1; } public void setK1(ObjectI k1) { this.k1 = k1; } public List getL1() { return l1; } public void setL1(List l1) { this.l1 = l1; } public List getM1() { return m1; } public void setM1(List m1) { this.m1 = m1; } public ObjectL getN1() { return n1; } public void setN1(ObjectL n1) { this.n1 = n1; } public List getO1() { return o1; } public void setO1(List o1) { this.o1 = o1; } public ObjectN getP1() { return p1; } public void setP1(ObjectN p1) { this.p1 = p1; } public int getQ1() { return q1; } public void setQ1(int q1) { this.q1 = q1; } public long getR1() { return r1; } public void setR1(long r1) { this.r1 = r1; } public long[] getS1() { return s1; } public void setS1(long[] s1) { this.s1 = s1; } public ObjectO getT1() { return t1; } public void setT1(ObjectO t1) { this.t1 = t1; } public ObjectP getU1() { return u1; } public void setU1(ObjectP u1) { this.u1 = u1; } public List getV1() { return v1; } public void setV1(List v1) { this.v1 = v1; } public List getW1() { return w1; } public void setW1(List w1) { this.w1 = w1; } public List getX1() { return x1; } public void setX1(List x1) { this.x1 = x1; } public List getY1() { return y1; } public void setY1(List y1) { this.y1 = y1; } public List getZ1() { return z1; } public void setZ1(List z1) { this.z1 = z1; } public ObjectT getA2() { return a2; } public void setA2(ObjectT a2) { this.a2 = a2; } public List getB2() { return b2; } public void setB2(List b2) { this.b2 = b2; } public ObjectV getC2() { return c2; } public void setC2(ObjectV c2) { this.c2 = c2; } public List getD2() { return d2; } public void setD2(List d2) { this.d2 = d2; } public List getE2() { return e2; } public void setE2(List e2) { this.e2 = e2; } public ObjectX getF2() { return f2; } public void setF2(ObjectX f2) { this.f2 = f2; } public ObjectY getG2() { return g2; } public void setG2(ObjectY g2) { this.g2 = g2; } public ObjectZ getH2() { return h2; } public void setH2(ObjectZ h2) { this.h2 = h2; } public int getI2() { return i2; } public void setI2(int i2) { this.i2 = i2; } public ObjectA1 getJ2() { return j2; } public void setJ2(ObjectA1 j2) { this.j2 = j2; } public List getK2() { return k2; } public void setK2(List k2) { this.k2 = k2; } public ObjectB1 getL2() { return l2; } public void setL2(ObjectB1 l2) { this.l2 = l2; } public List getM2() { return m2; } public void setM2(List m2) { this.m2 = m2; } public int getN2() { return n2; } public void setN2(int n2) { this.n2 = n2; } public ObjectD1 getO2() { return o2; } public void setO2(ObjectD1 o2) { this.o2 = o2; } public int getP2() { return p2; } public void setP2(int p2) { this.p2 = p2; } public long getQ2() { return q2; } public void setQ2(long q2) { this.q2 = q2; } public long getR2() { return r2; } public void setR2(long r2) { this.r2 = r2; } public int getS2() { return s2; } public void setS2(int s2) { this.s2 = s2; } public int getT2() { return t2; } public void setT2(int t2) { this.t2 = t2; } public int getU2() { return u2; } public void setU2(int u2) { this.u2 = u2; } public int getV2() { return v2; } public void setV2(int v2) { this.v2 = v2; } public int getW2() { return w2; } public void setW2(int w2) { this.w2 = w2; } public List getX2() { return x2; } public void setX2(List x2) { this.x2 = x2; } public List getY2() { return y2; } public void setY2(List y2) { this.y2 = y2; } public ObjectF1 getZ2() { return z2; } public void setZ2(ObjectF1 z2) { this.z2 = z2; } public List getA3() { return a3; } public void setA3(List a3) { this.a3 = a3; } public List getB3() { return b3; } public void setB3(List b3) { this.b3 = b3; } public List getC3() { return c3; } public void setC3(List c3) { this.c3 = c3; } public ObjectH1 getD3() { return d3; } public void setD3(ObjectH1 d3) { this.d3 = d3; } public List getE3() { return e3; } public void setE3(List e3) { this.e3 = e3; } public ObjectI1 getF3() { return f3; } public void setF3(ObjectI1 f3) { this.f3 = f3; } public ObjectJ1 getG3() { return g3; } public void setG3(ObjectJ1 g3) { this.g3 = g3; } public ObjectK1 getH3() { return h3; } public void setH3(ObjectK1 h3) { this.h3 = h3; } public ObjectL1 getI3() { return i3; } public void setI3(ObjectL1 i3) { this.i3 = i3; } public ObjectM1 getJ3() { return j3; } public void setJ3(ObjectM1 j3) { this.j3 = j3; } public ObjectN1 getK3() { return k3; } public void setK3(ObjectN1 k3) { this.k3 = k3; } public List getL3() { return l3; } public void setL3(List l3) { this.l3 = l3; } public List getM3() { return m3; } public void setM3(List m3) { this.m3 = m3; } public ObjectP1 getN3() { return n3; } public void setN3(ObjectP1 n3) { this.n3 = n3; } public List getO3() { return o3; } public void setO3(List o3) { this.o3 = o3; } public ObjectR1 getP3() { return p3; } public void setP3(ObjectR1 p3) { this.p3 = p3; } public ObjectS1 getQ3() { return q3; } public void setQ3(ObjectS1 q3) { this.q3 = q3; } public List getR3() { return r3; } public void setR3(List r3) { this.r3 = r3; } public List getS3() { return s3; } public void setS3(List s3) { this.s3 = s3; } public ObjectV1 getT3() { return t3; } public void setT3(ObjectV1 t3) { this.t3 = t3; } public List getU3() { return u3; } public void setU3(List u3) { this.u3 = u3; } public int getV3() { return v3; } public void setV3(int v3) { this.v3 = v3; } public ObjectW1 getW3() { return w3; } public void setW3(ObjectW1 w3) { this.w3 = w3; } public List getX3() { return x3; } public void setX3(List x3) { this.x3 = x3; } public List getY3() { return y3; } public void setY3(List y3) { this.y3 = y3; } public List getZ3() { return z3; } public void setZ3(List z3) { this.z3 = z3; } public int getA4() { return a4; } public void setA4(int a4) { this.a4 = a4; } public List getB4() { return b4; } public void setB4(List b4) { this.b4 = b4; } public ObjectZ1 getC4() { return c4; } public void setC4(ObjectZ1 c4) { this.c4 = c4; } public List getD4() { return d4; } public void setD4(List d4) { this.d4 = d4; } public ObjectB2 getE4() { return e4; } public void setE4(ObjectB2 e4) { this.e4 = e4; } public List getF4() { return f4; } public void setF4(List f4) { this.f4 = f4; } public List getG4() { return g4; } public void setG4(List g4) { this.g4 = g4; } public List getH4() { return h4; } public void setH4(List h4) { this.h4 = h4; } public ObjectF2 getI4() { return i4; } public void setI4(ObjectF2 i4) { this.i4 = i4; } public ObjectG2 getJ4() { return j4; } public void setJ4(ObjectG2 j4) { this.j4 = j4; } public ObjectH2 getK4() { return k4; } public void setK4(ObjectH2 k4) { this.k4 = k4; } public ObjectI2 getL4() { return l4; } public void setL4(ObjectI2 l4) { this.l4 = l4; } public int getM4() { return m4; } public void setM4(int m4) { this.m4 = m4; } public ObjectJ2 getN4() { return n4; } public void setN4(ObjectJ2 n4) { this.n4 = n4; } public List getO4() { return o4; } public void setO4(List o4) { this.o4 = o4; } public int getP4() { return p4; } public void setP4(int p4) { this.p4 = p4; } public int getQ4() { return q4; } public void setQ4(int q4) { this.q4 = q4; } public List getR4() { return r4; } public void setR4(List r4) { this.r4 = r4; } public List getS4() { return s4; } public void setS4(List s4) { this.s4 = s4; } public int getT4() { return t4; } public void setT4(int t4) { this.t4 = t4; } public boolean isU4() { return u4; } public void setU4(boolean u4) { this.u4 = u4; } public List getV4() { return v4; } public void setV4(List v4) { this.v4 = v4; } public int getW4() { return w4; } public void setW4(int w4) { this.w4 = w4; } public ObjectM2 getX4() { return x4; } public void setX4(ObjectM2 x4) { this.x4 = x4; } public ObjectM2 getY4() { return y4; } public void setY4(ObjectM2 y4) { this.y4 = y4; } public List getZ4() { return z4; } public void setZ4(List z4) { this.z4 = z4; } public List getA5() { return a5; } public void setA5(List a5) { this.a5 = a5; } public boolean[] getB5() { return b5; } public void setB5(boolean[] b5) { this.b5 = b5; } public ObjectO2 getC5() { return c5; } public void setC5(ObjectO2 c5) { this.c5 = c5; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectA.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectA { private static final String NULL = "NULL"; private String a = NULL; private String b = NULL; private String c = NULL; private String d = NULL; private String e = NULL; private int f; private int g; private float h; private String i = NULL; private int j; private String k = NULL; private String l = NULL; private String m = NULL; private int n = 1; private String o = NULL; private String p = NULL; private int q; private int r; private String s = "NULL"; private String t = "NULL"; private String u = "NULL"; private String v = "NULL"; public static String getNULL() { return NULL; } public String getA() { return a; } public void setA(String a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } public String getC() { return c; } public void setC(String c) { this.c = c; } public String getD() { return d; } public void setD(String d) { this.d = d; } public String getE() { return e; } public void setE(String e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public float getH() { return h; } public void setH(float h) { this.h = h; } public String getI() { return i; } public void setI(String i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public String getK() { return k; } public void setK(String k) { this.k = k; } public String getL() { return l; } public void setL(String l) { this.l = l; } public String getM() { return m; } public void setM(String m) { this.m = m; } public int getN() { return n; } public void setN(int n) { this.n = n; } public String getO() { return o; } public void setO(String o) { this.o = o; } public String getP() { return p; } public void setP(String p) { this.p = p; } public int getQ() { return q; } public void setQ(int q) { this.q = q; } public int getR() { return r; } public void setR(int r) { this.r = r; } public String getS() { return s; } public void setS(String s) { this.s = s; } public String getT() { return t; } public void setT(String t) { this.t = t; } public String getU() { return u; } public void setU(String u) { this.u = u; } public String getV() { return v; } public void setV(String v) { this.v = v; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectA1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectA1 { private List a; private CommonObject b; private CommonObject c; private List d; private boolean e = true; public List getA() { return a; } public void setA(List a) { this.a = a; } public CommonObject getB() { return b; } public void setB(CommonObject b) { this.b = b; } public CommonObject getC() { return c; } public void setC(CommonObject c) { this.c = c; } public List getD() { return d; } public void setD(List d) { this.d = d; } public boolean isE() { return e; } public void setE(boolean e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectA2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectA2 { private int a; private int b; private long c; private int d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectB.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectB { private long a; private long b; private long c; private long d; private long e; private long f; private long g; private long h; private long i; private long j; private long k = 0; private long l = 0; private long m = 0; private long n; private long o; private long p; private int q; public long getA() { return a; } public void setA(long a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } public long getD() { return d; } public void setD(long d) { this.d = d; } public long getE() { return e; } public void setE(long e) { this.e = e; } public long getF() { return f; } public void setF(long f) { this.f = f; } public long getG() { return g; } public void setG(long g) { this.g = g; } public long getH() { return h; } public void setH(long h) { this.h = h; } public long getI() { return i; } public void setI(long i) { this.i = i; } public long getJ() { return j; } public void setJ(long j) { this.j = j; } public long getK() { return k; } public void setK(long k) { this.k = k; } public long getL() { return l; } public void setL(long l) { this.l = l; } public long getM() { return m; } public void setM(long m) { this.m = m; } public long getN() { return n; } public void setN(long n) { this.n = n; } public long getO() { return o; } public void setO(long o) { this.o = o; } public long getP() { return p; } public void setP(long p) { this.p = p; } public int getQ() { return q; } public void setQ(int q) { this.q = q; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectB1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectB1 { List a; private int b; public List getA() { return a; } public void setA(List a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectB2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import com.alibaba.fastjson.annotation.JSONField; import java.util.List; public class ObjectB2 { @JSONField(serialize = false) private int a = 1; @JSONField(serialize = false) private long b; private List c; private List d; public int getA() { return a; } public void setA(int a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public List getD() { return d; } public void setD(List d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectC.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectC { private int a; private int b = 0; private long c; private int d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectC1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectC1 { private int a; private int b; private int c; private int d; private int e; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectC2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectC2 { private int a; private boolean b; public int getA() { return a; } public void setA(int a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectD.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectD { private int a; private int b; private int c; private int d; private boolean e; private List f; private int g; private int h; private long i; private long j; private int k; private int l; private ObjectD_B m; private long n; private long o; private long dieFans; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public boolean isE() { return e; } public void setE(boolean e) { this.e = e; } public List getF() { return f; } public void setF(List f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public long getI() { return i; } public void setI(long i) { this.i = i; } public long getJ() { return j; } public void setJ(long j) { this.j = j; } public int getK() { return k; } public void setK(int k) { this.k = k; } public int getL() { return l; } public void setL(int l) { this.l = l; } public ObjectD_B getM() { return m; } public void setM(ObjectD_B m) { this.m = m; } public long getN() { return n; } public void setN(long n) { this.n = n; } public long getO() { return o; } public void setO(long o) { this.o = o; } public long getDieFans() { return dieFans; } public void setDieFans(long dieFans) { this.dieFans = dieFans; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectD1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectD1 { private int a; private int b; private List c; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectD1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectD1_A { private int a; private List b; private int c; private CommonObject d; private int e; private int f; public int getA() { return a; } public void setA(int a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public CommonObject getD() { return d; } public void setD(CommonObject d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectD2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectD2 { private int a; private int b; private int c; private List d; private List e; private List f; private List g; private List h; private List i; private int j; private int k; private int l; private boolean m; private boolean n; private int o; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public List getD() { return d; } public void setD(List d) { this.d = d; } public List getE() { return e; } public void setE(List e) { this.e = e; } public List getF() { return f; } public void setF(List f) { this.f = f; } public List getG() { return g; } public void setG(List g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } public List getI() { return i; } public void setI(List i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public int getK() { return k; } public void setK(int k) { this.k = k; } public int getL() { return l; } public void setL(int l) { this.l = l; } public boolean isM() { return m; } public void setM(boolean m) { this.m = m; } public boolean isN() { return n; } public void setN(boolean n) { this.n = n; } public int getO() { return o; } public void setO(int o) { this.o = o; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectD_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectD_A { private int a; private boolean b; public int getA() { return a; } public void setA(int a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectD_B.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectD_B { private int a; private int b; private int c; private int d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectE.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectE { private int a; private int b; private int c; private int d; private int e; private boolean f; private long g; private int h; private int i; public int j() { return -1; } public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public boolean isF() { return f; } public void setF(boolean f) { this.f = f; } public long getG() { return g; } public void setG(long g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public int getI() { return i; } public void setI(int i) { this.i = i; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectE1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectE1 { private int a; private int b; private int c; private int d; private long e; private long f; private boolean g; private int h; private int i; private int j; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public long getE() { return e; } public void setE(long e) { this.e = e; } public long getF() { return f; } public void setF(long f) { this.f = f; } public boolean isG() { return g; } public void setG(boolean g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public int getI() { return i; } public void setI(int i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectE2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectE2 { private int a; private boolean b; public int getA() { return a; } public void setA(int a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectF.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectF { protected long a; protected int b; protected int c; protected long d; protected long e; protected String f = ""; protected long g; protected String h = ""; protected String i = ""; protected int j; protected long k; protected int l; private int m; protected List n; protected List o; protected List p; public long getA() { return a; } public void setA(long a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public long getD() { return d; } public void setD(long d) { this.d = d; } public long getE() { return e; } public void setE(long e) { this.e = e; } public String getF() { return f; } public void setF(String f) { this.f = f; } public long getG() { return g; } public void setG(long g) { this.g = g; } public String getH() { return h; } public void setH(String h) { this.h = h; } public String getI() { return i; } public void setI(String i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public long getK() { return k; } public void setK(long k) { this.k = k; } public int getL() { return l; } public void setL(int l) { this.l = l; } public int getM() { return m; } public void setM(int m) { this.m = m; } public List getN() { return n; } public void setN(List n) { this.n = n; } public List getO() { return o; } public void setO(List o) { this.o = o; } public List getP() { return p; } public void setP(List p) { this.p = p; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectF1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import com.alibaba.fastjson.annotation.JSONField; import java.util.List; public class ObjectF1 { long a = -1; int b = 0; long c = 0; int d = 0; int e = 0; @JSONField(serialize = false) String f = ""; transient boolean g; long h; long i; int j; int k; int l; int m; int n; List o; int p; int q; public long getA() { return a; } public void setA(long a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public String getF() { return f; } public void setF(String f) { this.f = f; } public boolean isG() { return g; } public void setG(boolean g) { this.g = g; } public long getH() { return h; } public void setH(long h) { this.h = h; } public long getI() { return i; } public void setI(long i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public int getK() { return k; } public void setK(int k) { this.k = k; } public int getL() { return l; } public void setL(int l) { this.l = l; } public int getM() { return m; } public void setM(int m) { this.m = m; } public int getN() { return n; } public void setN(int n) { this.n = n; } public List getO() { return o; } public void setO(List o) { this.o = o; } public int getP() { return p; } public void setP(int p) { this.p = p; } public int getQ() { return q; } public void setQ(int q) { this.q = q; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectF2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectF2 { private int a; private int b; private List c; private boolean d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectG.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import com.alibaba.fastjson.annotation.JSONField; public class ObjectG { public static final String tesdt = "tesdt"; @JSONField(name = "a") private long a; private long b; private ObjectF c; public long getA() { return a; } public void setA(long a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } public ObjectF getC() { return c; } public void setC(ObjectF c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectG1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectG1 { private int a; private int b; private int c; } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectG2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectG2 { private int a; private boolean b = true; private List c; public int getA() { return a; } public void setA(int a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectH.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectH { private int a; private long b; private int c; private int d; private int e; private int f; private int g; private int h; private int i; private int j; private int k; private int l; private List m; private int n; private int o; private boolean p = false; private boolean q = false; public int getA() { return a; } public void setA(int a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public int getI() { return i; } public void setI(int i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public int getK() { return k; } public void setK(int k) { this.k = k; } public int getL() { return l; } public void setL(int l) { this.l = l; } public List getM() { return m; } public void setM(List m) { this.m = m; } public int getN() { return n; } public void setN(int n) { this.n = n; } public int getO() { return o; } public void setO(int o) { this.o = o; } public boolean isP() { return p; } public void setP(boolean p) { this.p = p; } public boolean isQ() { return q; } public void setQ(boolean q) { this.q = q; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectH1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectH1 { private List a; private List b; private List c; private List d; private int e; private int f; private int g; private int h; private int i; private int j; private int k; private int l; private List m; private List n; private List o; public List getA() { return a; } public void setA(List a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public List getD() { return d; } public void setD(List d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public int getI() { return i; } public void setI(int i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public int getK() { return k; } public void setK(int k) { this.k = k; } public int getL() { return l; } public void setL(int l) { this.l = l; } public List getM() { return m; } public void setM(List m) { this.m = m; } public List getN() { return n; } public void setN(List n) { this.n = n; } public List getO() { return o; } public void setO(List o) { this.o = o; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectH2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectH2 { private boolean a; private int b; private int c; private boolean d; private List e; public boolean isA() { return a; } public void setA(boolean a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } public List getE() { return e; } public void setE(List e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectH_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectH_A { private int a; private int b; private int c; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectI.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectI { private String a; private int b; private long c; private int d; private int e; private int f; private int g; private List h; private List i; private int j; private int k; private int l; public String getA() { return a; } public void setA(String a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } public List getI() { return i; } public void setI(List i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public int getK() { return k; } public void setK(int k) { this.k = k; } public int getL() { return l; } public void setL(int l) { this.l = l; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectI1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectI1 { private int a = 0; private long b = 0; private int c = 0; private List d; public int getA() { return a; } public void setA(int a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public List getD() { return d; } public void setD(List d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectI2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectI2 { private int a; private List b; private boolean c; public int getA() { return a; } public void setA(int a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } public boolean isC() { return c; } public void setC(boolean c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectI_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectI_A { int a; int b; boolean c; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public boolean isC() { return c; } public void setC(boolean c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectJ.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectJ { private long a; private int b; private int c; private int d; private int e; private int f; private int g; private int h; private List i; private int j; private int k; private int l; private int m; private List n; private List o; private int p; private int q; private int r; private int s; private int t; private int x; private int y; private int z; private int a1; private int b1; private List c1; private List d1; private List e1; private int f1; private int g1; boolean h1; public long getA() { return a; } public void setA(long a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public List getI() { return i; } public void setI(List i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public int getK() { return k; } public void setK(int k) { this.k = k; } public int getL() { return l; } public void setL(int l) { this.l = l; } public int getM() { return m; } public void setM(int m) { this.m = m; } public List getN() { return n; } public void setN(List n) { this.n = n; } public List getO() { return o; } public void setO(List o) { this.o = o; } public int getP() { return p; } public void setP(int p) { this.p = p; } public int getQ() { return q; } public void setQ(int q) { this.q = q; } public int getR() { return r; } public void setR(int r) { this.r = r; } public int getS() { return s; } public void setS(int s) { this.s = s; } public int getT() { return t; } public void setT(int t) { this.t = t; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getZ() { return z; } public void setZ(int z) { this.z = z; } public int getA1() { return a1; } public void setA1(int a1) { this.a1 = a1; } public int getB1() { return b1; } public void setB1(int b1) { this.b1 = b1; } public List getC1() { return c1; } public void setC1(List c1) { this.c1 = c1; } public List getD1() { return d1; } public void setD1(List d1) { this.d1 = d1; } public List getE1() { return e1; } public void setE1(List e1) { this.e1 = e1; } public int getF1() { return f1; } public void setF1(int f1) { this.f1 = f1; } public int getG1() { return g1; } public void setG1(int g1) { this.g1 = g1; } public boolean isH1() { return h1; } public void setH1(boolean h1) { this.h1 = h1; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectJ1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectJ1 { private int a = 0; private int b = 0; private List c; private int d = 0; private List e; private List f; private List g; private List h; private boolean i = false; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public List getE() { return e; } public void setE(List e) { this.e = e; } public List getF() { return f; } public void setF(List f) { this.f = f; } public List getG() { return g; } public void setG(List g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } public boolean isI() { return i; } public void setI(boolean i) { this.i = i; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectJ1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectJ1_A { private int a = 0; private int b = 0; private int c = 0; private int d = 0; private int e = 0; private List f; private List g; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public List getF() { return f; } public void setF(List f) { this.f = f; } public List getG() { return g; } public void setG(List g) { this.g = g; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectJ1_C.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectJ1_C { private int a = 0; private int b = 0; private int c = 0; private int d = 0; private boolean e = false; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public boolean isE() { return e; } public void setE(boolean e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectJ2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectJ2 { private boolean a; private boolean b; public boolean isA() { return a; } public void setA(boolean a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectJ_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectJ_A { private long a; private int b; private int c; private int d; private int e; private int f; private int g; private int h; private int i; private List j; private List k; private List l; private List m; public long getA() { return a; } public void setA(long a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public int getI() { return i; } public void setI(int i) { this.i = i; } public List getJ() { return j; } public void setJ(List j) { this.j = j; } public List getK() { return k; } public void setK(List k) { this.k = k; } public List getL() { return l; } public void setL(List l) { this.l = l; } public List getM() { return m; } public void setM(List m) { this.m = m; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectJ_B.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectJ_B { private long a; private int b; private long c; private int d; private int e; private int f; private int g; private int h; private int i; public long getA() { return a; } public void setA(long a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public int getI() { return i; } public void setI(int i) { this.i = i; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectJ_C.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectJ_C { private int a; private int b; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectK.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectK { private int a; private int b = 0; private int c = 0; private int d = 0; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectK1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectK1 { private int a = 0; private boolean b = false; private int c = 0; private int d = 0; private int e = 0; private List f; private List g; private int h = 0; private List i; public int getA() { return a; } public void setA(int a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public List getF() { return f; } public void setF(List f) { this.f = f; } public List getG() { return g; } public void setG(List g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public List getI() { return i; } public void setI(List i) { this.i = i; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectK1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectK1_A { private int a = 0; private int b = 0; private int c = 0; private int d = 0; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectK1_C.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectK1_C { private int a = 0; private int b = 0; private boolean c = false; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public boolean isC() { return c; } public void setC(boolean c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectK2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectK2 { private int a; private List b; public int getA() { return a; } public void setA(int a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectK2_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectK2_A { private int a; private int b; private int c; private int d; private int e; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectL.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectL { private List a; private List b; private List c; public List getA() { return a; } public void setA(List a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectL1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.HashMap; import java.util.List; public class ObjectL1 { List a; int b; int c; int d; long e; long f; List g; List h; HashMap> i; boolean j = false; public List getA() { return a; } public void setA(List a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public long getE() { return e; } public void setE(long e) { this.e = e; } public long getF() { return f; } public void setF(long f) { this.f = f; } public List getG() { return g; } public void setG(List g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } public HashMap> getI() { return i; } public void setI(HashMap> i) { this.i = i; } public boolean isJ() { return j; } public void setJ(boolean j) { this.j = j; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectL1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectL1_A { protected int a; protected int b; protected int c; protected int d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectL2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectL2 { int a; ObjectL2_A b; List c ; int d; public int getA() { return a; } public void setA(int a) { this.a = a; } public ObjectL2_A getB() { return b; } public void setB(ObjectL2_A b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectL2_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectL2_A { int a = 1; int b = 2; int c = 4; int d = 5; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectL2_B.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectL2_B { int a; int b; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectL2_C.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectL2_C { int a; int b; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectL_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectL_A { private int a; private int b; private long c; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectL_B.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectL_B { private int a; private List b; private List c; private long d; public int getA() { return a; } public void setA(int a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public long getD() { return d; } public void setD(long d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectM.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectM { private int a; private int b; private String c = ""; private long d; private int e; private int f; private List g; private List h; private ObjectM_B i; private long j; public int getA() { return a; } public void setA(int 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; } public long getD() { return d; } public void setD(long d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public List getG() { return g; } public void setG(List g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } public ObjectM_B getI() { return i; } public void setI(ObjectM_B i) { this.i = i; } public long getJ() { return j; } public void setJ(long j) { this.j = j; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectM1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectM1 { private int a; private int b; private int c; private int d; private List e; private List f; private int g; private int h; private int i; private int j; private int k; private boolean l; private int m; private int n; private int o; private int p; private boolean q; private CommonObject r; private int s; private long t; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public List getE() { return e; } public void setE(List e) { this.e = e; } public List getF() { return f; } public void setF(List f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public int getI() { return i; } public void setI(int i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public int getK() { return k; } public void setK(int k) { this.k = k; } public boolean isL() { return l; } public void setL(boolean l) { this.l = l; } public int getM() { return m; } public void setM(int m) { this.m = m; } public int getN() { return n; } public void setN(int n) { this.n = n; } public int getO() { return o; } public void setO(int o) { this.o = o; } public int getP() { return p; } public void setP(int p) { this.p = p; } public boolean isQ() { return q; } public void setQ(boolean q) { this.q = q; } public CommonObject getR() { return r; } public void setR(CommonObject r) { this.r = r; } public int getS() { return s; } public void setS(int s) { this.s = s; } public long getT() { return t; } public void setT(long t) { this.t = t; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectM1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectM1_A { private int a; private int b; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectM1_B.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectM1_B { private long a; private String b; private String c; private int d; private long e; private int f; private int g; private List h; private List i; private int j; private int k; private boolean l; public long getA() { return a; } public void setA(long a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } public String getC() { return c; } public void setC(String c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public long getE() { return e; } public void setE(long e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } public List getI() { return i; } public void setI(List i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public int getK() { return k; } public void setK(int k) { this.k = k; } public boolean isL() { return l; } public void setL(boolean l) { this.l = l; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectM1_C.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectM1_C { private int a; private int b; private int c; private int d; private int e; private int f; private int g; private List h; private List i; private int j; private int k; private int l; private int m; private int n; private int o; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } public List getI() { return i; } public void setI(List i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public int getK() { return k; } public void setK(int k) { this.k = k; } public int getL() { return l; } public void setL(int l) { this.l = l; } public int getM() { return m; } public void setM(int m) { this.m = m; } public int getN() { return n; } public void setN(int n) { this.n = n; } public int getO() { return o; } public void setO(int o) { this.o = o; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectM2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectM2 { private long a; private int b; private boolean c; private int d; private List e; public long getA() { return a; } public void setA(long a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public boolean isC() { return c; } public void setC(boolean c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public List getE() { return e; } public void setE(List e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectM2_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectM2_A { private int a; public int getA() { return a; } public void setA(int a) { this.a = a; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectM_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectM_A { private int a; private int b; private long c; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectM_B.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectM_B { private int a; private int b; private int c; private long d; private List e; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public long getD() { return d; } public void setD(long d) { this.d = d; } public List getE() { return e; } public void setE(List e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectN.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectN { private List a; private List b; private List c; private List d; private List e; private List f; private List g; private List h; private List i; private List j; private List k; private List l; public List getA() { return a; } public void setA(List a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public List getD() { return d; } public void setD(List d) { this.d = d; } public List getE() { return e; } public void setE(List e) { this.e = e; } public List getF() { return f; } public void setF(List f) { this.f = f; } public List getG() { return g; } public void setG(List g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } public List getI() { return i; } public void setI(List i) { this.i = i; } public List getJ() { return j; } public void setJ(List j) { this.j = j; } public List getK() { return k; } public void setK(List k) { this.k = k; } public List getL() { return l; } public void setL(List l) { this.l = l; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectN1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectN1 { private int a; private int b; private boolean c; private boolean d; private int e; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public boolean isC() { return c; } public void setC(boolean c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectN2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectN2 { private int a; private int b; private long c; private int d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectO.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import com.alibaba.fastjson.annotation.JSONField; import java.util.List; public class ObjectO { public static final String tstN = "tstN"; @JSONField(name = "a") private long a; private List b; public long getA() { return a; } public void setA(long a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectO1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.io.Serializable; import java.util.List; public class ObjectO1 implements Serializable { int a; int b; List c; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectO1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.io.Serializable; public class ObjectO1_A implements Serializable { int a; int b; int c; int d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectO2.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectO2 { private int a; private boolean b = true; private int c; public int getA() { return a; } public void setA(int a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectO_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectO_A { private int a; private int b; private int c; private int d; private int e; private int f; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectP.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import com.alibaba.fastjson.annotation.JSONField; import java.util.List; public class ObjectP { public static final String tsnst = "tsnst"; @JSONField(name = "a") private long a; private List b; public static String getTsnst() { return tsnst; } public long getA() { return a; } public void setA(long a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectP1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectP1 { private int a; private int b; private int c; private List d; private int e = 0; private int f = 0; private List g; private List h; private List i; private boolean j = true; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public List getD() { return d; } public void setD(List d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public List getG() { return g; } public void setG(List g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } public List getI() { return i; } public void setI(List i) { this.i = i; } public boolean isJ() { return j; } public void setJ(boolean j) { this.j = j; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectP1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectP1_A { private int a = 0; private int b = 0; private int c = 0; private boolean d = false; private int e = 0; private int f = 0; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectP1_B.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectP1_B { private long a = 0; private int b = 0; private int c = 0; private int d = 0; private int e = 0; private int f = 0; private long g = 0; private boolean h = true; public long getA() { return a; } public void setA(long a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public long getG() { return g; } public void setG(long g) { this.g = g; } public boolean isH() { return h; } public void setH(boolean h) { this.h = h; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectP_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectP_A { private int a; private int b; private int c; private boolean d; private boolean e; private boolean f; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } public boolean isE() { return e; } public void setE(boolean e) { this.e = e; } public boolean isF() { return f; } public void setF(boolean f) { this.f = f; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectQ.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectQ { private int a; private int b; private boolean c = false; private List d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public boolean isC() { return c; } public void setC(boolean c) { this.c = c; } public List getD() { return d; } public void setD(List d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectQ1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectQ1 { private int a; private int b; private long c; private int d; private int e; private int f; private int g; private int h; private int i; private int j; private int k; private int l; private int m; private List n; private int o; private long p; private int q; private int r; private int s; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public int getI() { return i; } public void setI(int i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public int getK() { return k; } public void setK(int k) { this.k = k; } public int getL() { return l; } public void setL(int l) { this.l = l; } public int getM() { return m; } public void setM(int m) { this.m = m; } public List getN() { return n; } public void setN(List n) { this.n = n; } public int getO() { return o; } public void setO(int o) { this.o = o; } public long getP() { return p; } public void setP(long p) { this.p = p; } public int getQ() { return q; } public void setQ(int q) { this.q = q; } public int getR() { return r; } public void setR(int r) { this.r = r; } public int getS() { return s; } public void setS(int s) { this.s = s; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectQ1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectQ1_A { private int a; private List b; private int c; private boolean d; private boolean e; public int getA() { return a; } public void setA(int a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } public boolean isE() { return e; } public void setE(boolean e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectQ1_B.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectQ1_B { private int a; private boolean b; public int getA() { return a; } public void setA(int a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectR.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectR { private int a; private int b; private int c; private int d; private List e; private int f; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public List getE() { return e; } public void setE(List e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectR1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectR1 { private List a; private int b; private List c; private boolean d; private boolean e; private int f; private int g; private boolean h; private long i; private long j; private List k; public List getA() { return a; } public void setA(List a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } public boolean isE() { return e; } public void setE(boolean e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public boolean isH() { return h; } public void setH(boolean h) { this.h = h; } public long getI() { return i; } public void setI(long i) { this.i = i; } public long getJ() { return j; } public void setJ(long j) { this.j = j; } public List getK() { return k; } public void setK(List k) { this.k = k; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectS.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectS { private int a; private int b; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectS1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectS1 { private int a; private int b; private int c = 0; private int d; private int e; private List f; private boolean g = false; private List h; private List i; private List j; private boolean k = true; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public List getF() { return f; } public void setF(List f) { this.f = f; } public boolean isG() { return g; } public void setG(boolean g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } public List getI() { return i; } public void setI(List i) { this.i = i; } public List getJ() { return j; } public void setJ(List j) { this.j = j; } public boolean isK() { return k; } public void setK(boolean k) { this.k = k; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectS1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectS1_A { private int a; private int b; private int c; private boolean d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectT.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectT { private int a = 0; private int b = 0; private int c = 0; private List d; private int e = 0; private int f; private int g; private int h; private int i; private int j; private boolean k = false; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public List getD() { return d; } public void setD(List d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public int getI() { return i; } public void setI(int i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public boolean isK() { return k; } public void setK(boolean k) { this.k = k; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectT1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectT1 { private int a; private int b; private int c; private int d; private int e; private int f; private int g; private int h; private long i; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public long getI() { return i; } public void setI(long i) { this.i = i; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectT_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectT_A { private int a; private boolean b; private long c; public int getA() { return a; } public void setA(int a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectU.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectU { private int a; private Integer b; private int c; private int d; private int e; private int f; private boolean g; public int getA() { return a; } public void setA(int a) { this.a = a; } public Integer getB() { return b; } public void setB(Integer b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public boolean isG() { return g; } public void setG(boolean g) { this.g = g; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectU1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectU1 { private int a; private String b = ""; private String c = ""; private String d = ""; private List e; private List f; private long g; private long h; private long i; private long j; private long k; private long l; private List m; public int getA() { return a; } public void setA(int a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } public String getC() { return c; } public void setC(String c) { this.c = c; } public String getD() { return d; } public void setD(String d) { this.d = d; } public List getE() { return e; } public void setE(List e) { this.e = e; } public List getF() { return f; } public void setF(List f) { this.f = f; } public long getG() { return g; } public void setG(long g) { this.g = g; } public long getH() { return h; } public void setH(long h) { this.h = h; } public long getI() { return i; } public void setI(long i) { this.i = i; } public long getJ() { return j; } public void setJ(long j) { this.j = j; } public long getK() { return k; } public void setK(long k) { this.k = k; } public long getL() { return l; } public void setL(long l) { this.l = l; } public List getM() { return m; } public void setM(List m) { this.m = m; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectU1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectU1_A { private int a; private long b; private int c; public int getA() { return a; } public void setA(int a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectU1_B.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectU1_B { private int a; private long b; private List c; private boolean d; private boolean e; public int getA() { return a; } public void setA(int a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } public boolean isE() { return e; } public void setE(boolean e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectU1_C.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectU1_C { private int a; private boolean b; public int getA() { return a; } public void setA(int a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectV.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectV { private List a; private List b; public List getA() { return a; } public void setA(List a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectV1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectV1 { private int a; private int b; private List c; private List d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public List getD() { return d; } public void setD(List d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectV1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectV1_A { private int a; private List b; private boolean c; public int getA() { return a; } public void setA(int a) { this.a = a; } public List getB() { return b; } public void setB(List b) { this.b = b; } public boolean isC() { return c; } public void setC(boolean c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectV_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectV_A { private int a; private int b; private int c; private int d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectW.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectW { private long a; private int b; private long c; private int d; private String e; private long f; public long getA() { return a; } public void setA(long a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public long getC() { return c; } public void setC(long c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public String getE() { return e; } public void setE(String e) { this.e = e; } public long getF() { return f; } public void setF(long f) { this.f = f; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectW1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectW1 { private int a; private int b; private List c; private boolean d; private List e; private int f = 0; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } public List getE() { return e; } public void setE(List e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectX.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectX { private long a = 0; private int b; private List c; private int d = 0; private int e; private List f; private List g; private List h; public long getA() { return a; } public void setA(long a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public List getC() { return c; } public void setC(List c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public List getF() { return f; } public void setF(List f) { this.f = f; } public List getG() { return g; } public void setG(List g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectX1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectX1 { int a; int b; String c; String d; long e; public int getA() { return a; } public void setA(int 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; } public String getD() { return d; } public void setD(String d) { this.d = d; } public long getE() { return e; } public void setE(long e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectY.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectY { private List a; private long b; private int c = 0; private boolean d = false; private int e = -1; private int f = 0; private int g = 0; private int h; private boolean i =false; private List j; private List k; public List getA() { return a; } public void setA(List a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public int getF() { return f; } public void setF(int f) { this.f = f; } public int getG() { return g; } public void setG(int g) { this.g = g; } public int getH() { return h; } public void setH(int h) { this.h = h; } public boolean isI() { return i; } public void setI(boolean i) { this.i = i; } public List getJ() { return j; } public void setJ(List j) { this.j = j; } public List getK() { return k; } public void setK(List k) { this.k = k; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectY1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectY1 { private int a; private int b; private int c; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectY_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectY_A { private int a = 0; private int b; private int c; private int d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectZ.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectZ { private int a; private long b; public int getA() { return a; } public void setA(int a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectZ1.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectZ1 { private int a; private int b; private int c; private int d; private int e; private List f; private List g; private List h; private List i; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public List getF() { return f; } public void setF(List f) { this.f = f; } public List getG() { return g; } public void setG(List g) { this.g = g; } public List getH() { return h; } public void setH(List h) { this.h = h; } public List getI() { return i; } public void setI(List i) { this.i = i; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectZ1_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class ObjectZ1_A { private int a; private int b; private int c; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/OjectN_A.java ================================================ package com.alibaba.fastjson.deserializer.issues3796.bean; public class OjectN_A { private long a; private String b; private String c; private int d; private String e; public long getA() { return a; } public void setA(long a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } public String getC() { return c; } public void setC(String c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public String getE() { return e; } public void setE(String e) { this.e = e; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues569/TestIssues569.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues569/beans/Dept.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues569/beans/MyResponse.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues569/parser/DefaultFieldDeserializerBug569.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/issues569/parser/ParserConfigBug569.java ================================================ 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 deserializers = super.getDeserializers(); ObjectDeserializer deserializer = deserializers.get(type); if (deserializer != null) { return deserializer; } if (type == null) { type = clazz; } deserializer = deserializers.get(type); if (deserializer != null) { return deserializer; } { 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) { deserializer = deserializers.get(clazz); } if (deserializer != null) { return deserializer; } 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 { deserializers.put(Class.forName("java.awt.Point"), AwtCodec.instance); deserializers.put(Class.forName("java.awt.Font"), AwtCodec.instance); deserializers.put(Class.forName("java.awt.Rectangle"), AwtCodec.instance); deserializers.put(Class.forName("java.awt.Color"), AwtCodec.instance); } catch (Throwable e) { // skip awtError = true; } deserializer = AwtCodec.instance; } } if (!jdk8Error) { try { if (className.startsWith("java.time.")) { deserializers.put(Class.forName("java.time.LocalDateTime"), Jdk8DateCodec.instance); deserializers.put(Class.forName("java.time.LocalDate"), Jdk8DateCodec.instance); deserializers.put(Class.forName("java.time.LocalTime"), Jdk8DateCodec.instance); deserializers.put(Class.forName("java.time.ZonedDateTime"), Jdk8DateCodec.instance); deserializers.put(Class.forName("java.time.OffsetDateTime"), Jdk8DateCodec.instance); deserializers.put(Class.forName("java.time.OffsetTime"), Jdk8DateCodec.instance); deserializers.put(Class.forName("java.time.ZoneOffset"), Jdk8DateCodec.instance); deserializers.put(Class.forName("java.time.ZoneRegion"), Jdk8DateCodec.instance); deserializers.put(Class.forName("java.time.ZoneId"), Jdk8DateCodec.instance); deserializers.put(Class.forName("java.time.Period"), Jdk8DateCodec.instance); deserializers.put(Class.forName("java.time.Duration"), Jdk8DateCodec.instance); deserializers.put(Class.forName("java.time.Instant"), Jdk8DateCodec.instance); deserializer = deserializers.get(clazz); } else if (className.startsWith("java.util.Optional")) { deserializers.put(Class.forName("java.util.Optional"), OptionalCodec.instance); deserializers.put(Class.forName("java.util.OptionalDouble"), OptionalCodec.instance); deserializers.put(Class.forName("java.util.OptionalInt"), OptionalCodec.instance); deserializers.put(Class.forName("java.util.OptionalLong"), OptionalCodec.instance); deserializer = deserializers.get(clazz); } } catch (Throwable e) { // skip jdk8Error = true; } } if (className.equals("java.nio.file.Path")) { deserializers.put(clazz, 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 (deserializer == null) { deserializer = deserializers.get(type); } if (deserializer != null) { return deserializer; } if (clazz.isEnum()) { deserializer = new EnumDeserializer(clazz); } else if (clazz.isArray()) { deserializer = ObjectArrayCodec.instance; } else if (clazz == Set.class || clazz == HashSet.class || clazz == Collection.class || clazz == List.class || clazz == ArrayList.class) { deserializer = CollectionCodec.instance; } else if (Collection.class.isAssignableFrom(clazz)) { deserializer = CollectionCodec.instance; } else if (Map.class.isAssignableFrom(clazz)) { deserializer = MapDeserializer.instance; } else if (Throwable.class.isAssignableFrom(clazz)) { deserializer = new ThrowableDeserializer(this, clazz); } else { deserializer = createJavaBeanDeserializer(clazz, type); } putDeserializer(type, deserializer); return deserializer; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/javabean/ConvertDO.java ================================================ package com.alibaba.fastjson.deserializer.javabean; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Date; import java.util.List; import java.util.Map; /** * @author ylyue * @since 2021/3/23 */ @Data @NoArgsConstructor @AllArgsConstructor public class ConvertDO implements Serializable { private static final long serialVersionUID = 3987648902475498726L; private int inta; private Integer intb; private long longa; private Long longb; private boolean booleana; private Boolean booleanb; private Character character; private String str; private String[] arrayStr; private long[] arrayLong; private List list; private Date date; // private DateTime dateTime; // private LocalDate localDate; // private LocalTime localTime; // private LocalDateTime localDateTime; private Map map; private JSONObject jsonObject; private JSONArray jsonArray; private List jsonObjectList; private Map strToMap; private JSONObject strToJsonObject; private JSONArray strToJsonArray; private List strToJsonObjectList; private ConvertEnum convertEnum; } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/javabean/ConvertEnum.java ================================================ package com.alibaba.fastjson.deserializer.javabean; /** * @author ylyue * @since 2021/3/24 */ public enum ConvertEnum { A_A, BB_B; } ================================================ FILE: src/test/java/com/alibaba/fastjson/deserializer/javabean/JavaBeanConvertTest.java ================================================ package com.alibaba.fastjson.deserializer.javabean; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.util.TypeUtils; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Map; /** * JavaBean类型转换器测试 * * @author ylyue * @since 2021/3/23 */ public class JavaBeanConvertTest { @Test public void javaBeanDeserializerTest() { Map map = new HashMap(); map.put("key1", "value1"); map.put("key2", "value2"); JSONObject jsonObject = new JSONObject(); jsonObject.put("aaa", 1); jsonObject.put("bbb", 2); jsonObject.put("ccc", "11111"); JSONArray jsonArray = new JSONArray(); jsonArray.add(jsonObject); JSONObject paramJson = new JSONObject(); // JSON - JSON paramJson.put("map", map); paramJson.put("jsonObject", jsonObject); paramJson.put("jsonArray", jsonArray); paramJson.put("jsonObjectList", jsonArray); // JSONString - JSON paramJson.put("strToMap", map); paramJson.put("strToJsonObject", jsonObject.toJSONString()); paramJson.put("strToJsonArray", jsonArray.toJSONString()); paramJson.put("strToJsonObjectList", jsonArray.toJSONString()); // 基本类型 paramJson.put("character", "c"); paramJson.put("str", "STR"); paramJson.put("inta", "1"); paramJson.put("intb", "2"); paramJson.put("longa", "3"); paramJson.put("longb", 888l); paramJson.put("booleana", "1"); paramJson.put("booleanb", true); // 数组 paramJson.put("arrayStr", new String[]{"aaaa", "bbbbb", "cccc"}); paramJson.put("arrayLong", new Long[]{1L, 2L, 3L}); paramJson.put("list", new String[]{"aaaa", "bbbbb", "cccc"}); // 时间类型 paramJson.put("date", "2021-03-23"); paramJson.put("dateTime", "2021-03-24"); paramJson.put("localDate", "2021-03-24"); paramJson.put("localTime", "16:03:24"); paramJson.put("localDateTime", "2021-03-24 16:03:24"); // 其它 paramJson.put("convertEnum", "A_A"); ConvertDO convertDO = TypeUtils.castToJavaBean(paramJson, ConvertDO.class, ParserConfig.getGlobalInstance()); Assert.assertNotNull(convertDO); // System.out.println(convertDO); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/jsonpath/issue3493/TestIssue3493.java ================================================ package com.alibaba.fastjson.jsonpath.issue3493; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONPath; import org.junit.Assert; import org.junit.Test; /** * @author wangzn * @since 2020/10/27 10:27 */ public class TestIssue3493 { @Test public void testIssue3493(){ String json = "{\n" + "\"result\": [\n" + "{\n" + "\"puid\": \"21025318\"\n" + "},\n" + "{\n" + "\"puid\": \"21482682\"\n" + "},\n" + "{\n" + "\"puid\": \"21025345\"\n" + "}\n" + "],\n" + "\"state\": 0\n" + "}"; Object list = JSONPath.extract(json, "$.result[0,2].puid"); JSONArray jsonArray = JSON.parseArray(list.toString()); Assert.assertEquals(jsonArray.size(), 2); Assert.assertEquals(jsonArray.get(0), "21025318"); Assert.assertEquals(jsonArray.get(1), "21025345"); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/jsonpath/issue3607/TestIssue3607.java ================================================ package com.alibaba.fastjson.jsonpath.issue3607; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONPath; import org.junit.Assert; import org.junit.Test; import java.util.List; /** * @author : ganyu *

@Date: 2021/1/6 10:57

*/ public class TestIssue3607 { @Test public void testIssue3607() { TestData testData = JSON.parseObject("{\n" + " \"data\": {\n" + " \"dataRows\": [\n" + " {\n" + " \"dataFields\": [\n" + " {\n" + " \"id\": 1332,\n" + " \"name\": \"gmtRegular\",\n" + " \"status\": \"success\",\n" + " \"valueType\": \"DATE\"\n" + " },\n" + " {\n" + " \"id\": 302,\n" + " \"name\": \"deptNo\",\n" + " \"status\": \"success\",\n" + " \"value\": \"C3736\",\n" + " \"valueType\": \"STRING\"\n" + " },\n" + " {\n" + " \"id\": 143,\n" + " \"name\": \"gmtOrigRegular\",\n" + " \"status\": \"success\",\n" + " \"value\": 1621126800000,\n" + " \"valueType\": \"DATE\"\n" + " },\n" + " {\n" + " \"id\": 135,\n" + " \"name\": \"name\",\n" + " \"status\": \"success\",\n" + " \"value\": \"\",\n" + " \"valueType\": \"STRING\"\n" + " },\n" + " {\n" + " \"id\": 133,\n" + " \"name\": \"workNo\",\n" + " \"status\": \"success\",\n" + " \"value\": \"29*6\",\n" + " \"valueType\": \"STRING\"\n" + " },\n" + " {\n" + " \"id\": 140,\n" + " \"name\": \"gmtEntry\",\n" + " \"status\": \"success\",\n" + " \"value\": 1605456000000,\n" + " \"valueType\": \"DATE\"\n" + " },\n" + " {\n" + " \"id\": 199,\n" + " \"name\": \"superWorkNo\",\n" + " \"status\": \"success\",\n" + " \"value\": \"240397\",\n" + " \"valueType\": \"STRING\"\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + " },\n" + " \"status\": \"success\",\n" + " \"success\": true\n" + "}", TestData.class); List evalResult = (List) JSONPath.eval(testData, "$.data.dataRows[*].dataFields[*].value", false); Assert.assertEquals(testData.getData().getDataRows().get(0).getDataFields().size(), evalResult.size()); } static class TestData { private Test1 data; private String status; private Boolean success; public Test1 getData() { return data; } public void setData(Test1 data) { this.data = data; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } } static class Test1 { List dataRows; public List getDataRows() { return dataRows; } public void setDataRows(List dataRows) { this.dataRows = dataRows; } } static class Test2 { List dataFields; public List getDataFields() { return dataFields; } public void setDataFields(List dataFields) { this.dataFields = dataFields; } } static class Test3 { private Integer id; private String name; private String status; private String value; private String valueType; 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 String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getValueType() { return valueType; } public void setValueType(String valueType) { this.valueType = valueType; } } } ================================================ FILE: src/test/java/com/alibaba/fastjson/parser/JSONScannerTest.java ================================================ /* * Copyright 2018 Diffblue Limited * * 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.parser.JSONScanner; import com.diffblue.deeptestutils.Reflector; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Calendar; import java.util.Locale; public class JSONScannerTest { @Rule public ExpectedException thrown = ExpectedException.none(); /* testedClasses: JSONScanner */ /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 82 branch to line 83 */ @Test public void charArrayCompare1() throws Throwable { // Arrange String src = ""; int offset = 7; char[] dest = { '\u0000' }; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("charArrayCompare", Reflector.forName("java.lang.String"), Reflector.forName("int"), Reflector.forName("char []")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, src, offset, dest); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest.This test covers `boolean * charArrayCompare(String, char [])' block 2 (line 81) * This test covers `boolean charArrayCompare(String, char [])' block 3 (line * 82) * This test covers `boolean charArrayCompare(String, char [])' block 4 (line * 82) * This test covers `boolean charArrayCompare(String, char [])' block 5 (line * 86) * This test covers `boolean charArrayCompare(String, char [])' block 7 (line * 86) * This test covers `boolean charArrayCompare(String, char [])' block 8 (line * 86) * This test covers `boolean charArrayCompare(String, char [])' block 10 * (line 87) * This test covers `boolean charArrayCompare(String, char [])' block 11 * (line 87) * This test covers `boolean charArrayCompare(String, char [])' block 13 * (line 88) * */ @Test public void charArrayCompare3() throws Throwable { // Arrange String src = "!!!!!!!\"&&"; int offset = 6; char[] dest = { '\u0000' }; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("charArrayCompare", Reflector.forName("java.lang.String"), Reflector.forName("int"), Reflector.forName("char []")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, src, offset, dest); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 82 branch to line 86 * */ @Test public void charArrayCompare4() throws Throwable { // Arrange String src = "!\"&&&&&"; int offset = 0; char[] dest = { }; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("charArrayCompare", Reflector.forName("java.lang.String"), Reflector.forName("int"), Reflector.forName("char []")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, src, offset, dest); // Assert result Assert.assertEquals(true, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 707 * - conditional line 707 branch to line 708 * - conditional line 708 branch to line 715 * - conditional line 715 branch to line 719 * - conditional line 719 branch to line 719 * - conditional line 719 branch to line 723 * - conditional line 723 branch to line 724 * - conditional line 724 branch to line 731 */ @Test public void checkDate1() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '1'; char y3 = '1'; char M0 = '1'; char M1 = '0'; int d0 = 51; int d1 = 48; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(true, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 704 * - conditional line 704 branch to line 704 * - conditional line 704 branch to line 705 */ @Test public void checkDate2() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '1'; char y3 = '1'; char M0 = '0'; char M1 = '\u8031'; int d0 = 0; int d1 = 0; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 707 * - conditional line 707 branch to line 708 * - conditional line 708 branch to line 715 * - conditional line 715 branch to line 719 * - conditional line 719 branch to line 720 * - conditional line 720 branch to line 720 * - conditional line 720 branch to line 721 */ @Test public void checkDate3() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '1'; char y3 = '1'; char M0 = '1'; char M1 = '0'; int d0 = 49; int d1 = 32810; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 707 * - conditional line 707 branch to line 708 * - conditional line 708 branch to line 715 * - conditional line 715 branch to line 719 * - conditional line 719 branch to line 719 * - conditional line 719 branch to line 720 * - conditional line 720 branch to line 720 * - conditional line 720 branch to line 721 */ @Test public void checkDate4() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '1'; char y3 = '1'; char M0 = '1'; char M1 = '0'; int d0 = 50; int d1 = 32810; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 691 */ @Test public void checkDate5() throws Throwable { // Arrange char y0 = '4'; char y1 = '\u0000'; char y2 = '\u0000'; char y3 = '\u0000'; char M0 = '\u0000'; char M1 = '\u0000'; int d0 = 0; int d1 = 0; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 691 */ @Test public void checkDate6() throws Throwable { // Arrange char y0 = '\u0000'; char y1 = '\u0000'; char y2 = '\u0000'; char y3 = '\u0000'; char M0 = '\u0000'; char M1 = '\u0000'; int d0 = 0; int d1 = 0; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 704 * - conditional line 704 branch to line 705 */ @Test public void checkDate7() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '0'; char y3 = '0'; char M0 = '0'; char M1 = '\u0000'; int d0 = 0; int d1 = 0; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 694 */ @Test public void checkDate8() throws Throwable { // Arrange char y0 = '2'; char y1 = '\u0011'; char y2 = '0'; char y3 = '\u0830'; char M0 = '1'; char M1 = '\u0000'; int d0 = 0; int d1 = 0; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 707 * - conditional line 707 branch to line 708 * - conditional line 708 branch to line 715 * - conditional line 715 branch to line 719 * - conditional line 719 branch to line 720 * - conditional line 720 branch to line 720 * - conditional line 720 branch to line 731 */ @Test public void checkDate9() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '1'; char y3 = '1'; char M0 = '1'; char M1 = '0'; int d0 = 49; int d1 = 49; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(true, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 707 * - conditional line 707 branch to line 708 * - conditional line 708 branch to line 715 * - conditional line 715 branch to line 719 * - conditional line 719 branch to line 719 * - conditional line 719 branch to line 723 * - conditional line 723 branch to line 728 */ @Test public void checkDate10() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '1'; char y3 = '1'; char M0 = '1'; char M1 = '0'; int d0 = 8388658; int d1 = 32810; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 707 * - conditional line 707 branch to line 708 * - conditional line 708 branch to line 715 * - conditional line 715 branch to line 716 * - conditional line 716 branch to line 716 * - conditional line 716 branch to line 731 */ @Test public void checkDate11() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '1'; char y3 = '1'; char M0 = '1'; char M1 = '0'; int d0 = 48; int d1 = 49; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(true, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 697 */ @Test public void checkDate12() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '\u8030'; char y3 = '\u0830'; char M0 = '1'; char M1 = '\u0000'; int d0 = 0; int d1 = 0; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 707 * - conditional line 707 branch to line 708 * - conditional line 708 branch to line 715 * - conditional line 715 branch to line 716 * - conditional line 716 branch to line 717 */ @Test public void checkDate13() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '1'; char y3 = '1'; char M0 = '1'; char M1 = '0'; int d0 = 48; int d1 = 0; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 707 * - conditional line 707 branch to line 708 * - conditional line 708 branch to line 715 * - conditional line 715 branch to line 719 * - conditional line 719 branch to line 719 * - conditional line 719 branch to line 723 * - conditional line 723 branch to line 724 * - conditional line 724 branch to line 724 * - conditional line 724 branch to line 725 */ @Test public void checkDate14() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '1'; char y3 = '1'; char M0 = '1'; char M1 = '0'; int d0 = 51; int d1 = -2147483600; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 707 * - conditional line 707 branch to line 708 * - conditional line 708 branch to line 708 * - conditional line 708 branch to line 709 */ @Test public void checkDate15() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '1'; char y3 = '1'; char M0 = '1'; char M1 = '\u8031'; int d0 = 0; int d1 = 0; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 700 */ @Test public void checkDate16() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '0'; char y3 = '\u0830'; char M0 = '1'; char M1 = '\u0000'; int d0 = 0; int d1 = 0; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 690 branch to line 690 * - conditional line 690 branch to line 693 * - conditional line 693 branch to line 693 * - conditional line 693 branch to line 696 * - conditional line 696 branch to line 696 * - conditional line 696 branch to line 699 * - conditional line 699 branch to line 699 * - conditional line 699 branch to line 703 * - conditional line 703 branch to line 707 * - conditional line 707 branch to line 712 */ @Test public void checkDate17() throws Throwable { // Arrange char y0 = '2'; char y1 = '1'; char y2 = '0'; char y3 = '0'; char M0 = '\u0000'; char M1 = '\u0000'; int d0 = 0; int d1 = 0; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkDate", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("int"), Reflector.forName("int")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(null, y0, y1, y2, y3, M0, M1, d0, d1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 643 * - conditional line 643 branch to line 648 */ @Test public void checkTime1() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '\u0000'; char h1 = '\u0000'; char m0 = '\u0000'; char m1 = '\u0000'; char s0 = '\u0000'; char s1 = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 643 * - conditional line 643 branch to line 644 * - conditional line 644 branch to line 645 */ @Test public void checkTime2() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '2'; char h1 = '\u0000'; char m0 = '\u0000'; char m1 = '\u0000'; char s0 = '\u0000'; char s1 = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 636 * - conditional line 636 branch to line 636 * - conditional line 636 branch to line 637 */ @Test public void checkTime3() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '0'; char h1 = '<'; char m0 = '\u0000'; char m1 = '\u0000'; char s0 = '\u0000'; char s1 = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 636 * - conditional line 636 branch to line 637 */ @Test public void checkTime4() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '0'; char h1 = ' '; char m0 = '\u0000'; char m1 = '\u0000'; char s0 = '\u0000'; char s1 = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 643 * - conditional line 643 branch to line 644 * - conditional line 644 branch to line 644 * - conditional line 644 branch to line 645 */ @Test public void checkTime5() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '2'; char h1 = '5'; char m0 = '\u0000'; char m1 = '\u0000'; char s0 = '\u0000'; char s1 = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 636 * - conditional line 636 branch to line 636 * - conditional line 636 branch to line 651 * - conditional line 651 branch to line 651 * - conditional line 651 branch to line 652 * - conditional line 652 branch to line 653 */ @Test public void checkTime6() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '0'; char h1 = '9'; char m0 = '1'; char m1 = '\u0000'; char s0 = '\u0000'; char s1 = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 640 * - conditional line 640 branch to line 640 * - conditional line 640 branch to line 641 */ @Test public void checkTime7() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '1'; char h1 = '='; char m0 = '1'; char m1 = '\u0000'; char s0 = '\u0000'; char s1 = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 640 * - conditional line 640 branch to line 640 * - conditional line 640 branch to line 651 * - conditional line 651 branch to line 651 * - conditional line 651 branch to line 652 * - conditional line 652 branch to line 653 */ @Test public void checkTime8() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '1'; char h1 = '9'; char m0 = '1'; char m1 = '\u0000'; char s0 = '\u0000'; char s1 = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 640 * - conditional line 640 branch to line 640 * - conditional line 640 branch to line 651 * - conditional line 651 branch to line 655 * - conditional line 655 branch to line 660 */ @Test public void checkTime9() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '1'; char h1 = '9'; char m0 = ' '; char m1 = '\u0000'; char s0 = '\u0000'; char s1 = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 640 * - conditional line 640 branch to line 640 * - conditional line 640 branch to line 651 * - conditional line 651 branch to line 651 * - conditional line 651 branch to line 652 * - conditional line 652 branch to line 652 * - conditional line 652 branch to line 663 * - conditional line 663 branch to line 663 * - conditional line 663 branch to line 664 * - conditional line 664 branch to line 665 */ @Test public void checkTime10() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '1'; char h1 = '9'; char m0 = '4'; char m1 = '3'; char s0 = '1'; char s1 = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 640 * - conditional line 640 branch to line 640 * - conditional line 640 branch to line 651 * - conditional line 651 branch to line 651 * - conditional line 651 branch to line 655 * - conditional line 655 branch to line 656 * - conditional line 656 branch to line 663 * - conditional line 663 branch to line 663 * - conditional line 663 branch to line 664 * - conditional line 664 branch to line 664 * - conditional line 664 branch to line 665 */ @Test public void checkTime11() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '1'; char h1 = '9'; char m0 = '6'; char m1 = '0'; char s0 = '1'; char s1 = '\u0430'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 640 * - conditional line 640 branch to line 640 * - conditional line 640 branch to line 651 * - conditional line 651 branch to line 651 * - conditional line 651 branch to line 655 * - conditional line 655 branch to line 656 * - conditional line 656 branch to line 663 * - conditional line 663 branch to line 663 * - conditional line 663 branch to line 667 * - conditional line 667 branch to line 668 * - conditional line 668 branch to line 669 */ @Test public void checkTime12() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '1'; char h1 = '9'; char m0 = '6'; char m1 = '0'; char s0 = '6'; char s1 = '\u0430'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 640 * - conditional line 640 branch to line 640 * - conditional line 640 branch to line 651 * - conditional line 651 branch to line 651 * - conditional line 651 branch to line 655 * - conditional line 655 branch to line 656 * - conditional line 656 branch to line 663 * - conditional line 663 branch to line 663 * - conditional line 663 branch to line 667 * - conditional line 667 branch to line 672 */ @Test public void checkTime13() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '1'; char h1 = '9'; char m0 = '6'; char m1 = '0'; char s0 = '>'; char s1 = '\u0430'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 640 * - conditional line 640 branch to line 640 * - conditional line 640 branch to line 651 * - conditional line 651 branch to line 651 * - conditional line 651 branch to line 655 * - conditional line 655 branch to line 656 * - conditional line 656 branch to line 663 * - conditional line 663 branch to line 663 * - conditional line 663 branch to line 667 * - conditional line 667 branch to line 668 * - conditional line 668 branch to line 675 */ @Test public void checkTime14() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '1'; char h1 = '9'; char m0 = '6'; char m1 = '0'; char s0 = '6'; char s1 = '0'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(true, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 640 * - conditional line 640 branch to line 640 * - conditional line 640 branch to line 651 * - conditional line 651 branch to line 651 * - conditional line 651 branch to line 652 * - conditional line 652 branch to line 652 * - conditional line 652 branch to line 663 * - conditional line 663 branch to line 663 * - conditional line 663 branch to line 664 * - conditional line 664 branch to line 664 * - conditional line 664 branch to line 665 */ @Test public void checkTime15() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '1'; char h1 = '9'; char m0 = '4'; char m1 = '3'; char s0 = '1'; char s1 = '\u0430'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 640 * - conditional line 640 branch to line 640 * - conditional line 640 branch to line 651 * - conditional line 651 branch to line 651 * - conditional line 651 branch to line 652 * - conditional line 652 branch to line 652 * - conditional line 652 branch to line 653 */ @Test public void checkTime16() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '1'; char h1 = '9'; char m0 = '4'; char m1 = ':'; char s0 = '\u0000'; char s1 = '\u0000'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 635 branch to line 639 * - conditional line 639 branch to line 640 * - conditional line 640 branch to line 640 * - conditional line 640 branch to line 651 * - conditional line 651 branch to line 651 * - conditional line 651 branch to line 655 * - conditional line 655 branch to line 656 * - conditional line 656 branch to line 657 */ @Test public void checkTime17() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", ""); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = ""; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; char h0 = '1'; char h1 = '9'; char m0 = '6'; char m1 = '1'; char s0 = '1'; char s1 = '\u0430'; // Act Class c = Reflector.forName("com.alibaba.fastjson.parser.JSONScanner"); Method m = c.getDeclaredMethod("checkTime", Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char"), Reflector.forName("char")); m.setAccessible(true); boolean retval = (Boolean)m.invoke(objectUnderTest, h0, h1, m0, m1, s0, s1); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 2040 branch to line 2040 */ @Test public void info1() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; Locale locale = ((Locale)Reflector.getInstance("java.util.Locale")); objectUnderTest.locale = locale; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", "(((("); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 7; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = "!!!!"; objectUnderTest.pos = 0; objectUnderTest.sp = 0; char[] charArray = { '\u0000' }; objectUnderTest.sbuf = charArray; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; // Act String retval = objectUnderTest.info(); // Assert result Assert.assertEquals("pos 7, json : ((((", retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 736 branch to line 736 */ @Test public void isEOF1() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", null); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 0; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = null; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u001a'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; // Act boolean retval = objectUnderTest.isEOF(); // Assert result Assert.assertEquals(true, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 736 branch to line 736 */ @Test public void isEOF2() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", null); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 1; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = null; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u0000'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; // Act boolean retval = objectUnderTest.isEOF(); // Assert result Assert.assertEquals(false, retval); } /* * Test generated by Diffblue Deeptest. * This test case covers: * - conditional line 736 branch to line 736 */ @Test public void isEOF3() throws Throwable { // Arrange JSONScanner objectUnderTest = ((JSONScanner)Reflector.getInstance("com.alibaba.fastjson.parser.JSONScanner")); objectUnderTest.hasSpecial = false; objectUnderTest.token = 0; objectUnderTest.locale = null; objectUnderTest.np = 0; objectUnderTest.features = 0; Reflector.setField(objectUnderTest, "text", null); objectUnderTest.calendar = null; objectUnderTest.matchStat = 0; objectUnderTest.bp = 1; Reflector.setField(objectUnderTest, "len", 0); objectUnderTest.stringDefaultValue = null; objectUnderTest.pos = 0; objectUnderTest.sp = 0; objectUnderTest.sbuf = null; objectUnderTest.ch = '\u001a'; objectUnderTest.timeZone = null; objectUnderTest.eofPos = 0; // Act boolean retval = objectUnderTest.isEOF(); // Assert result Assert.assertEquals(false, retval); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/SerializeWriterTest.java ================================================ package com.alibaba.fastjson.serializer; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; 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 str = createLargeBasicStr(); this.doTestWrite(str); } private String createLargeBasicStr() { String tmp = new String(IOUtils.DIGITS); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 400; i++) { builder.append(tmp); } return 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()); } @Test public void test_large() throws Exception { SerializeWriter writer = new SerializeWriter(); for (int i = 0; i < 1024 * 1024; ++i) { writer.write(i); } writer.close(); } @Test public void testBytesBufLocal() throws Exception { String str = createLargeBasicStr(); SerializeWriter writer = new SerializeWriter(); //写入大于12K的字符串 writer.writeString(str); writer.writeString(str); byte[] bytes = writer.toBytes("UTF-8"); writer.close(); //检查bytesLocal大小,如果缓存成功应该大于等于输出的bytes长度 Field bytesBufLocalField = SerializeWriter.class.getDeclaredField("bytesBufLocal"); bytesBufLocalField.setAccessible(true); ThreadLocal bytesBufLocal = (ThreadLocal) bytesBufLocalField.get(null); byte[] bytesLocal = bytesBufLocal.get(); Assert.assertNotNull("bytesLocal is null", bytesLocal); Assert.assertTrue("bytesLocal is smaller than expected", bytesLocal.length >= bytes.length); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/SerializeWriterToBytesTest.java ================================================ package com.alibaba.fastjson.serializer; import com.alibaba.fastjson.util.IOUtils; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * @author gongdewei 2020/5/15 */ public class SerializeWriterToBytesTest { /** * Execute toBytes periodically, use tools to analyze JVM memory allocation. * For example, Memory Allocation Record of YourKit java profiler */ public static void testLargeStrToBytes() { String str = createTestStr(); for (int i = 0; i < 600; i++) { SerializeWriter writer = new SerializeWriter(); try { writer.writeString(str); writer.toBytes("UTF-8"); } finally { writer.close(); } try { Thread.sleep(1000); } catch (InterruptedException e) { } } } public static void testLargeStrWriteToEx() throws IOException { String str = createTestStr(); ByteArrayOutputStream baos = new ByteArrayOutputStream(str.length()+2); for (int i = 0; i < 600; i++) { SerializeWriter writer = new SerializeWriter(); try { writer.writeString(str); writer.writeToEx(baos, IOUtils.UTF8); } finally { writer.close(); baos.reset(); } try { Thread.sleep(1000); } catch (InterruptedException e) { } } } private static String createTestStr() { String tmp = new String(IOUtils.DIGITS); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 400; i++) { builder.append(tmp); } return builder.toString(); } public static void main(String[] args) throws IOException { testLargeStrToBytes(); // testLargeStrWriteToEx(); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/TestBean.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/TestParse.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/issue3084/TestRefWithQuote.java ================================================ package com.alibaba.fastjson.serializer.issue3084; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class TestRefWithQuote { public static class X { private String x; public X(String x) { this.x = x; } public String getX() { return x; } public void setX(String x) { this.x = x; } } @Test public void testIssue3084() { Map origin = new HashMap(); TestRefWithQuote.X x = new TestRefWithQuote.X("x"); origin.put("aaaa\"", x); origin.put("bbbb\"", x); try { String json = JSON.toJSONString(origin, true); JSONObject root = JSON.parseObject(json); assertSame(root.get("bbbb\\"), root.get("aaaa\\")); } catch (Exception e) { fail("should not fail !!!"); } } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/issue3177/Test3177Bean.java ================================================ package com.alibaba.fastjson.serializer.issue3177; /** * * @author shenzhou-6 * @since 2020年05月26日 * * https://github.com/alibaba/fastjson/issues/3177 */ public class Test3177Bean { static class Parent { private String _status; public String get_status() { return _status; } public void set_status(String _status) { this._status = _status; } } static class Son extends Parent { private String status; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/issue3177/TestIssues3177.java ================================================ package com.alibaba.fastjson.serializer.issue3177; import com.alibaba.fastjson.JSON; import org.junit.Assert; import org.junit.Test; /** * * @author shenzhou-6 * @since 2020年05月26日 * * https://github.com/alibaba/fastjson/issues/3177 */ public class TestIssues3177 { @Test public void testIssues3177(){ Test3177Bean.Son son = new Test3177Bean.Son(); son.setStatus("status"); Assert.assertEquals("{\"status\":\"status\"}",JSON.toJSONString(son)); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/issue3473/SerializeWriterJavaSqlDateTest.java ================================================ package com.alibaba.fastjson.serializer.issue3473; import java.sql.Date; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.time.DateUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; /** * package com.alibaba.fastjson.serializer.issue3473
* description: java.sql.Date序列化测试
* Copyright 2019 thunisoft, Inc. All rights reserved. * * @author fanzhongwei * @date 20-9-29 */ public class SerializeWriterJavaSqlDateTest { private Map data = new HashMap(1, 1); @Before public void before() throws ParseException { data.put("sqlDate", new Date(DateUtils.parseDate("2020-09-29", "yyyy-MM-dd") .getTime())); } @Test public void yyyy_MM_dd_HH_mm_ss_test() { String json = JSON.toJSONString(data, SerializerFeature.WriteDateUseDateFormat); Assert.assertEquals("{\"sqlDate\":\"2020-09-29 00:00:00\"}", json); } @Test public void yyyy_MM_dd_test() { String json = JSON.toJSONString(data); Assert.assertEquals("{\"sqlDate\":\"2020-09-29\"}", json); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/issue3479/TestIssue3479.java ================================================ package com.alibaba.fastjson.serializer.issue3479; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.serializer.SerializerFeature; public class TestIssue3479 { @JSONType(seeAlso = {Dog.class, Cat.class}, typeKey = "typeKey") public static abstract class Animal { private String typeKey; public String getTypeKey() { return typeKey; } public void setTypeKey(String typeKey) { this.typeKey = typeKey; } } @JSONType(typeName = "dog") public static class Dog extends Animal { private String dogName; public String getDogName() { return dogName; } public void setDogName(String dogName) { this.dogName = dogName; } @Override public String toString() { return "Dog{" + "dogName='" + dogName + '\'' + '}'; } } @JSONType(typeName = "cat") public static class Cat extends Animal { private String catName; public String getCatName() { return catName; } public void setCatName(String catName) { this.catName = catName; } @Override public String toString() { return "Cat{" + "catName='" + catName + '\'' + '}'; } } public static void main(String[] args) { Dog dog = new Dog(); dog.dogName = "dog1001"; String text = JSON.toJSONString(dog, SerializerFeature.WriteClassName); System.out.println(text); Dog dog2 = (Dog) JSON.parseObject(text, Animal.class); System.out.println(dog2); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/issue3638and3067/Issue3638and3067Test.java ================================================ package com.alibaba.fastjson.serializer.issue3638and3067; import com.alibaba.fastjson.JSONObject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.sql.Timestamp; /** * @author Shilong Li (Lori) * @project fastjson * @filename Issue3638and3067Test * @date 2021/4/17 14:47 */ public class Issue3638and3067Test { JSONObject jo; @Before public void init() { jo = new JSONObject(); } @Test public void testTime1() { jo.put("d1", "2021-04-17 15:14:00"); Assert.assertEquals(new Timestamp(jo.getDate("d1").getTime()), jo.getTimestamp("d1")); } @Test public void testTime2() { jo.put("d2", "1970-01-01 08:00:00"); Assert.assertEquals(new Timestamp(jo.getDate("d2").getTime()), jo.getTimestamp("d2")); } @Test public void testTime3() { jo.put("d3", "1970-01-01 07:00:00"); Assert.assertEquals(new Timestamp(jo.getDate("d3").getTime()), jo.getTimestamp("d3")); } @Test public void testTime4() { jo.put("d4", "1900-01-01"); Assert.assertEquals(new Timestamp(jo.getDate("d4").getTime()), jo.getTimestamp("d4")); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/issues3601/TestEntity.java ================================================ package com.alibaba.fastjson.serializer.issues3601; import lombok.Data; @Data public class TestEntity { private TestEnum testEnum; private String testName; } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/issues3601/TestEnum.java ================================================ package com.alibaba.fastjson.serializer.issues3601; import com.alibaba.fastjson.annotation.JSONField; public enum TestEnum { @JSONField test1("1"), // @JSONField test2("2"); private String title; TestEnum(String title) { this.title = title; } // @JSONField public String getTitle() { return title; } private Integer i = 100; @JSONField public Integer getI() { return i; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/serializer/issues3601/TestIssue3601.java ================================================ package com.alibaba.fastjson.serializer.issues3601; import com.alibaba.fastjson.JSON; import org.junit.Assert; import org.junit.Test; public class TestIssue3601 { @Test public void enumTest() { TestEntity testEntity = new TestEntity(); testEntity.setTestName("ganyu"); testEntity.setTestEnum(TestEnum.test1); String json = JSON.toJSONString(testEntity); System.out.println(json); Assert.assertEquals("{\"testEnum\":\"test1\",\"testName\":\"ganyu\"}", json); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/support/jaxrs/TestIssue885.java ================================================ 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"); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/support/jaxrs/User.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/fastjson/validate/JSONValidateTest_0.java ================================================ package com.alibaba.fastjson.validate; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONValidator; import com.alibaba.json.test.benchmark.decode.EishayDecodeBytes; import junit.framework.TestCase; import java.io.ByteArrayInputStream; public class JSONValidateTest_0 extends TestCase { public void test_validate_benchmark() throws Exception { String json = JSON.toJSONString(EishayDecodeBytes.instance.getContent()); for (int n = 0; n < 10; ++n) { long start = System.currentTimeMillis(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { JSONValidator validator = JSONValidator.from(json); validator.validate(); // 518 } System.out.println("millis : " + (System.currentTimeMillis() - start)); } } public void test_validate_utf8_benchmark() throws Exception { byte[] json = JSON.toJSONBytes(EishayDecodeBytes.instance.getContent()); for (int n = 0; n < 5; ++n) { long start = System.currentTimeMillis(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { JSONValidator validator = JSONValidator.fromUtf8(json); validator.validate(); } System.out.println("millis : " + (System.currentTimeMillis() - start)); } } } ================================================ FILE: src/test/java/com/alibaba/fastjson/validate/JSONValidateTest_T1 ================================================ package com.alibaba.fastjson.validate; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import com.alibaba.fastjson.JSONValidator; import junit.framework.TestCase; public class JSONValidateTest_T1 { @Before public void setUp() throws Exception { } @Test public void testCap1Case1() { try { JSONValidator.from((String) null).validate(); fail("Should not be able to validate a null object but it did"); } catch (Exception e) { } } @Test public void testCap1Case2() { try { JSONValidator jsv = JSONValidator.from((String) null); jsv.setSupportMultiValue(true); jsv.validate(); fail("Should not be able to validate a null object but it did"); } catch (Exception e) { } } @Test public void testCap1Case3() { JSONValidator jsv = JSONValidator.from("{\"a\" : \"b\"}"); assertTrue(jsv.validate()); } @Test public void testCap1Case4() { JSONValidator jsv = JSONValidator.from("true"); assertTrue(jsv.validate()); } @Test public void testCap1Case5() { JSONValidator jsv = JSONValidator.from("{\"a\" : \"b\"}{\"a\" : \"b\"}"); assertFalse(jsv.validate()); } @Test public void testCap1Case6() { JSONValidator jsv = JSONValidator.from("true true"); jsv.setSupportMultiValue(true); assertTrue(jsv.validate()); } @Test public void testCap1Case7() { JSONValidator jsv = JSONValidator.from("true true false"); assertFalse(jsv.validate()); } @Test public void testCap1Case8() { JSONValidator jsv = JSONValidator.from("true true false"); jsv.setSupportMultiValue(true); assertTrue(jsv.validate()); } @Test public void testCap1Case9() { JSONValidator jsv = JSONValidator.from(""); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case10() { JSONValidator jsv = JSONValidator.from(""); jsv.setSupportMultiValue(true); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case11() { JSONValidator jsv = JSONValidator.from("ÏÇ◊ÎÏ◊Œ„´ˇÁ¨ˆØÏ◊ı˜"); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case12() { JSONValidator jsv = JSONValidator.from("ÏÇ◊ÎÏ◊Œ„´ˇÁ¨ˆØÏ◊ı˜"); jsv.setSupportMultiValue(true); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case13() { JSONValidator jsv = JSONValidator.from("ÏÇ◊ÎÏ◊Œ„´ ˇÁ¨ˆØÏ◊ı˜"); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case14() { JSONValidator jsv = JSONValidator.from("ÏÇ◊ÎÏ◊Œ„´ ˇÁ¨ˆØÏ◊ı˜"); jsv.setSupportMultiValue(true); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case15() { JSONValidator jsv = JSONValidator.from("ÏÇ◊ÎÏ◊Œ„´ ˇÁ¨ˆØÏ◊ı˜ ÏÇ◊ÎÏ◊Œ„´"); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case16() { JSONValidator jsv = JSONValidator.from("ÏÇ◊ÎÏ◊Œ„´ ˇÁ¨ˆØÏ◊ı˜ ÏÇ◊ÎÏ◊Œ„´"); jsv.setSupportMultiValue(true); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case17() { JSONValidator jsv = JSONValidator.from("{\"a\" : \"b\"},{\"a\" : \"b\"}"); assertFalse(jsv.validate()); } @Test public void testCap1Case18() { JSONValidator jsv = JSONValidator.from("{\"a\" : \"b\"},{\"a\" : \"b\"},{\"a\" : \"b\"}"); assertFalse(jsv.validate()); } @Test public void testCap1Case19() { JSONValidator jsv = JSONValidator.from("[{\"a\" : {\"b\" : \"c\"}}]"); assertTrue(jsv.validate()); } @Test public void testCap1Case20() { JSONValidator jsv = JSONValidator.from("[{\"a\" : {\"b\" : \"c\"}}],[{\"a\" : {\"b\" : \"c\"}}]"); assertFalse(jsv.validate()); } @Test public void testCap1Case21() { JSONValidator jsv = JSONValidator.from("[{\"a\" : {\"b\" : \"c\"}}],[{\"a\" : {\"b\" : \"c\"}}],[{\"a\" : {\"b\" : \"c\"}}]"); assertFalse(jsv.validate()); } @Test public void testCap1Case22() { JSONValidator jsv = JSONValidator.from("true, true"); assertFalse(jsv.validate()); } @Test public void testCap1Case23() { JSONValidator jsv = JSONValidator.from("true, true, true"); assertFalse(jsv.validate()); } @Test public void testCap1Case24() { JSONValidator jsv = JSONValidator.from("{\"a\" : {\"b\" : \"c\"}}"); assertTrue(jsv.validate()); } @Test public void testCap1Case25() { JSONValidator jsv = JSONValidator.from("{\"a\" : {\"b\" : \"c\"}},{\"a\" : {\"b\" : \"c\"}}"); assertFalse(jsv.validate()); } @Test public void testCap1Case26() { JSONValidator jsv = JSONValidator.from("{\"a\" : {\"b\" : \"c\"}},{\"a\" : {\"b\" : \"c\"}},{\"a\" : {\"b\" : \"c\"}}"); assertFalse(jsv.validate()); } @Test public void testCap1Case27() { JSONValidator jsv = JSONValidator.from("[{\"a\" : \"b\"}]"); assertTrue(jsv.validate()); } @Test public void testCap1Case28() { JSONValidator jsv = JSONValidator.from("[{\"a\" : \"b\"}],[{\"a\" : \"b\"}]"); assertFalse(jsv.validate()); } @Test public void testCap1Case29() { JSONValidator jsv = JSONValidator.from("[{\"a\" : \"b\"}],[{\"a\" : \"b\"}],[{\"a\" : \"b\"}]"); assertFalse(jsv.validate()); } @Test public void testCap1Case30() { JSONValidator jsv = JSONValidator.from("{\"a\" : {\"b\" : {\"c\" : \"d\"}}}"); assertTrue(jsv.validate()); } @Test public void testCap1Case31() { JSONValidator jsv = JSONValidator.from("{\"a\" : {\"b\" : {\"c\" : \"d\"}}},{\"a\" : {\"b\" : {\"c\" : \"d\"}}}"); assertFalse(jsv.validate()); } @Test public void testCap1Case32() { JSONValidator jsv = JSONValidator.from("{\"a\" : {\"b\" : {\"c\" : \"d\"}}},{\"a\" : {\"b\" : {\"c\" : \"d\"}}},{\"a\" : {\"b\" : {\"c\" : \"d\"}}}"); assertFalse(jsv.validate()); } @Test public void testCap1Case33() { JSONValidator jsv = JSONValidator.from("[{\"a\" : {\"b\" : \"c\"}}]"); assertTrue(jsv.validate()); } @Test public void testCap1Case34() { JSONValidator jsv = JSONValidator.from("[{\"a\" : {\"b\" : \"c\"}}],[{\"a\" : {\"b\" : \"c\"}}]"); assertFalse(jsv.validate()); } @Test public void testCap1Case35() { JSONValidator jsv = JSONValidator.from("[{\"a\" : {\"b\" : \"c\"}}],[{\"a\" : {\"b\" : \"c\"}}],[{\"a\" : {\"b\" : \"c\"}}]"); assertFalse(jsv.validate()); } @Test public void testCap1Case36() { JSONValidator jsv = JSONValidator.from("{\"a\" : {\"b\" : {\"c\" : {\"d\" : \"e\"}}}}"); assertTrue(jsv.validate()); } @Test public void testCap1Case37() { JSONValidator jsv = JSONValidator.from("{\"a\" : {\"b\" : {\"c\" : {\"d\" : \"e\"}}}},{\"a\" : {\"b\" : {\"c\" : {\"d\" : \"e\"}}}}"); assertFalse(jsv.validate()); } @Test public void testCap1Case38() { JSONValidator jsv = JSONValidator.from("{\"a\" : {\"b\" : {\"c\" : {\"d\" : \"e\"}}}},{\"a\" : {\"b\" : {\"c\" : {\"d\" : \"e\"}}}},{\"a\" : {\"b\" : {\"c\" : {\"d\" : \"e\"}}}}"); assertFalse(jsv.validate()); } @Test public void testCap1Case39() { JSONValidator jsv = JSONValidator.from("[{\"a\" : {\"b\" : {\"c\" : \"d\"}}}]"); assertTrue(jsv.validate()); } @Test public void testCap1Case40() { JSONValidator jsv = JSONValidator.from("[{\"a\" : {\"b\" : {\"c\" : \"d\"}}}],[{\"a\" : {\"b\" : {\"c\" : \"d\"}}}]"); assertFalse(jsv.validate()); } @Test public void testCap1Case41() { JSONValidator jsv = JSONValidator.from("[{\"a\" : {\"b\" : {\"c\" : \"d\"}}}],[{\"a\" : {\"b\" : {\"c\" : \"d\"}}}],[{\"a\" : {\"b\" : {\"c\" : \"d\"}}}]"); assertFalse(jsv.validate()); } @Test public void testCap1Case42() { JSONValidator jsv = JSONValidator.from("1e4"); assertTrue(jsv.validate()); } @Test public void testCap1Case43() { JSONValidator jsv = JSONValidator.from("e10"); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case44() { JSONValidator jsv = JSONValidator.from("4e"); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case46() { JSONValidator jsv = JSONValidator.from("12.34"); assertTrue(jsv.validate()); } @Test public void testCap1Case47() { JSONValidator jsv = JSONValidator.from(".3"); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case48() { JSONValidator jsv = JSONValidator.from("13."); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case50() { JSONValidator jsv = JSONValidator.from("-12"); assertTrue(jsv.validate()); } @Test public void testCap1Case51() { JSONValidator jsv = JSONValidator.from("+43"); assertTrue(jsv.validate()); } @Test public void testCap1Case52() { JSONValidator jsv = JSONValidator.from("-"); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case53() { JSONValidator jsv = JSONValidator.from("[\"a\",\"b\"]"); assertTrue(jsv.validate()); } @Test public void testCap1Case54() { JSONValidator jsv = JSONValidator.from("1,2]"); assertFalse(jsv.validate()); } @Test public void testCap1Case55() { JSONValidator jsv = JSONValidator.from("[{\"a\":\"b\"},123"); assertFalse(jsv.validate()); } @Test public void testCap1Case56() { JSONValidator jsv = JSONValidator.from("[1 {\"abc\":\"zxy\"}"); assertFalse(jsv.validate()); } @Test public void testCap1Case57() { JSONValidator jsv = JSONValidator.from("{\"123\": [1,2,3]}"); assertTrue(jsv.validate()); } @Test public void testCap1Case58() { JSONValidator jsv = JSONValidator.from("\"Zxy\":\"abc\",\"x\":\"y\"}"); assertFalse(jsv.validate()); } @Test public void testCap1Case59() { JSONValidator jsv = JSONValidator.from("{\"h\":[12,23],\"a\":\"b\""); assertFalse(jsv.validate()); } @Test public void testCap1Case60() { JSONValidator jsv = JSONValidator.from("{\"a\":\"z\" \"b\":\"y\""); assertFalse(jsv.validate()); } @Test public void testCap1Case61() { JSONValidator jsv = JSONValidator.from("{\"123\"\"abc\", \"efg\":\"456\""); assertFalse(jsv.validate()); } @Test public void testCap1Case62() { JSONValidator jsv = JSONValidator.from("\"abc\""); assertTrue(jsv.validate()); } @Test public void testCap1Case63() { JSONValidator jsv = JSONValidator.from("abc\""); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case64() { JSONValidator jsv = JSONValidator.from("\"abc"); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case65() { JSONValidator jsv = JSONValidator.from("null"); assertTrue(jsv.validate()); } @Test public void testCap1Case66() { JSONValidator jsv = JSONValidator.from("abc"); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case67() { JSONValidator jsv = JSONValidator.from("true"); assertTrue(jsv.validate()); } @Test public void testCap1Case68() { JSONValidator jsv = JSONValidator.from("true;"); assertFalse(jsv.validate()); assertNull(jsv.getType()); } @Test public void testCap1Case69() { JSONValidator jsv = JSONValidator.from("true "); assertFalse(jsv.validate()); } @Test public void testCap1Case70() { JSONValidator jsv = JSONValidator.from("true\t"); assertFalse(jsv.validate()); } @Test public void testCap1Case71() { JSONValidator jsv = JSONValidator.from("true\r"); assertFalse(jsv.validate()); } @Test public void testCap1Case72() { JSONValidator jsv = JSONValidator.from("true\n"); assertFalse(jsv.validate()); } @Test public void testCap1Case73() { JSONValidator jsv = JSONValidator.from("true\f"); assertFalse(jsv.validate()); } @Test public void testCap1Case74() { JSONValidator jsv = JSONValidator.from("true\b"); assertFalse(jsv.validate()); } @Test public void testCap1Case75() { JSONValidator jsv = JSONValidator.from("true,"); assertFalse(jsv.validate()); } @Test public void testCap1Case76() { JSONValidator jsv = JSONValidator.from("true]"); assertFalse(jsv.validate()); } @Test public void testCap1Case77() { JSONValidator jsv = JSONValidator.from("true}"); assertFalse(jsv.validate()); } @Test public void testCap1Case78() { JSONValidator jsv = JSONValidator.from("true\0"); assertFalse(jsv.validate()); } @Test public void testCap1Case79() { JSONValidator jsv = JSONValidator.from("{\"abc\":\"bcd\"}"); assertTrue(jsv.validate()); } @Test public void testCap1Case80() { JSONValidator jsv = JSONValidator.from("{\"cat\":\"dog\"\"cat\":\"dog\"}"); assertFalse(jsv.validate()); } @Test public void testCap1Case81() { JSONValidator jsv = JSONValidator.from("{}"); assertTrue(jsv.validate()); } @Test public void testCap1Case82() { JSONValidator jsv = JSONValidator.from("{ }"); assertTrue(jsv.validate()); } @Test public void testCap1Case83() { JSONValidator jsv = JSONValidator.from("{abc:\"abc\"}"); assertFalse(jsv.validate()); } @Test public void testCap1Case84() { JSONValidator jsv = JSONValidator.from("{\"xyz\" }"); assertFalse(jsv.validate()); } @Test public void testCap1Case85() { JSONValidator jsv = JSONValidator.from("{\"test\": test}"); assertFalse(jsv.validate()); } @Test public void testCap1Case86() { JSONValidator jsv = JSONValidator.from("{\"hello\":\"world\", \"x\":\"y\"}"); assertTrue(jsv.validate()); } @Test public void testCap1Case87() { JSONValidator jsv = JSONValidator.from("[ 123 ]"); assertTrue(jsv.validate()); } @Test public void testCap1Case88() { JSONValidator jsv = JSONValidator.from("[ \"ab\""); assertFalse(jsv.validate()); } @Test public void testCap1Case89() { JSONValidator jsv = JSONValidator.from("[ true,\"g\" ]"); assertTrue(jsv.validate()); } @Test public void testCap1Case90() { JSONValidator jsv = JSONValidator.from("[ tru ]"); assertFalse(jsv.validate()); } @Test public void testCap1Case91() { JSONValidator jsv = JSONValidator.from("[ ]"); assertTrue(jsv.validate()); } @Test public void testCap1Case92() { JSONValidator jsv = JSONValidator.from("4.3e-1"); assertTrue(jsv.validate()); } @Test public void testCap1Case94() { JSONValidator jsv = JSONValidator.from("[4.3e-1]"); assertTrue(jsv.validate()); } @Test public void testCap1Case193() { JSONValidator jsv = JSONValidator.from("4.3e-13"); assertTrue(jsv.validate()); } @Test public void testCap1Case95() { JSONValidator jsv = JSONValidator.from("4.3e-:"); assertFalse(jsv.validate()); } @Test public void testCap1Case96() { JSONValidator jsv = JSONValidator.from("4.3e-."); assertFalse(jsv.validate()); } @Test public void testCap1Case97() { JSONValidator jsv = JSONValidator.from("4.3e+13"); assertTrue(jsv.validate()); } @Test public void testCap1Case98() { JSONValidator jsv = JSONValidator.from("4.3e13"); assertTrue(jsv.validate()); } @Test public void testCap1Case99() { JSONValidator jsv = JSONValidator.from("4.3E-1"); assertTrue(jsv.validate()); } @Test public void testCap1Case100() { JSONValidator jsv = JSONValidator.from("4.3"); assertTrue(jsv.validate()); } @Test public void testCap1Case101() { JSONValidator jsv = JSONValidator.from("4.:"); assertFalse(jsv.validate()); } @Test public void testCap1Case102() { JSONValidator jsv = JSONValidator.from("4..:"); assertFalse(jsv.validate()); } @Test public void testCap1Case103() { JSONValidator jsv = JSONValidator.from("45.3"); assertTrue(jsv.validate()); } @Test public void testCap1Case104() { JSONValidator jsv = JSONValidator.from("+4.3"); assertTrue(jsv.validate()); } @Test public void testCap1Case105() { JSONValidator jsv = JSONValidator.from("+]"); assertFalse(jsv.validate()); } @Test public void testCap1Case106() { JSONValidator jsv = JSONValidator.from("+."); assertFalse(jsv.validate()); } @Test public void testCap1Case107() { JSONValidator jsv = JSONValidator.from("-4.3"); assertTrue(jsv.validate()); } @Test public void testCap1Case108() { JSONValidator jsv = JSONValidator.from("9"); assertTrue(jsv.validate()); } @Test public void testCap1Case109() { JSONValidator jsv = JSONValidator.from("8"); assertTrue(jsv.validate()); } @Test public void testCap1Case110() { JSONValidator jsv = JSONValidator.from("7"); assertTrue(jsv.validate()); } @Test public void testCap1Case111() { JSONValidator jsv = JSONValidator.from("6"); assertTrue(jsv.validate()); } @Test public void testCap1Case112() { JSONValidator jsv = JSONValidator.from("5"); assertTrue(jsv.validate()); } @Test public void testCap1Case114() { JSONValidator jsv = JSONValidator.from("3"); assertTrue(jsv.validate()); } @Test public void testCap1Case115() { JSONValidator jsv = JSONValidator.from("2"); assertTrue(jsv.validate()); } @Test public void testCap1Case116() { JSONValidator jsv = JSONValidator.from("1"); assertTrue(jsv.validate()); } @Test public void testCap1Case117() { JSONValidator jsv = JSONValidator.from("0"); assertTrue(jsv.validate()); } @Test public void testCap1Case118() { JSONValidator jsv = JSONValidator.from("{\"abc\":\"\"}"); assertTrue(jsv.validate()); } @Test public void testCap1Case119() { JSONValidator jsv = JSONValidator.from("[\"a\"]"); assertTrue(jsv.validate()); } @Test public void testCap1Case120() { JSONValidator jsv = JSONValidator.from("\""); assertFalse(jsv.validate()); } @Test public void testCap1Case121() { JSONValidator jsv = JSONValidator.from("[\"\\\n\"]"); assertTrue(jsv.validate()); } @Test public void testCap1Case122() { JSONValidator jsv = JSONValidator.from("[\"\\\uffff\"]"); assertTrue(jsv.validate()); } @Test public void testCap1Case124() { JSONValidator jsv = JSONValidator.from("{\"qwe\":true}"); assertTrue(jsv.validate()); } @Test public void testCap1Case125() { JSONValidator jsv = JSONValidator.from("[true]"); assertTrue(jsv.validate()); } @Test public void testCap1Case126() { JSONValidator jsv = JSONValidator.from("[true, false]"); assertTrue(jsv.validate()); } @Test public void testCap1Case123() { JSONValidator jsv = JSONValidator.from("true"); assertTrue(jsv.validate()); } @Test public void testCap1Case127() { JSONValidator jsv = JSONValidator.from("truu"); assertFalse(jsv.validate()); } @Test public void testCap1Case128() { JSONValidator jsv = JSONValidator.from("trr"); assertFalse(jsv.validate()); } @Test public void testCap1Case129() { JSONValidator jsv = JSONValidator.from("tt"); assertFalse(jsv.validate()); } @Test public void testCap1Case130() { JSONValidator jsv = JSONValidator.from("{\"hi\":false}"); assertTrue(jsv.validate()); } @Test public void testCap1Case131() { JSONValidator jsv = JSONValidator.from("[false]"); assertTrue(jsv.validate()); } @Test public void testCap1Case132() { JSONValidator jsv = JSONValidator.from("{\"abc\":false, \"bcd\":\"a\"}"); assertTrue(jsv.validate()); } @Test public void testCap1Case133() { JSONValidator jsv = JSONValidator.from("false"); assertTrue(jsv.validate()); } @Test public void testCap1Case134() { JSONValidator jsv = JSONValidator.from("falss"); assertFalse(jsv.validate()); } @Test public void testCap1Case135() { JSONValidator jsv = JSONValidator.from("fall"); assertFalse(jsv.validate()); } @Test public void testCap1Case136() { JSONValidator jsv = JSONValidator.from("faa"); assertFalse(jsv.validate()); } @Test public void testCap1Case137() { JSONValidator jsv = JSONValidator.from("fo"); assertFalse(jsv.validate()); } @Test public void testCap1Case138() { JSONValidator jsv = JSONValidator.from("null1"); assertFalse(jsv.validate()); } @Test public void testCap1Case139() { JSONValidator jsv = JSONValidator.from("{\"abc\":null}"); assertTrue(jsv.validate()); } @Test public void testCap1Case140() { JSONValidator jsv = JSONValidator.from("[null]"); assertTrue(jsv.validate()); } @Test public void testCap1Case141() { JSONValidator jsv = JSONValidator.from("{\"test\":[null,null]}"); assertTrue(jsv.validate()); } @Test public void testCap1Case142() { JSONValidator jsv = JSONValidator.from("null"); assertTrue(jsv.validate()); } @Test public void testCap1Case143() { JSONValidator jsv = JSONValidator.from("nulo"); assertFalse(jsv.validate()); } @Test public void testCap1Case144() { JSONValidator jsv = JSONValidator.from("nui"); assertFalse(jsv.validate()); } @Test public void testCap1Case145() { JSONValidator jsv = JSONValidator.from("no"); assertFalse(jsv.validate()); } @Test public void testCap1Case146() { JSONValidator jsv = JSONValidator.from("[]"); jsv.validate(); assertEquals(JSONValidator.Type.Array, jsv.getType()); } @Test public void testCap1Case147() { JSONValidator jsv = JSONValidator.from("[1]"); jsv.validate(); assertEquals(JSONValidator.Type.Array, jsv.getType()); } @Test public void testCap1Case148() { JSONValidator jsv = JSONValidator.from("[1,2]"); jsv.validate(); assertEquals(JSONValidator.Type.Array, jsv.getType()); } @Test public void testCap1Case149() { JSONValidator jsv = JSONValidator.from("{}"); jsv.validate(); assertEquals(JSONValidator.Type.Object, jsv.getType()); } @Test public void testCap1Case150() { JSONValidator jsv = JSONValidator.from("{\"a\":\"b\"}"); jsv.validate(); assertEquals(JSONValidator.Type.Object, jsv.getType()); } @Test public void testCap1Case151() { JSONValidator jsv = JSONValidator.from("{\"a\":\"b\",\"a\":\"b\"}"); jsv.validate(); assertEquals(JSONValidator.Type.Object, jsv.getType()); } @Test public void testCap1Case152() { JSONValidator jsv = JSONValidator.from("\"\""); jsv.validate(); assertEquals(JSONValidator.Type.Value, jsv.getType()); } @Test public void testCap1Case153() { JSONValidator jsv = JSONValidator.from("\"true\""); jsv.validate(); assertEquals(JSONValidator.Type.Value, jsv.getType()); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/validate/JSONValidateTest_basic.java ================================================ package com.alibaba.fastjson.validate; import com.alibaba.fastjson.JSONValidator; import junit.framework.TestCase; public class JSONValidateTest_basic extends TestCase { public void test_for_bastic_true() throws Exception { assertTrue(JSONValidator.from("{\"id\":true}").validate()); assertTrue(JSONValidator.from("[true]").validate()); assertTrue(JSONValidator.from("true").validate()); } public void test_for_bastic_false() throws Exception { assertTrue(JSONValidator.from("{\"id\":false}").validate()); assertTrue(JSONValidator.from("[false]").validate()); assertTrue(JSONValidator.from("false").validate()); } public void test_for_bastic_null() throws Exception { assertTrue(JSONValidator.from("{\"id\":null}").validate()); assertTrue(JSONValidator.from("[null]").validate()); assertTrue(JSONValidator.from("null").validate()); } public void test_long2ip() { long a = 1677734491111L; long b = 2697245671L; long longVal = a; int intVal = -1597721625; long unsignedIntVal = intVal & 0xFFFFFFFFL; boolean negative = (longVal & 0xFFFFFFFF00000000L) != 0; System.out.println(intVal & 0xFFFFFFFFL); System.out.println((int) b); byte[] bytes0 = new byte[8]; byte[] bytes1 = new byte[8]; byte[] bytes2 = new byte[8]; putLong(bytes0, 0, a); putLong(bytes1, 0, b); putLong(bytes2, 0, 0xFFFFFFFF00000000L); System.out.println(""); } static void putLong(byte[] b, int off, long val) { b[off + 7] = (byte) (val ); b[off + 6] = (byte) (val >>> 8); b[off + 5] = (byte) (val >>> 16); b[off + 4] = (byte) (val >>> 24); b[off + 3] = (byte) (val >>> 32); b[off + 2] = (byte) (val >>> 40); b[off + 1] = (byte) (val >>> 48); b[off ] = (byte) (val >>> 56); } } ================================================ FILE: src/test/java/com/alibaba/fastjson/validate/JSONValidateTest_file.java ================================================ package com.alibaba.fastjson.validate; import com.alibaba.fastjson.JSONValidator; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; public class JSONValidateTest_file extends TestCase { public void test_for_file() throws Exception { for (int i = 0; i < 10; ++i) { long start = System.currentTimeMillis(); File file = new File("/Users/wenshao/Downloads/000002_0.json"); FileInputStream is = new FileInputStream(file); JSONValidator validator = JSONValidator.fromUtf8(is); assertTrue(validator.validate()); validator.close(); // 642 335 796 System.out.println("millis " + (System.currentTimeMillis() - start)); } } public void test_for_file2() throws Exception { File file = new File("/Users/wenshao/Downloads/000002_0.json"); byte[] bytes = FileUtils.readFileToByteArray(file); for (int i = 0; i < 10; ++i) { long start = System.currentTimeMillis(); ByteArrayInputStream is = new ByteArrayInputStream(bytes); JSONValidator validator = JSONValidator.fromUtf8(is); assertTrue(validator.validate()); validator.close(); // 642 335 796 System.out.println("millis " + (System.currentTimeMillis() - start)); } } public void test_for_fileReader() throws Exception { for (int i = 0; i < 10; ++i) { long start = System.currentTimeMillis(); File file = new File("/Users/wenshao/Downloads/000002_0.json"); Reader is = new InputStreamReader(new FileInputStream(file), "UTF8"); JSONValidator validator = JSONValidator.from(is); assertTrue(validator.validate()); validator.close(); // 642 335 796 System.out.println("millis " + (System.currentTimeMillis() - start)); } } } ================================================ FILE: src/test/java/com/alibaba/json/ArrayRefTest2.java ================================================ 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 + "}"; } } } ================================================ FILE: src/test/java/com/alibaba/json/ByteArrayTest2.java ================================================ package com.alibaba.json; 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 junit.framework.TestCase; import org.junit.Assert; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; public class ByteArrayTest2 extends TestCase { public static class CertFile { public String name; public byte[] data; } public void test_0() throws Exception { ParserConfig.getGlobalInstance().setAutoTypeSupport(true); CertFile file = new CertFile(); file.name = "testname"; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 2048; i++) { sb.append("1"); } file.data = sb.toString().getBytes(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); JSONWriter writer = new JSONWriter(new OutputStreamWriter(bos)); writer.config(SerializerFeature.WriteClassName, true); writer.writeObject(file); writer.flush(); System.out.println(bos); byte[] data = bos.toByteArray(); Charset charset = Charset.forName("UTF-8"); CertFile convertFile = (CertFile)JSON.parse(data, 0, data.length, charset.newDecoder(), Feature.AllowArbitraryCommas, Feature.IgnoreNotMatch, Feature.SortFeidFastMatch, Feature.DisableCircularReferenceDetect, Feature.AutoCloseSource); Assert.assertEquals(file.name, convertFile.name); Assert.assertArrayEquals(file.data, convertFile.data); } } ================================================ FILE: src/test/java/com/alibaba/json/SerializerFeatureDistinctTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/TestGC.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/AnnotationTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/AnnotationTest2.java ================================================ 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 AnnotationTest2 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 { @JSONField(name = "ID") private int id; private String name; private String descrition; 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; } @JSONField(name = "desc") public String getDescrition() { return descrition; } @JSONField(name = "desc") public void setDescrition(String descrition) { this.descrition = descrition; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/AnnotationTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/AppendableFieldTest.java ================================================ 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 AppendableFieldTest 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); } public void test_codec_null_1() throws Exception { V0 v = new V0(); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); Assert.assertTrue(!mapping.isAsmEnable()); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty); Assert.assertEquals("{\"value\":\"\"}", text); } public static class V0 { private Appendable value; public Appendable getValue() { return value; } public void setValue(Appendable value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ArmoryTest.java ================================================ 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.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(); MessageBody body = new MessageBody(); Item item = new Item(); body.getItems().add(item); message.add(new MessageHead()); message.add(body); String text = JSON.toJSONString(message, SerializerFeature.SortField, SerializerFeature.UseSingleQuotes); Assert.assertEquals("[{},{'items':[{'id':0,'name':'xx'}]}]", text); } public static class Item { private int id; private String name = "xx"; 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 MessageHead { } public static class MessageBody { private List items = new ArrayList(); public List getItems() { return items; } public void setItems(List items) { this.items = items; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ArrayListFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ArrayListFieldTest_1.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ArrayListFloatFieldTest.java ================================================ 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; public class ArrayListFloatFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(new ArrayList()); user.getValue().add(1F); String text = JSON.toJSONString(user); System.out.println(text); User user1 = JSON.parseObject(text, User.class); Assert.assertEquals(user.getValue(), user1.getValue()); } public static class User { private ArrayList value; public User() { } public List getValue() { return value; } public void setValue(ArrayList value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ArrayRefTest.java ================================================ 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 + "}"; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/Base64Test.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/Base64Test2.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/BigDecimalFieldTest.java ================================================ package com.alibaba.json.bvt; import java.math.BigDecimal; 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 BigDecimalFieldTest 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); 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\":0}", text); } public static class V0 { private BigDecimal value; public BigDecimal getValue() { return value; } public void setValue(BigDecimal value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/BigIntegerFieldTest.java ================================================ package com.alibaba.json.bvt; import java.math.BigInteger; 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 BigIntegerFieldTest 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); 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\":0}", text); } public static class V0 { private BigInteger value; public BigInteger getValue() { return value; } public void setValue(BigInteger value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest.java ================================================ 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 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); 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 Boolean[] value; public Boolean[] getValue() { return value; } public void setValue(Boolean[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest_primitive.java ================================================ 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 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); } public static class V0 { private boolean[] value; public boolean[] getValue() { return value; } public void setValue(boolean[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/BooleanArrayFieldTest_primitive_private.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/Bug12.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/Bug89.java ================================================ 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 } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/BuilderTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_4.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_5_base64.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_6_gzip.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ByteArrayFieldTest_7_gzip_hex.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ByteFieldTest.java ================================================ 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 ByteFieldTest extends TestCase { public void test_codec() throws Exception { V0 v = new V0(); v.setValue((byte) 10); String text = JSON.toJSONString(v); System.out.println(text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v1.getValue(), v.getValue()); } 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_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\":0}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(Byte.valueOf((byte) 0), v1.getValue()); } public static class V0 { private Byte value; public Byte getValue() { return value; } public void setValue(Byte value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/CastTest.java ================================================ 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.JSONArray; public class CastTest extends TestCase { public void test_0() throws Exception { String text; { List list = new ArrayList(); list.add(new Header()); Body body = new Body("张三"); body.getItems().add(new Item()); list.add(body); text = JSON.toJSONString(list); System.out.println(text); } JSONArray array = JSON.parseArray(text); // Body body = array.getObject(1, Body.class); // Assert.assertEquals(1, body.getItems().size()); // Assert.assertEquals("张三", body.getName()); } public static class Header { } public static class Body { private String name; public Body(){ } public Body(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } private List items = new ArrayList(); public List getItems() { return items; } public void setItems(List items) { this.items = items; } } public static class Item { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/CastTest2.java ================================================ package com.alibaba.json.bvt; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; public class CastTest2 extends TestCase { public void test_0() throws Exception { String text; { List list = new ArrayList(); list.add(new Header()); Body body = new Body("张三"); body.getItems().put("1", new Item()); list.add(body); text = JSON.toJSONString(list); System.out.println(text); } JSONArray array = JSON.parseArray(text); Body body = array.getObject(1, Body.class); Assert.assertEquals("张三", body.getName()); Assert.assertEquals(1, body.getItems().size()); } public static class Header { } public static class Body { private String name; public Body(){ } public Body(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } private Map items = new HashMap(); public Map getItems() { return items; } public void setItems(Map items) { this.items = items; } } public static class Item { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/CharTypesTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/CharsetFieldTest.java ================================================ package com.alibaba.json.bvt; import java.nio.charset.Charset; 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 CharsetFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(Charset.forName("UTF-8")); 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 Charset value; public Charset getValue() { return value; } public void setValue(Charset value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ChineseSpaceTest.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/CircularReferenceTest.java ================================================ package com.alibaba.json.bvt; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import com.alibaba.json.test.entity.case2.Category; public class CircularReferenceTest extends TestCase { public void test_0() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream objectOut = new ObjectOutputStream(out); Category p = new Category(); p.setId(1); p.setName("root"); { Category child = new Category(); child.setId(2); child.setName("child"); p.getChildren().add(child); child.setParent(p); } objectOut.writeObject(p); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ClassFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/CurrencyTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/CurrencyTest3.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/CurrencyTest4.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/CurrencyTest5.java ================================================ 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¥\"}}"; String str4 = "{\"value\":{\"currencyCode\":\"CNY\",\"displayName\":\"人民币\",\"numericCodeAsString\":\"156\",\"symbol\":\"¥\"}}"; assertTrue(text.equals(str1) || text.equals(str2) || text.equals(str3) || text.equals(str4)); Currency currency = JSON.parseObject(text, VO.class).value; assertSame(Currency.getInstance("CNY"), currency); } public static class VO { public Currency value; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/CurrencyTest_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/DefaultJSONParserTest.java ================================================ /* * 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.HashMap; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; public class DefaultJSONParserTest extends TestCase { public void test_double() { DefaultJSONParser parser = new DefaultJSONParser("3.4"); parser.config(Feature.UseBigDecimal, false); Assert.assertEquals("3.4", parser.getInput()); Assert.assertEquals(false, parser.isEnabled(Feature.UseBigDecimal)); Object result = parser.parse(); 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 { DefaultJSONParser parser = new DefaultJSONParser("{\"name\":3]"); parser.parse(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error2() { Exception error = null; try { DefaultJSONParser parser = new DefaultJSONParser("ttr"); parser.parse(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error3() { Exception error = null; try { DefaultJSONParser parser = new DefaultJSONParser("33"); parser.parseObject(new HashMap()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error4() { Exception error = null; try { DefaultJSONParser parser = new DefaultJSONParser("]"); parser.parse(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error6() { Exception error = null; try { DefaultJSONParser parser = new DefaultJSONParser("{\"a\"33"); parser.parse(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error7() { Exception error = null; try { DefaultJSONParser parser = new DefaultJSONParser("{\"a\":{}3"); parser.parse(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error11() { Exception error = null; try { DefaultJSONParser parser = new DefaultJSONParser("{]"); parser.parse(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/DefaultJSONParserTest_ref.java ================================================ /* * 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/DeprecatedClassTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/DisableSpecialKeyDetectTest.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/DoubleArrayFieldTest_primitive.java ================================================ 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 DoubleArrayFieldTest_primitive 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); 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 double[] value; public double[] getValue() { return value; } public void setValue(double[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/DoubleFieldTest_A.java ================================================ 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 DoubleFieldTest_A extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(1001D); 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()); } 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); System.out.println(text); User user1 = JSON.parseObject(text, User.class); Assert.assertEquals(user1.getValue(), user.getValue()); } public static class User { private Double value; public Double getValue() { return value; } public void setValue(Double value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/EmptyArrayAsNullTest.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/EmptyObjectTest.java ================================================ 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 EmptyObjectTest 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("{}", text); JSON.parseObject(text, V0.class); } 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("{}", text); } public static class V0 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/EnumFieldTest.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/EnumFieldTest2.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/EnumFieldTest2_private.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/EnumFieldTest3.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/EnumFieldTest3_private.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/EnumerationTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/FastJsonBigClassTest.java ================================================ 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"))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/FieldBasedTest.java ================================================ package com.alibaba.json.bvt; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializeConfig; import junit.framework.TestCase; /** * @author TimAndy */ public class FieldBasedTest extends TestCase { public void test_filed_based_parse() { Student student = new Student("123", "你好世界", 60); String json = JSON.toJSONString(student, new SerializeConfig(true)); Student result = JSON.parseObject(json, Student.class, new ParserConfig(true)); assertNotNull(result); assertEquals("123", result.id); assertEquals("你好世界", result.name); assertEquals(60, result.score); } static final class Student { private String id; private String name; private int score; Student() { } Student(String id, String name, int score) { this.id = id; this.name = name; this.score = score; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/FileFieldTest.java ================================================ package com.alibaba.json.bvt; import java.io.File; 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 FileFieldTest 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); 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); Assert.assertEquals("{\"value\":null}", JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); Assert.assertEquals("{value:null}", JSON.toJSONStringZ(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); Assert.assertEquals("{value:null}", JSON.toJSONStringZ(v, mapping, SerializerFeature.UseSingleQuotes, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); Assert.assertEquals("{'value':null}", JSON.toJSONStringZ(v, mapping, SerializerFeature.UseSingleQuotes, SerializerFeature.QuoteFieldNames, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); } public static class V0 { private File value; public File getValue() { return value; } public void setValue(File value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/FinalTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/FloatArrayFieldTest_primitive.java ================================================ 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 FloatArrayFieldTest_primitive 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); 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 float[] value; public float[] getValue() { return value; } public void setValue(float[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/FloatFieldTest.java ================================================ package com.alibaba.json.bvt; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class FloatFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(1001F); String text = JSON.toJSONString(user); System.out.println(text); User user1 = JSON.parseObject(text, User.class); Assert.assertTrue(user1.getValue() == user.getValue()); } public static class User { private float value; public float getValue() { return value; } public void setValue(float value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/FloatFieldTest_A.java ================================================ 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 FloatFieldTest_A extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(1001F); 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()); } 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); System.out.println(text); User user1 = JSON.parseObject(text, User.class); Assert.assertEquals(user1.getValue(), user.getValue()); } public static class User { private Float value; public Float getValue() { return value; } public void setValue(Float value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/FluentSetterTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/GetSetNotMatchTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/GroovyTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/IncomingDataPointTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/InetAddressFieldTest.java ================================================ package com.alibaba.json.bvt; import java.net.InetAddress; 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 InetAddressFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(InetAddress.getLocalHost()); 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 InetAddress value; public InetAddress getValue() { return value; } public void setValue(InetAddress value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/InetSocketAddressFieldTest.java ================================================ package com.alibaba.json.bvt; import java.net.InetSocketAddress; 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 InetSocketAddressFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(new InetSocketAddress(33)); 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 void test_codec_null_2() throws Exception { User user = JSON.parseObject("{\"value\":{\"address\":null,\"port\":33}}", User.class); Assert.assertEquals(33, user.getValue().getPort()); } public static class User { private InetSocketAddress value; public InetSocketAddress getValue() { return value; } public void setValue(InetSocketAddress value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/IntArrayFieldTest_primitive.java ================================================ 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 IntArrayFieldTest_primitive extends TestCase { public void test_array() throws Exception { Assert.assertEquals("[1]", JSON.toJSONString(new int[] { 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 int[] value; public int[] getValue() { return value; } public void setValue(int[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/IntKeyMapTest.java ================================================ 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:{}}"); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/IntegerArrayFieldTest.java ================================================ 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 IntegerArrayFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(new Integer[] { Integer.valueOf(1), Integer.valueOf(2) }); 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()[0], user.getValue()[0]); Assert.assertEquals(user1.getValue()[1], user.getValue()[1]); } 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 void test_codec_null_1() throws Exception { User user = new User(); user.setValue(null); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(user, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty); User user1 = JSON.parseObject(text, User.class); Assert.assertEquals(0, user1.getValue().length); } public static class User { private Integer[] value; public Integer[] getValue() { return value; } public void setValue(Integer[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/Issue213Test.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONArrayTest.java ================================================ /* * 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.StringWriter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.concurrent.atomic.AtomicInteger; 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 JSONArrayTest extends TestCase { public void test_toString() throws Exception { StringWriter out = new StringWriter(); new JSONArray().writeJSONString(out); Assert.assertEquals("[]", out.toString()); Assert.assertEquals("[]", new JSONArray().toString()); } public void test_toJSONString() throws Exception { Assert.assertEquals("null", JSONArray.toJSONString(null)); Assert.assertEquals("[null]", JSONArray.toJSONString(Collections.singletonList(null))); } public void test_1() throws Exception { JSONArray array = new JSONArray(3); Assert.assertEquals(true, array.isEmpty()); array.add(1); Assert.assertEquals(false, array.isEmpty()); Assert.assertEquals(true, array.contains(1)); Assert.assertEquals(1, array.toArray()[0]); { Object[] items = new Object[1]; array.toArray(items); Assert.assertEquals(1, items[0]); } Assert.assertEquals(true, array.containsAll(Collections.singletonList(1))); Assert.assertEquals(true, array.remove(Integer.valueOf(1))); Assert.assertEquals(true, array.isEmpty()); array.addAll(Collections.singletonList(1)); Assert.assertEquals(1, array.size()); array.removeAll(Collections.singletonList(1)); Assert.assertEquals(0, array.size()); array.addAll(0, Arrays.asList(1, 2, 3)); Assert.assertEquals(3, array.size()); array.clear(); array.addAll(0, Arrays.asList(1, 2, 3)); Assert.assertEquals(true, array.retainAll(Arrays.asList(1, 2))); Assert.assertEquals(2, array.size()); Assert.assertEquals(true, array.retainAll(Arrays.asList(2, 4))); Assert.assertEquals(1, array.size()); array.set(0, 4); Assert.assertEquals(4, array.toArray()[0]); array.add(0, 4); Assert.assertEquals(4, array.toArray()[0]); array.remove(0); array.remove(0); Assert.assertEquals(0, array.size()); array.addAll(Arrays.asList(1, 2, 3, 4, 5, 4, 3)); Assert.assertEquals(2, array.indexOf(3)); Assert.assertEquals(6, array.lastIndexOf(3)); { AtomicInteger count = new AtomicInteger(); for (ListIterator iter = array.listIterator(); iter.hasNext(); iter.next()) { count.incrementAndGet(); } Assert.assertEquals(7, count.get()); } { AtomicInteger count = new AtomicInteger(); for (ListIterator iter = array.listIterator(2); iter.hasNext(); iter.next()) { count.incrementAndGet(); } Assert.assertEquals(5, count.get()); } { Assert.assertEquals(2, array.subList(2, 4).size()); } } public void test_2() throws Exception { JSONArray array = new JSONArray(); array.add(123); array.add("222"); array.add(3); array.add(true); array.add("true"); array.add(null); Assert.assertEquals(123, array.getByte(0).byteValue()); Assert.assertEquals(123, array.getByteValue(0)); Assert.assertEquals(123, array.getShort(0).shortValue()); Assert.assertEquals(123, array.getShortValue(0)); Assert.assertTrue(123F == array.getFloat(0).floatValue()); Assert.assertTrue(123F == array.getFloatValue(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)); Assert.assertEquals(new BigDecimal("123"), array.getBigDecimal(0)); Assert.assertEquals(222, array.getIntValue(1)); Assert.assertEquals(new Integer(222), array.getInteger(1)); Assert.assertEquals(new Long(222), array.getLong(1)); Assert.assertEquals(new BigDecimal("222"), array.getBigDecimal(1)); Assert.assertEquals(true, array.getBooleanValue(4)); Assert.assertEquals(Boolean.TRUE, array.getBoolean(4)); Assert.assertEquals(0, array.getIntValue(5)); Assert.assertEquals(0, array.getLongValue(5)); Assert.assertEquals(null, array.getInteger(5)); Assert.assertEquals(null, array.getLong(5)); Assert.assertEquals(null, array.getBigDecimal(5)); Assert.assertEquals(null, array.getBoolean(5)); Assert.assertEquals(false, array.getBooleanValue(5)); } public void test_getObject_null() throws Exception { JSONArray array = new JSONArray(); array.add(null); Assert.assertTrue(array.getJSONObject(0) == null); } public void test_getObject() throws Exception { JSONArray array = new JSONArray(); array.add(new JSONObject()); Assert.assertEquals(0, array.getJSONObject(0).size()); } public void test_getObject_map() throws Exception { JSONArray array = new JSONArray(); array.add(new HashMap()); Assert.assertEquals(0, array.getJSONObject(0).size()); } public void test_getArray() throws Exception { JSONArray array = new JSONArray(); array.add(new ArrayList()); Assert.assertEquals(0, array.getJSONArray(0).size()); } public void test_getArray_1() throws Exception { JSONArray array = new JSONArray(); array.add(new JSONArray()); Assert.assertEquals(0, array.getJSONArray(0).size()); } public void test_constructor() throws Exception { List list = new ArrayList(); JSONArray array = new JSONArray(list); array.add(3); Assert.assertEquals(1, list.size()); Assert.assertEquals(3, list.get(0)); } public void test_getJavaBean() throws Exception { JSONArray array = JSON.parseArray("[{id:123, name:'aaa'}]"); Assert.assertEquals(1, array.size()); Assert.assertEquals(123, array.getObject(0, User.class).getId()); } public static class User { 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONArrayTest2.java ================================================ package com.alibaba.json.bvt; import java.math.BigInteger; import com.alibaba.fastjson.JSON; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONArray; public class JSONArrayTest2 extends TestCase { public void test_0() throws Exception { long time = System.currentTimeMillis(); JSONArray array = new JSONArray(); array.add(null); array.add(1); array.add(time); Assert.assertEquals(0, array.getByteValue(0)); Assert.assertEquals(0, array.getShortValue(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)); Assert.assertEquals(new java.sql.Date(time), array.getSqlDate(2)); Assert.assertEquals(new java.sql.Timestamp(time), array.getTimestamp(2)); JSONArray array2 = (JSONArray) array.clone(); Assert.assertEquals(0, array2.getByteValue(0)); Assert.assertEquals(0, array2.getShortValue(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)); Assert.assertEquals(new java.sql.Date(time), array2.getSqlDate(2)); Assert.assertEquals(new java.sql.Timestamp(time), array2.getTimestamp(2)); Assert.assertEquals(array2.size(), array2.size()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONArrayTest3.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONArrayTest_hashCode.java ================================================ package com.alibaba.json.bvt; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; public class JSONArrayTest_hashCode extends TestCase { public void test_hashCode() throws Exception { Assert.assertEquals(new JSONArray().hashCode(), new JSONArray().hashCode()); } public void test_hashCode_1() throws Exception { Assert.assertEquals(JSON.parseArray("[]"), JSON.parseArray("[]")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONBytesTest.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONBytesTest2.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONBytesTest3.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONExceptionTest.java ================================================ /* * 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 org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; public class JSONExceptionTest extends TestCase { public void test_all() throws Exception { Assert.assertEquals("xxx", new JSONException("xxx").getMessage()); Assert.assertEquals(null, new JSONException().getMessage()); Assert.assertEquals("xxx", new JSONException("xxx", new RuntimeException()).getMessage()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONFeidDemo2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONFieldDefaultValueTest.java ================================================ package com.alibaba.json.bvt; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class JSONFieldDefaultValueTest extends TestCase { public void test_default_value() throws Exception { Model m = new Model(); String s = JSON.toJSONString(m); System.out.println(s); Model m2 = JSON.parseObject(s, Model.class); assertEquals("string", m2.getString()); assertEquals(false, m2.getaBoolean()); assertEquals(true, m2.getaBoolean2().booleanValue()); assertEquals(0, m2.getAnInt()); assertEquals(888, m2.getInteger().intValue()); assertEquals(0, m2.getaShort()); assertEquals(88, m2.getaShort2().shortValue()); assertEquals('\u0000', m2.getaChar()); assertEquals('J', m2.getCharacter().charValue()); assertEquals(0, m2.getaByte()); assertEquals(8, m2.getaByte2().byteValue()); assertEquals(0, m2.getaLong()); assertEquals(8888, m2.getaLong2().longValue()); assertEquals("0.0", "" + m2.getaFloat()); assertEquals("8.8", "" + m2.getaFloat2()); assertEquals("0.0", "" + m2.getaDouble()); assertEquals("88.88", "" + m2.getaDouble2()); } public void test_not_null() throws Exception { Model m = new Model("test", true, 888, (short)88, 'J', (byte)8, 8888L, 8.8F, 88.88, false, 999, (short)99, 'C', (byte)9, 9999L, 9.9F, 99.99); String s = JSON.toJSONString(m); System.out.println(s); Model m2 = JSON.parseObject(s, Model.class); assertEquals("test", m2.getString()); assertEquals(true, m2.getaBoolean()); assertEquals(false, m2.getaBoolean2().booleanValue()); assertEquals(888, m2.getAnInt()); assertEquals(999, m2.getInteger().intValue()); assertEquals(88, m2.getaShort()); assertEquals(99, m2.getaShort2().shortValue()); assertEquals('J', m2.getaChar()); assertEquals('C', m2.getCharacter().charValue()); assertEquals(8, m2.getaByte()); assertEquals(9, m2.getaByte2().byteValue()); assertEquals(8888, m2.getaLong()); assertEquals(9999, m2.getaLong2().longValue()); assertEquals("8.8", "" + m2.getaFloat()); assertEquals("9.9", "" + m2.getaFloat2()); assertEquals("88.88", "" + m2.getaDouble()); assertEquals("99.99", "" + m2.getaDouble2()); } public static class Model { @JSONField(defaultValue = "string") private String string; @JSONField(defaultValue = "true") //shouldn't work private boolean aBoolean; @JSONField(defaultValue = "888") //shouldn't work private int anInt; @JSONField(defaultValue = "88") //shouldn't work private short aShort; @JSONField(defaultValue = "J") //shouldn't work private char aChar; @JSONField(defaultValue = "8") //shouldn't work private byte aByte; @JSONField(defaultValue = "8888") //shouldn't work private long aLong; @JSONField(defaultValue = "8.8") //shouldn't work private float aFloat; @JSONField(defaultValue = "88.88") //shouldn't work private double aDouble; @JSONField(defaultValue = "true") private Boolean aBoolean2; @JSONField(defaultValue = "888") private Integer integer; @JSONField(defaultValue = "88") private Short aShort2; @JSONField(defaultValue = "J") private Character character; @JSONField(defaultValue = "8") private Byte aByte2; @JSONField(defaultValue = "8888") private Long aLong2; @JSONField(defaultValue = "8.8") private Float aFloat2; @JSONField(defaultValue = "88.88") private Double aDouble2; public Model(String string, boolean aBoolean, int anInt, short aShort, char aChar, byte aByte, long aLong, float aFloat, double aDouble, Boolean aBoolean2, Integer integer, Short aShort2, Character character, Byte aByte2, Long aLong2, Float aFloat2, Double aDouble2) { this.string = string; this.aBoolean = aBoolean; this.anInt = anInt; this.aShort = aShort; this.aChar = aChar; this.aByte = aByte; this.aLong = aLong; this.aFloat = aFloat; this.aDouble = aDouble; this.aBoolean2 = aBoolean2; this.integer = integer; this.aShort2 = aShort2; this.character = character; this.aByte2 = aByte2; this.aLong2 = aLong2; this.aFloat2 = aFloat2; this.aDouble2 = aDouble2; } public Model() { } public String getString() { return string; } public void setString(String string) { this.string = string; } public boolean getaBoolean() { return aBoolean; } public void setaBoolean(boolean aBoolean) { this.aBoolean = aBoolean; } public int getAnInt() { return anInt; } public void setAnInt(int anInt) { this.anInt = anInt; } public short getaShort() { return aShort; } public void setaShort(short aShort) { this.aShort = aShort; } public char getaChar() { return aChar; } public void setaChar(char aChar) { this.aChar = aChar; } public byte getaByte() { return aByte; } public void setaByte(byte aByte) { this.aByte = aByte; } public long getaLong() { return aLong; } public void setaLong(long aLong) { this.aLong = aLong; } public float getaFloat() { return aFloat; } public void setaFloat(float aFloat) { this.aFloat = aFloat; } public double getaDouble() { return aDouble; } public void setaDouble(double aDouble) { this.aDouble = aDouble; } public Boolean getaBoolean2() { return aBoolean2; } public void setaBoolean2(Boolean aBoolean2) { this.aBoolean2 = aBoolean2; } public Integer getInteger() { return integer; } public void setInteger(Integer integer) { this.integer = integer; } public Short getaShort2() { return aShort2; } public void setaShort2(Short aShort2) { this.aShort2 = aShort2; } public Character getCharacter() { return character; } public void setCharacter(Character character) { this.character = character; } public Byte getaByte2() { return aByte2; } public void setaByte2(Byte aByte2) { this.aByte2 = aByte2; } public Long getaLong2() { return aLong2; } public void setaLong2(Long aLong2) { this.aLong2 = aLong2; } public Float getaFloat2() { return aFloat2; } public void setaFloat2(Float aFloat2) { this.aFloat2 = aFloat2; } public Double getaDouble2() { return aDouble2; } public void setaDouble2(Double aDouble2) { this.aDouble2 = aDouble2; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONFromObjectTest.java ================================================ package com.alibaba.json.bvt; import java.util.ArrayList; import java.util.HashMap; import java.util.List; 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 JSONFromObjectTest extends TestCase { public void test_0() throws Exception { User user = new User(); user.setId(3); user.setName("周访"); JSONObject json = (JSONObject) JSON.toJSON(user); Assert.assertEquals(new Long(3), json.getLong("id")); Assert.assertEquals("周访", json.getString("name")); } public void test_1() throws Exception { JSONObject user = new JSONObject(); user.put("id", 3); user.put("name", "周访"); JSONObject json = (JSONObject) JSON.toJSON(user); Assert.assertEquals(new Long(3), json.getLong("id")); Assert.assertEquals("周访", json.getString("name")); } public void test_2() throws Exception { HashMap user = new HashMap(); user.put("id", 3); user.put("name", "周访"); JSONObject json = (JSONObject) JSON.toJSON(user); Assert.assertEquals(new Long(3), json.getLong("id")); Assert.assertEquals("周访", json.getString("name")); } public void test_3() throws Exception { List users = new ArrayList(); HashMap user = new HashMap(); user.put("id", 3); user.put("name", "周访"); users.add(user); JSONArray array = (JSONArray) JSON.toJSON(users); JSONObject json = array.getJSONObject(0); Assert.assertEquals(new Long(3), json.getLong("id")); Assert.assertEquals("周访", json.getString("name")); } public void test_error() throws Exception { C c = new C(); JSONException error = null; try { JSON.toJSON(c); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public static class User { 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; } } public static class C { public int getId() { throw new UnsupportedOperationException(); } public void setId(int id) { throw new UnsupportedOperationException(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectFluentTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest.java ================================================ /* * 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.StringWriter; import java.math.BigDecimal; import java.util.Collections; import java.util.Date; import java.util.HashMap; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONObject; public class JSONObjectTest extends TestCase { public void test_toJSONObject() throws Exception { { Assert.assertNull(JSONObject.parse(null)); } } public void test_writeJSONString() throws Exception { { StringWriter out = new StringWriter(); new JSONObject().writeJSONString(out); Assert.assertEquals("{}", out.toString()); } } public void test_getLong() throws Exception { JSONObject json = new JSONObject(true); json.put("A", 55L); json.put("B", 55); json.put("K", true); Assert.assertEquals(json.getLong("A").longValue(), 55L); Assert.assertEquals(json.getLong("B").longValue(), 55L); Assert.assertEquals(json.getLong("C"), null); Assert.assertEquals(json.getBooleanValue("K"), true); Assert.assertEquals(json.getBoolean("K"), Boolean.TRUE); } public void test_getLong_1() throws Exception { JSONObject json = new JSONObject(false); json.put("A", 55L); json.put("B", 55); Assert.assertEquals(json.getLong("A").longValue(), 55L); Assert.assertEquals(json.getLong("B").longValue(), 55L); Assert.assertEquals(json.getLong("C"), null); } public void test_getDate() throws Exception { long currentTimeMillis = System.currentTimeMillis(); JSONObject json = new JSONObject(); json.put("A", new Date(currentTimeMillis)); json.put("B", currentTimeMillis); Assert.assertEquals(json.getDate("A").getTime(), currentTimeMillis); Assert.assertEquals(json.getDate("B").getTime(), currentTimeMillis); Assert.assertEquals(json.getLong("C"), null); } public void test_getBoolean() throws Exception { JSONObject json = new JSONObject(); json.put("A", true); Assert.assertEquals(json.getBoolean("A").booleanValue(), true); Assert.assertEquals(json.getLong("C"), null); } public void test_getInt() throws Exception { JSONObject json = new JSONObject(); json.put("A", 55L); json.put("B", 55); Assert.assertEquals(json.getInteger("A").intValue(), 55); Assert.assertEquals(json.getInteger("B").intValue(), 55); Assert.assertEquals(json.getInteger("C"), null); } public void test_order() throws Exception { JSONObject json = new JSONObject(true); json.put("C", 55L); json.put("B", 55); json.put("A", 55); Assert.assertEquals("C", json.keySet().toArray()[0]); Assert.assertEquals("B", json.keySet().toArray()[1]); Assert.assertEquals("A", json.keySet().toArray()[2]); Assert.assertEquals(0, json.getIntValue("D")); Assert.assertEquals(0L, json.getLongValue("D")); Assert.assertEquals(false, json.getBooleanValue("D")); } public void test_all() throws Exception { JSONObject json = new JSONObject(); Assert.assertEquals(true, json.isEmpty()); json.put("C", 51L); json.put("B", 52); json.put("A", 53); Assert.assertEquals(false, json.isEmpty()); Assert.assertEquals(true, json.containsKey("C")); Assert.assertEquals(false, json.containsKey("D")); Assert.assertEquals(true, json.containsValue(52)); Assert.assertEquals(false, json.containsValue(33)); Assert.assertEquals(null, json.remove("D")); Assert.assertEquals(51L, json.remove("C")); Assert.assertEquals(2, json.keySet().size()); Assert.assertEquals(2, json.values().size()); Assert.assertEquals(new BigDecimal("53"), json.getBigDecimal("A")); json.putAll(Collections.singletonMap("E", 99)); Assert.assertEquals(3, json.values().size()); json.clear(); Assert.assertEquals(0, json.values().size()); json.putAll(Collections.singletonMap("E", 99)); Assert.assertEquals(99L, json.getLongValue("E")); Assert.assertEquals(99, json.getIntValue("E")); Assert.assertEquals("99", json.getString("E")); Assert.assertEquals(null, json.getString("F")); Assert.assertEquals(null, json.getDate("F")); Assert.assertEquals(null, json.getBoolean("F")); } public void test_all_2() throws Exception { JSONObject array = new JSONObject(); array.put("0", 123); array.put("1", "222"); array.put("2", 3); array.put("3", true); array.put("4", "true"); array.put("5", "2.0"); Assert.assertEquals(123, array.getIntValue("0")); Assert.assertEquals(123, array.getLongValue("0")); Assert.assertEquals(new BigDecimal("123"), array.getBigDecimal("0")); Assert.assertEquals(222, array.getIntValue("1")); Assert.assertEquals(3, array.getByte("2").byteValue()); Assert.assertEquals(3, array.getByteValue("2")); Assert.assertEquals(3, array.getShort("2").shortValue()); Assert.assertEquals(3, array.getShortValue("2")); Assert.assertEquals(new Integer(222), array.getInteger("1")); Assert.assertEquals(new Long(222), array.getLong("1")); Assert.assertEquals(new BigDecimal("222"), array.getBigDecimal("1")); Assert.assertEquals(true, array.getBooleanValue("4")); 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 { JSONObject json = new JSONObject(); json.put("obj", null); 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(); json.put("obj", new JSONObject()); Assert.assertEquals(0, json.getJSONObject("obj").size()); } public void test_getObject_map() throws Exception { JSONObject json = new JSONObject(); json.put("obj", new HashMap()); Assert.assertEquals(0, json.getJSONObject("obj").size()); } public void test_getObjectOrDefault() { JSONObject json = new JSONObject(); json.put("testKey", "testVal"); json.put("testKey2", null); Assert.assertEquals("default", json.getOrDefault("testNonKet", "default")); Assert.assertEquals("default", json.getOrDefault("testKey2", "default")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest2.java ================================================ package com.alibaba.json.bvt; import java.util.LinkedHashMap; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class JSONObjectTest2 extends TestCase { public void test_0() throws Exception { Map map = new LinkedHashMap(); JSONObject obj = new JSONObject(map); Assert.assertEquals(obj.size(), map.size()); map.put("a", 1); Assert.assertEquals(obj.size(), map.size()); Assert.assertEquals(obj.get("a"), map.get("a")); map.put("b", new int[] { 1 }); JSONArray array = obj.getJSONArray("b"); Assert.assertEquals(array.size(), 1); map.put("c", new JSONArray()); JSONArray array2 = obj.getJSONArray("b"); Assert.assertEquals(array2.size(), 1); Assert.assertEquals(obj.getByteValue("d"), 0); Assert.assertEquals(obj.getShortValue("d"), 0); 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); JSONObject obj2 = (JSONObject) obj.clone(); Assert.assertEquals(obj.size(), obj2.size()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest3.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest4.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest5.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest6.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest7.java ================================================ package com.alibaba.json.bvt; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; public class JSONObjectTest7 extends TestCase { public void test() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"test\":null,\"a\":\"cc\"}"); assertEquals(2, jsonObject.entrySet().size()); assertTrue(jsonObject.containsKey("test")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest_get.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest_getBigInteger.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest_getDate.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest_getObj.java ================================================ package com.alibaba.json.bvt; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import org.junit.Assert; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.HashMap; import java.util.List; 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 void test_get_obj() throws Exception { JSONObject obj = new JSONObject(); obj.put("value", new HashMap()); Assert.assertEquals(new JSONObject(), obj.getObject("value", JSONObject.class)); } public void test_get_obj2() throws Exception { List json = JSON.parseArray("[{\"values\":[{}]}]", JSONObject.class); for (JSONObject obj : json) { Object values = obj.getObject("values", new TypeReference>() {}); } } public static class Model { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest_getObj_2.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest_get_2.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest_hashCode.java ================================================ package com.alibaba.json.bvt; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class JSONObjectTest_hashCode extends TestCase { public void test_hashCode() throws Exception { Assert.assertEquals(new JSONObject().hashCode(), new JSONObject().hashCode()); } public void test_hashCode_1() throws Exception { Assert.assertEquals(JSON.parseObject("{a:1}"), JSON.parseObject("{'a':1}")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONObjectTest_readObject.java ================================================ package com.alibaba.json.bvt; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.ParserConfig; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class JSONObjectTest_readObject extends TestCase { public void test_0() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", 123); jsonObject.put("obj", new JSONObject()); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(bytesOut); objOut.writeObject(jsonObject); objOut.flush(); byte[] bytes = bytesOut.toByteArray(); ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes); ObjectInputStream objIn = new ObjectInputStream(bytesIn); Object obj = objIn.readObject(); assertEquals(JSONObject.class, obj.getClass()); assertEquals(jsonObject, obj); } public void test_2() throws Exception { JSONObject jsonObject = JSON.parseObject("{123:345}"); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(bytesOut); objOut.writeObject(jsonObject); objOut.flush(); byte[] bytes = bytesOut.toByteArray(); ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes); ObjectInputStream objIn = new ObjectInputStream(bytesIn); Object obj = objIn.readObject(); assertEquals(JSONObject.class, obj.getClass()); assertEquals(jsonObject, obj); } public void test_3() throws Exception { JSONObject jsonObject = JSON.parseObject("{123:345,\"items\":[1,2,3,4]}"); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(bytesOut); objOut.writeObject(jsonObject); objOut.flush(); byte[] bytes = bytesOut.toByteArray(); ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes); ObjectInputStream objIn = new ObjectInputStream(bytesIn); Object obj = objIn.readObject(); assertEquals(JSONObject.class, obj.getClass()); assertEquals(jsonObject, obj); } public void test_4() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("val", new Byte[]{}); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(bytesOut); objOut.writeObject(jsonObject); objOut.flush(); byte[] bytes = bytesOut.toByteArray(); ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes); ObjectInputStream objIn = new ObjectInputStream(bytesIn); Object obj = objIn.readObject(); assertEquals(JSONObject.class, obj.getClass()); assertEquals(jsonObject.toJSONString(), JSON.toJSONString(obj)); } public void test_5() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("val", new byte[]{}); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(bytesOut); objOut.writeObject(jsonObject); objOut.flush(); byte[] bytes = bytesOut.toByteArray(); ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes); ObjectInputStream objIn = new ObjectInputStream(bytesIn); Object obj = objIn.readObject(); assertEquals(JSONObject.class, obj.getClass()); assertEquals(jsonObject.toJSONString(), JSON.toJSONString(obj)); } public void test_6() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("val", new Character[]{}); jsonObject.put("cls", java.lang.Number.class); jsonObject.put("nums", new java.lang.Number[] {}); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(bytesOut); objOut.writeObject(jsonObject); objOut.flush(); byte[] bytes = bytesOut.toByteArray(); ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes); ObjectInputStream objIn = new ObjectInputStream(bytesIn); Object obj = objIn.readObject(); assertEquals(JSONObject.class, obj.getClass()); assertEquals(jsonObject.toJSONString(), JSON.toJSONString(obj)); } public void test_7() throws Exception { ParserConfig.global.setSafeMode(true); try { JSONObject jsonObject = new JSONObject(); jsonObject.put("m", new java.util.HashMap()); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(bytesOut); objOut.writeObject(jsonObject); objOut.flush(); byte[] bytes = bytesOut.toByteArray(); ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes); ObjectInputStream objIn = new ObjectInputStream(bytesIn); Object obj = objIn.readObject(); } finally { ParserConfig.global.setSafeMode(false); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONParseTest.java ================================================ /* * 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.ArrayList; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class JSONParseTest extends TestCase { public void test_0() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("scheduleAlarmRules", new ArrayList()); String jsonString = jsonObject.toJSONString(); String text = "{\"scheduleAlarmRules\":[]}"; Object jsonValue = JSON.parse(text); System.out.println(jsonValue); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTest.java ================================================ /* * 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(""); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTest2.java ================================================ package com.alibaba.json.bvt; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringReader; import java.math.BigDecimal; import java.math.BigInteger; 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.TypeReference; public class JSONTest2 extends TestCase { public void test_0() throws Exception { StringReader reader = new StringReader("{a:1,b:2}"); String text = IOUtils.toString(reader); JSONObject json = (JSONObject) JSON.parse(text); Assert.assertEquals(2, json.size()); Assert.assertEquals(1, json.getIntValue("a")); Assert.assertEquals(2, json.getIntValue("b")); } public void test_1() throws Exception { InputStream input = new ByteArrayInputStream("{a:1,b:2}".getBytes()); String text = IOUtils.toString(input); JSONObject json = (JSONObject) JSON.parse(text); Assert.assertEquals(2, json.size()); Assert.assertEquals(1, json.getIntValue("a")); Assert.assertEquals(2, json.getIntValue("b")); } public void test_2() throws Exception { Assert.assertEquals(new Byte((byte) 1), JSON.parseObject("1", Byte.class)); Assert.assertEquals(new Short((short) 1), JSON.parseObject("1", Short.class)); Assert.assertEquals(new Integer((int) 1), JSON.parseObject("1", Integer.class)); Assert.assertEquals(new Long((long) 1), JSON.parseObject("1", Long.class)); Assert.assertEquals(new Float((float) 1), JSON.parseObject("1", Float.class)); Assert.assertEquals(new Double((double) 1), JSON.parseObject("1", Double.class)); } public void test_3() throws Exception { Assert.assertEquals(new Byte((byte) 1), JSON.parseObject("1", byte.class)); Assert.assertEquals(new Short((short) 1), JSON.parseObject("1", short.class)); Assert.assertEquals(new Integer((int) 1), JSON.parseObject("1", int.class)); Assert.assertEquals(new Long((long) 1), JSON.parseObject("1", long.class)); Assert.assertEquals(new Float((float) 1), JSON.parseObject("1", float.class)); Assert.assertEquals(new Double((double) 1), JSON.parseObject("1", double.class)); } public void test_4() throws Exception { Assert.assertEquals(new BigInteger("1"), JSON.parseObject("1", BigInteger.class)); Assert.assertEquals(new BigDecimal("1"), JSON.parseObject("1", BigDecimal.class)); } public void test_5() throws Exception { Assert.assertArrayEquals(new byte[] { 1 }, (byte[]) JSON.parseObject("[1]", byte[].class)); Assert.assertArrayEquals(new short[] { 1 }, (short[]) JSON.parseObject("[1]", short[].class)); Assert.assertArrayEquals(new int[] { 1 }, (int[]) JSON.parseObject("[1]", int[].class)); Assert.assertArrayEquals(new long[] { 1 }, (long[]) JSON.parseObject("[1]", long[].class)); float[] array1 = JSON.parseObject("[1]", float[].class); double[] array2 = JSON.parseObject("[1]", double[].class); } public void test_6() throws Exception { Assert.assertArrayEquals(new Byte[] { 1 }, (Byte[]) JSON.parseObject("[1]", Byte[].class)); Assert.assertArrayEquals(new Short[] { 1 }, (Short[]) JSON.parseObject("[1]", Short[].class)); Assert.assertArrayEquals(new Integer[] { 1 }, (Integer[]) JSON.parseObject("[1]", Integer[].class)); Assert.assertArrayEquals(new Long[] { 1L }, (Long[]) JSON.parseObject("[1]", Long[].class)); Float[] array1 = JSON.parseObject("[1]", Float[].class); Double[] array2 = JSON.parseObject("[1]", Double[].class); } public void test_7() throws Exception { Assert.assertNull(JSON.parseObject(null, new TypeReference() {}.getType(), 0)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTest3.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTest_Bytes.java ================================================ 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.JSONObject; public class JSONTest_Bytes extends TestCase { @SuppressWarnings("rawtypes") public void test_bytes() throws Exception { for (int i = 0; i < 10; ++i) { String charset = "UTF-8"; String text = "{name:'张三', age:27}"; Map map = JSON.parseObject(text.getBytes(charset), Map.class); Assert.assertEquals("张三", map.get("name")); Assert.assertEquals(27, map.get("age")); } for (int i = 0; i < 10; ++i) { String charset = "UTF-8"; String text = "{name:'张三', age:27}"; JSONObject map = (JSONObject) JSON.parse(text.getBytes(charset)); Assert.assertEquals("张三", map.get("name")); Assert.assertEquals(27, map.get("age")); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTest_Bytes_1.java ================================================ 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))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTest_null.java ================================================ package com.alibaba.json.bvt; import java.lang.reflect.Type; import java.nio.charset.Charset; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; public class JSONTest_null extends TestCase { public void test_0() throws Exception { Assert.assertNull(JSON.parseArray(null)); Assert.assertNull(JSON.parseArray("")); Assert.assertNull(JSON.parseArray("null")); Assert.assertNull(JSON.parseArray(null, new Type[] { Object.class, Object.class })); Assert.assertNull(JSON.parseObject((char[]) null, 0, int.class, Feature.AllowArbitraryCommas)); Assert.assertNull(JSON.parseObject(new char[0], 0, int.class, Feature.AllowArbitraryCommas)); Assert.assertNull(JSON.parseObject("null".toCharArray(), 4, Object.class, Feature.AllowArbitraryCommas)); Assert.assertNull(JSON.parseObject("null".toCharArray(), 4, Object.class)); Assert.assertNull(JSON.parse("null".getBytes(), 0, 4, Charset.forName("UTF-8").newDecoder(), Feature.AllowArbitraryCommas)); Assert.assertNull(JSON.parse((byte[]) null, 0, 0, Charset.forName("UTF-8").newDecoder(), Feature.AllowArbitraryCommas)); Assert.assertNull(JSON.parse(new byte[0], 0, 0, Charset.forName("UTF-8").newDecoder(), Feature.AllowArbitraryCommas)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTest_overflow.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTokenTest.java ================================================ package com.alibaba.json.bvt; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.JSONToken; public class JSONTokenTest extends TestCase { public void test_0 () throws Exception { new JSONToken(); Assert.assertEquals("int", JSONToken.name(JSONToken.LITERAL_INT)); Assert.assertEquals("float", JSONToken.name(JSONToken.LITERAL_FLOAT)); Assert.assertEquals("string", JSONToken.name(JSONToken.LITERAL_STRING)); Assert.assertEquals("iso8601", JSONToken.name(JSONToken.LITERAL_ISO8601_DATE)); Assert.assertEquals("true", JSONToken.name(JSONToken.TRUE)); Assert.assertEquals("false", JSONToken.name(JSONToken.FALSE)); Assert.assertEquals("null", JSONToken.name(JSONToken.NULL)); Assert.assertEquals("new", JSONToken.name(JSONToken.NEW)); Assert.assertEquals("(", JSONToken.name(JSONToken.LPAREN)); Assert.assertEquals(")", JSONToken.name(JSONToken.RPAREN)); Assert.assertEquals("{", JSONToken.name(JSONToken.LBRACE)); Assert.assertEquals("}", JSONToken.name(JSONToken.RBRACE)); Assert.assertEquals("[", JSONToken.name(JSONToken.LBRACKET)); Assert.assertEquals("]", JSONToken.name(JSONToken.RBRACKET)); Assert.assertEquals(",", JSONToken.name(JSONToken.COMMA)); Assert.assertEquals(":", JSONToken.name(JSONToken.COLON)); Assert.assertEquals("ident", JSONToken.name(JSONToken.IDENTIFIER)); Assert.assertEquals("fieldName", JSONToken.name(JSONToken.FIELD_NAME)); Assert.assertEquals("EOF", JSONToken.name(JSONToken.EOF)); Assert.assertEquals("Unknown", JSONToken.name(Integer.MAX_VALUE)); Assert.assertEquals("Set", JSONToken.name(JSONToken.SET)); Assert.assertEquals("TreeSet", JSONToken.name(JSONToken.TREE_SET)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTypeTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTypeTest1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTypeTest_orders_arrayMapping.java ================================================ 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); } public void test_2() throws Exception { String json = "[1001,\"xx\"]"; JSON.parseObject(json, 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSONTypeTest_orders_arrayMapping_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSON_isValid_0.java ================================================ package com.alibaba.json.bvt; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class JSON_isValid_0 extends TestCase { public void test_for_isValid_0() throws Exception { assertFalse(JSON.isValid(null)); assertFalse(JSON.isValid("")); } public void test_for_isValid_value() throws Exception { assertTrue(JSON.isValid("null")); assertTrue(JSON.isValid("123")); assertTrue(JSON.isValid("12.34")); assertTrue(JSON.isValid("true")); assertTrue(JSON.isValid("false")); assertTrue(JSON.isValid("\"abc\"")); } public void test_for_isValid_obj() throws Exception { assertTrue(JSON.isValid("{}")); assertTrue(JSON.isValid("{\"id\":123}")); assertTrue(JSON.isValid("{\"id\":\"123\"}")); assertTrue(JSON.isValid("{\"id\":true}")); assertTrue(JSON.isValid("{\"id\":{}}")); } public void test_for_isValid_obj_1() throws Exception { assertTrue(JSON.isValidObject("{}")); assertTrue(JSON.isValidObject("{\"id\":123}")); assertTrue(JSON.isValidObject("{\"id\":\"123\"}")); assertTrue(JSON.isValidObject("{\"id\":true}")); assertTrue(JSON.isValidObject("{\"id\":{}}")); } public void test_for_isValid_array() throws Exception { assertTrue(JSON.isValid("[]")); assertTrue(JSON.isValid("[[],[]]")); assertTrue(JSON.isValid("[{\"id\":123}]")); assertTrue(JSON.isValid("[{\"id\":\"123\"}]")); assertTrue(JSON.isValid("[{\"id\":true}]")); assertTrue(JSON.isValid("[{\"id\":{}}]")); } public void test_for_isValid_array_1() throws Exception { assertTrue(JSON.isValidArray("[]")); assertTrue(JSON.isValidArray("[[],[]]")); assertTrue(JSON.isValidArray("[{\"id\":123}]")); assertTrue(JSON.isValidArray("[{\"id\":\"123\"}]")); assertTrue(JSON.isValidArray("[{\"id\":true}]")); assertTrue(JSON.isValidArray("[{\"id\":{}}]")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSON_isValid_1_error.java ================================================ package com.alibaba.json.bvt; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class JSON_isValid_1_error extends TestCase { public void test_for_isValid_0() throws Exception { assertFalse(JSON.isValid(null)); assertFalse(JSON.isValid("")); } public void test_for_isValid_value() throws Exception { assertFalse(JSON.isValid("nul")); assertFalse(JSON.isValid("null,null")); assertFalse(JSON.isValid("123,")); assertFalse(JSON.isValid("123,123")); assertFalse(JSON.isValid("12.34,true")); assertFalse(JSON.isValid("12.34,123")); assertFalse(JSON.isValid("tru")); assertFalse(JSON.isValid("true,123")); assertFalse(JSON.isValid("fals")); assertFalse(JSON.isValid("false,123")); assertFalse(JSON.isValid("\"abc")); assertFalse(JSON.isValid("\"abc\",123")); } public void test_for_isValid_obj() throws Exception { assertFalse(JSON.isValid("{")); assertFalse(JSON.isValid("{\"id\":123,}}")); assertFalse(JSON.isValid("{\"id\":\"123}")); assertFalse(JSON.isValid("{\"id\":{]}")); assertFalse(JSON.isValid("{\"id\":{")); } public void test_for_isValid_obj_1() throws Exception { assertFalse(JSON.isValidObject("{")); assertFalse(JSON.isValidObject("{\"id\":123,}}")); assertFalse(JSON.isValidObject("{\"id\":\"123}")); assertFalse(JSON.isValidObject("{\"id\":{]}")); assertFalse(JSON.isValidObject("{\"id\":{")); } public void test_for_isValid_array() throws Exception { assertFalse(JSON.isValid("[")); assertFalse(JSON.isValid("[[,[]]")); assertFalse(JSON.isValid("[{\"id\":123]")); assertFalse(JSON.isValid("[{\"id\":\"123\"}")); assertFalse(JSON.isValid("[{\"id\":true]")); assertFalse(JSON.isValid("[{\"id\":{}]")); } public void test_for_isValid_array_1() throws Exception { assertFalse(JSON.isValidArray("[")); assertFalse(JSON.isValidArray("[[,[]]")); assertFalse(JSON.isValidArray("[{\"id\":123]")); assertFalse(JSON.isValidArray("[{\"id\":\"123\"}")); assertFalse(JSON.isValidArray("[{\"id\":true]")); assertFalse(JSON.isValidArray("[{\"id\":{}]")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSON_toJSONStringTest.java ================================================ /* * 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.Collections; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.JavaBeanSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; public class JSON_toJSONStringTest extends TestCase { public void test_0() throws Exception { User user = new User(); user.setId(123); user.setName("毛头"); SerializeConfig mapping = new SerializeConfig(); mapping.put(User.class, new JavaBeanSerializer(User.class, "id")); JSONSerializer serializer = new JSONSerializer(mapping); serializer.write(user); String jsonString = serializer.toString(); Assert.assertEquals("{\"id\":123}", jsonString); } public void test_1() throws Exception { User user = new User(); user.setId(123); user.setName("毛头"); SerializeConfig mapping = new SerializeConfig(); mapping.put(User.class, new JavaBeanSerializer(User.class, Collections.singletonMap("id", "uid"))); JSONSerializer serializer = new JSONSerializer(mapping); serializer.write(user); String jsonString = serializer.toString(); Assert.assertEquals("{\"uid\":123}", 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JSON_toJavaObject_test.java ================================================ 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.parser.ParserConfig; import com.alibaba.fastjson.util.TypeUtils; public class JSON_toJavaObject_test extends TestCase { public void test_0() throws Exception { A a = (A) JSON.toJavaObject(new JSONObject(), A.class); Assert.assertNotNull(a); } public void test_1() throws Exception { A a = (A) TypeUtils.cast(new B(), A.class, ParserConfig.getGlobalInstance()); Assert.assertNotNull(a); } public static class A { } public static interface IB { } public static class B extends A implements IB { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JavaBeanMappingTest.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JavaBeanTest.java ================================================ /* * 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.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class JavaBeanTest extends TestCase { public void f_test_toJSON() throws Exception { User user = new User(); user.setName("校长"); user.setAge(3); user.setSalary(new BigDecimal("123456789.0123")); String jsonString = JSON.toJSONString(user); System.out.println(jsonString); JSON.parseObject(jsonString); User user1 = JSON.parseObject(jsonString, User.class); Assert.assertEquals(user.getAge(), user1.getAge()); Assert.assertEquals(user.getName(), user1.getName()); Assert.assertEquals(user.getSalary(), user1.getSalary()); } public void test_toJSON_List() throws Exception { User user = new User(); user.setName("校长"); user.setAge(3); user.setSalary(new BigDecimal("123456789.0123")); user.setBirthdate(new Date()); user.setOld(true); List userList = new ArrayList(); userList.add(user); String jsonString = JSON.toJSONString(userList); System.out.println(jsonString); List userList1 = JSON.parseArray(jsonString, User.class); User user1 = userList1.get(0); Assert.assertEquals(user.getAge(), user1.getAge()); Assert.assertEquals(user.getName(), user1.getName()); Assert.assertEquals(user.getSalary(), user1.getSalary()); Assert.assertEquals(user.getBirthdate(), user1.getBirthdate()); Assert.assertEquals(user.isOld(), user1.isOld()); } @SuppressWarnings("unchecked") public void f_testComposite() throws Exception { Group group = new Group(); group.setName("神棍"); User user = new User(); user.setName("校长"); user.setAge(3); user.setSalary(new BigDecimal("123456789.0123")); group.getUsers().add(user); ((List) group.getUsers2()).add(user); String jsonString = JSON.toJSONString(group); System.out.println(jsonString); JSON.parseObject(jsonString); Group group1 = JSON.parseObject(jsonString, Group.class); Assert.assertEquals(group.getName(), group1.getName()); User user1 = group1.getUsers().get(0); Assert.assertEquals(user.getAge(), user1.getAge()); Assert.assertEquals(user.getName(), user1.getName()); Assert.assertEquals(user.getSalary(), user1.getSalary()); } public static class User { private String name; private int age; private BigDecimal salary; private Date birthdate; private boolean old; public boolean isOld() { return old; } public void setOld(boolean old) { this.old = old; } public Date getBirthdate() { return birthdate; } public void setBirthdate(Date birthdate) { this.birthdate = birthdate; } 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 BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } } public static class Group { private List users = new ArrayList(); private List users2 = new ArrayList(); private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public List getUsers() { return users; } public void setUsers(List users) { this.users = users; } public List getUsers2() { return users2; } public void setUsers2(List users2) { this.users2 = users2; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/JsonValueTest.java ================================================ /* * 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LexerTest.java ================================================ /* * 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.math.BigDecimal; import java.math.BigInteger; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.parser.JSONScanner; import com.alibaba.fastjson.parser.JSONToken; public class LexerTest extends TestCase { public void test_float() throws Exception { String text = "123456789.0123"; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(); BigDecimal decimalValue = lexer.decimalValue(); Assert.assertEquals(new BigDecimal("123456789.0123"), decimalValue); } public void test_string() throws Exception { { JSONScanner lexer = new JSONScanner("\"中国\""); lexer.nextToken(); Assert.assertEquals("中国", lexer.stringVal()); } { JSONScanner lexer = new JSONScanner("\"中国\t\""); lexer.nextToken(); Assert.assertEquals("中国\t", lexer.stringVal()); } { JSONScanner lexer = new JSONScanner("\"中国\tV5\""); lexer.nextToken(); Assert.assertEquals("中国\tV5", lexer.stringVal()); } StringBuilder buf = new StringBuilder(); buf.append('"'); buf.append("\\\\\\/\\b\\f\\n\\r\\t\\u" + Integer.toHexString('中')); buf.append('"'); buf.append('\u2001'); String text = buf.toString(); JSONScanner lexer = new JSONScanner(text.toCharArray(), text.length() - 1); lexer.nextToken(); Assert.assertEquals(0, lexer.pos()); String stringVal = lexer.stringVal(); Assert.assertEquals("\"\\\\/\\b\\f\\n\\r\\t中\"", JSON.toJSONString(stringVal)); } public void test_string2() throws Exception { StringBuilder buf = new StringBuilder(); buf.append('"'); for (int i = 0; i < 200; ++i) { buf.append("\\\\\\/\\b\\f\\n\\r\\t\\u" + Integer.toHexString('中')); } buf.append('"'); String text = buf.toString(); JSONScanner lexer = new JSONScanner(text.toCharArray(), text.length()); lexer.nextToken(); Assert.assertEquals(0, lexer.pos()); lexer.stringVal(); } public void test_string3() throws Exception { StringBuilder buf = new StringBuilder(); buf.append('"'); for (int i = 0; i < 200; ++i) { buf.append("abcdefghijklmn012345689ABCDEFG"); } buf.append('"'); String text = buf.toString(); JSONScanner lexer = new JSONScanner(text.toCharArray(), text.length()); lexer.nextToken(); Assert.assertEquals(0, lexer.pos()); lexer.stringVal(); } public void test_string4() throws Exception { StringBuilder buf = new StringBuilder(); buf.append('"'); for (int i = 0; i < 200; ++i) { buf.append("\\tabcdefghijklmn012345689ABCDEFG"); } buf.append('"'); String text = buf.toString(); JSONScanner lexer = new JSONScanner(text.toCharArray(), text.length()); lexer.nextToken(); Assert.assertEquals(0, lexer.pos()); lexer.stringVal(); // Assert.assertEquals("\"\\\\\\/\\b\\f\\n\\r\\t中\"", // JSON.toJSONString(stringVal)); } public void test_empty() throws Exception { JSONScanner lexer = new JSONScanner("".toCharArray(), 0); lexer.nextToken(); Assert.assertEquals(JSONToken.EOF, lexer.token()); } public void test_isWhitespace() throws Exception { new JSONScanner("".toCharArray(), 0); Assert.assertTrue(JSONScanner.isWhitespace(' ')); Assert.assertTrue(JSONScanner.isWhitespace('\b')); Assert.assertTrue(JSONScanner.isWhitespace('\f')); Assert.assertTrue(JSONScanner.isWhitespace('\n')); Assert.assertTrue(JSONScanner.isWhitespace('\r')); Assert.assertTrue(JSONScanner.isWhitespace('\t')); Assert.assertFalse(JSONScanner.isWhitespace('k')); } public void test_error() throws Exception { JSONScanner lexer = new JSONScanner("k"); lexer.nextToken(); Assert.assertEquals(JSONToken.ERROR, lexer.token()); } public void test_error1() throws Exception { Exception error = null; try { JSONScanner lexer = new JSONScanner("\"\\k\""); lexer.nextToken(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void f_test_ident() throws Exception { { JSONScanner lexer = new JSONScanner("ttue"); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } { JSONScanner lexer = new JSONScanner("tree"); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } { JSONScanner lexer = new JSONScanner("truu"); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } { JSONScanner lexer = new JSONScanner("fflse"); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } { JSONScanner lexer = new JSONScanner("nalse"); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } { JSONScanner lexer = new JSONScanner("faase"); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } { JSONScanner lexer = new JSONScanner("falle"); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } { JSONScanner lexer = new JSONScanner("falss"); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } { JSONScanner lexer = new JSONScanner("nnll"); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } { JSONScanner lexer = new JSONScanner("nuul"); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } { JSONScanner lexer = new JSONScanner("nulk"); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } { StringBuilder buf = new StringBuilder(); buf.append('n'); for (char ch = 'A'; ch <= 'Z'; ++ch) { buf.append(ch); } for (char ch = 'a'; ch <= 'z'; ++ch) { buf.append(ch); } JSONScanner lexer = new JSONScanner(buf.toString()); lexer.nextToken(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); } } public void test_number() throws Exception { String text = "[0,1,-1,2E3,2E+3,2E-3,2e3,2e+3,2e-3]"; JSONArray array = JSON.parseArray(text); Assert.assertEquals(0, array.get(0)); Assert.assertEquals(1, array.get(1)); Assert.assertEquals(-1, array.get(2)); Assert.assertEquals(new BigDecimal("2E3"), array.get(3)); Assert.assertEquals(new BigDecimal("2E3"), array.get(4)); Assert.assertEquals(new BigDecimal("2E-3"), array.get(5)); Assert.assertEquals(new BigDecimal("2E3"), array.get(6)); Assert.assertEquals(new BigDecimal("2E3"), array.get(7)); Assert.assertEquals(new BigDecimal("2E-3"), array.get(8)); for (long i = Long.MIN_VALUE; i <= Long.MIN_VALUE + 1000 * 10; ++i) { Assert.assertEquals(i, JSON.parse(Long.toString(i))); } for (long i = Long.MAX_VALUE - 1000 * 10; i <= Long.MAX_VALUE && i > 0; ++i) { Assert.assertEquals(i, JSON.parse(Long.toString(i))); } } public void test_big_integer_1() throws Exception { String text = Long.MAX_VALUE + "1234"; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(); Assert.assertEquals(new BigInteger(text), lexer.integerValue()); } public void test_big_integer_2() throws Exception { String text = Long.MIN_VALUE + "1234"; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(); Assert.assertEquals(new BigInteger(text), lexer.integerValue()); } public void test_big_integer_3() throws Exception { String text = "9223372036854775809"; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(); Assert.assertEquals(new BigInteger(text), lexer.integerValue()); } public void test_error2() { Exception error = null; try { JSONScanner lexer = new JSONScanner("--"); lexer.nextToken(); lexer.integerValue(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error3() { Exception error = null; try { JSONScanner lexer = new JSONScanner(""); lexer.nextToken(); lexer.nextToken(); lexer.integerValue(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LinkedListFieldTest.java ================================================ package com.alibaba.json.bvt; import java.util.LinkedList; 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 LinkedListFieldTest 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); 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); Assert.assertEquals("{\"value\":[]}", JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); Assert.assertEquals("{value:[]}", JSON.toJSONStringZ(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); Assert.assertEquals("{value:[]}", JSON.toJSONStringZ(v, mapping, SerializerFeature.UseSingleQuotes, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); Assert.assertEquals("{'value':[]}", JSON.toJSONStringZ(v, mapping, SerializerFeature.UseSingleQuotes, SerializerFeature.QuoteFieldNames, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); } public static class V0 { private LinkedList value; public LinkedList getValue() { return value; } public void setValue(LinkedList value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ListFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ListFieldTest2.java ================================================ 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 ListFieldTest2 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 List value; public List getValue() { return value; } public void setValue(List value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ListFieldTest3.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ListFloatFieldTest.java ================================================ 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; public class ListFloatFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(new ArrayList()); user.getValue().add(1F); String text = JSON.toJSONString(user); System.out.println(text); User user1 = JSON.parseObject(text, User.class); Assert.assertEquals(user1.getValue(), user.getValue()); } public static class User { private List value; public List getValue() { return value; } public void setValue(List value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LocaleFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongArrayFieldTest.java ================================================ 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 LongArrayFieldTest 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); 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 Long[] value; public Long[] getValue() { return value; } public void setValue(Long[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongArrayFieldTest_primitive.java ================================================ 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 LongArrayFieldTest_primitive 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); 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 long[] value; public long[] getValue() { return value; } public void setValue(long[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongFieldTest.java ================================================ package com.alibaba.json.bvt; 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 LongFieldTest extends TestCase { public void test_codec() throws Exception { V0 v = new V0(); v.setValue(1001L); String text = JSON.toJSONString(v); System.out.println(text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v1.getValue(), v.getValue()); } 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_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); 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.WriteNullNumberAsZero); Assert.assertEquals("{\"value\":0}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(Long.valueOf(0), v1.getValue()); } public static class V0 { private Long value; public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongFieldTest_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongFieldTest_2_private.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongFieldTest_2_stream.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongFieldTest_3.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongFieldTest_3_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongFieldTest_3_stream.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongFieldTest_4.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongFieldTest_4_stream.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/LongFieldTest_primitive.java ================================================ package com.alibaba.json.bvt; 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 LongFieldTest_primitive extends TestCase { public void test_codec() throws Exception { V0 v = new V0(); v.setValue(1001L); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v1.getValue(), v.getValue()); } 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\":123}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v1.getValue(), v.getValue()); } 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\":123}", 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.WriteNullNumberAsZero); Assert.assertEquals("{\"value\":123}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(123, v1.getValue()); } public static class V0 { private long value = 123L; public long getValue() { return value; } public void setValue(long value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/MapRefTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/MapRefTest1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/MapRefTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/MapRefTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/MapRefTest4.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/MapRefTest5.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/MapRefTest6.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/MapTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/MapTest2.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/MaterializedInterfaceTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/MaterializedInterfaceTest2.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ModuleTest.java ================================================ package com.alibaba.json.bvt; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.alibaba.fastjson.serializer.MiscCodec; import com.alibaba.fastjson.serializer.ObjectSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.spi.Module; import junit.framework.TestCase; public class ModuleTest extends TestCase { public void test_for_module() throws Exception { ParserConfig config = new ParserConfig(); config.register(new MyModuel2()); config.register(new MyModuel()); assertSame(MiscCodec.instance, config.getDeserializer(A.class)); } public void test_for_module_1() throws Exception { SerializeConfig config = new SerializeConfig(); config.register(new MyModuel2()); config.register(new MyModuel()); assertSame(MiscCodec.instance, config.getObjectWriter(A.class)); } public static class A { } public static class MyModuel implements Module { @Override public ObjectDeserializer createDeserializer(ParserConfig config, Class type) { return MiscCodec.instance; } @Override public ObjectSerializer createSerializer(SerializeConfig config, Class type) { return MiscCodec.instance; } } public static class MyModuel2 implements Module { @Override public ObjectDeserializer createDeserializer(ParserConfig config, Class type) { return null; } @Override public ObjectSerializer createSerializer(SerializeConfig config, Class type) { return null; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/NotWriteRootClassNameTest.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/NumberFieldTest.java ================================================ package com.alibaba.json.bvt; import java.math.BigDecimal; 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 NumberFieldTest extends TestCase { public void test_codec() throws Exception { V0 v = new V0(); v.setValue(1001L); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v1.getValue().intValue(), v.getValue().intValue()); } public void test_codec_no_asm() throws Exception { V0 v = new V0(); v.setValue(1001L); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":1001}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(Integer.valueOf(1001), v1.getValue()); } 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_2_no_asm() throws Exception { V0 v = new V0(); v.setValue(Long.MAX_VALUE); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":" + Long.MAX_VALUE + "}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(new Long(Long.MAX_VALUE), v1.getValue()); } public void test_codec_2_asm() throws Exception { V0 v = new V0(); v.setValue(Long.MAX_VALUE); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(true); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":" + Long.MAX_VALUE + "}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(new Long(Long.MAX_VALUE), v1.getValue()); } public void test_codec_3_no_asm() throws Exception { V0 v = new V0(); v.setValue(new BigDecimal("3.2")); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":3.2}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(new BigDecimal("3.2"), v1.getValue()); } public void test_codec_3_asm() throws Exception { V0 v = new V0(); v.setValue(new BigDecimal("3.2")); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(true); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":3.2}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(new BigDecimal("3.2"), v1.getValue()); } public void test_codec_min_no_asm() throws Exception { V0 v = new V0(); v.setValue(Long.MIN_VALUE); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":" + Long.MIN_VALUE + "}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(new Long(Long.MIN_VALUE), v1.getValue()); } public void test_codec_min_asm() throws Exception { V0 v = new V0(); v.setValue(Long.MIN_VALUE); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(true); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":" + Long.MIN_VALUE + "}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(new Long(Long.MIN_VALUE), v1.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\":0}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(Integer.valueOf(0), v1.getValue()); } public void test_codec_null_1_asm() throws Exception { V0 v = new V0(); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(true); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero); Assert.assertEquals("{\"value\":0}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(Integer.valueOf(0), v1.getValue()); } public void test_codec_cast() throws Exception { V0 v1 = JSON.parseObject("{\"value\":\"12.3\"}", V0.class); Assert.assertEquals(new BigDecimal("12.3"), v1.getValue()); } public static class V0 { private Number value; public Number getValue() { return value; } public void setValue(Number value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/OOMTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ObjectArrayFieldTest.java ================================================ 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 ObjectArrayFieldTest 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); 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 Object[] value; public Object[] getValue() { return value; } public void setValue(Object[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ObjectFieldTest.java ================================================ 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 ObjectFieldTest extends TestCase { public void test_codec_null() throws Exception { SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); { V0 v = new V0(); 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()); } { V0 v = new V0(); v.setValue(Integer.valueOf(123)); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":123}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v1.getValue(), v.getValue()); } } public void test_codec_null_1() throws Exception { SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); { V0 v = new V0(); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty); Assert.assertEquals("{\"value\":null}", text); } { V0 v = new V0(); v.setValue(Integer.valueOf(123)); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":123}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v1.getValue(), v.getValue()); } } public static class V0 { private Object value; public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/OverriadeTest.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ParseArrayTest.java ================================================ package com.alibaba.json.bvt; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.TreeMap; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class ParseArrayTest extends TestCase { public void test_0 () throws Exception { List list = JSON.parseArray("[{}, {}]", new Type[] {TreeMap.class, HashMap.class}); Assert.assertTrue(list.get(0) instanceof TreeMap); Assert.assertTrue(list.get(1) instanceof HashMap); } public void test_1 () throws Exception { List list = JSON.parseArray("[1, 2, \"abc\"]", new Type[] {int.class, Integer.class, String.class}); Assert.assertTrue(list.get(0) instanceof Integer); Assert.assertTrue(list.get(1) instanceof Integer); Assert.assertTrue(list.get(2) instanceof String); } public void test_2 () throws Exception { List list = JSON.parseArray("[1, null, \"abc\"]", new Type[] {int.class, Integer.class, String.class}); Assert.assertTrue(list.get(0) instanceof Integer); Assert.assertTrue(list.get(1) == null); Assert.assertTrue(list.get(2) instanceof String); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/PatternFieldTest.java ================================================ package com.alibaba.json.bvt; import java.util.regex.Pattern; 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 PatternFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(Pattern.compile(".")); 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().pattern(), user.getValue().pattern()); } 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 Pattern value; public Pattern getValue() { return value; } public void setValue(Pattern value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/PointTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/PointTest2.java ================================================ package com.alibaba.json.bvt; import java.awt.Point; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; 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, Feature.SupportAutoType); 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/PublicFieldDoubleTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/PublicFieldFloatTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/PublicFieldLongTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/PublicFieldStringTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/RectangleTest.java ================================================ package com.alibaba.json.bvt; import java.awt.Rectangle; import com.alibaba.fastjson.parser.Feature; 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, Feature.SupportAutoType); Assert.assertEquals(v, v2); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest_manual.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/SerializeEnumAsJavaBeanTest_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/SerializeWriterTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ServiceLoaderTest.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ShortArrayFieldTest_primitive.java ================================================ 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 ShortArrayFieldTest_primitive extends TestCase { public void test_array() throws Exception { Assert.assertEquals("[1]", JSON.toJSONString(new short[] { 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 short[] value; public short[] getValue() { return value; } public void setValue(short[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/SlashTest.java ================================================ package com.alibaba.json.bvt; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class SlashTest extends TestCase { public void test_0 () throws Exception { String text = "{\"errorMessage\":\"resource '/rpc/hello/none.json' is not found !\"}"; JSONObject json = (JSONObject) JSON.parse(text); Assert.assertEquals("{\"errorMessage\":\"resource '/rpc/hello/none.json' is not found !\"}", json.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/SpecialKeyTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/SpecialKeyTest2.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/SqlDateTest1.java ================================================ package com.alibaba.json.bvt; import java.sql.Date; 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.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)); } // // public void test_date2() throws Exception { // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // java.util.Date d = sdf.parse("2019-09-12 16:00:00"); // java.sql.Date ds = new java.sql.Date(d.getTime()); //// System.out.println("Java Obj: " + sdf.format(ds)); // // String jvs = JSON.toJSONString(ds); //// System.out.println("JSON Str: " + jvs); // // java.sql.Date d2s = JSON.parseObject(jvs, java.sql.Date.class); //// System.out.println("Java Obj: " + sdf.format(d2s)); //// System.out.println("LONG: " + d2s.getTime()); // // assertEquals(d.getTime(), d2s.getTime()); // } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/SqlTimestampTest.java ================================================ package com.alibaba.json.bvt; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.sql.Timestamp; import java.util.Locale; import java.util.TimeZone; public class SqlTimestampTest extends TestCase { protected void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getDefault(); JSON.defaultLocale = Locale.getDefault(); } public void test_date() throws Exception { Timestamp ts = new Timestamp( 97, 2, 17, 15, 53, 01, 12345678 ); System.out.println('"' + ts.toString() + '"'); String json = JSON.toJSONString(ts, SerializerFeature.UseISO8601DateFormat); System.out.println(json); Timestamp ts2 = JSON.parseObject(json, Timestamp.class); String json2 = JSON.toJSONString(ts2, SerializerFeature.UseISO8601DateFormat); System.out.println(json2); assertEquals('"' + ts.toString() + '"', '"' + ts2.toString() + '"'); } public void test_date_1() throws Exception { // 2020-04-11 03:10:19.516 Timestamp ts = new Timestamp( 97, 2, 17, 15, 53, 01, 516000000 ); System.out.println('"' + ts.toString() + '"'); String json = JSON.toJSONString(ts, SerializerFeature.UseISO8601DateFormat); System.out.println(json); Timestamp ts2 = JSON.parseObject(json, Timestamp.class); String json2 = JSON.toJSONString(ts2, SerializerFeature.UseISO8601DateFormat); System.out.println(json2); assertEquals('"' + ts.toString() + '"', '"' + ts2.toString() + '"'); } // 1997-03-17 15:53:01.01 public void test_date_2() throws Exception { // 2020-04-11 03:10:19.516 Timestamp ts = new Timestamp( 97, 3, 17, 15, 53, 01, 10000000 ); System.out.println('"' + ts.toString() + '"'); String json = JSON.toJSONString(ts, SerializerFeature.UseISO8601DateFormat); System.out.println(json); Timestamp ts2 = JSON.parseObject(json, Timestamp.class); String json2 = JSON.toJSONString(ts2, SerializerFeature.UseISO8601DateFormat); System.out.println(json2); assertEquals('"' + ts.toString() + '"', '"' + ts2.toString() + '"'); } public void test_date_999999999() throws Exception { // 2020-04-11 03:10:19.516 Timestamp ts = new Timestamp( 97, 2, 17, 15, 53, 01, 999999999 ); System.out.println('"' + ts.toString() + '"'); String json = JSON.toJSONString(ts, SerializerFeature.UseISO8601DateFormat); System.out.println(json); Timestamp ts2 = JSON.parseObject(json, Timestamp.class); String json2 = JSON.toJSONString(ts2, SerializerFeature.UseISO8601DateFormat); System.out.println(json2); assertEquals('"' + ts.toString() + '"', '"' + ts2.toString() + '"'); } public void test_date_x1() throws Exception { // 2020-04-11 03:10:19.516 Timestamp ts = new Timestamp( 97, 2, 17, 15, 53, 01, 5 ); System.out.println('"' + ts.toString() + '"'); String json = JSON.toJSONString(ts, SerializerFeature.UseISO8601DateFormat); Timestamp ts2 = JSON.parseObject(json, Timestamp.class); System.out.println(json); String json2 = JSON.toJSONString(ts2, SerializerFeature.UseISO8601DateFormat); System.out.println(json2); assertEquals('"' + ts.toString() + '"', '"' + ts2.toString() + '"'); } public void test_date_x2() throws Exception { // 2020-04-11 03:10:19.516 Timestamp ts = new Timestamp( 97, 2, 17, 15, 53, 01, 50 ); System.out.println('"' + ts.toString() + '"'); String json = JSON.toJSONString(ts, SerializerFeature.UseISO8601DateFormat); Timestamp ts2 = JSON.parseObject(json, Timestamp.class); System.out.println(json); String json2 = JSON.toJSONString(ts2, SerializerFeature.UseISO8601DateFormat); System.out.println(json2); assertEquals('"' + ts.toString() + '"', '"' + ts2.toString() + '"'); } public void test_date_x() throws Exception { // 2020-04-11 03:10:19.516 int nanos = 1; for (int i = 0; i < 8; i++) { nanos = nanos * 10; Timestamp ts = new Timestamp( 97, 2, 17, 15, 53, 01, nanos ); System.out.println("_ts_: \"" + ts.toString() + '"'); String json = JSON.toJSONString(ts, SerializerFeature.UseISO8601DateFormat); System.out.println("json: " + json); Timestamp ts2 = JSON.parseObject(json, Timestamp.class); String json2 = JSON.toJSONString(ts2, SerializerFeature.UseISO8601DateFormat); System.out.println("json: " + json2); assertEquals('"' + ts.toString() + '"', '"' + ts2.toString() + '"'); System.out.println(); } } public void test_date_xx() throws Exception { // 2020-04-11 03:10:19.516 int nanos = 0; for (int i = 0; i < 9; i++) { nanos = nanos * 10 + (i + 1); Timestamp ts = new Timestamp( 97, 2, 17, 15, 53, 01, nanos ); System.out.println('"' + ts.toString() + '"'); String json = JSON.toJSONString(ts, SerializerFeature.UseISO8601DateFormat); Timestamp ts2 = JSON.parseObject(json, Timestamp.class); String json2 = JSON.toJSONString(ts2, SerializerFeature.UseISO8601DateFormat); System.out.println(json); System.out.println(json2); assertEquals('"' + ts.toString() + '"', '"' + ts2.toString() + '"'); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/StringBufferFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/StringBuilderFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/StringDeserializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/StringFieldTest.java ================================================ package com.alibaba.json.bvt; 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 StringFieldTest 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 static class V0 { private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/StringFieldTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/StringFieldTest_special.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/StringFieldTest_special_1.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/StringFieldTest_special_2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/StringFieldTest_special_3.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/StringFieldTest_special_reader.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/StringFieldTest_special_singquote.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/SymbolTableTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TabCharTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestDeprecate.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestExternal.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestExternal2.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestExternal3.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestExternal4.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestExternal5.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestExternal6.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestFlase.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestForEmoji.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestForPascalStyle.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestMultiLevelClass.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestMultiLevelClass2.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestNullKeyMap.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestSerializable.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TestTimeUnit.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TimeZoneFieldTest.java ================================================ package com.alibaba.json.bvt; 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; public class TimeZoneFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(TimeZone.getDefault()); 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 TimeZone value; public TimeZone getValue() { return value; } public void setValue(TimeZone value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TimestampTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/TypeUtilstTest.java ================================================ /* * 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.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.List; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TypeUtilstTest extends TestCase { public void test_0() throws Exception { List personList = new ArrayList(); { Person p = new Person(); p.setF1(true); p.setF2(true); p.setF3((byte) 3); p.setF4((byte) 4); p.setF5((short) 5); p.setF6((short) 6); p.setF7(7); p.setF8(8); p.setF9(9L); p.setF10(10L); p.setF11(new BigInteger("12345678901234567890123456789012345678901234567890")); p.setF12(new BigDecimal("1234567890123456789012345678901234567890.1234567890")); p.setF13("F13"); p.setF14(new Date()); p.setF15(15); p.setF16(16F); p.setF17(17); p.setF18(18D); personList.add(p); } { Person person = new Person(); personList.add(person); } String jsonString = JSON.toJSONString(personList); JSON.parseArray(jsonString, Person.class); // CGLibExtJSONParser parser = new CGLibExtJSONParser(text); } public static class Person { private boolean f1; private Boolean f2; private byte f3; private Byte f4; private short f5; private Short f6; private int f7; private Integer f8; private long f9; private Long f10; private BigInteger f11; private BigDecimal f12; private String f13; private Date f14; private float f15; private Float f16; private double f17; private Double f18; public boolean isF1() { return f1; } public void setF1(boolean f1) { this.f1 = f1; } public Boolean getF2() { return f2; } public void setF2(Boolean f2) { this.f2 = f2; } public byte getF3() { return f3; } public void setF3(byte f3) { this.f3 = f3; } public Byte getF4() { return f4; } public void setF4(Byte f4) { this.f4 = f4; } public short getF5() { return f5; } public void setF5(short f5) { this.f5 = f5; } public Short getF6() { return f6; } public void setF6(Short f6) { this.f6 = f6; } public int getF7() { return f7; } public void setF7(int f7) { this.f7 = f7; } public Integer getF8() { return f8; } public void setF8(Integer f8) { this.f8 = f8; } public long getF9() { return f9; } public void setF9(long f9) { this.f9 = f9; } public Long getF10() { return f10; } public void setF10(Long f10) { this.f10 = f10; } public BigInteger getF11() { return f11; } public void setF11(BigInteger f11) { this.f11 = f11; } public BigDecimal getF12() { return f12; } public void setF12(BigDecimal f12) { this.f12 = f12; } public String getF13() { return f13; } public void setF13(String f13) { this.f13 = f13; } public Date getF14() { return f14; } public void setF14(Date f14) { this.f14 = f14; } public float getF15() { return f15; } public void setF15(float f15) { this.f15 = f15; } public Float getF16() { return f16; } public void setF16(Float f16) { this.f16 = f16; } public double getF17() { return f17; } public void setF17(double f17) { this.f17 = f17; } public Double getF18() { return f18; } public void setF18(Double f18) { this.f18 = f18; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/URIFieldTest.java ================================================ package com.alibaba.json.bvt; import java.net.URI; 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 URIFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(URI.create("http://www.alibaba.com/abc")); 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 URI value; public URI getValue() { return value; } public void setValue(URI value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/URLFieldTest.java ================================================ package com.alibaba.json.bvt; import java.net.URL; 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 URLFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(new URL("http://code.alibaba-tech.com")); 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().toString(), user.getValue().toString()); } 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 URL value; public URL getValue() { return value; } public void setValue(URL value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/UUIDFieldTest.java ================================================ package com.alibaba.json.bvt; import java.util.UUID; 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 UUIDFieldTest extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(UUID.randomUUID()); 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_upper_case() throws Exception { User user = new User(); String text ="{\"value\":\"79104776-6CA7-4E41-948F-4D2ECD06502A\"}"; user = JSON.parseObject(text, User.class); Assert.assertEquals("79104776-6CA7-4E41-948F-4D2ECD06502A", user.getValue().toString().toUpperCase()); } 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 UUID value; public UUID getValue() { return value; } public void setValue(UUID value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/UnQuoteFieldNamesTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/WildcardTypeTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/WriteClassNameTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/WriteClassNameTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/XX01.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/annotation/AnnotationTest.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/annotation/CustomDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/annotation/CustomSerializerTest.java ================================================ 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('}'); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/annotation/CustomSerializerTest_enum.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/annotation/DeserializeUsingTest.java ================================================ 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 void test_deserializeUsing2() throws Exception { String jsonStr = "{'subjectList':['CHINESE','MATH']}"; Teacher teacher = JSON.parseObject(jsonStr).toJavaObject(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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/annotation/JSONTypeAutoTypeCheckHandlerTest.java ================================================ package com.alibaba.json.bvt.annotation; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.parser.ParserConfig; import junit.framework.TestCase; public class JSONTypeAutoTypeCheckHandlerTest extends TestCase { public void test_for_checkAutoType() throws Exception { Cat cat = (Cat) JSON.parseObject("{\"@type\":\"Cat\",\"catId\":123}", Animal.class); assertEquals(123, cat.catId); } @JSONType(autoTypeCheckHandler = MyAutoTypeCheckHandler.class) public static class Animal { } public static class Cat extends Animal { public int catId; } public static class Mouse extends Animal { } public static class MyAutoTypeCheckHandler implements ParserConfig.AutoTypeCheckHandler { public Class handler(String typeName, Class expectClass, int features) { if ("Cat".equals(typeName)) { return Cat.class; } if ("Mouse".equals(typeName)) { return Mouse.class; } return null; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/annotation/JSONTypejsonType_alphabetic_Test.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/annotation/JsonSeeAlsoTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/annotation/SerializeUsingTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/annotation/SerializeUsingWhenString.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/ASMDeserTest.java ================================================ package com.alibaba.json.bvt.asm; import java.util.ArrayList; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class ASMDeserTest extends TestCase { public void test_codec() throws Exception { String text = JSON.toJSONString(new Entity()); Assert.assertEquals("[]", text); Entity object = JSON.parseObject(text, Entity.class); Assert.assertEquals(0, object.size()); } public void test_codec_1() throws Exception { String text = JSON.toJSONString(new VO()); Assert.assertEquals("{\"value\":[]}", text); VO object = JSON.parseObject(text, VO.class); Assert.assertEquals(0, object.getValue().size()); } public void test_ArrayList() throws Exception { ArrayList object = JSON.parseObject("[]", ArrayList.class); Assert.assertEquals(0, object.size()); } public void test_error() throws Exception { Exception error = null; try { JSON.parseObject("[]", EntityError.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public static class VO { private Entity value = new Entity(); public Entity getValue() { return value; } public void setValue(Entity value) { this.value = value; } } public static class Entity extends ArrayList { } public static class EntityError extends ArrayList { public EntityError(){ throw new RuntimeException(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/ASMDeserTest2.java ================================================ package com.alibaba.json.bvt.asm; import java.util.ArrayList; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class ASMDeserTest2 extends TestCase { public void test_codec_1() throws Exception { String text = JSON.toJSONString(new VO()); Assert.assertEquals("{\"value\":[]}", text); VO object = JSON.parseObject(text, VO.class); Assert.assertEquals(0, object.getValue().size()); } public static class VO { private Entity value = new Entity(); public Entity getValue() { return value; } public void setValue(Entity value) { this.value = value; } } public static class Entity extends ArrayList { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/ASMUtilsTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/Case0.java ================================================ package com.alibaba.json.bvt.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class Case0 extends TestCase { public void test_0() throws Exception { V0 entity = new V0(); entity.setValue("abc"); String jsonString = JSON.toJSONString(entity); System.out.println(jsonString); V0 entity2 = JSON.parseObject(jsonString, V0.class); Assert.assertEquals(entity.getValue(), entity2.getValue()); } public static class V0 { private int id; private String value; private long v2; public long getV2() { return v2; } public void setV2(long v2) { this.v2 = v2; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/Case_Eishay.java ================================================ package com.alibaba.json.bvt.asm; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.json.test.benchmark.decode.EishayDecodeBytes; import data.media.MediaContent; public class Case_Eishay extends TestCase { private final String text; public Case_Eishay(){ super(); this.text = EishayDecodeBytes.instance.getText(); } public void test_0() throws Exception { //JavaBeanMapping.getGlobalInstance().setAsmEnable(false); System.out.println(text); MediaContent object = JSON.parseObject(text, MediaContent.class); String text2 = JSON.toJSONString(object, SerializerFeature.WriteEnumUsingToString); System.out.println(text2); System.out.println(JSON.toJSONString(JSON.parseObject(text2), true)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/ClassReaderTest.java ================================================ package com.alibaba.json.bvt.asm; import junit.framework.TestCase; public class ClassReaderTest extends TestCase { public void test_read() throws Exception { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/Huge_200_ClassTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/Huge_300_ClassTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/JSONASMUtilTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/LoopTest.java ================================================ package com.alibaba.json.bvt.asm; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class LoopTest extends TestCase { public void test_loop() throws Exception { Department department = JSON.parseObject("{id:12,name:'R & D', members:[{id:2001, name:'jobs'}]}", Department.class); Assert.assertNotNull(department); Assert.assertEquals(12, department.getId()); } public static class Department { private int id; private String name; private List members = new ArrayList(); 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 List getMembers() { return members; } public void setMembers(List members) { this.members = members; } } public static class Employee { private int id; private String name; private Department department; 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 getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/SortFieldTest.java ================================================ package com.alibaba.json.bvt.asm; 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; public class SortFieldTest extends TestCase { public void test_0() throws Exception { V0 entity = new V0(); String text = JSON.toJSONString(entity, 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); 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); } public void test_1() throws Exception { V1 entity = new V1(); String text = JSON.toJSONString(entity, SerializerFeature.SortField); System.out.println(text); // 按字段顺序输出 // {"f1":0,"f2":0,"f3":0,"f4":0,"f5":0} Assert.assertEquals("{\"f1\":0,\"f2\":0,\"f3\":0,\"f4\":0,\"f5\":0}", text); JSONObject object = JSON.parseObject(text); text = JSON.toJSONString(object, SerializerFeature.SortField); Assert.assertEquals("{\"f1\":0,\"f2\":0,\"f3\":0,\"f4\":0,\"f5\":0}", text); } public static class V1 { private int f2; private int f1; private int f4; private int f3; private int f5; 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 getF4() {return f4;} public void setF4(int f4) {this.f4 = f4;} public int getF3() {return f3;} public void setF3(int f3) {this.f3 = f3;} public int getF5() {return f5;} public void setF5(int f5) {this.f5 = f5;} } public static class V0 { private int f5; private int f4; private int f3; private int f2; private int f1; private int f0; private int f6; private int f7; private int f8; private int f9; private int f14; private int f13; private int f12; private int f11; private int f10; public int getF5() { return f5; } public void setF5(int f5) { this.f5 = f5; } public int getF4() { return f4; } public void setF4(int f4) { this.f4 = f4; } public int getF3() { return f3; } public void setF3(int f3) { this.f3 = f3; } 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 int getF6() { return f6; } public void setF6(int f6) { this.f6 = f6; } public int getF7() { return f7; } public void setF7(int f7) { this.f7 = f7; } public int getF8() { return f8; } public void setF8(int f8) { this.f8 = f8; } public int getF9() { return f9; } public void setF9(int f9) { this.f9 = f9; } public int getF14() { return f14; } public void setF14(int f14) { this.f14 = f14; } public int getF13() { return f13; } public void setF13(int f13) { this.f13 = f13; } public int getF12() { return f12; } public void setF12(int f12) { this.f12 = f12; } public int getF11() { return f11; } public void setF11(int f11) { this.f11 = f11; } public int getF10() { return f10; } public void setF10(int f10) { this.f10 = f10; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/TestList.java ================================================ package com.alibaba.json.bvt.asm; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestList extends TestCase { public void test_0() throws Exception { VO o = new VO(); o.setId(123); { Map> item = new HashMap>(); item.put("1", Arrays.asList("a1", "b1")); o.getItems().add(item); } { Map> item = new HashMap>(); item.put("2", Arrays.asList("a2", "b2")); o.getItems().add(item); } String text = JSON.toJSONString(o); VO o1 = JSON.parseObject(text, VO.class); String text1 = JSON.toJSONString(o1); Assert.assertEquals(text1, text); Assert.assertEquals("{\"id\":123,\"items\":[{\"1\":[\"a1\",\"b1\"]},{\"2\":[\"a2\",\"b2\"]}]}", text); } public static class VO { private int id; private List>> items = new ArrayList>>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public List>> getItems() { return items; } public void setItems(List>> items) { this.items = items; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/TestNonASM.java ================================================ package com.alibaba.json.bvt.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.ParserConfig; public class TestNonASM extends TestCase { public void test_no_asm() throws Exception { ParserConfig mapping = new ParserConfig(); mapping.setAsmEnable(false); Assert.assertEquals(false, mapping.isAsmEnable()); mapping.setAsmEnable(true); Assert.assertEquals(true, mapping.isAsmEnable()); } public void test_error() throws Exception { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/asm/TestType.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/atomic/AtomicBooleanReadOnlyTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/atomic/AtomicIntegerArrayFieldTest.java ================================================ package com.alibaba.json.bvt.atomic; import java.util.concurrent.atomic.AtomicIntegerArray; 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 AtomicIntegerArrayFieldTest 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); 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 void test_codec_null_2() throws Exception { V0 v = JSON.parseObject("{\"value\":[1,2]}", V0.class); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty); Assert.assertEquals("{\"value\":[1,2]}", text); } public static class V0 { private AtomicIntegerArray value; public AtomicIntegerArray getValue() { return value; } public void setValue(AtomicIntegerArray value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/atomic/AtomicIntegerReadOnlyTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/atomic/AtomicLongArrayFieldTest.java ================================================ package com.alibaba.json.bvt.atomic; import java.util.concurrent.atomic.AtomicLongArray; 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 AtomicLongArrayFieldTest 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); 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 void test_codec_null_2() throws Exception { V0 v = JSON.parseObject("{\"value\":[1,2]}", V0.class); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty); Assert.assertEquals("{\"value\":[1,2]}", text); } public static class V0 { private AtomicLongArray value; public AtomicLongArray getValue() { return value; } public void setValue(AtomicLongArray value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/atomic/AtomicLongReadOnlyTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/awt/ColorTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/awt/FontTest.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/awt/FontTest2.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/BigDecimal_BrowserCompatible.java ================================================ package com.alibaba.json.bvt.basicType; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import java.util.LinkedHashMap; import java.util.Map; public class BigDecimal_BrowserCompatible extends TestCase { public void test_for_issue() throws Exception { Map map = new LinkedHashMap(); map.put("id1", new BigDecimal("-9223370018640066466")); map.put("id2", new BigDecimal("9223370018640066466")); map.put("id3", new BigDecimal("100")); assertEquals("{\"id1\":\"-9223370018640066466\",\"id2\":\"9223370018640066466\",\"id3\":100}", JSON.toJSONString(map, SerializerFeature.BrowserCompatible) ); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/BigDecimal_field.java ================================================ package com.alibaba.json.bvt.basicType; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import static com.alibaba.fastjson.serializer.SerializerFeature.BrowserCompatible; public class BigDecimal_field extends TestCase { public void test_for_issue() throws Exception { assertEquals("{\"value\":\"9007199254741992\"}" , JSON.toJSONString( new Model(9007199254741992L))); assertEquals("{\"value\":\"-9007199254741992\"}" , JSON.toJSONString( new Model(-9007199254741992L))); assertEquals("{\"value\":9007199254740990}" , JSON.toJSONString( new Model(9007199254740990L))); assertEquals("{\"value\":-9007199254740990}" , JSON.toJSONString( new Model(-9007199254740990L))); assertEquals("{\"value\":100}" , JSON.toJSONString( new Model(100))); assertEquals("{\"value\":-100}" , JSON.toJSONString( new Model(-100))); } public static class Model { @JSONField(serialzeFeatures = BrowserCompatible) public BigDecimal value; public Model() { } public Model(long value) { this.value = BigDecimal.valueOf(value); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/BigDecimal_type.java ================================================ package com.alibaba.json.bvt.basicType; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONType; import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import static com.alibaba.fastjson.serializer.SerializerFeature.BrowserCompatible; public class BigDecimal_type extends TestCase { public void test_for_issue() throws Exception { assertEquals("{\"value\":\"9007199254741992\"}" , JSON.toJSONString( new Model(9007199254741992L))); assertEquals("{\"value\":\"-9007199254741992\"}" , JSON.toJSONString( new Model(-9007199254741992L))); assertEquals("{\"value\":9007199254740990}" , JSON.toJSONString( new Model(9007199254740990L))); assertEquals("{\"value\":-9007199254740990}" , JSON.toJSONString( new Model(-9007199254740990L))); assertEquals("{\"value\":100}" , JSON.toJSONString( new Model(100))); assertEquals("{\"value\":-100}" , JSON.toJSONString( new Model(-100))); } @JSONType(serialzeFeatures = BrowserCompatible) public static class Model { public BigDecimal value; public Model() { } public Model(long value) { this.value = BigDecimal.valueOf(value); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/BigInteger_BrowserCompatible.java ================================================ package com.alibaba.json.bvt.basicType; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.math.BigInteger; import java.util.LinkedHashMap; import java.util.Map; public class BigInteger_BrowserCompatible extends TestCase { public void test_for_issue() throws Exception { Map map = new LinkedHashMap(); map.put("id1", 9223370018640066466L); map.put("id2", new BigInteger("9223370018640066466")); assertEquals("{\"id1\":\"9223370018640066466\",\"id2\":\"9223370018640066466\"}", JSON.toJSONString(map, SerializerFeature.BrowserCompatible) ); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/DoubleNullTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/DoubleNullTest_primitive.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/DoubleTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/DoubleTest2_obj.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/DoubleTest3_random.java ================================================ package com.alibaba.json.bvt.basicType; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.util.Collections; import java.util.HashMap; import java.util.Random; public class DoubleTest3_random extends TestCase { public void test_ran() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { double val = rand.nextDouble(); String str = JSON.toJSONString(new Model(val)); Model m = JSON.parseObject(str, Model.class); assertEquals(val, m.value); } } public void test_ran_2() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { double val = rand.nextDouble(); String str = JSON.toJSONString(new Model(val), SerializerFeature.BeanToArray); Model m = JSON.parseObject(str, Model.class, Feature.SupportArrayToBean); assertEquals(val, m.value); } } public void test_ran_3() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { double val = rand.nextDouble(); String str = JSON.toJSONString(Collections.singletonMap("val", val)); double val2 = JSON.parseObject(str).getDoubleValue("val"); assertEquals(val, val2); } } public void test_ran_4() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { double val = rand.nextDouble(); HashMap map = new HashMap(); map.put("val", val); String str = JSON.toJSONString(map); double val2 = JSON.parseObject(str).getDoubleValue("val"); assertEquals(val, val2); } } public static class Model { public double value; public Model() { } public Model(double value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/FloatNullTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/FloatNullTest_primitive.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/FloatTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/FloatTest2_obj.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/FloatTest3_array_random.java ================================================ package com.alibaba.json.bvt.basicType; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.util.Collections; import java.util.HashMap; import java.util.Random; public class FloatTest3_array_random extends TestCase { public void test_ran() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { float val = rand.nextFloat(); String str = JSON.toJSONString(new Model(new float[]{val})); Model m = JSON.parseObject(str, Model.class); assertEquals(val, m.value[0]); } } public void test_ran_2() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 10; ++i) { float val = rand.nextFloat(); String str = JSON.toJSONString(new Model(new float[]{val}), SerializerFeature.BeanToArray); Model m = JSON.parseObject(str, Model.class, Feature.SupportArrayToBean); assertEquals(val, m.value[0]); } } public static class Model { public float[] value; public Model() { } public Model(float[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/FloatTest3_random.java ================================================ package com.alibaba.json.bvt.basicType; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.util.Collections; import java.util.HashMap; import java.util.Random; public class FloatTest3_random extends TestCase { public void test_ran() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { float val = rand.nextFloat(); String str = JSON.toJSONString(new Model(val)); Model m = JSON.parseObject(str, Model.class); assertEquals(val, m.value); } } public void test_ran_2() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { float val = rand.nextFloat(); String str = JSON.toJSONString(new Model(val), SerializerFeature.BeanToArray); Model m = JSON.parseObject(str, Model.class, Feature.SupportArrayToBean); assertEquals(val, m.value); } } public void test_ran_3() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { float val = rand.nextFloat(); String str = JSON.toJSONString(Collections.singletonMap("val", val)); float val2 = JSON.parseObject(str).getFloatValue("val"); assertEquals(val, val2); } } public void test_ran_4() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { float val = rand.nextFloat(); HashMap map = new HashMap(); map.put("val", val); String str = JSON.toJSONString(map); float val2 = JSON.parseObject(str).getFloatValue("val"); assertEquals(val, val2); } } public static class Model { public float value; public Model() { } public Model(float value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/IntNullTest_primitive.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/IntTest.java ================================================ 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()); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/IntegerNullTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/LongNullTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/LongNullTest_primitive.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/LongTest.java ================================================ 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()); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/LongTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/LongTest2_obj.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/basicType/LongTest_browserCompatible.java ================================================ 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()); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug1.java ================================================ 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);// 出错 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug11.java ================================================ package com.alibaba.json.bvt.bug; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class Bug11 extends TestCase { public void test_bug11() throws Exception { String text = "[{KH:\"(2010-2011-2)-13105-13039-1\", JC:\"1\"}] "; JSON.parse(text); System.out.println(text); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug13.java ================================================ 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"); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug14.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_10.java ================================================ package com.alibaba.json.bvt.bug; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class Bug_10 extends TestCase { public void test_0() throws Exception { String text = "{'jdbcUrl':\"jdbc:wrap-jdbc:filters=default:name=com.alibaba.dragoon.monitor:jdbc:mysql:\\/\\/10.20.129.167\\/dragoon_v25monitordb?useUnicode=true&characterEncoding=UTF-8\"}"; JSON.parse(text); } public void test_1() throws Exception { String text = "{'jdbcUrl':'jdbc:wrap-jdbc:filters=default:name=com.alibaba.dragoon.monitor:jdbc:mysql:\\/\\/10.20.129.167\\/dragoon_v25monitordb?useUnicode=true&characterEncoding=UTF-8'}"; JSON.parse(text); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin_case2.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_101_for_rongganlin_case3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_102_for_rongganlin.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_105_for_SpitFire.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_127_for_qiuyan81.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_376_for_iso8601.java ================================================ /* * 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_6.java ================================================ package com.alibaba.json.bvt.bug; import java.util.HashMap; import java.util.List; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class Bug_6 extends TestCase { public void test_bug6() throws Exception { Entity entity = new Entity(); String jsonString = JSON.toJSONString(entity); System.out.println(jsonString); JSON.parseObject(jsonString, Entity.class); } public static class Entity { private List> list = null; public List> getList() { return list; } public void setList(List> list) { this.list = list; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_7.java ================================================ package com.alibaba.json.bvt.bug; import java.math.BigInteger; import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.concurrent.atomic.AtomicLongArray; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.fastjson.JSON; public class Bug_7 extends TestCase { public void test_floatArray() throws Exception { float[] a = new float[] { 1, 2 }; String text = JSON.toJSONString(a); JSON json = (JSON) JSON.parse(text); Assert.assertEquals("[1.0,2.0]", json.toJSONString()); } public void test_doubleArray() throws Exception { double[] a = new double[] { 1, 2 }; String text = JSON.toJSONString(a); JSON json = (JSON) JSON.parse(text); Assert.assertEquals("[1.0,2.0]", json.toJSONString()); } public void test_bigintegerArray() throws Exception { BigInteger[] a = new BigInteger[] { new BigInteger("214748364812"), new BigInteger("2147483648123") }; String text = JSON.toJSONString(a); Assert.assertEquals("[214748364812,2147483648123]", text); JSON json = (JSON) JSON.parse(text); Assert.assertEquals("[214748364812,2147483648123]", json.toJSONString()); } public void test_AtomicIntegerArray() throws Exception { AtomicIntegerArray array = new AtomicIntegerArray(3); array.set(0, 1); array.set(1, 2); array.set(2, 3); String text = JSON.toJSONString(array); Assert.assertEquals("[1,2,3]", text); } public void test_AtomicLongArray() throws Exception { AtomicLongArray array = new AtomicLongArray(3); array.set(0, 1); array.set(1, 2); array.set(2, 3); String text = JSON.toJSONString(array); Assert.assertEquals("[1,2,3]", text); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_8.java ================================================ package com.alibaba.json.bvt.bug; import java.util.List; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONArray; public class Bug_8 extends TestCase { public void test_0() throws Exception { List typeList = JSONArray.parseArray("['java.lang.Class','java.lang.Long']", String.class); Assert.assertEquals("java.lang.Class", typeList.get(0)); Assert.assertEquals("java.lang.Long", typeList.get(1)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_KimShen.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_42283905.java ================================================ 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 + "}"; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_42283905_1.java ================================================ 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 + "}"; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_80108116.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_ArrayMember.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_BlankRain_Issue_502.java ================================================ 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.时间 = 时间; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_DiffType.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_Double2Tag.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_Exception.java ================================================ package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import java.util.Map; 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); // // // Object obj = JSON.parse(text); // assertEquals(JSONObject.class, obj.getClass()); // // Throwable throwable = JSON.parseObject(text, Throwable.class); // assertEquals(RuntimeException.class, throwable.getClass()); // // Object obj2 = JSON.parse(text); // assertEquals(JSONObject.class, obj2.getClass()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_519.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_534.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_535.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_Issue_603.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_JSONObject.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_Jay.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_Jay_1.java ================================================ 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\"}}"); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_JeryZeng.java ================================================ 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\"}}")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_Johnny.java ================================================ 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() { } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_Next.java ================================================ 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 + '\'' + '}'; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_NonStringKeyMap.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_O_I_See_you.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_5.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_6.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_agapple.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_agapple_2.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_akvadrako.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_alibank.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_apollo0317.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_array.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_ascii_0_31.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_bbl.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_booleanField.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_builder.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_cduym.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_chengchao.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_chengchao_1.java ================================================ package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; import junit.framework.TestCase; public class Bug_for_chengchao_1 extends TestCase { public void test_0() throws Exception { ParserConfig config = new ParserConfig(); config.setAutoTypeSupport(true); String str = "{\"@type\":\"test.MapDone\",\"data\":{\"@type\":\"test.HiluxDataByOpsmeta\",\"attends\":{\"@type\":\"java.util.HashMap\",\"center.na61\":2},\"datasByOpsmeta\":{\"@type\":\"java.util.HashMap\",{\"@type\":\"test.AppInst\",\"app\":\"wdkhummer\",\"appGroup\":\"wdkhummerhost\",\"env\":\"PUBLISH\",\"hostname\":\"wdkhummer011009059229.na61\",\"idc\":\"na61\",\"ip\":\"11.9.59.229\",\"online\":true}:{\"@type\":\"test.MiddlewareDimData\",\"attends\":{\"@type\":\"java.util.HashMap\"},\"expectAttends\":{\"@type\":\"java.util.HashMap\"},\"logLineCount\":0,\"values\":{}}}}}"; JSON.parse(str, config, JSON.DEFAULT_PARSER_FEATURE); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_chengyi.java ================================================ package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.annotation.JSONCreator; import junit.framework.TestCase; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Bug_for_chengyi extends TestCase { public void test_0() throws Exception { List> pairList = new ArrayList(); Pair pair = Pair.of("cy", 1); pairList.add(pair); final String s = JSON.toJSONString(pairList); final List pairs = JSONArray.parseArray(s, Pair.class); System.out.println(); } public static class Pair implements Serializable { private static final long serialVersionUID = -2140946024027818984L; public final A fst; public final B snd; public Pair() { fst = null; snd = null; } @JSONCreator public Pair(A fst, B snd) { this.fst = fst; this.snd = snd; } @Override public String toString() { return "[" + fst + "," + snd + "]"; } private boolean equals(Object x, Object y) { return (x == null && y == null) || (x != null && x.equals(y)); } @SuppressWarnings("rawtypes") @Override public boolean equals(Object other) { return other instanceof Pair && equals(fst, ((Pair) other).fst) && equals(snd, ((Pair) other).snd); } /** * 覆盖hashCode方法 * * @return hashCode */ @Override public int hashCode() { if (fst == null) { return (snd == null) ? 0 : snd.hashCode() + 1; } else if (snd == null) { return fst.hashCode() + 2; } else { return fst.hashCode() * 17 + snd.hashCode(); } } public static Pair of(A a, B b) { return new Pair(a, b); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_cnhans.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_dargoner.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_divde_zero.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_dongqi.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon26.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon26_1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo1.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo3.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo_long.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_field.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_franklee77.java ================================================ 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(){ } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_fushou.java ================================================ 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() { } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic_1.java ================================================ 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>() { }); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_generic_huansi.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_gongwenhua.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_hifor_issue_511.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_hmy8.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_huangchun.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_huling.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_184.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_229.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_232.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_236.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_242.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_252.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_253.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_256.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_262.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_265.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_268.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_269.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_273.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_278.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_280.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_283.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_285.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_291.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_296.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_297.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_304.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_316.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_318.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_320.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_330.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_331.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_336.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_349.java ================================================ 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 + '}'; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_352.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_364.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_372.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_383.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_389.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_414.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_415.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_423.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_426.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_427.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_430.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_434.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_435.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_439.java ================================================ 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*/}"); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_446.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_447.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_448.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_449.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_457.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_462.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_465.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_469.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_470.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_479.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_489.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_491.java ================================================ 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) {}); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_492.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_537.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_545.java ================================================ 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{}"); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555_setter.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_555_setter2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_569.java ================================================ 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 */ } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_569_1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_field.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_field2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_572_private.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_630.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_676.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_694.java ================================================ 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; } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_729.java ================================================ 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 + "]"; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_807.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_937.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_jared1.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_javaeye_litterJava.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_jial10802.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei1.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei2.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_jinghui70.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_jinguwei.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_json_array.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_jsonobj_null.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_juewu.java ================================================ 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\"}]}}"; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_km.java ================================================ package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.concurrent.TimeUnit; public class Bug_for_km extends TestCase { public void test_for_issue() throws Exception { String str = "{\n" + "\t\"bizSubmitInfos\": [{\n" + "\t\t\"bizType\": \"ISSUE\",\n" + "\t\t\"privacyInfo\": \"{\\\"bcAnchorMid\\\":\\\"101CITI000000001000\\\",\\\"bcMid\\\":\\\"102BABA000000000001\\\",\\\"bcSubmitMid\\\":\\\"102BABA000000000001\\\",\\\"bizId\\\":\\\"transfer_autoTest_pri_weiweitestt_8857136636875877184\\\",\\\"bizType\\\":\\\"ISSUE\\\",\\\"currency\\\":\\\"USD\\\",\\\"exchangeRate\\\":{\\\"encryptedExchangeRate\\\":\\\"123\\\",\\\"envelopeKeyInfos\\\":{}},\\\"pcAmount\\\":{\\\"envelopeKeyInfos\\\":{},\\\"proof\\\":\\\"proff\\\"}}\",\n" + "\t\t\"submitInfoList\": [{\n" + "\t\t\t\"checkPrivacyResult\": {\n" + "\t\t\t\t\"checkResult\": \"{\\\"checkResultStatus\\\":\\\"ACCEPT\\\",\\\"hashOfPrivacyPreservingInfo\\\":\\\"NfYRZwG/Yki8LU01vsyWINGaXv94+gYoPBFVMFEKyTM=\\\",\\\"memberId\\\":\\\"101CITI000000001000\\\"}\",\n" + "\t\t\t\t\"signature\": \"testing_signature\"\n" + "\t\t\t},\n" + "\t\t\t\"pid\": \"101CITI000000001000\"\n" + "\t\t}]\n" + "\t}],\n" + "\t\"resultInfo\": {\n" + "\t\t\"resultCode\": \"SUCCESS\",\n" + "\t\t\"resultCodeId\": \"00000000\",\n" + "\t\t\"resultMsg\": \"success\",\n" + "\t\t\"resultStatus\": \"S\"\n" + "\t}\n" + "}"; WhaleGeneratePrivacyResponseBody resp = JSON.parseObject(str, WhaleGeneratePrivacyResponseBody.class); System.out.println(resp.resultInfo.resultStatus); // System.out.println(str); } public static class WhaleGeneratePrivacyResponseBody { public ResultInfo resultInfo; } /** * @author freud.wy * @version $Id: ResultInfo.java, v 0.1 2019-05-28 上午11:02 freud.wy Exp $$ */ public static class ResultInfo { private String resultStatus; private String resultCodeId; private String resultCode; private String resultMsg; /** * Getter method for property resultStatus. * * @return property value of resultStatus */ public String getResultStatus() { return resultStatus; } /** * Setter method for property resultStatus. * * @param resultStatus value to be assigned to property resultStatus */ public void setResultStatus(String resultStatus) { this.resultStatus = resultStatus; } /** * Getter method for property resultCodeId. * * @return property value of resultCodeId */ public String getResultCodeId() { return resultCodeId; } /** * Setter method for property resultCodeId. * * @param resultCodeId value to be assigned to property resultCodeId */ public void setResultCodeId(String resultCodeId) { this.resultCodeId = resultCodeId; } /** * Getter method for property resultCode. * * @return property value of resultCode */ public String getResultCode() { return resultCode; } /** * Setter method for property resultCode. * * @param resultCode value to be assigned to property resultCode */ public void setResultCode(String resultCode) { this.resultCode = resultCode; } /** * Getter method for property resultMsg. * * @return property value of resultMsg */ public String getResultMsg() { return resultMsg; } /** * Setter method for property resultMsg. * * @param resultMsg value to be assigned to property resultMsg */ public void setResultMsg(String resultMsg) { this.resultMsg = resultMsg; } @Override public String toString() { return String.format("resultStatus[%s],resultCodeId[%s],resultCode[%s],resultMsg[%s]",resultStatus,resultCodeId,resultCode,resultMsg); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_1.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_10.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_11.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_2.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_3.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_4.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_5.java ================================================ package com.alibaba.json.bvt.bug; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Bug_for_lenolix_5 extends TestCase { public void test_for_objectKey() throws Exception { final Map obj = new HashMap(); final Object obja = new Object(); final Object objb = new Object(); obj.put(obja, objb); final String newJsonString = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteClassName); System.out.println(newJsonString); final Object newObject = JSON.parse(newJsonString); System.out.println(newObject); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_6.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_7.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_8.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_lenolix_9.java ================================================ 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; } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_leupom_3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_liqing.java ================================================ package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import junit.framework.TestCase; public class Bug_for_liqing extends TestCase { public void test_for_issue() throws Exception { ParserConfig config = new ParserConfig(); config.setAutoTypeSupport(true); String json = "{\"@type\":\"java.util.HashMap\",\"wcChangeAttr\":{\"@type\":\"com.alibaba.json.bvt.bug.Bug_for_liqing.TpFeedBackDO\",\"attributes\":{\"@type\":\"java.util.concurrent.ConcurrentHashMap\"},\"wcStatus\":102B}}"; JSON.parse(json, config); } public static class TpFeedBackDO { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_liuwanzhen_ren.java ================================================ package com.alibaba.json.bvt.bug; import java.util.HashMap; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class Bug_for_liuwanzhen_ren extends TestCase { public void test_0() throws Exception { Bean bean = new Bean(); bean.setAction("123"); HashMap paramMap = new HashMap(); paramMap.put("url1", "123"); paramMap.put("url2", "456"); bean.setParamMap(paramMap); String str = JSON.toJSONString(bean); System.out.println(str); Bean bean2 = JSON.parseObject(str, Bean.class); System.out.println(bean2.getAction()); System.out.println(bean2.getParamMap()); } public static class Bean { private String action; private HashMap paramMap; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public HashMap getParamMap() { return paramMap; } public void setParamMap(HashMap paramMap) { this.paramMap = paramMap; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_liuying.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_long_whitespace.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_ludong.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_luogongwu.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_maiksagill.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_melin.java ================================================ 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; public class Bug_for_melin extends TestCase { public void test_for_melin() throws Exception { Entity object = new Entity(); object.setId(123); object.setName("\\"); String text = JSON.toJSONString(object); // {"id":123,"name":"\\"} Assert.assertEquals("{\"id\":123,\"name\":\"\\\\\"}", text); } public void test_for_melin_() throws Exception { Map map = new LinkedHashMap(); map.put("id", 123); map.put("name", "\\"); String text = JSON.toJSONString(map); // {"id":123,"name":"\\"} Assert.assertEquals("{\"id\":123,\"name\":\"\\\\\"}", text); } public static class Entity { 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_boolean.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_byte.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_double.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_float.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_int.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_long.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_primitive_short.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_qianbi.java ================================================ package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Bug_for_qianbi extends TestCase { public void test_for_bug() throws Exception { String json = "\n" + "[{\"a\":\"1A18810QBYZN5T3M3CH6K3\",\"r\":[\"44304\",\"103467\"]},{\"a\":\"1A188104CTUW5TXFGCJPDW\",\"r\":[\"24391\",\"56132\",\"44304\",\"15567\"]},{\"a\":\"1A18812GJ9P37TOGKPT8BQ\",\"r\":[\"24539\",\"44304\",\"56259\"]} ,{\"a\":\"1A188104CTUW5TXFGCJPDW\",\"r\":[\"24391\",\"44304\",\"15567\"]}]"; JSON.parse(json); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_qqdwll2012.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_rd.java ================================================ package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.concurrent.TimeUnit; public class Bug_for_rd extends TestCase { public void test_for_issue() throws Exception { String json = "{ \"sitePayId\": \"2019071889031100000152604119889\", \"extendInfo\": \"{\\\"saveAsset\\\":\\\"false\\\",\\\"acquirementId\\\":\\\"20190718194010800100177150204979354\\\",\\\"orderTerminalType\\\":\\\"WEB\\\",\\\"acqSiteUserId\\\":\\\"2177220032166157\\\",\\\"siteReqBizId\\\":\\\"111023437\\\",\\\"msisdn\\\":\\\"01966114400\\\",\\\"originalMerchantOrderId\\\":\\\"602109378031994\\\"}\", \"netPayId\": \"2019071819039101720000454701\", \"resultInfo\": { \"resultCode\": \"SUCCESS\", \"resultCodeId\": \"00000000\", \"resultMsg\": \"Success\", \"resultStatus\": \"S\" } }"; PayResponse object = JSON.parseObject(json, PayResponse.class); String extendInfo = object.getExtendInfo(); assertEquals(object.getExtendInfo(), JSON.parseObject(json).get("extendInfo")); } public void test_for_issue_1() throws Exception { String json = "{\"unit\": \"MINUTES\"}"; V1 v = JSON.parseObject(json, V1.class); assertEquals(TimeUnit.MINUTES, v.unit); } public void test_for_issue_2() throws Exception { String json = "{\"sitePayId\": \"MINUTES\"}"; V1 v = JSON.parseObject(json, V1.class); assertEquals("MINUTES", v.sitePayId); } public void test_for_issue_3() throws Exception { String json = "{\"sitePayId\": \"MINUTES\\\"A\"}"; V1 v = JSON.parseObject(json, V1.class); assertEquals("MINUTES\"A", v.sitePayId); } public void test_for_issue_4() throws Exception { String json = "{ \"sitePayId\": \"MINUTES\\\"A\"}"; V1 v = JSON.parseObject(json, V1.class); assertEquals("MINUTES\"A", v.sitePayId); } public void test_for_issue_5() throws Exception { String json = "{ \"sitePayId\": \"\\\"A\"}"; V1 v = JSON.parseObject(json, V1.class); assertEquals("\"A", v.sitePayId); } public void test_for_issue_6() throws Exception { String json = "{ \"sitePayId\": \"S\"}"; V1 v = JSON.parseObject(json, V1.class); assertEquals("S", v.sitePayId); } public static class PayResponse { private String sitePayId; private String extendInfo; private String netPayId; public String getSitePayId() { return sitePayId; } public void setSitePayId(String sitePayId) { this.sitePayId = sitePayId; } public String getExtendInfo() { return extendInfo; } public void setExtendInfo(String extendInfo) { this.extendInfo = extendInfo; } public String getNetPayId() { return netPayId; } public void setNetPayId(String netPayId) { this.netPayId = netPayId; } } public static class V1 { public String sitePayId; public TimeUnit unit; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_rendong.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_ruiqi.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_sankun.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_sanxiao.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_set.java ================================================ 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[]"); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_shortArray.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat5.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat6.java ================================================ package com.alibaba.json.bvt.bug; import java.util.LinkedHashSet; 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 LinkedHashSet(); 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat7.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat8.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_smoothrat9.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_stv_liu.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_sunai.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_taolei0628.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_uin57.java ================================================ package com.alibaba.json.bvt.bug; import java.io.Serializable; 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.annotation.JSONField; public class Bug_for_uin57 extends TestCase { public void test_multiArray() throws Exception { String jsonString = "{\"block\":{\"boxList\":[{\"dx\":1,\"dy\":1},{\"dx\":0,\"dy\":0},{\"dx\":0,\"dy\":2},{\"dx\":2,\"dy\":0},{\"dx\":2,\"dy\":2}],\"centerBox\":{\"dx\":1,\"dy\":1},\"offsetX\":0,\"offsetY\":0},\"boxs\":[[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null,null,null,null,null]]}"; GameSnapShot gs = JSON.parseObject(jsonString, GameSnapShot.class); Block block = gs.getBlock(); Assert.assertEquals(5, block.getBoxList().size()); Assert.assertEquals(1, block.getBoxList().get(0).getX()); Assert.assertEquals(1, block.getBoxList().get(0).getY()); Assert.assertEquals(0, block.getBoxList().get(2).getX()); Assert.assertEquals(2, block.getBoxList().get(2).getY()); Box[][] boxs = gs.getBoxs(); Assert.assertEquals(20, boxs.length); Assert.assertEquals(12, boxs[0].length); } public static class GameSnapShot implements Serializable { /** * */ private static final long serialVersionUID = 8755961532274905269L; protected Box[][] boxs = null; private Block block; public GameSnapShot(){ super(); } public GameSnapShot(Box[][] boxs, Block block){ super(); this.boxs = boxs; this.block = block; } public Box[][] getBoxs() { return boxs; } public void setBoxs(Box[][] boxs) { this.boxs = boxs; } public Block getBlock() { return block; } public void setBlock(Block block) { this.block = block; } } public static class Box { @JSONField(name = "dx") private int x; @JSONField(name = "dy") private int y; public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } public static class Block { private List boxList = new ArrayList(); private Box centerBox; private int offsetX; private int offsetY; public int getOffsetX() { return offsetX; } public void setOffsetX(int offsetX) { this.offsetX = offsetX; } public int getOffsetY() { return offsetY; } public void setOffsetY(int offsetY) { this.offsetY = offsetY; } public Box getCenterBox() { return centerBox; } public void setCenterBox(Box centerBox) { this.centerBox = centerBox; } public List getBoxList() { return boxList; } public void setBoxList(List boxList) { this.boxList = boxList; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_vikingschow.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran.java ================================================ 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 ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_wangran2.java ================================================ 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 ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_wsky.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_wtusmchen.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_wuyexiong.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_wuzhengmao.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_xiayucai2012.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_xiedun.java ================================================ package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class Bug_for_xiedun extends TestCase { public void test_for_issue() throws Exception { // File file = new File("/Users/wenshao/Downloads/json.txt"); // // BufferedReader reader = new BufferedReader(new FileReader(file)); // char[] buf = new char[20480]; // int readed = reader.read(buf); // String content = new String(buf); // // JSON.parse(content); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin2.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin_int.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_xuzebin.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yangqi.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yangzhou.java ================================================ package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.ArrayList; import java.util.Date; import java.util.List; public class Bug_for_yangzhou extends TestCase { public void test_for_issue() throws Exception { String test = "{\"distinct\":false,\"oredCriteria\":[{\"allCriteria\":[{\"betweenValue\":false,\"condition\":\"area_id =\",\"listValue\":false,\"noValue\":false,\"singleValue\":true,\"value\":917477670000000000},{\"betweenValue\":false,\"condition\":\"cabinet_id =\",\"listValue\":false,\"noValue\":false,\"singleValue\":true,\"value\":500036},{\"betweenValue\":false,\"condition\":\"status =\",\"listValue\":false,\"noValue\":false,\"singleValue\":true,\"value\":0}],\"criteria\":[{\"$ref\":\"$.oredCriteria[0].allCriteria[0]\"},{\"$ref\":\"$.oredCriteria[0].allCriteria[1]\"},{\"$ref\":\"$.oredCriteria[0].allCriteria[2]\"}],\"valid\":true}],\"page\":true,\"pageIndex\":0,\"pageSize\":1,\"pageStart\":1}"; System.out.println(test); CabinetAuthCodeParam cabinetAuthCodeParam = JSONObject.toJavaObject(JSON.parseObject(test), CabinetAuthCodeParam.class); System.out.println(JSON.toJSONString(cabinetAuthCodeParam)); final String jsonString = JSON.toJSONString(cabinetAuthCodeParam); assertEquals("{\"distinct\":false,\"oredCriteria\":[{\"allCriteria\":[{\"listValue\":false,\"noValue\":false,\"condition\":\"area_id =\",\"betweenValue\":false,\"singleValue\":true,\"value\":917477670000000000},{\"listValue\":false,\"noValue\":false,\"condition\":\"cabinet_id =\",\"betweenValue\":false,\"singleValue\":true,\"value\":500036},{\"listValue\":false,\"noValue\":false,\"condition\":\"status =\",\"betweenValue\":false,\"singleValue\":true,\"value\":0}],\"criteria\":[{\"$ref\":\"$.oredCriteria[0].allCriteria[0]\"},{\"$ref\":\"$.oredCriteria[0].allCriteria[1]\"},{\"$ref\":\"$.oredCriteria[0].allCriteria[2]\"}],\"valid\":true}],\"page\":true,\"pageIndex\":0,\"pageSize\":1,\"pageStart\":1}", jsonString); // CabinetAuthCodeRecordParam cabinetAuthCodeRecordParam = JSONObject.toJavaObject(JSON.parseObject(jsonString), CabinetAuthCodeRecordParam.class); // System.out.println(JSON.toJSONString(cabinetAuthCodeRecordParam)); } public static class CabinetAuthCodeParam { protected String orderByClause; protected boolean distinct; protected boolean page; protected int pageIndex; protected int pageSize; protected int pageStart; protected List oredCriteria; public CabinetAuthCodeParam() { oredCriteria = new ArrayList(); } public CabinetAuthCodeParam appendOrderByClause(OrderCondition orderCondition, SortType sortType) { if (null != orderByClause) { orderByClause = orderByClause + ", " + orderCondition.getColumnName() + " " + sortType.getValue(); } else { orderByClause = orderCondition.getColumnName() + " " + sortType.getValue(); } return this; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public void setPage(boolean page) { this.page = page; } public boolean isPage() { return page; } public int getPageIndex() { return pageIndex; } public void setPageSize(int pageSize) { this.pageSize = pageSize < 1 ? 10 : pageSize; this.pageIndex = pageStart < 1 ? 0 : (pageStart - 1) * this.pageSize; } public int getPageSize() { return pageSize; } public void setPageStart(int pageStart) { this.pageStart = pageStart < 1 ? 1 : pageStart; this.pageIndex = (this.pageStart - 1) * this.pageSize; } public int getPageStart() { return pageStart; } public List getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList(); } public boolean isValid() { return criteria.size() > 0; } public List getAllCriteria() { return criteria; } public List getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andGmtCreateIsNull() { addCriterion("gmt_create is null"); return (Criteria) this; } public Criteria andGmtCreateIsNotNull() { addCriterion("gmt_create is not null"); return (Criteria) this; } public Criteria andGmtCreateEqualTo(Date value) { addCriterion("gmt_create =", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateNotEqualTo(Date value) { addCriterion("gmt_create <>", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateGreaterThan(Date value) { addCriterion("gmt_create >", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateGreaterThanOrEqualTo(Date value) { addCriterion("gmt_create >=", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateLessThan(Date value) { addCriterion("gmt_create <", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateLessThanOrEqualTo(Date value) { addCriterion("gmt_create <=", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateIn(List values) { addCriterion("gmt_create in", values, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateNotIn(List values) { addCriterion("gmt_create not in", values, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateBetween(Date value1, Date value2) { addCriterion("gmt_create between", value1, value2, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateNotBetween(Date value1, Date value2) { addCriterion("gmt_create not between", value1, value2, "gmtCreate"); return (Criteria) this; } public Criteria andGmtModifiedIsNull() { addCriterion("gmt_modified is null"); return (Criteria) this; } public Criteria andGmtModifiedIsNotNull() { addCriterion("gmt_modified is not null"); return (Criteria) this; } public Criteria andGmtModifiedEqualTo(Date value) { addCriterion("gmt_modified =", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedNotEqualTo(Date value) { addCriterion("gmt_modified <>", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedGreaterThan(Date value) { addCriterion("gmt_modified >", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedGreaterThanOrEqualTo(Date value) { addCriterion("gmt_modified >=", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedLessThan(Date value) { addCriterion("gmt_modified <", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedLessThanOrEqualTo(Date value) { addCriterion("gmt_modified <=", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedIn(List values) { addCriterion("gmt_modified in", values, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedNotIn(List values) { addCriterion("gmt_modified not in", values, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedBetween(Date value1, Date value2) { addCriterion("gmt_modified between", value1, value2, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedNotBetween(Date value1, Date value2) { addCriterion("gmt_modified not between", value1, value2, "gmtModified"); return (Criteria) this; } public Criteria andAreaIdIsNull() { addCriterion("area_id is null"); return (Criteria) this; } public Criteria andAreaIdIsNotNull() { addCriterion("area_id is not null"); return (Criteria) this; } public Criteria andAreaIdEqualTo(Long value) { addCriterion("area_id =", value, "areaId"); return (Criteria) this; } public Criteria andAreaIdNotEqualTo(Long value) { addCriterion("area_id <>", value, "areaId"); return (Criteria) this; } public Criteria andAreaIdGreaterThan(Long value) { addCriterion("area_id >", value, "areaId"); return (Criteria) this; } public Criteria andAreaIdGreaterThanOrEqualTo(Long value) { addCriterion("area_id >=", value, "areaId"); return (Criteria) this; } public Criteria andAreaIdLessThan(Long value) { addCriterion("area_id <", value, "areaId"); return (Criteria) this; } public Criteria andAreaIdLessThanOrEqualTo(Long value) { addCriterion("area_id <=", value, "areaId"); return (Criteria) this; } public Criteria andAreaIdIn(List values) { addCriterion("area_id in", values, "areaId"); return (Criteria) this; } public Criteria andAreaIdNotIn(List values) { addCriterion("area_id not in", values, "areaId"); return (Criteria) this; } public Criteria andAreaIdBetween(Long value1, Long value2) { addCriterion("area_id between", value1, value2, "areaId"); return (Criteria) this; } public Criteria andAreaIdNotBetween(Long value1, Long value2) { addCriterion("area_id not between", value1, value2, "areaId"); return (Criteria) this; } public Criteria andAuthCodeIsNull() { addCriterion("auth_code is null"); return (Criteria) this; } public Criteria andAuthCodeIsNotNull() { addCriterion("auth_code is not null"); return (Criteria) this; } public Criteria andAuthCodeEqualTo(String value) { addCriterion("auth_code =", value, "authCode"); return (Criteria) this; } public Criteria andAuthCodeNotEqualTo(String value) { addCriterion("auth_code <>", value, "authCode"); return (Criteria) this; } public Criteria andAuthCodeGreaterThan(String value) { addCriterion("auth_code >", value, "authCode"); return (Criteria) this; } public Criteria andAuthCodeGreaterThanOrEqualTo(String value) { addCriterion("auth_code >=", value, "authCode"); return (Criteria) this; } public Criteria andAuthCodeLessThan(String value) { addCriterion("auth_code <", value, "authCode"); return (Criteria) this; } public Criteria andAuthCodeLessThanOrEqualTo(String value) { addCriterion("auth_code <=", value, "authCode"); return (Criteria) this; } public Criteria andAuthCodeLike(String value) { addCriterion("auth_code like", value, "authCode"); return (Criteria) this; } public Criteria andAuthCodeNotLike(String value) { addCriterion("auth_code not like", value, "authCode"); return (Criteria) this; } public Criteria andAuthCodeIn(List values) { addCriterion("auth_code in", values, "authCode"); return (Criteria) this; } public Criteria andAuthCodeNotIn(List values) { addCriterion("auth_code not in", values, "authCode"); return (Criteria) this; } public Criteria andAuthCodeBetween(String value1, String value2) { addCriterion("auth_code between", value1, value2, "authCode"); return (Criteria) this; } public Criteria andAuthCodeNotBetween(String value1, String value2) { addCriterion("auth_code not between", value1, value2, "authCode"); return (Criteria) this; } public Criteria andCabinetIdIsNull() { addCriterion("cabinet_id is null"); return (Criteria) this; } public Criteria andCabinetIdIsNotNull() { addCriterion("cabinet_id is not null"); return (Criteria) this; } public Criteria andCabinetIdEqualTo(Long value) { addCriterion("cabinet_id =", value, "cabinetId"); return (Criteria) this; } public Criteria andCabinetIdNotEqualTo(Long value) { addCriterion("cabinet_id <>", value, "cabinetId"); return (Criteria) this; } public Criteria andCabinetIdGreaterThan(Long value) { addCriterion("cabinet_id >", value, "cabinetId"); return (Criteria) this; } public Criteria andCabinetIdGreaterThanOrEqualTo(Long value) { addCriterion("cabinet_id >=", value, "cabinetId"); return (Criteria) this; } public Criteria andCabinetIdLessThan(Long value) { addCriterion("cabinet_id <", value, "cabinetId"); return (Criteria) this; } public Criteria andCabinetIdLessThanOrEqualTo(Long value) { addCriterion("cabinet_id <=", value, "cabinetId"); return (Criteria) this; } public Criteria andCabinetIdIn(List values) { addCriterion("cabinet_id in", values, "cabinetId"); return (Criteria) this; } public Criteria andCabinetIdNotIn(List values) { addCriterion("cabinet_id not in", values, "cabinetId"); return (Criteria) this; } public Criteria andCabinetIdBetween(Long value1, Long value2) { addCriterion("cabinet_id between", value1, value2, "cabinetId"); return (Criteria) this; } public Criteria andCabinetIdNotBetween(Long value1, Long value2) { addCriterion("cabinet_id not between", value1, value2, "cabinetId"); return (Criteria) this; } public Criteria andCabinetNoIsNull() { addCriterion("cabinet_no is null"); return (Criteria) this; } public Criteria andCabinetNoIsNotNull() { addCriterion("cabinet_no is not null"); return (Criteria) this; } public Criteria andCabinetNoEqualTo(String value) { addCriterion("cabinet_no =", value, "cabinetNo"); return (Criteria) this; } public Criteria andCabinetNoNotEqualTo(String value) { addCriterion("cabinet_no <>", value, "cabinetNo"); return (Criteria) this; } public Criteria andCabinetNoGreaterThan(String value) { addCriterion("cabinet_no >", value, "cabinetNo"); return (Criteria) this; } public Criteria andCabinetNoGreaterThanOrEqualTo(String value) { addCriterion("cabinet_no >=", value, "cabinetNo"); return (Criteria) this; } public Criteria andCabinetNoLessThan(String value) { addCriterion("cabinet_no <", value, "cabinetNo"); return (Criteria) this; } public Criteria andCabinetNoLessThanOrEqualTo(String value) { addCriterion("cabinet_no <=", value, "cabinetNo"); return (Criteria) this; } public Criteria andCabinetNoLike(String value) { addCriterion("cabinet_no like", value, "cabinetNo"); return (Criteria) this; } public Criteria andCabinetNoNotLike(String value) { addCriterion("cabinet_no not like", value, "cabinetNo"); return (Criteria) this; } public Criteria andCabinetNoIn(List values) { addCriterion("cabinet_no in", values, "cabinetNo"); return (Criteria) this; } public Criteria andCabinetNoNotIn(List values) { addCriterion("cabinet_no not in", values, "cabinetNo"); return (Criteria) this; } public Criteria andCabinetNoBetween(String value1, String value2) { addCriterion("cabinet_no between", value1, value2, "cabinetNo"); return (Criteria) this; } public Criteria andCabinetNoNotBetween(String value1, String value2) { addCriterion("cabinet_no not between", value1, value2, "cabinetNo"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Short value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Short value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Short value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Short value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Short value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Short value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Short value1, Short value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Short value1, Short value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andAssignTimeIsNull() { addCriterion("assign_time is null"); return (Criteria) this; } public Criteria andAssignTimeIsNotNull() { addCriterion("assign_time is not null"); return (Criteria) this; } public Criteria andAssignTimeEqualTo(Date value) { addCriterion("assign_time =", value, "assignTime"); return (Criteria) this; } public Criteria andAssignTimeNotEqualTo(Date value) { addCriterion("assign_time <>", value, "assignTime"); return (Criteria) this; } public Criteria andAssignTimeGreaterThan(Date value) { addCriterion("assign_time >", value, "assignTime"); return (Criteria) this; } public Criteria andAssignTimeGreaterThanOrEqualTo(Date value) { addCriterion("assign_time >=", value, "assignTime"); return (Criteria) this; } public Criteria andAssignTimeLessThan(Date value) { addCriterion("assign_time <", value, "assignTime"); return (Criteria) this; } public Criteria andAssignTimeLessThanOrEqualTo(Date value) { addCriterion("assign_time <=", value, "assignTime"); return (Criteria) this; } public Criteria andAssignTimeIn(List values) { addCriterion("assign_time in", values, "assignTime"); return (Criteria) this; } public Criteria andAssignTimeNotIn(List values) { addCriterion("assign_time not in", values, "assignTime"); return (Criteria) this; } public Criteria andAssignTimeBetween(Date value1, Date value2) { addCriterion("assign_time between", value1, value2, "assignTime"); return (Criteria) this; } public Criteria andAssignTimeNotBetween(Date value1, Date value2) { addCriterion("assign_time not between", value1, value2, "assignTime"); return (Criteria) this; } public Criteria andUseTimeIsNull() { addCriterion("use_time is null"); return (Criteria) this; } public Criteria andUseTimeIsNotNull() { addCriterion("use_time is not null"); return (Criteria) this; } public Criteria andUseTimeEqualTo(Date value) { addCriterion("use_time =", value, "useTime"); return (Criteria) this; } public Criteria andUseTimeNotEqualTo(Date value) { addCriterion("use_time <>", value, "useTime"); return (Criteria) this; } public Criteria andUseTimeGreaterThan(Date value) { addCriterion("use_time >", value, "useTime"); return (Criteria) this; } public Criteria andUseTimeGreaterThanOrEqualTo(Date value) { addCriterion("use_time >=", value, "useTime"); return (Criteria) this; } public Criteria andUseTimeLessThan(Date value) { addCriterion("use_time <", value, "useTime"); return (Criteria) this; } public Criteria andUseTimeLessThanOrEqualTo(Date value) { addCriterion("use_time <=", value, "useTime"); return (Criteria) this; } public Criteria andUseTimeIn(List values) { addCriterion("use_time in", values, "useTime"); return (Criteria) this; } public Criteria andUseTimeNotIn(List values) { addCriterion("use_time not in", values, "useTime"); return (Criteria) this; } public Criteria andUseTimeBetween(Date value1, Date value2) { addCriterion("use_time between", value1, value2, "useTime"); return (Criteria) this; } public Criteria andUseTimeNotBetween(Date value1, Date value2) { addCriterion("use_time not between", value1, value2, "useTime"); return (Criteria) this; } public Criteria andBizTypeIsNull() { addCriterion("biz_type is null"); return (Criteria) this; } public Criteria andBizTypeIsNotNull() { addCriterion("biz_type is not null"); return (Criteria) this; } public Criteria andBizTypeEqualTo(Short value) { addCriterion("biz_type =", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeNotEqualTo(Short value) { addCriterion("biz_type <>", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeGreaterThan(Short value) { addCriterion("biz_type >", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeGreaterThanOrEqualTo(Short value) { addCriterion("biz_type >=", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeLessThan(Short value) { addCriterion("biz_type <", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeLessThanOrEqualTo(Short value) { addCriterion("biz_type <=", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeIn(List values) { addCriterion("biz_type in", values, "bizType"); return (Criteria) this; } public Criteria andBizTypeNotIn(List values) { addCriterion("biz_type not in", values, "bizType"); return (Criteria) this; } public Criteria andBizTypeBetween(Short value1, Short value2) { addCriterion("biz_type between", value1, value2, "bizType"); return (Criteria) this; } public Criteria andBizTypeNotBetween(Short value1, Short value2) { addCriterion("biz_type not between", value1, value2, "bizType"); return (Criteria) this; } public Criteria andBizOutIdIsNull() { addCriterion("biz_out_id is null"); return (Criteria) this; } public Criteria andBizOutIdIsNotNull() { addCriterion("biz_out_id is not null"); return (Criteria) this; } public Criteria andBizOutIdEqualTo(Long value) { addCriterion("biz_out_id =", value, "bizOutId"); return (Criteria) this; } public Criteria andBizOutIdNotEqualTo(Long value) { addCriterion("biz_out_id <>", value, "bizOutId"); return (Criteria) this; } public Criteria andBizOutIdGreaterThan(Long value) { addCriterion("biz_out_id >", value, "bizOutId"); return (Criteria) this; } public Criteria andBizOutIdGreaterThanOrEqualTo(Long value) { addCriterion("biz_out_id >=", value, "bizOutId"); return (Criteria) this; } public Criteria andBizOutIdLessThan(Long value) { addCriterion("biz_out_id <", value, "bizOutId"); return (Criteria) this; } public Criteria andBizOutIdLessThanOrEqualTo(Long value) { addCriterion("biz_out_id <=", value, "bizOutId"); return (Criteria) this; } public Criteria andBizOutIdIn(List values) { addCriterion("biz_out_id in", values, "bizOutId"); return (Criteria) this; } public Criteria andBizOutIdNotIn(List values) { addCriterion("biz_out_id not in", values, "bizOutId"); return (Criteria) this; } public Criteria andBizOutIdBetween(Long value1, Long value2) { addCriterion("biz_out_id between", value1, value2, "bizOutId"); return (Criteria) this; } public Criteria andBizOutIdNotBetween(Long value1, Long value2) { addCriterion("biz_out_id not between", value1, value2, "bizOutId"); return (Criteria) this; } public Criteria andFeatureIsNull() { addCriterion("feature is null"); return (Criteria) this; } public Criteria andFeatureIsNotNull() { addCriterion("feature is not null"); return (Criteria) this; } public Criteria andFeatureEqualTo(String value) { addCriterion("feature =", value, "feature"); return (Criteria) this; } public Criteria andFeatureNotEqualTo(String value) { addCriterion("feature <>", value, "feature"); return (Criteria) this; } public Criteria andFeatureGreaterThan(String value) { addCriterion("feature >", value, "feature"); return (Criteria) this; } public Criteria andFeatureGreaterThanOrEqualTo(String value) { addCriterion("feature >=", value, "feature"); return (Criteria) this; } public Criteria andFeatureLessThan(String value) { addCriterion("feature <", value, "feature"); return (Criteria) this; } public Criteria andFeatureLessThanOrEqualTo(String value) { addCriterion("feature <=", value, "feature"); return (Criteria) this; } public Criteria andFeatureLike(String value) { addCriterion("feature like", value, "feature"); return (Criteria) this; } public Criteria andFeatureNotLike(String value) { addCriterion("feature not like", value, "feature"); return (Criteria) this; } public Criteria andFeatureIn(List values) { addCriterion("feature in", values, "feature"); return (Criteria) this; } public Criteria andFeatureNotIn(List values) { addCriterion("feature not in", values, "feature"); return (Criteria) this; } public Criteria andFeatureBetween(String value1, String value2) { addCriterion("feature between", value1, value2, "feature"); return (Criteria) this; } public Criteria andFeatureNotBetween(String value1, String value2) { addCriterion("feature not between", value1, value2, "feature"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } public enum OrderCondition { ID("id"), GMTCREATE("gmt_create"), GMTMODIFIED("gmt_modified"), AREAID("area_id"), AUTHCODE("auth_code"), CABINETID("cabinet_id"), CABINETNO("cabinet_no"), STATUS("status"), ASSIGNTIME("assign_time"), USETIME("use_time"), BIZTYPE("biz_type"), BIZOUTID("biz_out_id"), FEATURE("feature"); private String columnName; OrderCondition(String columnName) { this.columnName = columnName; } public String getColumnName() { return columnName; } public static OrderCondition getEnumByName(String name) { OrderCondition[] orderConditions = OrderCondition.values(); for (OrderCondition orderCondition : orderConditions) { if (orderCondition.name().equalsIgnoreCase(name)) { return orderCondition; } } throw new RuntimeException("OrderCondition of " + name + " enum not exist"); } @Override public String toString() { return columnName; } } public enum SortType { ASC("asc"), DESC("desc"); private String value; SortType(String value) { this.value = value; } public String getValue() { return value; } public static SortType getEnumByName(String name) { SortType[] sortTypes = SortType.values(); for (SortType sortType : sortTypes) { if (sortType.name().equalsIgnoreCase(name)) { return sortType; } } throw new RuntimeException("SortType of " + name + " enum not exist"); } @Override public String toString() { return value; } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yannywang.java ================================================ 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 ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei.java ================================================ 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"));; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei2.java ================================================ 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"));; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei3.java ================================================ 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" } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei4.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yaoming.java ================================================ 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; } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yaoming_1.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yuanmomo_Issue_504.java ================================================ 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 + '}'; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yuanmomo_Issue_505_1.java ================================================ 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 + "}"; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_yunban.java ================================================ package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class Bug_for_yunban extends TestCase { public void test_for_issue() throws Exception { List relationItemList = new LinkedList(); Map ext = new HashMap(); ext.put("a", "b"); ext.put("c", "d"); RelationItem relationItem = new RelationItem(); relationItem.setExt(ext); relationItem.setSourceId("12"); relationItemList.add(relationItem); relationItem = new RelationItem(); relationItem.setExt(ext); relationItem.setSourceId("55"); relationItemList.add(relationItem); //ParserConfig.getGlobalInstance().setAutoTypeSupport(true); //String a = JSON.toJSONString(relationItemList, SerializerFeature.WriteClassName); String a1 = JSON.toJSONString(relationItemList); System.out.println(a1); //ParserConfig.getGlobalInstance().setAutoTypeSupport(true); List relationItemList1 = JSON.parseObject(a1, new com.alibaba.fastjson.TypeReference>(){}); System.out.print("fdafda"); } public static class RelationItem { private String sourceId; private Map ext; public String getSourceId() { return sourceId; } public void setSourceId(String sourceId) { this.sourceId = sourceId; } public Map getExt() { return ext; } public void setExt(Map ext) { this.ext = ext; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_zengjie.java ================================================ 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'}}"); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhaoyao.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhongyin.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhuangzaowen.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Bug_for_zhuel.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/CollectionEmptyMapTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/FastJsonSerializeIterableTest.java ================================================ 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())); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1005.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue101.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1013.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1017.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue101_NoneASM.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue101_field.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue101_field_NoneASM.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1020.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1023.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1030.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1036.java ================================================ 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 + '}'; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1063.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1063_date.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1074.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1075.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue109.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue115.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue117.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue118.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue119.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue124.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue125.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue126.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue127.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue1296.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue141.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue143.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue146.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue153.java ================================================ 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[]>(){}); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue157.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue166.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue169.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue171.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue176.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue177.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue179.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue183.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue184.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue190.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue199.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue204.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue208.java ================================================ 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 名称; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue215.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue215_boolean_array.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue215_char_array.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue215_double_array.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue215_float_array.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue215_int_array.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue215_long_array.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue215_short_array.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue220.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue243.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue248_orderedField.java ================================================ 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]); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue274.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue363.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue408.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue569.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue569_1.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue585.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue62.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue64.java ================================================ 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"; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue688.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue689.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue69.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue72.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue74.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue743.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue744.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue744_1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue763.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue771.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue776.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue779.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue780.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue784.java ================================================ 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\"}]"); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue79.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue793.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue798.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue798_1.java ================================================ /* * 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue799.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue801.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue804.java ================================================ 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{ } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue821.java ================================================ 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'); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue859.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue868.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue869.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue869_1.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue87.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue878.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue87_hashset.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue87_treeset.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue887.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue89.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue894.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue900.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue900_1.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue912.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue922.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue923.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue939.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue94.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue942.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue943.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue944.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue952.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue955.java ================================================ 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; } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue96.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue963.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue975.java ================================================ package com.alibaba.json.bvt.bug; /** * Created by wenshao on 11/01/2017. */ public class Issue975 { } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue978.java ================================================ 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 java.util.Date(1483413683714L); JSONObject obj = (JSONObject) JSON.toJSON(model); assertEquals("{\"date\":\"2017-01-03 11:21:23\"}", obj.toJSONString()); } public void test_for_issue2() throws Exception { Model model = new Model(); model.date = new java.sql.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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue983.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue983_1.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue987.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue989.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue993.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue995.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue997.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue998.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue998_private.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue_611.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue_717.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue_748.java ================================================ 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 + '}'; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue_for_huangfeng.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue_for_jiongxiong.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue_for_oschina_3087749_2215732.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Issue_for_zuojing.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/JSONTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/KeyBug_for_zhongl.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Mogujie_01.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/Mogujie_02.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/SerDeserTest.java ================================================ /* * 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/StackTraceElementTest.java ================================================ 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()); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/StackTraceElementTest2.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/TestDouble.java ================================================ package com.alibaba.json.bvt.bug; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestDouble extends TestCase { public void test_doubleArray_2() throws Exception { double[] array = new double[] { 1, 2 }; A a = new A(); a.setValue(array); String text = JSON.toJSONString(a); A a1 = JSON.parseObject(text, A.class); } public static class A { private double[] value; public double[] getValue() { return value; } public void setValue(double[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/TestJSONMap.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/WuqiTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/bug201806/Bug_for_weiqiang.java ================================================ package com.alibaba.json.bvt.bug.bug201806; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Bug_for_weiqiang extends TestCase { public void test_for_bug() throws Exception { SerializeWriter sw = new SerializeWriter(); sw.config(SerializerFeature.WriteNullStringAsEmpty, Boolean.TRUE); JSONSerializer js = new JSONSerializer(sw); js.write(JSON.parseObject("{'operator':null, 'status':1}")); System.out.println(js); String json2 = JSON.toJSONString(JSON.parseObject("{'operator':null, 'status':1}"), SerializerFeature.WriteNullStringAsEmpty); System.out.println(json2); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/bug201810/LatLngTest.java ================================================ package com.alibaba.json.bvt.bug.bug201810; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import java.io.Serializable; public class LatLngTest extends TestCase { public void test_latlng() throws Exception { LatLng v = new LatLng(); JSON.toJSONString(v); } public static class LatLng implements Serializable { /** * serialVersionUID */ private static final long serialVersionUID = -9176496417369601807L; public LatLng() {} public LatLng(Double lat, Double lng) { this.lat = lat; this.lng = lng; } /** * 纬度 */ @Min(-90) @Max(90) @NotNull private Double lat; /** * 经度 */ @Min(-180) @Max(180) @NotNull private Double lng; /** * Getter method for property lat. * * @return property value of lat */ public Double getLat() { return lat; } /** * Setter method for property lat. * * @param lat value to be assigned to property lat */ public void setLat(Double lat) { this.lat = lat; } /** * Getter method for property lng. * * @return property value of lng */ public Double getLng() { return lng; } /** * Setter method for property lng. * * @param lng value to be assigned to property lng */ public void setLng(Double lng) { this.lng = lng; } @Override public String toString() { return lat + " " + lng; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/bug2019/Bug20190729_01.java ================================================ package com.alibaba.json.bvt.bug.bug2019; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; public class Bug20190729_01 extends TestCase { public void test_for_issue() throws Exception { JSONObject object = new JSONObject(); object.put("bucketId", 123); JSON.toJavaObject(object, BucketInfo.class); } public static class BucketInfo { private Integer bucketId; public Integer getBucketId() { return bucketId; } public void setBucketId(int bucketId) { this.bucketId = bucketId; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/bug2020/Bug_for_emptyList.java ================================================ package com.alibaba.json.bvt.bug.bug2020; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.List; import java.util.Map; import java.util.Set; public class Bug_for_emptyList extends TestCase { public void test_for_issue() throws Exception { String str = "{\"values\":[1,2,3],\"map\":{\"a\":1},\"keys\":[1,2,3],}"; VO vo = JSON.parseObject(str, VO.class); assertEquals(3, vo.values.size()); assertEquals(1, vo.map.size()); assertEquals(3, vo.keys.size()); } public static class VO { private java.util.List values = kotlin.collections.CollectionsKt.emptyList(); private java.util.Set keys = kotlin.collections.SetsKt.emptySet(); private java.util.Map map = kotlin.collections.MapsKt.emptyMap(); public List getValues() { return values; } public Map getMap() { return map; } public Set getKeys() { return keys; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/bug2020/Bug_for_money.java ================================================ package com.alibaba.json.bvt.bug.bug2020; import java.io.Serializable; import java.math.BigDecimal; import java.util.Currency; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; public class Bug_for_money extends TestCase { public void test_for_issue() throws Exception { JSONObject obj = JSON.parseObject( "{\"productMaxPriceAmt\":{\"amount\":4.99,\"centFactor\":100,\"cent\":499,\"currency\":\"USD\"," + "\"currencyCode\":\"USD\"}}"); Money money = obj.getObject("productMaxPriceAmt", Money.class); assertEquals("USD", money.getCurrencyCode()); assertEquals(new BigDecimal("4.99"), money.getAmount()); } public static class Money implements Serializable, Comparable { private static final long serialVersionUID = 6009335074727417445L; public static final String DEFAULT_CURRENCY_CODE = "CNY"; public static final int DEFAULT_ROUNDING_MODE = BigDecimal.ROUND_HALF_EVEN; private static final int[] centFactors = new int[] { 1, 10, 100, 1000 }; private long cent; private Currency currency; private String currencyCode; public Money() { this(0); } private Money(double amount) { this(amount, Currency.getInstance(DEFAULT_CURRENCY_CODE)); } public Money(double amount, Currency currency) { this.currency = currency; this.cent = Math.round(amount * getCentFactor()); } public BigDecimal getAmount() { return BigDecimal.valueOf(cent, currency.getDefaultFractionDigits()); } public long getCent() { return cent; } public Currency getCurrency() { return currency; } public int getCentFactor() { return centFactors[currency.getDefaultFractionDigits()]; } public boolean equals(Object other) { return (other instanceof Money) && equals((Money) other); } public boolean equals(Money other) { return currency.equals(other.currency) && (cent == other.cent); } public int hashCode() { return (int) (cent ^ (cent >>> 32)); } public int compareTo(Object other) { return compareTo((Money) other); } public int compareTo(Money other) { assertSameCurrencyAs(other); if (cent < other.cent) { return -1; } else if (cent == other.cent) { return 0; } else { return 1; } } public String toString() { return getAmount().toString(); } protected void assertSameCurrencyAs(Money other) { if (!currency.equals(other.currency)) { throw new IllegalArgumentException("Money math currency mismatch."); } } public void setCent(long l) { cent = l; } public void setCurrencyCode(String currencyCode) { if (currencyCode != null && !currencyCode.isEmpty()) { this.currencyCode = currencyCode; currency = Currency.getInstance(currencyCode); } } public String getCurrencyCode() { currencyCode = currency.getCurrencyCode(); return currencyCode; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/bug_for_caoyaojun1988.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/bug/bug_for_pengsong0302.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/builder/BuilderTest0.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/builder/BuilderTest0_private.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/builder/BuilderTest1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/builder/BuilderTest1_private.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/builder/BuilderTest2.java ================================================ 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 void setId(int id) { this.id = id; } public void setName(String name) { this.name = 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/builder/BuilderTest2_private.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/builder/BuilderTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/builder/BuilderTest3_private.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/builder/BuilderTest_error.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/builder/BuilderTest_error_private.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/cglib/TestCglib.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/comparing_json_modules/ComplexAndDecimalTest.java ================================================ 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"))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/comparing_json_modules/Floating_point_Test.java ================================================ 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 ); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/comparing_json_modules/Integral_types_Test.java ================================================ 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))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/comparing_json_modules/Invalid_Test.java ================================================ 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")); // } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/compatible/ThreadLocalCacheTest.java ================================================ 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); ThreadLocalCache.clearBytes(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/compatible/TypeUtilsComputeGettersTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/compatible/jsonlib/CompatibleTest0.java ================================================ package com.alibaba.json.bvt.compatible.jsonlib; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; public class CompatibleTest0 extends TestCase { protected void setUp() throws Exception { System.out.println(); } public void test_0() throws Exception { Map obj = new HashMap(); assertEquals(toCompatibleJSONString(obj), toJSONLibString(obj)); } public void test_1() throws Exception { VO vo = new VO(); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_2() throws Exception { V1 vo = new V1(); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } // {"media":{"size":58982400,"format":"video/mpg4","uri":"http://javaone.com/keynote.mpg","title":"Javaone Keynote","width":640,"height":480,"duration":18000000,"bitrate":262144,"persons":["Bill Gates","Steve Jobs"],"player":"JAVA"}{"images":[{"size":"LARGE","uri":"http://javaone.com/keynote_large.jpg","title":"Javaone Keynote","width":1024,"height":768},{"size":"SMALL","uri":"http://javaone.com/keynote_small.jpg","title":"Javaone Keynote","width":320,"height":240}]} public void test_3() throws Exception { V1 vo = new V1(); vo.setDate(new Date()); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_4() throws Exception { V1 vo = new V1(); vo.setF2('中'); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_5() throws Exception { V2 vo = new V2(); vo.setF1(0.2f); vo.setF2(33.3); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_6() throws Exception { V2 vo = new V2(); vo.setF1(0.1f); vo.setF2(33.3); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_7() throws Exception { V2 vo = new V2(); vo.setF2(0.1D); vo.setF1(33.3f); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_8() throws Exception { V3 vo = new V3(); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_9() throws Exception { V4 vo = new V4(); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_10() throws Exception { Object vo = null; assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_11() throws Exception { Object vo = new HashMap(); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public static void assertEquals(String fastJSON, String jsonLib) { System.out.println("fastjson: " + fastJSON); System.out.println("json-lib: " + jsonLib); Assert.assertEquals(JSON.parse(fastJSON), JSON.parse(jsonLib)); } private static final SerializeConfig mapping; static { mapping = new SerializeConfig(); mapping.put(Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式 } private static final SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, // 输出空置字段 SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null }; // 序列化为和JSON-LIB兼容的字符串 public static String toCompatibleJSONString(Object object) { return JSON.toJSONString(object, mapping, features); } public static String toJSONLibString(Object object) { net.sf.json.JSONObject obj = net.sf.json.JSONObject.fromObject(object); return obj.toString(); } public static class V4 { private Map items; public Map getItems() { return items; } public void setItems(Map items) { this.items = items; } } public static class V3 { private List items; public List getItems() { return items; } public void setItems(List items) { this.items = items; } } public static class V2 { private float f1; private double f2; private Float f3; private Double f4; 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; } public Float getF3() { return f3; } public void setF3(Float f3) { this.f3 = f3; } public Double getF4() { return f4; } public void setF4(Double f4) { this.f4 = f4; } } public static class V1 { private Boolean f1; private Character f2; private String f3; private Date date; private boolean f4; private char f5; public Boolean getF1() { return f1; } public void setF1(Boolean f1) { this.f1 = f1; } public Character getF2() { return f2; } public void setF2(Character f2) { this.f2 = f2; } public String getF3() { return f3; } public void setF3(String f3) { this.f3 = f3; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public boolean isF4() { return f4; } public void setF4(boolean f4) { this.f4 = f4; } public char getF5() { return f5; } public void setF5(char f5) { this.f5 = f5; } } public static class VO { private int id; private String name; private BigDecimal salary; private List items; private Byte f1; private Short f2; private Integer f3; private Long f4; private BigInteger f5; private BigDecimal f6; private byte f7; private short f8; private int f9; private long f10; public Byte getF1() { return f1; } public void setF1(Byte f1) { this.f1 = f1; } public Short getF2() { return f2; } public void setF2(Short f2) { this.f2 = f2; } public Integer getF3() { return f3; } public void setF3(Integer f3) { this.f3 = f3; } public Long getF4() { return f4; } public void setF4(Long f4) { this.f4 = f4; } public BigInteger getF5() { return f5; } public void setF5(BigInteger f5) { this.f5 = f5; } public BigDecimal getF6() { return f6; } public void setF6(BigDecimal f6) { this.f6 = f6; } public byte getF7() { return f7; } public void setF7(byte f7) { this.f7 = f7; } public short getF8() { return f8; } public void setF8(short f8) { this.f8 = f8; } public int getF9() { return f9; } public void setF9(int f9) { this.f9 = f9; } public long getF10() { return f10; } public void setF10(long f10) { this.f10 = f10; } public BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } 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 List getItems() { return items; } public void setItems(List items) { this.items = items; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/compatible/jsonlib/CompatibleTest_noasm.java ================================================ package com.alibaba.json.bvt.compatible.jsonlib; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; public class CompatibleTest_noasm extends TestCase { protected void setUp() throws Exception { System.out.println(); } public void test_0() throws Exception { Map obj = new HashMap(); assertEquals(toCompatibleJSONString(obj), toJSONLibString(obj)); } public void test_1() throws Exception { VO vo = new VO(); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_2() throws Exception { V1 vo = new V1(); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } // {"media":{"size":58982400,"format":"video/mpg4","uri":"http://javaone.com/keynote.mpg","title":"Javaone Keynote","width":640,"height":480,"duration":18000000,"bitrate":262144,"persons":["Bill Gates","Steve Jobs"],"player":"JAVA"}{"images":[{"size":"LARGE","uri":"http://javaone.com/keynote_large.jpg","title":"Javaone Keynote","width":1024,"height":768},{"size":"SMALL","uri":"http://javaone.com/keynote_small.jpg","title":"Javaone Keynote","width":320,"height":240}]} public void test_3() throws Exception { V1 vo = new V1(); vo.setDate(new Date()); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_4() throws Exception { V1 vo = new V1(); vo.setF2('中'); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_5() throws Exception { V2 vo = new V2(); vo.setF1(1.1f); vo.setF2(2.2); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_6() throws Exception { V2 vo = new V2(); vo.setF1(0.1f); vo.setF2(3.3); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_7() throws Exception { V2 vo = new V2(); vo.setF1(1.1f); vo.setF2(0.1D); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_8() throws Exception { V3 vo = new V3(); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_9() throws Exception { V4 vo = new V4(); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_10() throws Exception { Object vo = null; assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public void test_11() throws Exception { Object vo = new HashMap(); assertEquals(toCompatibleJSONString(vo), toJSONLibString(vo)); } public static void assertEquals(String fastJSON, String jsonLib) { System.out.println("fastjson: " + fastJSON); System.out.println("json-lib: " + jsonLib); Assert.assertEquals(JSON.parse(fastJSON), JSON.parse(jsonLib)); } private static final SerializeConfig mapping; static { mapping = new SerializeConfig(); mapping.setAsmEnable(false); mapping.put(Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式 } private static final SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, // 输出空置字段 SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null }; // 序列化为和JSON-LIB兼容的字符串 public static String toCompatibleJSONString(Object object) { return JSON.toJSONString(object, mapping, features); } public static String toJSONLibString(Object object) { net.sf.json.JSONObject obj = net.sf.json.JSONObject.fromObject(object); return obj.toString(); } public static class V4 { private Map items; public Map getItems() { return items; } public void setItems(Map items) { this.items = items; } } public static class V3 { private List items; public List getItems() { return items; } public void setItems(List items) { this.items = items; } } public static class V2 { private float f1; private double f2; private Float f3; private Double f4; 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; } public Float getF3() { return f3; } public void setF3(Float f3) { this.f3 = f3; } public Double getF4() { return f4; } public void setF4(Double f4) { this.f4 = f4; } } public static class V1 { private Boolean f1; private Character f2; private String f3; private Date date; private boolean f4; private char f5; public Boolean getF1() { return f1; } public void setF1(Boolean f1) { this.f1 = f1; } public Character getF2() { return f2; } public void setF2(Character f2) { this.f2 = f2; } public String getF3() { return f3; } public void setF3(String f3) { this.f3 = f3; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public boolean isF4() { return f4; } public void setF4(boolean f4) { this.f4 = f4; } public char getF5() { return f5; } public void setF5(char f5) { this.f5 = f5; } } public static class VO { private int id; private String name; private BigDecimal salary; private List items; private Byte f1; private Short f2; private Integer f3; private Long f4; private BigInteger f5; private BigDecimal f6; private byte f7; private short f8; private int f9; private long f10; public Byte getF1() { return f1; } public void setF1(Byte f1) { this.f1 = f1; } public Short getF2() { return f2; } public void setF2(Short f2) { this.f2 = f2; } public Integer getF3() { return f3; } public void setF3(Integer f3) { this.f3 = f3; } public Long getF4() { return f4; } public void setF4(Long f4) { this.f4 = f4; } public BigInteger getF5() { return f5; } public void setF5(BigInteger f5) { this.f5 = f5; } public BigDecimal getF6() { return f6; } public void setF6(BigDecimal f6) { this.f6 = f6; } public byte getF7() { return f7; } public void setF7(byte f7) { this.f7 = f7; } public short getF8() { return f8; } public void setF8(short f8) { this.f8 = f8; } public int getF9() { return f9; } public void setF9(int f9) { this.f9 = f9; } public long getF10() { return f10; } public void setF10(long f10) { this.f10 = f10; } public BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } 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 List getItems() { return items; } public void setItems(List items) { this.items = items; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/CalendarTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldFormatTest.java ================================================ 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); assertEquals("{\"publishTime\":\""+t2+"\",\"serverTime\":\""+t1+"\",\"startDate\":\""+t3+"\"}",text); Model model2 = JSON.parseObject(text, Model.class); SimpleDateFormat df4 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA); SimpleDateFormat df5 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); SimpleDateFormat df6 = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA); df4.setTimeZone(JSON.defaultTimeZone); df5.setTimeZone(JSON.defaultTimeZone); df6.setTimeZone(JSON.defaultTimeZone); assertEquals(t2, df4.format(model2.publishTime)); assertEquals(t1, df5.format(model2.serverTime)); assertEquals(t3, df6.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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest.java ================================================ package com.alibaba.json.bvt.date; import java.util.Date; 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 DateFieldTest extends TestCase { public void test_codec() throws Exception { V0 v = new V0(); v.setValue(new Date()); String text = JSON.toJSONString(v); Assert.assertEquals("{\"value\":" + v.getValue().getTime() + "}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v1.getValue(), v.getValue()); } 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_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; public Date getValue() { return value; } public void setValue(Date value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest10.java ================================================ package com.alibaba.json.bvt.date; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; 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 void test_5() throws Exception { String text = "{\"date\":\"2018-05-21T14:39:44.907+08:00\"}"; Model model = JSON.parseObject(text, Model.class); String str = JSON.toJSONString(model, SerializerFeature.UseISO8601DateFormat); assertEquals("{\"date\":\"2018-05-21T14:39:44.907+08:00\"}", str); // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // Date object = format.parse("2018-05-21T14:39:44.9077913+08:00"); // assertEquals(object.getTime(), model.date.getTime()); } public void test_6() throws Exception { String text = "{\"date\":\"4567-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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest11_reader.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest12_t.java ================================================ package com.alibaba.json.bvt.date; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import org.junit.Assert; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class DateFieldTest12_t extends TestCase { protected void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); JSON.defaultLocale = Locale.CHINA; } 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'T'HH:mm:ssZ", JSON.defaultLocale); format.setTimeZone(JSON.defaultTimeZone); Assert.assertEquals("{\"value\":\"" + format.format(object.getValue()) + "\"}", text); Entity object2 = JSON.parseObject(text, Entity.class); } public static class Entity { @JSONField(format = "yyyy-MM-ddTHH:mm:ssZ") private Date value; public Date getValue() { return value; } public void setValue(Date value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest5.java ================================================ package com.alibaba.json.bvt.date; import java.util.Date; 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 DateFieldTest5 extends TestCase { public void test_codec() throws Exception { SerializeConfig mapping = new SerializeConfig(); V0 v = new V0(); v.setValue(new Date()); String text = JSON.toJSONString(v, mapping); Assert.assertEquals("{\"value\":" + v.getValue().getTime() + "}", 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); Assert.assertEquals("{\"value\":" + v.getValue().getTime() + "}", 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); Assert.assertEquals("{\"value\":" + v.getValue().getTime() + "}", 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 = " ") public Date getValue() { return value; } public void setValue(Date value) { this.value = value; } public boolean is() { return true; } public boolean isa() { return true; } public Object get() { return true; } public Object geta() { return true; } @JSONField(serialize = false) public Object getA() { return true; } public static Object getB() { return true; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest6.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest7.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest8.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFieldTest9.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateFormatPriorityTest.java ================================================ package com.alibaba.json.bvt.date; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import junit.framework.TestCase; import org.junit.Assert; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class DateFormatPriorityTest extends TestCase { Calendar calendar; protected void setUp() { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); JSON.defaultLocale = Locale.CHINA; calendar = Calendar.getInstance(JSON.defaultTimeZone); calendar.set(1995, Calendar.OCTOBER, 26); } public void test_for_fastJsonConfig() throws IOException { FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM.dd"); FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); converter.setFastJsonConfig(config); converter.canRead(VO.class, MediaType.APPLICATION_JSON_UTF8); converter.canWrite(VO.class, MediaType.APPLICATION_JSON_UTF8); final ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); HttpOutputMessage out = new HttpOutputMessage() { public HttpHeaders getHeaders() { return new HttpHeaders() { private static final long serialVersionUID = 1L; @Override public MediaType getContentType() { return MediaType.APPLICATION_JSON; } }; } public OutputStream getBody() throws IOException { return byteOut; } }; VO vo = new VO(); vo.setDate(calendar.getTime()); converter.write(vo, VO.class, MediaType.APPLICATION_JSON_UTF8, out); byte[] bytes = byteOut.toByteArray(); String jsonString = new String(bytes, "UTF-8"); Assert.assertEquals("{\"date\":\"1995-10.26\"}", jsonString); } public void test_for_toJSONStringWithDateFormat() { VO vo = new VO(); vo.setDate(calendar.getTime()); String jsonString = JSON.toJSONStringWithDateFormat(vo, "yyyy.MM.dd"); assertEquals("{\"date\":\"1995.10.26\"}", jsonString); } public void test_for_Annotation() { VO2 vo2 = new VO2(); vo2.setDate(calendar.getTime()); String jsonString = JSON.toJSONString(vo2); assertEquals("{\"date\":\"1995.10-26\"}", jsonString); } public void test_for_DEFFAULT_DATE_FORMAT() { String defaultDateFormat = JSON.DEFFAULT_DATE_FORMAT; JSON.DEFFAULT_DATE_FORMAT = "MM-dd"; VO vo = new VO(); vo.setDate(calendar.getTime()); String jsonString = JSON.toJSONString(vo, SerializerFeature.WriteDateUseDateFormat); JSON.DEFFAULT_DATE_FORMAT = defaultDateFormat; assertEquals("{\"date\":\"10-26\"}", jsonString); } //Annotation + FastJsonConfig (Annotation优先) public void test_priority_01() throws Exception { //FastJsonConfig FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM.dd"); FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); converter.setFastJsonConfig(config); converter.canRead(VO.class, MediaType.APPLICATION_JSON_UTF8); converter.canWrite(VO.class, MediaType.APPLICATION_JSON_UTF8); final ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); HttpOutputMessage out = new HttpOutputMessage() { public HttpHeaders getHeaders() { return new HttpHeaders() { private static final long serialVersionUID = 1L; @Override public MediaType getContentType() { return MediaType.APPLICATION_JSON; } }; } public OutputStream getBody() throws IOException { return byteOut; } }; VO2 vo = new VO2(); vo.setDate(calendar.getTime()); converter.write(vo, VO.class, MediaType.APPLICATION_JSON_UTF8, out); byte[] bytes = byteOut.toByteArray(); String jsonString = new String(bytes, "UTF-8"); assertEquals("{\"date\":\"1995.10-26\"}", jsonString); } //toJSONStringWithDateFormat + Annotation (toJSONStringWithDateFormat优先) public void test_priority_02() throws Exception { VO2 vo = new VO2(); vo.setDate(calendar.getTime()); String jsonString = JSON.toJSONStringWithDateFormat(vo, "yyyy.MM.dd"); assertEquals("{\"date\":\"1995.10.26\"}", jsonString); } //Annotation + DEFFAULT_DATE_FORMAT (Annotation优先) public void test_priority_03() throws Exception { String defaultDateFormat = JSON.DEFFAULT_DATE_FORMAT; JSON.DEFFAULT_DATE_FORMAT = "MM-dd"; VO2 vo = new VO2(); vo.setDate(calendar.getTime()); String jsonString = JSON.toJSONString(vo, SerializerFeature.WriteDateUseDateFormat); JSON.DEFFAULT_DATE_FORMAT = defaultDateFormat; assertEquals("{\"date\":\"1995.10-26\"}", jsonString); } public static class VO { private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } public static class VO2 { @JSONField(format = "yyyy.MM-dd") private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateNewTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateTest.java ================================================ package com.alibaba.json.bvt.date; 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.serializer.SerializerFeature; public class DateTest extends TestCase { protected void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); JSON.defaultLocale = Locale.CHINA; } 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)); } public void test_parse() throws Exception { Date date = JSON.parseObject("\"2018-10-12 09:48:22 +0800\"", Date.class); assertEquals(1539308902000L, date.getTime()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateTest1.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateTest2.java ================================================ package com.alibaba.json.bvt.date; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import org.junit.Assert; import java.util.Date; import java.util.TimeZone; public class DateTest2 extends TestCase { private TimeZone timeZone; protected void setUp() throws Exception { timeZone = JSON.defaultTimeZone; } protected void tearDown() throws Exception { JSON.defaultTimeZone = timeZone; } public void test_date() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("America/Chicago"); Date date = new Date(1531928656055L); TestBean bean = new TestBean(); bean.setDate(date); String iso = JSON.toJSONString(bean, SerializerFeature.UseISO8601DateFormat); assertEquals("{\"date\":\"2018-07-18T10:44:16.055-05:00\"}", iso); } public static class TestBean { private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateTest_dotnet_5.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateTest_error.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/DateTest_tz.java ================================================ 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.JSON; 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/date/XMLGregorianCalendarTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/dubbo/TestForDubbo.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/emoji/EmojiTest0.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/DisableFieldSmartMatchTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/DisableFieldSmartMatchTest_2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/FeatureTest_8.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/FeaturesTest.java ================================================ 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 FeaturesTest 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\":null}", text); } public void test_1() throws Exception { SerializeConfig config = new SerializeConfig(); config.setAsmEnable(true); String text = JSON.toJSONString(new Entity(), config); Assert.assertEquals("{\"value\":null}", text); } public static class Entity { private Object value; @JSONField(serialzeFeatures = { SerializerFeature.WriteMapNullValue }) public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/FeaturesTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/FeaturesTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/FeaturesTest4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/FeaturesTest5.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/FeaturesTest5_1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/FeaturesTest6.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/FeaturesTest7.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest_field.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/IgnoreErrorGetterTest_private.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/InitStringFieldAsEmptyTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/WriteNullStringAsEmptyTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/feature/WriteNullStringAsEmptyTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/fullSer/EmtpyLinkedHashMapTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/fullSer/LongTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/fullSer/ToJavaObjectTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/fullSer/ToJavaObjectTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/fullSer/get_set_Test.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/fullSer/getfTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/fullSer/getfTest_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/fullSer/is_set_test_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/geo/FeatureCollectionTest.java ================================================ package com.alibaba.json.bvt.geo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.support.geo.FeatureCollection; import com.alibaba.fastjson.support.geo.Geometry; import com.alibaba.fastjson.support.geo.Point; import junit.framework.TestCase; public class FeatureCollectionTest extends TestCase { public void test_geo() throws Exception { String str = "{\n" + " \"type\": \"FeatureCollection\",\n" + " \"features\": [{\n" + " \"type\": \"Feature\",\n" + " \"geometry\": {\n" + " \"type\": \"Point\",\n" + " \"coordinates\": [102.0, 0.5]\n" + " },\n" + " \"properties\": {\n" + " \"prop0\": \"value0\"\n" + " }\n" + " }, {\n" + " \"type\": \"Feature\",\n" + " \"geometry\": {\n" + " \"type\": \"LineString\",\n" + " \"coordinates\": [\n" + " [102.0, 0.0],\n" + " [103.0, 1.0],\n" + " [104.0, 0.0],\n" + " [105.0, 1.0]\n" + " ]\n" + " },\n" + " \"properties\": {\n" + " \"prop0\": \"value0\",\n" + " \"prop1\": 0.0\n" + " }\n" + " }, {\n" + " \"type\": \"Feature\",\n" + " \"geometry\": {\n" + " \"type\": \"Polygon\",\n" + " \"coordinates\": [\n" + " [\n" + " [100.0, 0.0],\n" + " [101.0, 0.0],\n" + " [101.0, 1.0],\n" + " [100.0, 1.0],\n" + " [100.0, 0.0]\n" + " ]\n" + " ]\n" + " },\n" + " \"properties\": {\n" + " \"prop0\": \"value0\",\n" + " \"prop1\": {\n" + " \"this\": \"that\"\n" + " }\n" + " }\n" + " }]\n" + "}\n"; Geometry geometry = JSON.parseObject(str, Geometry.class); assertEquals(FeatureCollection.class, geometry.getClass()); assertEquals("{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"properties\":{\"prop0\":\"value0\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[102.0,0.5]}},{\"type\":\"Feature\",\"properties\":{\"prop1\":\"0.0\",\"prop0\":\"value0\"},\"geometry\":{\"type\":\"LineString\",\"coordinates\":[[102.0,0.0],[103.0,1.0],[104.0,0.0],[105.0,1.0]]}},{\"type\":\"Feature\",\"properties\":{\"prop1\":\"{\\\"this\\\":\\\"that\\\"}\",\"prop0\":\"value0\"},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[100.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]]]}}]}", JSON.toJSONString(geometry)); String str2 = JSON.toJSONString(geometry); assertEquals(str2, JSON.toJSONString(JSON.parseObject(str2, Geometry.class))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/geo/FeatureTest.java ================================================ package com.alibaba.json.bvt.geo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.support.geo.Feature; import com.alibaba.fastjson.support.geo.Geometry; import com.alibaba.fastjson.support.geo.Point; import junit.framework.TestCase; public class FeatureTest extends TestCase { public void test_geo() throws Exception { String str = "{\n" + " \"type\": \"Feature\",\n" + " \"bbox\": [-10.0, -10.0, 10.0, 10.0],\n" + " \"geometry\": {\n" + " \"type\": \"Polygon\",\n" + " \"coordinates\": [\n" + " [\n" + " [-10.0, -10.0],\n" + " [10.0, -10.0],\n" + " [10.0, 10.0],\n" + " [-10.0, -10.0]\n" + " ]\n" + " ]\n" + " }\n" + "}"; Geometry geometry = JSON.parseObject(str, Geometry.class); assertEquals(Feature.class, geometry.getClass()); assertEquals("{\"type\":\"Feature\",\"bbox\":[-10.0,-10.0,10.0,10.0],\"properties\":{},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[-10.0,-10.0],[10.0,-10.0],[10.0,10.0],[-10.0,-10.0]]]}}", JSON.toJSONString(geometry)); String str2 = JSON.toJSONString(geometry); assertEquals(str2, JSON.toJSONString(JSON.parseObject(str2, Geometry.class))); } public void test_geo_1() throws Exception { String str = "{\n" + " \"type\": \"Feature\",\n" + " \"id\": \"f2\",\n" + " \"geometry\": {\n" + " \"type\": \"Polygon\",\n" + " \"coordinates\": [\n" + " [\n" + " [-10.0, -10.0],\n" + " [10.0, -10.0],\n" + " [10.0, 10.0],\n" + " [-10.0, -10.0]\n" + " ]\n" + " ]\n" + " }\n" + "}"; Geometry geometry = JSON.parseObject(str, Geometry.class); assertEquals(Feature.class, geometry.getClass()); assertEquals("{\"type\":\"Feature\",\"id\":\"f2\",\"properties\":{},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[-10.0,-10.0],[10.0,-10.0],[10.0,10.0],[-10.0,-10.0]]]}}", JSON.toJSONString(geometry)); String str2 = JSON.toJSONString(geometry); assertEquals(str2, JSON.toJSONString(JSON.parseObject(str2, Geometry.class))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/geo/GeometryCollectionTest.java ================================================ package com.alibaba.json.bvt.geo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.support.geo.Geometry; import com.alibaba.fastjson.support.geo.GeometryCollection; import com.alibaba.fastjson.support.geo.LineString; import junit.framework.TestCase; public class GeometryCollectionTest extends TestCase { public void test_geo() throws Exception { String str = "{\n" + " \"type\": \"GeometryCollection\",\n" + " \"geometries\": [{\n" + " \"type\": \"Point\",\n" + " \"coordinates\": [100.0, 0.0]\n" + " }, {\n" + " \"type\": \"LineString\",\n" + " \"coordinates\": [\n" + " [101.0, 0.0],\n" + " [102.0, 1.0]\n" + " ]\n" + " }]\n" + "}"; Geometry geometry = JSON.parseObject(str, Geometry.class); assertEquals(GeometryCollection.class, geometry.getClass()); assertEquals( "{\"type\":\"GeometryCollection\",\"geometries\":[{\"type\":\"Point\",\"coordinates\":[100.0,0.0]},{\"type\":\"LineString\",\"coordinates\":[[101.0,0.0],[102.0,1.0]]}]}" , JSON.toJSONString(geometry)); String str2 = JSON.toJSONString(geometry); assertEquals(str2, JSON.toJSONString(JSON.parseObject(str2, Geometry.class))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/geo/LineStringTest.java ================================================ package com.alibaba.json.bvt.geo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.support.geo.Geometry; import com.alibaba.fastjson.support.geo.LineString; import junit.framework.TestCase; public class LineStringTest extends TestCase { public void test_geo() throws Exception { String str = "{\n" + " \"type\": \"LineString\",\n" + " \"coordinates\": [\n" + " [100.0, 0.0],\n" + " [101.0, 1.0]\n" + " ]\n" + "}"; Geometry geometry = JSON.parseObject(str, Geometry.class); assertEquals(LineString.class, geometry.getClass()); assertEquals("{\"type\":\"LineString\",\"coordinates\":[[100.0,0.0],[101.0,1.0]]}", JSON.toJSONString(geometry)); String str2 = JSON.toJSONString(geometry); assertEquals(str2, JSON.toJSONString(JSON.parseObject(str2, Geometry.class))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/geo/MultiLineStringTest.java ================================================ package com.alibaba.json.bvt.geo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.support.geo.Geometry; import com.alibaba.fastjson.support.geo.MultiLineString; import com.alibaba.fastjson.support.geo.MultiPoint; import junit.framework.TestCase; public class MultiLineStringTest extends TestCase { public void test_geo() throws Exception { String str = "{\n" + " \"type\": \"MultiLineString\",\n" + " \"coordinates\": [\n" + " [\n" + " [100.0, 0.0],\n" + " [101.0, 1.0]\n" + " ],\n" + " [\n" + " [102.0, 2.0],\n" + " [103.0, 3.0]\n" + " ]\n" + " ]\n" + "}"; Geometry geometry = JSON.parseObject(str, Geometry.class); assertEquals(MultiLineString.class, geometry.getClass()); assertEquals("{\"type\":\"MultiLineString\",\"coordinates\":[[[100.0,0.0],[101.0,1.0]],[[102.0,2.0],[103.0,3.0]]]}", JSON.toJSONString(geometry)); String str2 = JSON.toJSONString(geometry); assertEquals(str2, JSON.toJSONString(JSON.parseObject(str2, Geometry.class))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/geo/MultiPointTest.java ================================================ package com.alibaba.json.bvt.geo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.support.geo.Geometry; import com.alibaba.fastjson.support.geo.MultiPoint; import com.alibaba.fastjson.support.geo.Point; import junit.framework.TestCase; public class MultiPointTest extends TestCase { public void test_geo() throws Exception { String str = "{\n" + " \"type\": \"MultiPoint\",\n" + " \"coordinates\": [\n" + " [100.0, 0.0],\n" + " [101.0, 1.0]\n" + " ]\n" + "}"; Geometry geometry = JSON.parseObject(str, Geometry.class); assertEquals(MultiPoint.class, geometry.getClass()); assertEquals("{\"type\":\"MultiPoint\",\"coordinates\":[[100.0,0.0],[101.0,1.0]]}", JSON.toJSONString(geometry)); String str2 = JSON.toJSONString(geometry); assertEquals(str2, JSON.toJSONString(JSON.parseObject(str2, Geometry.class))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/geo/MultiPolygonTest.java ================================================ package com.alibaba.json.bvt.geo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.support.geo.Geometry; import com.alibaba.fastjson.support.geo.MultiPoint; import com.alibaba.fastjson.support.geo.MultiPolygon; import junit.framework.TestCase; public class MultiPolygonTest extends TestCase { public void test_geo() throws Exception { String str = "{\n" + " \"type\": \"MultiPolygon\",\n" + " \"coordinates\": [\n" + " [\n" + " [\n" + " [102.0, 2.0],\n" + " [103.0, 2.0],\n" + " [103.0, 3.0],\n" + " [102.0, 3.0],\n" + " [102.0, 2.0]\n" + " ]\n" + " ],\n" + " [\n" + " [\n" + " [100.0, 0.0],\n" + " [101.0, 0.0],\n" + " [101.0, 1.0],\n" + " [100.0, 1.0],\n" + " [100.0, 0.0]\n" + " ],\n" + " [\n" + " [100.2, 0.2],\n" + " [100.2, 0.8],\n" + " [100.8, 0.8],\n" + " [100.8, 0.2],\n" + " [100.2, 0.2]\n" + " ]\n" + " ]\n" + " ]\n" + "}"; Geometry geometry = JSON.parseObject(str, Geometry.class); assertEquals(MultiPolygon.class, geometry.getClass()); assertEquals( "{\"type\":\"MultiPolygon\",\"coordinates\":[[[[102.0,2.0],[103.0,2.0],[103.0,3.0],[102.0,3.0],[102.0,2.0]]],[[[100.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]],[[100.2,0.2],[100.2,0.8],[100.8,0.8],[100.8,0.2],[100.2,0.2]]]]}" , JSON.toJSONString(geometry)); String str2 = JSON.toJSONString(geometry); assertEquals(str2, JSON.toJSONString(JSON.parseObject(str2, Geometry.class))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/geo/PointTest.java ================================================ package com.alibaba.json.bvt.geo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.support.geo.Geometry; import com.alibaba.fastjson.support.geo.LineString; import com.alibaba.fastjson.support.geo.Point; import junit.framework.TestCase; public class PointTest extends TestCase { public void test_geo() throws Exception { String str = "{\n" + " \"type\": \"Point\",\n" + " \"coordinates\": [100.0, 0.0]\n" + "}"; Geometry geometry = JSON.parseObject(str, Geometry.class); assertEquals(Point.class, geometry.getClass()); assertEquals("{\"type\":\"Point\",\"coordinates\":[100.0,0.0]}", JSON.toJSONString(geometry)); String str2 = JSON.toJSONString(geometry); assertEquals(str2, JSON.toJSONString(JSON.parseObject(str2, Geometry.class))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/geo/PolygonTest.java ================================================ package com.alibaba.json.bvt.geo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.support.geo.Geometry; import com.alibaba.fastjson.support.geo.Point; import com.alibaba.fastjson.support.geo.Polygon; import junit.framework.TestCase; public class PolygonTest extends TestCase { public void test_geo() throws Exception { String str = "{\n" + " \"type\": \"Polygon\",\n" + " \"coordinates\": [\n" + " [\n" + " [100.0, 0.0],\n" + " [101.0, 0.0],\n" + " [101.0, 1.0],\n" + " [100.0, 1.0],\n" + " [100.0, 0.0]\n" + " ],\n" + " [\n" + " [100.8, 0.8],\n" + " [100.8, 0.2],\n" + " [100.2, 0.2],\n" + " [100.2, 0.8],\n" + " [100.8, 0.8]\n" + " ]\n" + " ]\n" + "}"; Geometry geometry = JSON.parseObject(str, Geometry.class); assertEquals(Polygon.class, geometry.getClass()); assertEquals("{\"type\":\"Polygon\",\"coordinates\":[[[100.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]],[[100.8,0.8],[100.8,0.2],[100.2,0.2],[100.2,0.8],[100.8,0.8]]]}", JSON.toJSONString(geometry)); String str2 = JSON.toJSONString(geometry); assertEquals(str2, JSON.toJSONString(JSON.parseObject(str2, Geometry.class))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/guava/ArrayListMultimapTest.java ================================================ package com.alibaba.json.bvt.guava; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.google.common.collect.ArrayListMultimap; 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, SerializerFeature.MapSortField); 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/guava/HashMultimapTest.java ================================================ 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); assertTrue(json.equals("{\"name\":[\"a\",\"b\"]}") || json.equals("{\"name\":[\"b\",\"a\"]}")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/guava/ImmutableMapTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/guava/LinkedListMultimapTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/guava/MultiMapTes.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1000/Issue1066.java ================================================ 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 + '\'' + '}'; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1000/Issue1079.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1000/Issue1080.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1000/Issue1082.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1000/Issue1083.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1000/Issue1085.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1000/Issue1086.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1000/Issue1089.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1000/Issue1089_private.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1000/Issue1095.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1109.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1112.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1120.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1121.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1134.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1138.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1140.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1144.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1146.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1150.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1151.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1152.java ================================================ 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); assertNotNull(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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1153.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1165.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_1.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_2.java ================================================ 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.LinkedHashMap; 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_3.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1177_4.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1178.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1187.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1188.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue1189.java ================================================ 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 } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1100/Issue969.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1202.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1203.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1205.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1222.java ================================================ 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() + "\""; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1222_1.java ================================================ 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() + "\""; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1225.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1226.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1227.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1229.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1231.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1233.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1235.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1235_noasm.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1240.java ================================================ package com.alibaba.json.bvt.issue_1200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; 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.addAccept("org.springframework.util.LinkedMultiValueMap"); 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, Feature.SupportAutoType); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1246.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1254.java ================================================ package com.alibaba.json.bvt.issue_1200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; /** * 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1256.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1262.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1265.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1267.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1271.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1272.java ================================================ 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().getClass()); } public static class Point { private Long userId; public long getUserId() { return userId; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1272_IgnoreError.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1274.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1276.java ================================================ 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 + '}'; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1278.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1281.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1293.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1298.java ================================================ 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; import java.util.Locale; import java.util.TimeZone; /** * Created by wenshao on 30/06/2017. */ public class Issue1298 extends TestCase { protected void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); JSON.defaultLocale = Locale.US; } 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1200/Issue1299.java ================================================ 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{ } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1300.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1303.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1307.java ================================================ 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 }) ); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1310.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1310_noasm.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1319.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1320.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_boolean.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_byte.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_decimal.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_double.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_float.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_long.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1330_short.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1335.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1341.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1344.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1357.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1362.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1363.java ================================================ 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 + "]"; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1367.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1367_jaxrs.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1368.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1369.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1370.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1371.java ================================================ 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)); // } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1375.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1392.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue1399.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1300/Issue_for_zuojian.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1400.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1405.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1422.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1423.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1424.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1425.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1429.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1443.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1445.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1449.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1450.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1458.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1465.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1472.java ================================================ package com.alibaba.json.bvt.issue_1400; public class Issue1472 { } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1474.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1478.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1480.java ================================================ 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.LinkedHashMap; import java.util.Map; public class Issue1480 extends TestCase { public void test_for_issue() throws Exception { Map map = new LinkedHashMap(); 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1482.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1486.java ================================================ 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 + '}'; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1487.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1492.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1493.java ================================================ 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-22T15:08:56"; LocalDateTime time1 = LocalDateTime.now(); time1 = time1.minusNanos(10L); System.out.println(time1.getNano()); LocalDateTime time2 = LocalDateTime.parse(stime2); 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\":\"2017-09-22 15:08:56\"}",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\":\"2017-09-22 15:08:56\"}",json); String pattern = "yyyy-MM-dd'T'HH:mm:ss"; String stime1 = DateTimeFormatter.ofPattern(pattern, Locale.CHINA).format(time1); json = JSON.toJSONStringWithDateFormat(test, "yyyy-MM-dd'T'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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1494.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1496.java ================================================ 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 + '}'; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue1498.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1400/Issue_for_wuye.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1500.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1503.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1510.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1513.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1524.java ================================================ 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"); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1529.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1548.java ================================================ 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{ } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1555.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1556.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1558.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1565.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1570.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1570_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1572.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1576.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1580.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1580_private.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1582.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1583.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1584.java ================================================ 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); Object key = entry.getKey(); Object value = entry.getValue(); assertTrue(key.equals("v") || key.equals("k")); if (key.equals("v")) { assertEquals("A", value); } else { assertEquals(1, value); } } 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/Issue1588.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1500/StringSerializer.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_field.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_getter.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_map.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_map_getter.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1611.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1612.java ================================================ 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 + '\'' + '}'; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1627.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1628.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1633.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1635.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1636.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1644.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1645.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1647.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1649.java ================================================ 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())); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1649_private.java ================================================ 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())); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1653.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1657.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1660.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1662.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1662_1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1665.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1679.java ================================================ 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; import java.util.Locale; import java.util.TimeZone; public class Issue1679 extends TestCase { protected void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); JSON.defaultLocale = Locale.CHINA; } 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue1683.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/Issue_for_gaorui.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/TestJson.java ================================================ 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 config = new ParserConfig(); config.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, config); System.out.println(obj); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/FeeTypeMEnum.java ================================================ package com.alibaba.json.bvt.issue_1600.issue_1699.def; public enum FeeTypeMEnum { TRADE, REFUND; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/InnerTypeMEnum.java ================================================ 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 ; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailIsJoinMEnum.java ================================================ 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; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailStatusMEnum.java ================================================ package com.alibaba.json.bvt.issue_1600.issue_1699.def; public enum RatingDetailStatusMEnum { INIT, SUCCESS, FAIL, WAIT; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/def/RatingDetailTypeMEnum.java ================================================ 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, ; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1600/issue_1699/obj/RatingDetailBO.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1701.java ================================================ package com.alibaba.json.bvt.issue_1700; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; 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.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; 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.*; 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.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; 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; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration public class Issue1701 { @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(); } @RestController @RequestMapping() public static class BeanController { @PostMapping(path = "/download", produces = "application/octet-stream;charset=UTF-8") public @ResponseBody ResponseEntity download(@RequestBody TestBean testBean) { byte[] body = new byte[0]; InputStream in; try { in = Issue1701.class.getClassLoader().getResourceAsStream(testBean.getName()); body = new byte[in.available()]; in.read(body); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=1.txt"); HttpStatus statusCode = HttpStatus.OK; ResponseEntity response = new ResponseEntity(body, headers, statusCode); return response; } } @ComponentScan(basePackages = "com.alibaba.json.bvt.issue_1700") @Configuration @EnableWebMvc public static class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void extendMessageConverters(List> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8)); converters.add(0, converter); } } @Test public void testBean() throws Exception { mockMvc.perform( (post("/download").characterEncoding("UTF-8") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"name\": \"1.txt\"}") )).andExpect(status().isOk()).andDo(print()); } static class TestBean { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1723.java ================================================ 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 + '}'; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1725.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1727.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1733_jsonpath.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1739.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1761.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1763.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1764.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1764_bean.java ================================================ 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 { assertEquals("{\"value\":\"9007199254741992\"}" , JSON.toJSONString( new Model(9007199254741992L))); assertEquals("{\"value\":\"9007199254741990\"}" , JSON.toJSONString( new Model(9007199254741990L))); assertEquals("{\"value\":100}" , JSON.toJSONString( new Model(100L))); assertEquals("{\"value\":\"-9007199254741990\"}" , JSON.toJSONString( new Model(-9007199254741990L))); assertEquals("{\"value\":-9007199254740990}" , JSON.toJSONString( new Model(-9007199254740990L))); } @JSONType(serialzeFeatures = BrowserCompatible) public static class Model { public long value; public Model() { } public Model(long value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1764_bean_biginteger.java ================================================ package com.alibaba.json.bvt.issue_1700; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.math.BigInteger; import static com.alibaba.fastjson.serializer.SerializerFeature.BrowserCompatible; public class Issue1764_bean_biginteger extends TestCase { public void test_for_issue() throws Exception { assertEquals("{\"value\":\"9007199254741992\"}" , JSON.toJSONString( new Model(9007199254741992L), BrowserCompatible)); assertEquals("{\"value\":\"-9007199254741992\"}" , JSON.toJSONString( new Model(-9007199254741992L), BrowserCompatible)); assertEquals("{\"value\":9007199254740990}" , JSON.toJSONString( new Model(9007199254740990L), BrowserCompatible)); assertEquals("{\"value\":-9007199254740990}" , JSON.toJSONString( new Model(-9007199254740990L), BrowserCompatible)); assertEquals("{\"value\":100}" , JSON.toJSONString( new Model(100), BrowserCompatible)); assertEquals("{\"value\":-100}" , JSON.toJSONString( new Model(-100), BrowserCompatible)); } public static class Model { public BigInteger value; public Model() { } public Model(long value) { this.value = BigInteger.valueOf(value); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1764_bean_biginteger_field.java ================================================ 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 java.math.BigInteger; import static com.alibaba.fastjson.serializer.SerializerFeature.BrowserCompatible; public class Issue1764_bean_biginteger_field extends TestCase { public void test_for_issue() throws Exception { assertEquals("{\"value\":\"9007199254741992\"}" , JSON.toJSONString( new Model(9007199254741992L))); assertEquals("{\"value\":\"-9007199254741992\"}" , JSON.toJSONString( new Model(-9007199254741992L))); assertEquals("{\"value\":9007199254740990}" , JSON.toJSONString( new Model(9007199254740990L))); assertEquals("{\"value\":-9007199254740990}" , JSON.toJSONString( new Model(-9007199254740990L))); assertEquals("{\"value\":100}" , JSON.toJSONString( new Model(100))); assertEquals("{\"value\":-100}" , JSON.toJSONString( new Model(-100))); } public static class Model { @JSONField(serialzeFeatures = BrowserCompatible) public BigInteger value; public Model() { } public Model(long value) { this.value = BigInteger.valueOf(value); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1764_bean_biginteger_type.java ================================================ package com.alibaba.json.bvt.issue_1700; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONType; import junit.framework.TestCase; import java.math.BigInteger; import static com.alibaba.fastjson.serializer.SerializerFeature.BrowserCompatible; public class Issue1764_bean_biginteger_type extends TestCase { public void test_for_issue() throws Exception { assertEquals("{\"value\":\"9007199254741992\"}" , JSON.toJSONString( new Model(9007199254741992L))); assertEquals("{\"value\":\"-9007199254741992\"}" , JSON.toJSONString( new Model(-9007199254741992L))); assertEquals("{\"value\":9007199254740990}" , JSON.toJSONString( new Model(9007199254740990L))); assertEquals("{\"value\":-9007199254740990}" , JSON.toJSONString( new Model(-9007199254740990L))); assertEquals("{\"value\":100}" , JSON.toJSONString( new Model(100))); assertEquals("{\"value\":-100}" , JSON.toJSONString( new Model(-100))); } @JSONType(serialzeFeatures = BrowserCompatible) public static class Model { public BigInteger value; public Model() { } public Model(long value) { this.value = BigInteger.valueOf(value); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1766.java ================================================ package com.alibaba.json.bvt.issue_1700; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.util.Date; public class Issue1766 extends TestCase { public void test_for_issue() throws Exception { // succ String json = "{\"name\":\"张三\"\n, \"birthday\":\"2017-01-01 01:01:01\"}"; User user = JSON.parseObject(json, User.class); assertEquals("张三", user.getName()); assertNotNull(user.getBirthday()); // failed json = "{\"name\":\"张三\", \"birthday\":\"2017-01-01 01:01:02\"\n}"; user = JSON.parseObject(json, User.class);// will exception assertEquals("张三", user.getName()); assertNotNull(user.getBirthday()); } public static class User { private String name; @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date birthday; public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1769.java ================================================ 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 java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Issue1769 extends TestCase { protected void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); JSON.defaultLocale = Locale.CHINA; } public void test_for_issue() throws Exception { byte[] newby = "{\"beginTime\":\"420180319160440\"}".getBytes(); QueryTaskResultReq rsp3 = JSON.parseObject(newby, QueryTaskResultReq.class); assertEquals("{\"beginTime\":\"152841225111920\"}", new String(JSON.toJSONBytes(rsp3))); } @JSONType(orders = {"beginTime"}) public static class QueryTaskResultReq { private Date beginTime; @JSONField(format = "yyyyMMddHHmmss") public Date getBeginTime() { return beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1772.java ================================================ package com.alibaba.json.bvt.issue_1700; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.text.SimpleDateFormat; import java.util.Date; public class Issue1772 extends TestCase { public void test_0() throws Exception { Date date = JSON.parseObject("\"-14189155200000\"", Date.class); assertEquals(-14189155200000L, date.getTime()); } public void test_1() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("time", "-14189155200000"); Model m = jsonObject.toJavaObject(Model.class); assertEquals(-14189155200000L, m.time.getTime()); } public static class Model { public Date time; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1780_JSONObject.java ================================================ package com.alibaba.json.bvt.issue_1700; import com.alibaba.fastjson.serializer.SerializerFeature; import org.junit.Assert; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue1780_JSONObject extends TestCase { public void test_for_issue() { org.json.JSONObject req = new org.json.JSONObject(); req.put("id", 1111); req.put("name", "name11"); String text = JSON.toJSONString(req, SerializerFeature.SortField); assertTrue("{\"id\":1111,\"name\":\"name11\"}".equals(text) || "{\"name\":\"name11\",\"id\":1111}".equals(text) ); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1780_Module.java ================================================ package com.alibaba.json.bvt.issue_1700; import java.io.IOException; import java.lang.reflect.Type; import com.alibaba.fastjson.serializer.SerializerFeature; import org.junit.Assert; import com.alibaba.fastjson.JSON; 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 com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.spi.Module; import junit.framework.TestCase; public class Issue1780_Module extends TestCase { public void test_for_issue() { org.json.JSONObject req = new org.json.JSONObject(); SerializeConfig config = new SerializeConfig(); config.register(new myModule()); req.put("id", 1111); req.put("name", "name11"); String text = JSON.toJSONString(req, SerializerFeature.SortField); assertTrue("{\"id\":1111,\"name\":\"name11\"}".equals(text) || "{\"name\":\"name11\",\"id\":1111}".equals(text)); } public class myModule implements Module { @SuppressWarnings("rawtypes") public ObjectDeserializer createDeserializer(ParserConfig config, Class type) { return null; } @SuppressWarnings("rawtypes") public ObjectSerializer createSerializer(SerializeConfig config, Class type) { return new ObjectSerializer() { public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { System.out.println("-------------myModule.createSerializer-------------------"); org.json.JSONObject req = (org.json.JSONObject) object; serializer.out.write(req.toString()); } }; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/Issue1785.java ================================================ package com.alibaba.json.bvt.issue_1700; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue1785 extends TestCase { public void test_for_issue() throws Exception { JSON.parseObject("\"2006-8-9\"", java.sql.Timestamp.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/issue1763_2/TestIssue1763_2.java ================================================ package com.alibaba.json.bvt.issue_1700.issue1763_2; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.alibaba.json.bvt.issue_1700.issue1763_2.bean.BaseResult; import com.alibaba.json.bvt.issue_1700.issue1763_2.bean.CouponResult; import com.alibaba.json.bvt.issue_1700.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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/issue1763_2/TypeReferenceBug1763_2.java ================================================ package com.alibaba.json.bvt.issue_1700.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(); } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/issue1763_2/bean/BaseResult.java ================================================ package com.alibaba.json.bvt.issue_1700.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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/issue1763_2/bean/CouponResult.java ================================================ package com.alibaba.json.bvt.issue_1700.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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1700/issue1763_2/bean/PageResult.java ================================================ package com.alibaba.json.bvt.issue_1700.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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1800/Issue1821.java ================================================ package com.alibaba.json.bvt.issue_1800; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; import junit.framework.TestCase; public class Issue1821 extends TestCase { public void test_for_issue() throws Exception { String str = "{\"type\":800,\"data\":\"HuYgMIxwfqdtvOJNv6kK025g5fh3yFHI2kaByO7udKk6FOBC3PGRWkGfwV0\\/vWQW6roN5ftKDHFZ3PWl0715OYue0rZj\\/VwrNsMvIL4MqTUNBBUGFU9SgZu87ss7RqmyijH6\\/sM968cK1Dv5U7Rrw79idl\\/hW8SILLn1YXvUa60=\"}"; String expectStr = "{\"type\":800,\"data\":\"HuYgMIxwfqdtvOJNv6kK025g5fh3yFHI2kaByO7udKk6FOBC3PGRWkGfwV0/vWQW6roN5ftKDHFZ3PWl0715OYue0rZj/VwrNsMvIL4MqTUNBBUGFU9SgZu87ss7RqmyijH6/sM968cK1Dv5U7Rrw79idl/hW8SILLn1YXvUa60=\"}"; Model m = JSON.parseObject(str, Model.class); assertEquals(expectStr, JSON.toJSONString(m)); str = "{\"type\":800,\"data\":\"Y29tLmFsaWJhYmEuZmFzdGpzb24=\"}"; m = JSON.parseObject(str, Model.class); assertEquals(str, JSON.toJSONString(m)); assertEquals("com.alibaba.fastjson", new String(m.data)); expectStr = str; str = "{\"type\":800,\"data\":\"\\u005929tLmFsaWJ\\u0068YmEuZmFzdGpzb24\\u003d\"}"; m = JSON.parseObject(str, Model.class); assertEquals(expectStr, JSON.toJSONString(m)); assertEquals("com.alibaba.fastjson", new String(m.data)); } @JSONType public static class Model { @JSONField(name="type", ordinal = 1) public int type; @JSONField(name="data", ordinal = 2) public byte[] data; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1800/Issue1834.java ================================================ package com.alibaba.json.bvt.issue_1800; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import junit.framework.TestCase; import java.util.Arrays; import java.util.List; public class Issue1834 extends TestCase { public void test_for_issue() throws Exception { IndexQuery_Number query_number = new IndexQuery_Number(); IndexQuery_Comparable query_comparable = new IndexQuery_Comparable(); List keys = Arrays.asList(1234); query_number.setKeys(keys); query_comparable.setKeys(keys); String json1 = JSON.toJSONString(query_number); System.out.println(json1); IndexQuery_Number queryNumber = JSON.parseObject(json1, new TypeReference(){}); String json2 = JSON.toJSONString(query_comparable); System.out.println(json2); IndexQuery_Comparable queryComparable = JSON.parseObject(json2, new TypeReference(){}); } static class IndexQuery_Comparable{ List keys; public List getKeys() { return keys; } public void setKeys(List keys) { this.keys = keys; } @Override public String toString() { return "IndexQuery{" + "keys=" + keys + '}'; } } static class IndexQuery_Number{ List keys; public List getKeys() { return keys; } public void setKeys(List keys) { this.keys = keys; } @Override public String toString() { return "IndexQuery{" + "keys=" + keys + '}'; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1800/Issue1856.java ================================================ package com.alibaba.json.bvt.issue_1800; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.Labels; import junit.framework.TestCase; public class Issue1856 extends TestCase { public void test_excludes() throws Exception { VO vo = new VO(); vo.setId(123); vo.setName("wenshao"); vo.setPassword("ooxxx"); vo.setInfo("fofo"); String text = JSON.toJSONString(vo, Labels.excludes("AuditIdEntity")); assertEquals("{\"id\":123,\"info\":\"fofo\",\"name\":\"wenshao\"}", text); } public static class VO { private int id; private String name; private String password; private String info; @JSONField(label = "LogicDeleteEntity") public int getId() { return id; } public void setId(int id) { this.id = id; } @JSONField(label = "LogicDeleteEntity") public String getName() { return name; } public void setName(String name) { this.name = name; } @JSONField(label = "AuditIdEntity") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1800/Issue1870.java ================================================ package com.alibaba.json.bvt.issue_1800; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.util.List; public class Issue1870 extends TestCase { public void test_for_issue() throws Exception { } public static class Comment { @JSONField(name = "pic_arr") public List pics; public List getPics() { return pics; } public void setPics(List pics) { this.pics = pics; } } public static class Pic { public int height; public String tburl; public String url; public String width; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1800/Issue1871.java ================================================ package com.alibaba.json.bvt.issue_1800; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; public class Issue1871 extends TestCase { public void test_for_issue() throws Exception { UnwrapClass m = new UnwrapClass(); m.map = new HashMap(); m.name = "ljw"; m.map.put("a", "1"); m.map.put("b", "2"); String json = JSON.toJSONString(m, SerializerFeature.WriteClassName); System.out.println(json); } public static class UnwrapClass { private String name; @JSONField(unwrapped = true) private Map map; public String getName() { return name; } public void setName(String name) { this.name = name; } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1800/Issue1879.java ================================================ package com.alibaba.json.bvt.issue_1800; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONCreator; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; public class Issue1879 extends TestCase { // public void test_for_issue() throws Exception { // String json = "{\n" + // " \"ids\" : \"1,2,3\"\n" + // "}"; // M1 m = JSON.parseObject(json, M1.class); // } public void test_for_issue_2() throws Exception { String json = "{\n" + " \"ids\" : \"1,2,3\"\n" + "}"; M2 m = JSON.parseObject(json, M2.class); } public static class M1 { private List ids; @JSONCreator public M1(@JSONField(name = "ids") String ids) { this.ids = new ArrayList(); for(String id : ids.split(",")) { this.ids.add(Long.valueOf(id)); } } public List getIds() { return ids; } public void setIds(List ids) { this.ids = ids; } } public static class M2 { private List ids; @JSONCreator public M2(@JSONField(name = "ids") Long id) { this.ids = new ArrayList(); this.ids.add(id); } public List getIds() { return ids; } public void setIds(List ids) { this.ids = ids; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1800/Issue1892.java ================================================ package com.alibaba.json.bvt.issue_1800; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.time.LocalDateTime; public class Issue1892 extends TestCase { public void test_for_issue() throws Exception { assertEquals("\"2018-10-10T00:00:00\"", JSON.toJSONString( LocalDateTime.of(2018, 10, 10, 0, 0) ) ); } public void test_for_issue_1() throws Exception { String json = JSON.toJSONString( LocalDateTime.of(2018, 10, 10, 0, 0, 40, 788000000) ); assertEquals("\"2018-10-10T00:00:40.788\"", json); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1800/Issue_for_dianxing.java ================================================ package com.alibaba.json.bvt.issue_1800; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue_for_dianxing extends TestCase { public void test_0() throws Exception { String s = "{\"alarmLevel\":null,\"error\":null,\"errorCount\":0,\"maxAlarmCount\":10,\"warn\":null," + "\"warnCount\":0}"; TopAlarm b = JSON.parseObject(s, TopAlarm.class); System.out.println(JSON.toJSONString(b)); } public static class TopAlarm { private Double error; //为null表示不报警 private int errorCount; private Double warn; //为null表示不报警 private int warnCount; private Integer alarmLevel; private int maxAlarmCount = 10; public TopAlarm() { } public Double getError() { return error; } public void setError(Double error) { this.error = error; } public Double getWarn() { return warn; } public void setWarn(Double warn) { this.warn = warn; } public int getErrorCount() { return errorCount; } public void setErrorCount(int errorCount) { this.errorCount = errorCount; } public int getWarnCount() { return warnCount; } public void setWarnCount(int warnCount) { this.warnCount = warnCount; } public Integer getAlarmLevel() { return alarmLevel; } public void setAlarmLevel(Integer alarmLevel) { this.alarmLevel = alarmLevel; } public int getMaxAlarmCount() { return maxAlarmCount; } public void setMaxAlarmCount(int maxAlarmCount) { this.maxAlarmCount = maxAlarmCount; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1800/Issue_for_float_zero.java ================================================ package com.alibaba.json.bvt.issue_1800; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue_for_float_zero extends TestCase { public void test_0() throws Exception { M1 m = new M1(1.0f); assertEquals("{\"val\":1.0}", JSON.toJSONString(m, SerializerFeature.WriteNullNumberAsZero)); } public void test_1() throws Exception { M2 m = new M2(1.0); assertEquals("{\"val\":1.0}", JSON.toJSONString(m, SerializerFeature.WriteNullNumberAsZero)); } public static class M1 { public float val; public M1(float val) { this.val = val; } } public static class M2 { public double val; public M2(double val) { this.val = val; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1901.java ================================================ package com.alibaba.json.bvt.issue_1900; 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 Issue1901 extends TestCase { protected Locale locale; protected TimeZone timeZone; protected void setUp() throws Exception { locale = JSON.defaultLocale; timeZone = JSON.defaultTimeZone; JSON.defaultLocale = Locale.CHINA; JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); } protected void tearDown() throws Exception { JSON.defaultLocale = locale; JSON.defaultTimeZone = timeZone; } public void test_for_issue() throws Exception { Model m = JSON.parseObject("{\"time\":\"Thu Mar 22 08:58:37 +0000 2018\"}", Model.class); assertEquals("{\"time\":\"星期四 三月 22 16:58:37 CST 2018\"}", JSON.toJSONString(m)); } public void test_for_issue_1() throws Exception { Model m = JSON.parseObject("{\"time\":\"星期四 三月 22 16:58:37 CST 2018\"}", Model.class); assertEquals("{\"time\":\"星期四 三月 22 16:58:37 CST 2018\"}", JSON.toJSONString(m)); } public static class Model { @JSONField(format = "EEE MMM dd HH:mm:ss zzz yyyy") public Date time; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1903.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.beans.Transient; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; public class Issue1903 extends TestCase { public void test_issue() throws Exception { MapHandler mh = new MapHandler(); mh.add("name", "test"); mh.add("age", 20); Issues1903 issues = (Issues1903) Proxy.newProxyInstance(mh.getClass().getClassLoader(), new Class[]{Issues1903.class}, mh); System.out.println(issues.getName()); System.out.println(issues.getAge()); System.out.println(JSON.toJSON(issues).toString()); //正确结果: {"age":20} System.out.println(JSON.toJSONString(issues)); //正确结果: {"age":20} Assert.assertEquals("{\"age\":20}", JSON.toJSON(issues).toString()); Assert.assertEquals("{\"age\":20}", JSON.toJSONString(issues)); } interface Issues1903{ @Transient @JSONField(serialzeFeatures = { SerializerFeature.SkipTransientField }) public String getName(); public void setName(String name); public Integer getAge(); public void setAge(Integer age); } class MapHandler implements InvocationHandler { Map map = new HashMap(); public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName().substring(3); String first = String.valueOf(name.charAt(0)); name = name.replaceFirst(first, first.toLowerCase()); return map.get(name); } public void add(String key, Object val){ map.put(key, val); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1909.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.util.List; public class Issue1909 extends TestCase { public void test_for_issue() throws Exception { JSONArray params = new JSONArray(); params.add("val1"); params.add(2); ParamRequest pr = new ParamRequest("methodName", "stringID", params); System.out.println(JSON.toJSONString(pr)); Request paramRequest = JSON.parseObject(JSON.toJSONString(pr), ParamRequest.class); } public static class ParamRequest extends Request { private String methodName; @JSONField(name = "id", ordinal = 3, serialize = true, deserialize = true) private Object id; private List params; public ParamRequest(String methodName, Object id, List params) { this.methodName = methodName; this.id = id; this.params = params; } public String getMethodName() { return methodName; } public Object getId() { return id; } public List getParams() { return params; } } public static class Request { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1933.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue1933 extends TestCase { public void test_for_issue() throws Exception { OrderInfoVO v0 = JSON.parseObject("{\"orderStatus\":1}", OrderInfoVO.class); assertEquals(1, v0.orderStatus); assertEquals(0, v0.oldStatus); assertEquals(0, v0.oldOrderStatus); } public void test_for_issue_1() throws Exception { OrderInfoVO v0 = JSON.parseObject("{\"oldStatus\":1}", OrderInfoVO.class); assertEquals(0, v0.orderStatus); assertEquals(1, v0.oldStatus); assertEquals(0, v0.oldOrderStatus); } public void test_for_issue_2() throws Exception { OrderInfoVO v0 = JSON.parseObject("{\"oldOrderStatus\":1}", OrderInfoVO.class); assertEquals(0, v0.orderStatus); assertEquals(0, v0.oldStatus); assertEquals(1, v0.oldOrderStatus); } public static class OrderInfoVO { private int orderStatus; private int oldStatus; private int oldOrderStatus; public int getOrderStatus() { return orderStatus; } public void setOrderStatus(int orderStatus) { this.orderStatus = orderStatus; } public int getOldStatus() { return oldStatus; } public void setOldStatus(int oldStatus) { this.oldStatus = oldStatus; } public int getOldOrderStatus() { return oldOrderStatus; } public void setOldOrderStatus(int oldOrderStatus) { this.oldOrderStatus = oldOrderStatus; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1939.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import javax.xml.bind.JAXBContext; import javax.xml.bind.annotation.*; import java.io.Serializable; import java.io.StringReader; import java.util.List; public class Issue1939 extends TestCase { @XmlRootElement(name = "Container") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "any" }) public static class Container implements Serializable { @XmlAnyElement(lax = true) public List any; } private static final String MESSAGE = "" + "0" + ""; public void test_for_issue() throws Exception { JAXBContext context = JAXBContext.newInstance(Container.class, Issue1939.class); Container con = (Container) context.createUnmarshaller().unmarshal(new StringReader(MESSAGE)); assertEquals("{\"any\":[\"0\"]}", JSON.toJSONString(con)); } public void test_for_issue_1() throws Exception { JAXBContext context = JAXBContext.newInstance(Container.class, Issue1939.class); Container con = (Container) context.createUnmarshaller().unmarshal(new StringReader(MESSAGE)); assertEquals("{\"any\":[\"0\"]}", JSON.toJSON(con).toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1941.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONType; import junit.framework.TestCase; public class Issue1941 extends TestCase { public void test_for_issue() throws Exception { String json = "{\"type\":\"floorV2\",\"templateId\":\"x123\",\"name\":\"floorname2\"}"; FloorV2 a=(FloorV2) JSON.parseObject(json,Area.class); assertEquals("floorname2", a.name); assertEquals("x123", a.templateId); } @JSONType(seeAlso = {FloorV2.class}, typeKey = "type") public static interface Area { } @JSONType(typeName = "floorV2") public static class FloorV2 implements Area { public String type; public String templateId; public String name; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1941_JSONField_order.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; import junit.framework.TestCase; public class Issue1941_JSONField_order extends TestCase { public void test_for_issue() throws Exception { String json = "{\"type\":\"floorV2\",\"templateId\":\"x123\",\"name\":\"floorname2\"}"; FloorV2 a=(FloorV2) JSON.parseObject(json,Area.class); assertEquals("floorname2", a.name); assertEquals("x123", a.templateId); } @JSONType(seeAlso = {FloorV2.class}, typeKey = "type") public static interface Area { } @JSONType(typeName = "floorV2") public static class FloorV2 implements Area { @JSONField(ordinal = -1) public String type; public String templateId; public String name; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1944.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue1944 extends TestCase { public void test_for_issue() throws Exception { assertEquals(90.82195113f, JSON.parseObject("{\"value\":90.82195113}", Model.class).value); } public static class Model { public float value; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1945.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import static com.alibaba.fastjson.serializer.SerializerFeature.WriteClassName; public class Issue1945 extends TestCase { public void test_0() throws Exception { B b = new B(); b.clazz = new Class[]{String.class}; b.aInstance = new HashMap(); b.aInstance.put("test", "test"); String s = JSON.toJSONString(b, WriteClassName); System.out.println(s); B a1 = JSON.parseObject(s, B.class); } static class B implements Serializable { public Class[] clazz; public Map aInstance; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1955.java ================================================ package com.alibaba.json.bvt.issue_1900; 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; public class Issue1955 extends TestCase { protected void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); JSON.defaultLocale = Locale.CHINA; } public void test_for_issue() throws Exception { String strVal = "0100-01-27 11:22:00.000"; Date date = JSON.parseObject('"' + strVal + '"', Date.class); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA); df.setTimeZone(JSON.defaultTimeZone); assertEquals(df.parse(strVal), date); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1972.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue1972 extends TestCase { public void test_for_issue() throws Exception { JSONObject jsonObject = new JSONObject(); final JSONObject a = new JSONObject(); final JSONObject b = new JSONObject(); a.put("b", b); b.put("c", "2018-04"); b.put("d", new JSONArray()); Integer obj = Integer.valueOf(123); jsonObject.put("a", a); JSONPath.arrayAdd(jsonObject,"$.a.b[c = '2018-04'].d", obj); assertEquals("{\"a\":{\"b\":{\"c\":\"2018-04\",\"d\":[123]}}}", jsonObject.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1977.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.util.Locale; import java.util.TimeZone; public class Issue1977 extends TestCase { protected void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); JSON.defaultLocale = Locale.CHINA; } public void test_for_issue() throws Exception { java.sql.Date date = new java.sql.Date(1533265119604L); String json = JSON.toJSONString(date, SerializerFeature.UseISO8601DateFormat); assertEquals("\"2018-08-03T10:58:39.604+08:00\"", json); // new java.sql.Date(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1987.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.time.LocalDateTime; public class Issue1987 extends TestCase { public void test_for_issue() throws Exception { JsonExample example = new JsonExample(); //test1 正确执行, test2, test3 执行出错 com.alibaba.fastjson.JSONException: can not cast to : java.time.LocalDateTime example.setTestLocalDateTime(LocalDateTime.now()); //纳秒数设置为0 ,test1,test2,test3 全部正确执行 //example.setTestLocalDateTime(LocalDateTime.now().withNano(0)); String text = JSON.toJSONString(example, SerializerFeature.PrettyFormat); System.out.println(text); //test1, 全部可以正常执行 JsonExample example1 = JSON.parseObject(text, JsonExample.class); System.out.println(JSON.toJSONString(example1)); //test2 纳秒数为0, 可以正常执行, 不为0则报错 JsonExample example2 = JSONObject.parseObject(text).toJavaObject(JsonExample.class); System.out.println(JSON.toJSONString(example2)); //test3 纳秒数为0, 可以正常执行, 不为0则报错 JsonExample example3 = JSON.parseObject(text).toJavaObject(JsonExample.class); System.out.println(JSON.toJSONString(example3)); } public static class JsonExample { private LocalDateTime testLocalDateTime; public LocalDateTime getTestLocalDateTime() { return testLocalDateTime; } public void setTestLocalDateTime(LocalDateTime testLocalDateTime) { this.testLocalDateTime = testLocalDateTime; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_1900/Issue1996.java ================================================ package com.alibaba.json.bvt.issue_1900; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue1996 extends TestCase { public void test_for_issue() throws Exception { StringBuilder sb = new StringBuilder(); char start = '\uD800'; char end = '\uDFFF'; for (char i = start; i <= end; i++) { if (Character.isLowSurrogate(i)) { sb.append(i); } } String s = sb.toString(); // ok String json1 = JSON.toJSONString(s); byte[] bytes = json1.getBytes("utf-8"); byte[] bytes2 = JSON.toJSONBytes(s); assertEquals(new String(bytes), new String(bytes2)); assertEquals(bytes.length, bytes2.length); for (int i = 0; i < bytes.length; i++) { assertEquals(bytes[i], bytes[i]); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2000/Issue2012.java ================================================ package com.alibaba.json.bvt.issue_2000; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue2012 extends TestCase { public void test_for_issue() throws Exception { Model foo = new Model(); foo.bytes = new byte[0]; String str = JSON.toJSONString(foo, SerializerFeature.WriteClassName); assertEquals("{\"@type\":\"com.alibaba.json.bvt.issue_2000.Issue2012$Model\",\"bytes\":x''}", str); ParserConfig config = new ParserConfig(); config.setAutoTypeSupport(true); foo = JSON.parseObject(str, Object.class,config); assertEquals(0, foo.bytes.length); } public static class Model { public byte[] bytes; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2000/Issue2040.java ================================================ package com.alibaba.json.bvt.issue_2000; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.fasterxml.jackson.databind.ObjectMapper; import junit.framework.TestCase; import org.gitlab4j.api.GitLabApi; import org.gitlab4j.api.GitLabApiException; import org.gitlab4j.api.models.AccessLevel; import org.gitlab4j.api.models.Permissions; import org.gitlab4j.api.models.Project; import org.gitlab4j.api.models.Visibility; import java.util.List; public class Issue2040 extends TestCase { final ParserConfig config = new ParserConfig(); protected void setUp() throws Exception { config.setJacksonCompatible(true); } public void test_for_issue_2040() throws Exception { Model model = JSON.parseObject("{\"accessLevel\":30,\"visibility\":\"PUBLIC\"}", Model.class, config); assertSame(AccessLevel.DEVELOPER, model.accessLevel); } public void test_for_issue_2040_2() throws Exception { String json = "{\n" + " \"project_access\": null,\n" + " \"group_access\": {\n" + " \"access_level\": 50,\n" + " \"notification_level\": 3\n" + " }\n" + " }"; ObjectMapper objectMapper = new ObjectMapper(); // Permissions permissions = objectMapper.readValue(json, Permissions.class); Permissions permissions = JSON.parseObject(json, Permissions.class, config); System.out.println(JSON.toJSONString(permissions)); } public static class Model { public AccessLevel accessLevel; public Visibility visibility; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2000/Issue2065.java ================================================ package com.alibaba.json.bvt.issue_2000; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import org.junit.Test; public class Issue2065 extends TestCase { public void test_for_issue() throws Exception { Exception error = null; try { JSON.parseObject("{\"code\":1}", Model.class); } catch (JSONException e) { error = e; } assertNotNull(error); error.printStackTrace(); } public void test_for_issue_01() { Exception error = null; try { JSON.parseObject("1", EnumClass.class); } catch (JSONException e) { error = e; } assertNotNull(error); error.printStackTrace(); } @Test public void test_for_issue_02() { JSON.parseObject("0", EnumClass.class); } @Test public void test_for_issue_03() { JSON.parseObject("{\"code\":0}", Model.class); } public static class Model { @JSONField(name = "code") private EnumClass code; public Model() {} public EnumClass getCode() { return code; } public void setCode(EnumClass code) { this.code = code; } } public static enum EnumClass { A(1); @JSONField private int code; EnumClass(int code) { this.code = code; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2000/Issue2066.java ================================================ package com.alibaba.json.bvt.issue_2000; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.List; public class Issue2066 extends TestCase { public void test_issue() throws Exception { JSON.parseObject("{\"values\":[[1,2],[3,4]]}", Model.class); } public static class Model { private List values; public List getValues() { return values; } public void setValues(List values) { this.values = values; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2000/Issue2074.java ================================================ package com.alibaba.json.bvt.issue_2000; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue2074 extends TestCase { public void test_for_issue() throws Exception { JSONObject object = new JSONObject(); object.put("name", null); assertEquals("{\"name\":null}" , object.toString(SerializerFeature.WriteMapNullValue)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2000/Issue2086.java ================================================ package com.alibaba.json.bvt.issue_2000; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue2086 extends TestCase { public void test_for_issue() throws Exception { JSON.parseObject("{\"id\":123}", Model.class); JSON.toJSONString(new Model()); } public static class Model { public void set() { } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2000/Issue2088.java ================================================ package com.alibaba.json.bvt.issue_2000; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Issue2088 extends TestCase { protected void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); JSON.defaultLocale = Locale.CHINA; } public void test_for_issue() throws Exception { String json = "{\"date\":\"20181011103607186+0800\"}"; Model m = JSON.parseObject(json, Model.class); SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSSZ"); format.setTimeZone(JSON.defaultTimeZone); Date date = format.parse("20181011103607186+0800"); assertEquals(date, m.date); } public void test_for_issue_1() throws Exception { String json = "{\"date\":\"20181011103607186-0800\"}"; Model m = JSON.parseObject(json, Model.class); SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSSZ", JSON.defaultLocale); format.setTimeZone(JSON.defaultTimeZone); Date date = format.parse("20181011103607186-0800"); assertEquals(date, m.date); } public static class Model { @JSONField(format = "yyyyMMddHHmmssSSSZ") public Date date; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2100/Issue2129.java ================================================ package com.alibaba.json.bvt.issue_2100; import com.alibaba.fastjson.JSON; import com.google.common.collect.LinkedHashMultimap; import junit.framework.TestCase; public class Issue2129 extends TestCase { public void test_for_issue() throws Exception { LinkedHashMultimap map = LinkedHashMultimap.create(); map.put("a", "1"); map.put("a", "b"); map.put("b", "1"); String json = JSON.toJSONString(map); assertEquals("{\"a\":[\"1\",\"b\"],\"b\":[\"1\"]}", json); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2100/Issue2130.java ================================================ package com.alibaba.json.bvt.issue_2100; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; public class Issue2130 extends TestCase { public void test_for_issue() throws Exception { String str = "{\"score\":0.000099369485}"; JSONObject object = JSON.parseObject(str); assertEquals("{\"score\":0.000099369485}", object.toJSONString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2100/Issue2132.java ================================================ package com.alibaba.json.bvt.issue_2100; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; public class Issue2132 extends TestCase { public void test_for_issue() throws Exception { Cpu cpu = new Cpu("intel", 3.3); Screen screen = new Screen(16, 9, "samsung"); Student student = new Student(); Computer computer = student.assembling(cpu,screen); cpu.setName("intell"); Object[] objectArray = new Object[4]; objectArray[0] = cpu; objectArray[1] = screen; objectArray[2] = "2"; objectArray[3] = "3"; List list1 = new ArrayList(); list1.add(objectArray); list1.add(computer); String s = JSON.toJSONString(list1); assertEquals("[[{\"name\":\"intell\",\"speed\":3.3},{\"height\":9,\"name\":\"samsung\",\"width\":16},\"2\",\"3\"],{\"cpu\":{\"$ref\":\"$[0][0]\"},\"screen\":{\"$ref\":\"$[0][1]\"}}]", s); } public static class Cpu { private String name; private double speed; public Cpu(String name, double speed) { this.name = name; this.speed = speed; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSpeed() { return speed; } public void setSpeed(double speed) { this.speed = speed; } } public static class Screen { private int width; private int height; private String name; public Screen(int width, int height, String name) { this.width = width; this.height = height; this.name = name; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static class Computer { Cpu cpu; Screen screen; public Computer(Cpu cpu, Screen screen) { this.cpu = cpu; this.screen = screen; } public Cpu getCpu() { return cpu; } public void setCpu(Cpu cpu) { this.cpu = cpu; } public Screen getScreen() { return screen; } public void setScreen(Screen screen) { this.screen = screen; } } public static class Student { private Cpu cpu; private Screen screen; public Computer assembling(Cpu cpu, Screen screen) { this.cpu = cpu; this.screen = screen; return new Computer(cpu, screen); } public Cpu getCpu() { return cpu; } public void setCpu(Cpu cpu) { this.cpu = cpu; } public Screen getScreen() { return screen; } public void setScreen(Screen screen) { this.screen = screen; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2100/Issue2150.java ================================================ package com.alibaba.json.bvt.issue_2100; import com.alibaba.fastjson.JSONArray; import junit.framework.TestCase; public class Issue2150 extends TestCase { public void test_for_issue() throws Exception { int [][][] arr = new int[100][100][100]; JSONArray jsonObj = (JSONArray) JSONArray.toJSON(arr); assertNotNull(jsonObj); assertNotNull(jsonObj.getJSONArray(0)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2100/Issue2156.java ================================================ package com.alibaba.json.bvt.issue_2100; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.TimeZone; public class Issue2156 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 sf = new SimpleDateFormat("yyyy-MM-dd"); // sf.setTimeZone(JSON.defaultTimeZone); // java.sql.Date date = new java.sql.Date(sf.parse("2018-07-15").getTime()); // String str = JSON.toJSONStringWithDateFormat(date, JSON.DEFFAULT_DATE_FORMAT); // assertEquals("\"2018-07-15\"", str); // } // // public void test_for_issue1() throws Exception { // SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); // sf.setTimeZone(JSON.defaultTimeZone); // java.sql.Date date = new java.sql.Date(sf.parse("2018-07-15").getTime()); // String str = JSON.toJSONStringWithDateFormat(date, JSON.DEFFAULT_DATE_FORMAT); // assertEquals("\"2018-07-15\"", str); // } // // public void test_for_issue2() throws Exception { // SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); // sf.setTimeZone(JSON.defaultTimeZone); // java.sql.Date date = java.sql.Date.valueOf("2018-07-15"); // String str = JSON.toJSONStringWithDateFormat(date, JSON.DEFFAULT_DATE_FORMAT); // assertEquals("\"2018-07-15\"", str); // } public void test_for_issue_time() throws Exception { java.sql.Time date = java.sql.Time.valueOf("12:13:14"); String str = JSON.toJSONStringWithDateFormat(date, JSON.DEFFAULT_DATE_FORMAT); assertEquals("\"12:13:14\"", str); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2100/Issue2164.java ================================================ package com.alibaba.json.bvt.issue_2100; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue2164 extends TestCase { public void test_for_issue() throws Exception { java.sql.Timestamp ts = new java.sql.Timestamp(-65001600000L); String json = JSON.toJSONString(ts); assertEquals("-65001600000", json); java.sql.Timestamp ts2 = JSON.parseObject(json, java.sql.Timestamp.class); assertEquals(ts.getTime(), ts2.getTime()); } public void test_for_issue_1() throws Exception { Model m = new Model(-65001600000L); String json = JSON.toJSONString(m); assertEquals("{\"time\":-65001600000}", json); Model m2 = JSON.parseObject(json, Model.class); assertEquals(m.time.getTime(), m2.time.getTime()); } public static class Model { public java.sql.Timestamp time; public Model() { } public Model(long ts) { this.time = new java.sql.Timestamp(ts); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2100/Issue2165.java ================================================ package com.alibaba.json.bvt.issue_2100; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; public class Issue2165 extends TestCase { public void test_for_issue() throws Exception { Exception error = null; try { JSON.parseObject("9295260120", Integer.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertEquals("parseInt error", error.getMessage()); } public void test_for_issue_1() throws Exception { Exception error = null; try { JSON.parseObject("{\"value\":9295260120}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertEquals("parseInt error, field : value", error.getMessage()); } public void test_for_issue_2() throws Exception { Exception error = null; try { JSON.parseObject("[9295260120]", Model.class, Feature.SupportArrayToBean); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertEquals("parseInt error : 9295260120", error.getMessage()); } public static class Model { public int value; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2100/Issue2179.java ================================================ package com.alibaba.json.bvt.issue_2100; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Type; 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.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.JSONSerializer; import com.alibaba.fastjson.serializer.ObjectSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.serializer.StringCodec; import com.alibaba.fastjson.spi.Module; import junit.framework.TestCase; public class Issue2179 extends TestCase { // 场景:序列化 public void test_for_issue() throws Exception { Model1 model = new Model1(ProductType1.Phone, ProductType1.Computer); String out = "{\"l_k_assbalv4\":{\"code\":1,\"prompt\":\"手机\"},\"type1\":{\"code\":2,\"prompt\":\"电脑\"}}"; Assert.assertEquals(out, JSON.toJSONString(model)); } // 场景:使用@JSONType的deserializer = EnumAwareSerializer1.class测试自定义反序列化器 public void test_for_issue2() { String str = "{\"l_k_assbalv4\":{\"code\":1,\"prompt\":\"手机\"},\"type1\":{\"code\":2,\"prompt\":\"电脑\"}}"; Model1 model = JSON.parseObject(str, Model1.class); String out = "{\"l_k_assbalv4\":{\"code\":1,\"prompt\":\"手机\"},\"type1\":{\"code\":2,\"prompt\":\"电脑\"}}"; Assert.assertEquals(out, JSON.toJSONString(model)); } // 场景:使用@JSONField的deserializeUsing = EnumAwareSerializer2.class测试自定义测试自定义反序化器 public void test_for_issue3() { // l_k_assbalv4对应Model2中的Type走自定义,type1走默认枚举反序列化 String str = "{\"l_k_assbalv4\":{\"code\":1,\"prompt\":\"手机\"},\"type1\":\"Computer\"}"; Model2 model = JSON.parseObject(str, Model2.class); String out = "{\"l_k_assbalv4\":{\"code\":1,\"prompt\":\"手机\"},\"type1\":{\"code\":2,\"prompt\":\"电脑\"}}"; Assert.assertEquals(out, JSON.toJSONString(model)); } // 场景:使用Module public void test_for_issue4() { ParserConfig config = new ParserConfig(); config.register(new MyModuel()); String str = "{\"type\":\"Phone\",\"type1\":\"Computer\"}"; Model3 model = JSON.parseObject(str, Model3.class, config); String out = "{\"type\":{\"code\":2,\"prompt\":\"电脑\"},\"type1\":{\"code\":1,\"prompt\":\"手机\"}}"; Assert.assertEquals(out, JSON.toJSONString(model)); } interface EnumAware { int getCode(); String getPrompt(); } @JSONType(serializeEnumAsJavaBean = true, deserializer = EnumAwareSerializer1.class) public static enum ProductType1 implements EnumAware { Phone(1, "手机"), Computer(2, "电脑"); public final int code; public final String prompt; ProductType1(int code, String prompt) { this.code = code; this.prompt = prompt; } @Override public int getCode() { return this.code; } @Override public String getPrompt() { return this.prompt; } public static ProductType1 get(int code) { switch (code) { case 1: return Phone; case 2: return Computer; default: return null; } } } public static class Model1 { @JSONField(name = "l_k_assbalv4") private ProductType1 type; private ProductType1 type1; public Model1(ProductType1 type, ProductType1 type1) { this.type = type; this.type1 = type1; } public ProductType1 getType() { return type; } public void setType(ProductType1 type) { this.type = type; } public ProductType1 getType1() { return type1; } public void setType1(ProductType1 type1) { this.type1 = type1; } } @JSONType(serializeEnumAsJavaBean = true) public static enum ProductType2 implements EnumAware { Phone(1, "手机"), Computer(2, "电脑"); public final int code; public final String prompt; ProductType2(int code, String prompt) { this.code = code; this.prompt = prompt; } @Override public int getCode() { return this.code; } @Override public String getPrompt() { return this.prompt; } public static ProductType2 get(int code) { switch (code) { case 1: return Phone; case 2: return Computer; default: return null; } } } public static class Model2 { @JSONField(name = "l_k_assbalv4", deserializeUsing = EnumAwareSerializer2.class) private ProductType2 type; private ProductType2 type1; public Model2(ProductType2 type, ProductType2 type1) { this.type = type; this.type1 = type1; } public ProductType2 getType() { return type; } public void setType(ProductType2 type) { this.type = type; } public ProductType2 getType1() { return type1; } public void setType1(ProductType2 type1) { this.type1 = type1; } } @JSONType(serializeEnumAsJavaBean = true) public static enum ProductType3 implements EnumAware { Phone(1, "手机"), Computer(2, "电脑"); public final int code; public final String prompt; @Override public int getCode() { return this.code; } ProductType3(int code, String prompt) { this.code = code; this.prompt = prompt; } @Override public String getPrompt() { return this.prompt; } public static ProductType3 get(int code) { switch (code) { case 1: return Phone; case 2: return Computer; default: return null; } } } public static class Model3 { private ProductType3 type; private ProductType3 type1; public Model3(ProductType3 type, ProductType3 type1) { this.type = type; this.type1 = type1; } public ProductType3 getType() { return type; } public void setType(ProductType3 type) { this.type = type; } public ProductType3 getType1() { return type1; } public void setType1(ProductType3 type1) { this.type1 = type1; } } public static class EnumAwareSerializer1 implements ObjectDeserializer { @SuppressWarnings("unchecked") public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { String val = StringCodec.instance.deserialze(parser, type, fieldName); System.out.println("-----------------EnumAwareSerializer1.deserialze-----------------------------"); System.out.println(val); return (T) ProductType1.get(JSON.parseObject(val).getInteger("code")); } @Override public int getFastMatchToken() { return JSONToken.LITERAL_STRING; } } public static class EnumAwareSerializer2 implements ObjectDeserializer { @SuppressWarnings("unchecked") public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { String val = StringCodec.instance.deserialze(parser, type, fieldName); System.out.println("-----------------EnumAwareSerializer2.deserialze-----------------------------"); System.out.println(val); return (T) ProductType2.get(JSON.parseObject(val).getInteger("code")); } @Override public int getFastMatchToken() { return JSONToken.LITERAL_STRING; } } public static class MyModuel implements Module { @SuppressWarnings("rawtypes") @Override public ObjectDeserializer createDeserializer(ParserConfig config, Class type) { return new ObjectDeserializer() { @SuppressWarnings("unchecked") @Override public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { String val = StringCodec.instance.deserialze(parser, type, fieldName); System.out.println("-----------MyModuel.deserialze------------------------"); System.out.println(val); try { Constructor c = Class.forName(type.getTypeName()).getDeclaredConstructor(ProductType3.class, ProductType3.class); return (T) c.newInstance(ProductType3.Computer, ProductType3.Phone); } catch (Exception e) { e.printStackTrace(); return null; } } @Override public int getFastMatchToken() { return JSONToken.LITERAL_STRING; } }; } @SuppressWarnings("rawtypes") @Override public ObjectSerializer createSerializer(SerializeConfig config, Class type) { return new ObjectSerializer() { @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; } System.err.println("--------------MyModuel.write-------------------------"); StringCodec.instance.write(serializer, ((ProductType3) object).name(), fieldName, fieldType, features); } }; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2100/Issue2182.java ================================================ package com.alibaba.json.bvt.issue_2100; import com.alibaba.fastjson.JSON; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import junit.framework.TestCase; public class Issue2182 extends TestCase { public void test_for_issue() throws Exception { Multimap multimap = ArrayListMultimap.create(); multimap.put("admin", "admin.create"); multimap.put("admin", "admin.update"); multimap.put("admin", "admin.delete"); multimap.put("user", "user.create"); multimap.put("user", "user.delete"); String json = JSON.toJSONString(multimap); assertEquals("{\"admin\":[\"admin.create\",\"admin.update\",\"admin.delete\"],\"user\":[\"user.create\",\"user.delete\"]}", json); ArrayListMultimap multimap1 = JSON.parseObject(json, ArrayListMultimap.class); assertEquals(multimap.size(), multimap1.size()); assertEquals(json, JSON.toJSONString(multimap1)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2100/Issue2185.java ================================================ package com.alibaba.json.bvt.issue_2100; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.Date; import java.util.HashMap; public class Issue2185 extends TestCase { public void test_for_issue() throws Exception { Exception error = null; try { JSONObject origin = new JSONObject(); JSONArray jsonArray = new JSONArray().fluentAdd(origin.getInnerMap()); jsonArray.getJSONObject(0).put("key", "value"); // now we expect jsonArray is [{"key":"value"}] assertEquals(1, jsonArray.getJSONObject(0).size()); assertTrue(origin.getInnerMap() == jsonArray.getJSONObject(0).getInnerMap()); } catch (JSONException ex) { error = ex; } assertNull(error); } /** * To prove casting from Map<Object,Object> won't cause exception * * @throws Exception */ public void test_for_issue_1() throws Exception { Exception error = null; try { HashMap origin = new HashMap(); origin.put(new Object(), "value"); JSONArray jsonArray = new JSONArray().fluentAdd(origin); jsonArray.getJSONObject(0); // now jsonArray is [{{}:"value"}] assertEquals(1, jsonArray.getJSONObject(0).size()); } catch (JSONException ex) { error = ex; } assertNull(error); } /** * To prove casting from Map<primitive type, Object> won't cause exception * * @throws Exception */ public void test_for_issue_2() throws Exception { Exception error = null; try { HashMap origin = new HashMap(); origin.put(5.3f, "value"); JSONArray jsonArray = new JSONArray().fluentAdd(origin); jsonArray.getJSONObject(0); // now jsonArray is [{5.3:"value"}] assertEquals(1, jsonArray.getJSONObject(0).size()); } catch (JSONException ex) { error = ex; } assertNull(error); } /** * To prove casting from Map<Date, Object> won't cause exception * * @throws Exception */ public void test_for_issue_3() throws Exception { Exception error = null; try { HashMap origin = new HashMap(); origin.put(new Date(), "value"); JSONArray jsonArray = new JSONArray().fluentAdd(origin); jsonArray.getJSONObject(0); // now jsonArray is [{154xxxxxxxxx:"value"}] assertEquals(1, jsonArray.getJSONObject(0).size()); } catch (JSONException ex) { error = ex; } assertNull(error); } public static class Model { public int value; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2100/Issue2189.java ================================================ package com.alibaba.json.bvt.issue_2100; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue2189 extends TestCase { public void test_for_issue() throws Exception { String str = "[{\"id\":\"1\",\"name\":\"a\"},{\"id\":\"2\",\"name\":\"b\"}]"; assertEquals("[\"1\",\"2\"]", JSONPath.extract(str, "$.*.id") .toString() ); } public void test_for_issue_1() throws Exception { String str = "[{\"id\":\"1\",\"name\":\"a\"},{\"id\":\"2\",\"name\":\"b\"}]"; assertEquals("[\"2\"]", JSONPath.extract(str, "$.*[?(@.name=='b')].id") .toString() ); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2201.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue2201 extends TestCase { public void test_for_issue() throws Exception { ParserConfig.getGlobalInstance().register("M2001", Model.class); String json = "{\"@type\":\"M2001\",\"id\":3}"; Model m = (Model) JSON.parseObject(json, Object.class); assertEquals(3, m.id); } public static class Model { public int id; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2206.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.time.LocalDateTime; public class Issue2206 extends TestCase { public void test_for_issue() throws Exception { JSON.parseObject("{\"date\":\"20181229162849\"}", Model.class); } public static class Model { public LocalDateTime date; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2214.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class Issue2214 extends TestCase { public void test_for_issue() throws Exception { List list = new ArrayList(); list.add("robin"); Object[] args = new Object[]{new List[][]{new List[]{list}}}; String text = JSON.toJSONString(args); Class clazz = User.class; Method method = clazz.getMethod("testGenericArrayArray2", List[][].class); Type[] types = method.getGenericParameterTypes(); List argList = JSON.parseArray(text, types); Object res = new User().testGenericArrayArray2((List[][]) argList.get(0)); System.out.println(res); } public static class User { public List[][] testGenericArrayArray2(List[][] res){ return res; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2216.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.util.Date; public class Issue2216 extends TestCase { public void test_for_issue() throws Exception { Model model = JSON.parseObject("{\"value\":\"20181229162849000+0800\"}", Model.class); assertNotNull(model); assertNotNull(model.value); assertEquals(1546072129000L, model.value.getTime()); } public void test_for_issue_2() throws Exception { Model model = JSON.parseObject("{\"value\":\"20181229162849000+0800\"}").toJavaObject(Model.class); assertNotNull(model); assertNotNull(model.value); assertEquals(1546072129000L, model.value.getTime()); } public static class Model { @JSONField(format = "yyyyMMddHHmmssSSSZ") public Date value; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2224.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import com.alibaba.json.bvt.issue_2200.issue2224.PersonCollection; import com.alibaba.json.bvt.issue_2200.issue2224_2.PersonGroupedCollection; import com.alibaba.json.bvt.issue_2200.issue2224_3.ArrayPersonGroupedCollection; import com.alibaba.json.bvt.issue_2200.issue2224_4.MAPersonGroupedCollection; import com.alibaba.json.bvt.issue_2200.issue2224_5.MA2PersonGroupedCollection; import junit.framework.TestCase; public class Issue2224 extends TestCase { //support inherit with other parameterized type public void test_for_issue() { String json = "[{\"idNo\":\"123456\",\"name\":\"tom\"},{\"idNo\":\"123457\",\"name\":\"jack\"}]"; PersonCollection personCollection = JSON.parseObject(json, PersonCollection.class); assertNotNull(personCollection); assertEquals(2, personCollection.size()); assertEquals("tom", personCollection.get("123456").getName()); assertEquals("jack", personCollection.get("123457").getName()); String json2 = JSON.toJSONString(personCollection); assertNotNull(json2); } //support inherit with other parameterized type and item type is generic public void test_for_issue_2() { String json = "[[{\"idNo\":\"123\",\"name\":\"张三\"},{\"idNo\":\"124\",\"name\":\"张三\"}],[{\"idNo\":\"223\",\"name\":\"李四\"},{\"idNo\":\"224\",\"name\":\"李四\"}]]"; PersonGroupedCollection personCollection = JSON.parseObject(json, PersonGroupedCollection.class); assertNotNull(personCollection); assertEquals(2, personCollection.size()); assertEquals(2, personCollection.get("张三").size()); assertEquals("123", personCollection.get("张三").get(0).getIdNo()); assertEquals("张三", personCollection.get("张三").get(0).getName()); assertEquals("124", personCollection.get("张三").get(1).getIdNo()); assertEquals("张三", personCollection.get("张三").get(1).getName()); assertEquals(2, personCollection.get("李四").size()); assertEquals("223", personCollection.get("李四").get(0).getIdNo()); assertEquals("李四", personCollection.get("李四").get(0).getName()); assertEquals("224", personCollection.get("李四").get(1).getIdNo()); assertEquals("李四", personCollection.get("李四").get(1).getName()); String json2 = JSON.toJSONString(personCollection); assertNotNull(json2); } //support inherit with other parameterized type and item type is bean array public void test_for_issue_3() { String json = "[[{\"idNo\":\"123\",\"name\":\"张三\"},{\"idNo\":\"124\",\"name\":\"张三\"}],[{\"idNo\":\"223\",\"name\":\"李四\"},{\"idNo\":\"224\",\"name\":\"李四\"}]]"; ArrayPersonGroupedCollection personCollection = JSON.parseObject(json, ArrayPersonGroupedCollection.class); assertNotNull(personCollection); assertEquals(2, personCollection.size()); assertEquals(2, personCollection.get("张三").length); assertEquals("123", personCollection.get("张三")[0].getIdNo()); assertEquals("张三", personCollection.get("张三")[0].getName()); assertEquals("124", personCollection.get("张三")[1].getIdNo()); assertEquals("张三", personCollection.get("张三")[1].getName()); assertEquals(2, personCollection.get("李四").length); assertEquals("223", personCollection.get("李四")[0].getIdNo()); assertEquals("李四", personCollection.get("李四")[0].getName()); assertEquals("224", personCollection.get("李四")[1].getIdNo()); assertEquals("李四", personCollection.get("李四")[1].getName()); String json2 = JSON.toJSONString(personCollection); assertNotNull(json2); } //support inherit with other parameterized type and item type is generic array public void test_for_issue_4() { String json = "[[{\"idNo\":\"123\",\"name\":\"张三\"},{\"idNo\":\"124\",\"name\":\"张三\"}],[{\"idNo\":\"223\",\"name\":\"李四\"},{\"idNo\":\"224\",\"name\":\"李四\"}]]"; MAPersonGroupedCollection personCollection = JSON.parseObject(json, MAPersonGroupedCollection.class); assertNotNull(personCollection); assertEquals(2, personCollection.size()); assertEquals(2, personCollection.get("张三").length); assertEquals("123", personCollection.get("张三")[0].get("idNo")); assertEquals("张三", personCollection.get("张三")[0].get("name")); assertEquals("124", personCollection.get("张三")[1].get("idNo")); assertEquals("张三", personCollection.get("张三")[1].get("name")); assertEquals(2, personCollection.get("李四").length); assertEquals("223", personCollection.get("李四")[0].get("idNo")); assertEquals("李四", personCollection.get("李四")[0].get("name")); assertEquals("224", personCollection.get("李四")[1].get("idNo")); assertEquals("李四", personCollection.get("李四")[1].get("name")); String json2 = JSON.toJSONString(personCollection); assertNotNull(json2); } //support inherit with other parameterized type and item type is generic array contains array public void test_for_issue_5() { String json = "[[{\"idNo\":[\"123\",\"123x\"],\"name\":[\"张三\",\"张三一\"]},{\"idNo\":[\"124\",\"124x\"],\"name\":[\"张三\",\"张三一\"]}],[{\"idNo\":[\"223\",\"223y\"],\"name\":[\"李四\",\"李小四\"]},{\"idNo\":[\"224\",\"224y\"],\"name\":[\"李四\",\"李小四\"]}]]"; MA2PersonGroupedCollection personCollection = JSON.parseObject(json, MA2PersonGroupedCollection.class); assertNotNull(personCollection); assertEquals(2, personCollection.size()); assertEquals(2, personCollection.get("张三").length); assertEquals(2, personCollection.get("张三")[0].get("idNo").length); assertEquals("123", personCollection.get("张三")[0].get("idNo")[0]); assertEquals("123x", personCollection.get("张三")[0].get("idNo")[1]); assertEquals(2, personCollection.get("张三")[0].get("name").length); assertEquals("张三", personCollection.get("张三")[0].get("name")[0]); assertEquals("张三一", personCollection.get("张三")[0].get("name")[1]); assertEquals(2, personCollection.get("张三")[1].get("idNo").length); assertEquals("124", personCollection.get("张三")[1].get("idNo")[0]); assertEquals("124x", personCollection.get("张三")[1].get("idNo")[1]); assertEquals(2, personCollection.get("张三")[1].get("name").length); assertEquals("张三", personCollection.get("张三")[1].get("name")[0]); assertEquals("张三一", personCollection.get("张三")[1].get("name")[1]); assertEquals(2, personCollection.get("李四").length); assertEquals(2, personCollection.get("李四")[0].get("idNo").length); assertEquals("223", personCollection.get("李四")[0].get("idNo")[0]); assertEquals("223y", personCollection.get("李四")[0].get("idNo")[1]); assertEquals(2, personCollection.get("李四")[0].get("name").length); assertEquals("李四", personCollection.get("李四")[0].get("name")[0]); assertEquals("李小四", personCollection.get("李四")[0].get("name")[1]); assertEquals(2, personCollection.get("李四")[1].get("idNo").length); assertEquals("224", personCollection.get("李四")[1].get("idNo")[0]); assertEquals("224y", personCollection.get("李四")[1].get("idNo")[1]); assertEquals(2, personCollection.get("李四")[1].get("name").length); assertEquals("李四", personCollection.get("李四")[1].get("name")[0]); assertEquals("李小四", personCollection.get("李四")[1].get("name")[1]); String json2 = JSON.toJSONString(personCollection); assertNotNull(json2); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2229.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.Date; public class Issue2229 extends TestCase { public void test_for_issue() throws Exception { Jon jon = JSON.parseObject("{\"dStr\":\" hahahaha \",\"user\":{\"createtime\":null,\"id\":0,\"username\":\" asdfsadf asdf asdf \"}}", Jon.class); assertEquals(" asdfsadf asdf asdf ", jon.user.username); } public void test_for_issue1() throws Exception { Jon jon1 = JSON.parseObject("{'dStr':' hahahaha ','user':{'createtime':null,'id':0,'username':' asdfsadf asdf asdf '}}", Jon.class); assertEquals(" asdfsadf asdf asdf ", jon1.user.username); } public static class Jon { public String dStr; public User user; } public static class User { public int id; public Date createtime; public String username; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2234.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.List; public class Issue2234 extends TestCase { public void test_for_issue() throws Exception { String userStr = "{\"name\":\"asdfad\",\"ss\":\"\"}"; User user = JSON.parseObject(userStr, User.class); } public static class User { public String name; public List ss; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2238.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.math.BigDecimal; public class Issue2238 extends TestCase { public void test_for_issue() throws Exception { CapitalLimitMonenyDTO capitalLimitMonenyDTO =new CapitalLimitMonenyDTO(); capitalLimitMonenyDTO.setMaxChargeMoney(new BigDecimal("200000")); capitalLimitMonenyDTO.setMinChargeMoney(new BigDecimal(0.01)); capitalLimitMonenyDTO.setMaxWithdrawMoney(new BigDecimal(0.01)); capitalLimitMonenyDTO.setMinWithdrawMoney(new BigDecimal("500000")); System.out.println(JSON.toJSONString(capitalLimitMonenyDTO)); } public static class CapitalLimitMonenyDTO { private BigDecimal maxChargeMoney; private BigDecimal minChargeMoney; private BigDecimal maxWithdrawMoney; private BigDecimal minWithdrawMoney; public BigDecimal getMaxChargeMoney() { return maxChargeMoney; } public void setMaxChargeMoney(BigDecimal maxChargeMoney) { this.maxChargeMoney = maxChargeMoney; } public BigDecimal getMinChargeMoney() { return minChargeMoney; } public void setMinChargeMoney(BigDecimal minChargeMoney) { this.minChargeMoney = minChargeMoney; } public BigDecimal getMaxWithdrawMoney() { return maxWithdrawMoney; } public void setMaxWithdrawMoney(BigDecimal maxWithdrawMoney) { this.maxWithdrawMoney = maxWithdrawMoney; } public BigDecimal getMinWithdrawMoney() { return minWithdrawMoney; } public void setMinWithdrawMoney(BigDecimal minWithdrawMoney) { this.minWithdrawMoney = minWithdrawMoney; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2239.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import junit.framework.TestCase; import java.util.List; public class Issue2239 extends TestCase { public void test_for_issue() throws Exception { String json = "{\"page\":{}}"; BaseResponse bean = JSON.parseObject(json, new TypeReference>() { }); // bean.getPage().getList(); // 得到的是空 } public static class Bean { } public static class BaseResponse { private PageBean page; public PageBean getPage() { return page; } } public static class PageBean { private List list; public List getList() { return list; } public void setList(List list) { this.list = list; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2240.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.Collections; import java.util.Map; public class Issue2240 extends TestCase { public void test_for_issue() throws Exception { ResultMap resultMap = new ResultMap(); resultMap.setA(Collections.emptyMap()); resultMap.setB(Collections.emptyMap()); assertEquals("{\"a\":{},\"b\":{}}", JSON.toJSONString(resultMap)); } public static class ResultMap { private Map a; private Map b; public Map getA() { return a; } public void setA(Map a) { this.a = a; } public Map getB() { return b; } public void setB(Map b) { this.b = b; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2241.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import org.joda.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Issue2241 extends TestCase { protected void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); JSON.defaultLocale = Locale.CHINA; } public void test_for_issue() throws Exception { String text = "{\"createTime\":1548166745}"; Order o = JSON.parseObject(text, Order.class); assertEquals(1548166745000L, o.createTime.getTime()); String json = JSON.toJSONString(o); assertEquals("{\"createTime\":1548166745}", json); } public void test_for_issue2() throws Exception { String text = "{\"createTime\":1548166745}"; Order2 o = JSON.parseObject(text, Order2.class); assertEquals(1548166745000L, o.createTime.getTimeInMillis()); String json = JSON.toJSONString(o); assertEquals("{\"createTime\":1548166745}", json); } public void test_for_issue3() throws Exception { String text = "{\"createTime\":\"20180714224948\"}"; Order3 o = JSON.parseObject(text, Order3.class); assertEquals(1531579788000L, o.createTime.getTimeInMillis()); String json = JSON.toJSONString(o); assertEquals("{\"createTime\":\"20180714224948\"}", json); } public void test_for_issue4() throws Exception { String text = "{\"createTime\":1548166745}"; Order4 o = JSON.parseObject(text, Order4.class); assertEquals(1548166745L, o.createTime.toEpochSecond()); String json = JSON.toJSONString(o); assertEquals("{\"createTime\":1548166745}", json); } public static class Order { @JSONField(format = "unixtime") public Date createTime; } public static class Order2 { @JSONField(format = "unixtime") public Calendar createTime; } public static class Order3 { @JSONField(format = "yyyyMMddHHmmss") public Calendar createTime; } public static class Order4 { @JSONField(format = "unixtime") public ZonedDateTime createTime; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2244.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.Date; public class Issue2244 extends TestCase { public void test_for_issue() throws Exception { String str = "\"2019-01-14T06:32:09.029Z\""; JSON.parseObject(str, Date.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2249.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; public class Issue2249 extends TestCase { public void test_for_issue() throws Exception { assertSame(Type.Big, JSON.parseObject("\"big\"", Type.class)); assertSame(Type.Big, JSON.parseObject("\"Big\"", Type.class)); assertSame(Type.Big, JSON.parseObject("\"BIG\"", Type.class)); assertSame(Type.Small, JSON.parseObject("\"Small\"", Type.class)); assertSame(Type.Small, JSON.parseObject("\"small\"", Type.class)); assertSame(Type.Small, JSON.parseObject("\"SMALL\"", Type.class)); assertSame(Type.Medium, JSON.parseObject("\"medium\"", Type.class)); assertSame(Type.Medium, JSON.parseObject("\"MEDIUM\"", Type.class)); assertSame(Type.Medium, JSON.parseObject("\"Medium\"", Type.class)); assertSame(Type.Medium, JSON.parseObject("\"MediuM\"", Type.class)); assertNull(JSON.parseObject("\"\"", Type.class)); } public void test_for_issue_1() throws Exception { assertSame(Type.Big, JSON.parseObject("{\"type\":\"bIG\"}", Model.class).type); assertSame(Type.Big, JSON.parseObject("{\"type\":\"big\"}", Model.class).type); assertSame(Type.Big, JSON.parseObject("{\"type\":\"Big\"}", Model.class).type); assertSame(Type.Big, JSON.parseObject("{\"type\":\"BIG\"}", Model.class).type); assertSame(Type.Small, JSON.parseObject("{\"type\":\"Small\"}", Model.class).type); assertSame(Type.Small, JSON.parseObject("{\"type\":\"SmAll\"}", Model.class).type); assertSame(Type.Small, JSON.parseObject("{\"type\":\"small\"}", Model.class).type); assertSame(Type.Small, JSON.parseObject("{\"type\":\"SMALL\"}", Model.class).type); assertSame(Type.Medium, JSON.parseObject("{\"type\":\"Medium\"}", Model.class).type); assertSame(Type.Medium, JSON.parseObject("{\"type\":\"MediuM\"}", Model.class).type); assertSame(Type.Medium, JSON.parseObject("{\"type\":\"medium\"}", Model.class).type); assertSame(Type.Medium, JSON.parseObject("{\"type\":\"MEDIUM\"}", Model.class).type); } public void test_for_issue_null() throws Exception { assertNull(JSON.parseObject("{\"type\":\"\"}", Model.class).type); } public void test_for_issue_null_2() throws Exception { assertNull(JSON.parseObject("{\"type\":\"\"}", Model.class, Feature.ErrorOnEnumNotMatch).type); } public void test_for_issue_error() throws Exception { Exception error = null; try { JSON.parseObject("\"xxx\"", Type.class, Feature.ErrorOnEnumNotMatch); } catch (JSONException e) { error = e; } assertNotNull(error); } public void test_for_issue_error_1() throws Exception { Exception error = null; try { JSON.parseObject("{\"type\":\"xxx\"}", Model.class, Feature.ErrorOnEnumNotMatch); } catch (JSONException e) { error = e; } assertNotNull(error); } public enum Type { Big,Small,Medium } public static class Model { public Type type; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2251.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.LinkedList; import java.util.Queue; public class Issue2251 extends TestCase { public void test_for_issue() throws Exception { Model m = new Model(); m.queue = new LinkedList(); m.queue.add(1); m.queue.add(2); String str = JSON.toJSONString(m); Model m2 = JSON.parseObject(str, Model.class); assertNotNull(m2.queue); } public static class Model { public Queue queue; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2253.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class Issue2253 extends TestCase { public void test_for_issue() throws Exception { List> result = new ArrayList(); result.add(new LinkedHashMap()); result.get(0).put("3", 3); result.get(0).put("2", 2); result.get(0).put("7", 7); assertEquals("[{\"3\":3,\"2\":2,\"7\":7}]", JSON.toJSONString(result, SerializerFeature.WriteMapNullValue)); result = JSON.parseObject(JSON.toJSONString(result, SerializerFeature.WriteMapNullValue), new TypeReference>>() {}, Feature.OrderedField); assertEquals("[{\"3\":3,\"2\":2,\"7\":7}]", JSON.toJSONString(result, SerializerFeature.WriteMapNullValue)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2254.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue2254 extends TestCase { public void test_for_issue() throws Exception { String jsonString = "{\"a\":[1.0,2.0]}"; //{"a":[1.0,2.0]} Exception error = null; try { JSON.parseObject(jsonString, TestClass.class); } catch (Exception ex) { error = ex; } assertNotNull(error); } public static class TestClass { public float[][] a; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2260.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.Calendar; public class Issue2260 extends TestCase { public void test_for_issue() throws Exception { String json = "{\"date\":\"1950-07-14\"}"; M1 m = JSON.parseObject(json, M1.class); assertEquals(1950, m.date.get(Calendar.YEAR)); } public void test_for_jdk8_zdt_1() throws Exception { String json = "{\"date\":\"1950-07-14\"}"; M2 m = JSON.parseObject(json, M2.class); assertEquals(1950, m.date.getYear()); } public void test_for_jdk8_zdt_2() throws Exception { String json = "{\"date\":\"1950-07-14 12:23:34\"}"; M2 m = JSON.parseObject(json, M2.class); assertEquals(1950, m.date.getYear()); } public void test_for_jdk8_zdt_3() throws Exception { String json = "{\"date\":\"1950-07-14T12:23:34\"}"; M2 m = JSON.parseObject(json, M2.class); assertEquals(1950, m.date.getYear()); } public void test_for_jdk8_ldt_1() throws Exception { String json = "{\"date\":\"1950-07-14\"}"; M3 m = JSON.parseObject(json, M3.class); assertEquals(1950, m.date.getYear()); } public void test_for_jdk8_ldt_2() throws Exception { String json = "{\"date\":\"1950-07-14 12:23:34\"}"; M3 m = JSON.parseObject(json, M3.class); assertEquals(1950, m.date.getYear()); } public void test_for_jdk8_ldt_3() throws Exception { String json = "{\"date\":\"1950-07-14T12:23:34\"}"; M3 m = JSON.parseObject(json, M3.class); assertEquals(1950, m.date.getYear()); } public static class M1 { public Calendar date; } public static class M2 { public ZonedDateTime date; } public static class M3 { public LocalDateTime date; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2262.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class Issue2262 extends TestCase { public void test_for_issue() throws Exception { Model m = new Model(); m.javaVersion = "1.6"; String json = JSON.toJSONString(m); assertEquals("{\"java.version\":\"1.6\"}", json); Model m2 = JSON.parseObject(json, Model.class); assertNotNull(m2); assertEquals(m.javaVersion, m2.javaVersion); } public static class Model { @JSONField(name = "java.version") public String javaVersion; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2264.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue2264 extends TestCase { public void test_for_issue() throws Exception { String oID="{\"sys\":\"ROC\",\"code\":0,\"messages\":\"分页获取信息成功!\",\"data\":{\"pageNum\":1,\"pageSize\":10,\"totalPages\":11,\"total\":110,\"records\":[{\"id\":\"64e72850-d149-46d6-8bd7-5f1d332d2a16\",\"tenantCode\":\"clouds_dianmo\",\"name\":\"asr_t1\",\"operatorId\":\"38ba5660-ef6e-4b66-9673-b0236832f179\",\"createTime\":\"2019-01-25 14:21:03\",\"updateTime\":\"2019-01-25 14:21:03\",\"status\":0,\"robotType\":1,\"policyType\":0,\"policyVersion\":null,\"description\":null,\"extensionJson\":null,\"operatorCode\":\"liyiwan\",\"insRcuCnt\":0,\"distRcuCnt\":0},{\"id\":\"4f6a0975-3980-4fd9-b27c-09aa258f4e36\",\"tenantCode\":\"cloudminds\",\"name\":\"xianglong\",\"operatorId\":\"b9bf937f-01c6-4fe8-86f8-43ce7a08167a\",\"createTime\":\"2019-01-25 11:48:03\",\"updateTime\":\"2019-01-25 13:03:00\",\"status\":0,\"robotType\":1,\"policyType\":0,\"policyVersion\":null,\"description\":null,\"extensionJson\":null,\"operatorCode\":\"zhangxianglong\",\"insRcuCnt\":0,\"distRcuCnt\":1},{\"id\":\"b209b3b8-7b41-49dd-a087-fb7f6b5bfa51\",\"tenantCode\":\"cloudminds\",\"name\":\"cloud_pu\",\"operatorId\":\"21d08412-9c19-49c0-9428-a6a5ad1bb548\",\"createTime\":\"2019-01-25 11:45:14\",\"updateTime\":\"2019-01-25 11:45:14\",\"status\":0,\"robotType\":1,\"policyType\":0,\"policyVersion\":null,\"description\":null,\"extensionJson\":null,\"operatorCode\":\"dian\",\"insRcuCnt\":0,\"distRcuCnt\":1},{\"id\":\"a35e468d-3ff5-48e4-a0e9-b86249167ee5\",\"tenantCode\":\"CloudPepper_Test\",\"name\":\"welcome\",\"operatorId\":\"ca69a720-8b8e-4ee5-8b12-63a20e897ef1\",\"createTime\":\"2019-01-25 11:05:42\",\"updateTime\":\"2019-01-25 14:07:05\",\"status\":0,\"robotType\":1,\"policyType\":0,\"policyVersion\":null,\"description\":null,\"extensionJson\":null,\"operatorCode\":\"duwei\",\"insRcuCnt\":0,\"distRcuCnt\":1},{\"id\":\"25243f56-b31d-4b58-bd96-c6920628b06c\",\"tenantCode\":\"roc\",\"name\":\"士大夫撒点\",\"operatorId\":\"06f82222-48a4-4a6a-b1cc-52148ed27651\",\"createTime\":\"2019-01-25 11:02:02\",\"updateTime\":\"2019-01-25 11:02:02\",\"status\":0,\"robotType\":1,\"policyType\":0,\"policyVersion\":null,\"description\":null,\"extensionJson\":null,\"operatorCode\":\"admin\",\"insRcuCnt\":0,\"distRcuCnt\":0},{\"id\":\"229d9c33-0606-4cda-a4d5-8c1feba2a5ed\",\"tenantCode\":\"cloudminds\",\"name\":\"LocalAsr\",\"operatorId\":\"38ba5660-ef6e-4b66-9673-b0236832f179\",\"createTime\":\"2019-01-25 10:51:43\",\"updateTime\":\"2019-01-25 10:51:43\",\"status\":0,\"robotType\":1,\"policyType\":0,\"policyVersion\":null,\"description\":null,\"extensionJson\":null,\"operatorCode\":\"liyiwan\",\"insRcuCnt\":0,\"distRcuCnt\":0},{\"id\":\"3aedd158-24b8-4021-a9a3-d6effc91a32a\",\"tenantCode\":\"cloudminds\",\"name\":\"cloudAsr\",\"operatorId\":\"38ba5660-ef6e-4b66-9673-b0236832f179\",\"createTime\":\"2019-01-25 10:27:59\",\"updateTime\":\"2019-01-25 10:27:59\",\"status\":0,\"robotType\":1,\"policyType\":0,\"policyVersion\":null,\"description\":null,\"extensionJson\":null,\"operatorCode\":\"liyiwan\",\"insRcuCnt\":0,\"distRcuCnt\":1},{\"id\":\"53065639-a467-4872-8333-73e085c99e43\",\"tenantCode\":\"CloudPepper_Test\",\"name\":\"asrtest\",\"operatorId\":\"394e0148-ba95-4c39-a9f9-973abb2c718a\",\"createTime\":\"2019-01-25 10:17:36\",\"updateTime\":\"2019-01-25 13:12:01\",\"status\":0,\"robotType\":1,\"policyType\":0,\"policyVersion\":null,\"description\":null,\"extensionJson\":null,\"operatorCode\":\"liuyanan\",\"insRcuCnt\":0,\"distRcuCnt\":1},{\"id\":\"da2db833-c065-49dd-bdb7-939c2026faa3\",\"tenantCode\":\"CloudPepper_Test\",\"name\":\"testwqeq\",\"operatorId\":\"bb5cd865-baea-42a0-a36d-b9e354b88f27\",\"createTime\":\"2019-01-24 19:20:04\",\"updateTime\":\"2019-01-24 19:20:27\",\"status\":0,\"robotType\":1,\"policyType\":0,\"policyVersion\":null,\"description\":null,\"extensionJson\":null,\"operatorCode\":\"cqtest01\",\"insRcuCnt\":0,\"distRcuCnt\":0},{\"id\":\"da672b14-d968-4776-97ba-b7c1addaa3b3\",\"tenantCode\":\"CloudPepper_Test\",\"name\":\"cqtestASR\",\"operatorId\":\"bb5cd865-baea-42a0-a36d-b9e354b88f27\",\"createTime\":\"2019-01-24 16:46:40\",\"updateTime\":\"2019-01-24 18:14:15\",\"status\":0,\"robotType\":1,\"policyType\":0,\"policyVersion\":null,\"description\":null,\"extensionJson\":null,\"operatorCode\":\"cqtest01\",\"insRcuCnt\":0,\"distRcuCnt\":2}]},\"errors\":null,\"action\":0,\"script\":\"\"}"; JSONObject json = JSONObject.parseObject(oID); String par="$..records[?(@.name=='asr_t1')].operatorId"; Object source = JSONPath.eval(json,par); String device_udid=JSONObject.toJSONString(source); assertEquals("[\"38ba5660-ef6e-4b66-9673-b0236832f179\"]", device_udid); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue2289.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.ObjectSerializer; import junit.framework.TestCase; public class Issue2289 extends TestCase { public void test_for_issue() throws Exception { B b = new B(); b.id = 123; JSONSerializer jsonSerializer = new JSONSerializer(); jsonSerializer.writeAs(b, A.class); String str = jsonSerializer.toString(); assertEquals("{}", str); } public static class A { } public static class B extends A { public int id; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/Issue_for_luohaoyu.java ================================================ package com.alibaba.json.bvt.issue_2200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; public class Issue_for_luohaoyu extends TestCase { public void test_for_issue() throws Exception { Map map = new HashMap(); map.put(null, 123); String str = JSON.toJSONString(map); assertEquals("{null:123}", str); JSONObject object = JSON.parseObject(str); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224/CollectionEx.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224; import java.util.Collection; interface CollectionEx extends Collection { } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224/KeyedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; public abstract class KeyedCollection implements CollectionEx, Cloneable { private transient Map items = new LinkedHashMap(); protected abstract TKey getKeyForItem(TItem item); public TItem get(TKey key) { return this.items.get(key); } //region override public int size() { return this.items.size(); } public boolean isEmpty() { return this.items.isEmpty(); } public boolean contains(Object key) { return this.items.containsKey(key); } public Iterator iterator() { return this.items.values().iterator(); } public Object[] toArray() { return this.items.values().toArray(); } public T[] toArray(T[] a) { return this.items.values().toArray(a); } public boolean add(TItem item) { if (item == null) throw new IllegalArgumentException("item can not be null."); TKey key = this.getKeyForItem(item); this.items.put(key, item); return true; } public boolean remove(Object key) { return this.items.remove(key) != null; } public boolean containsAll(Collection keys) { return this.items.keySet().containsAll(keys); } public boolean addAll(Collection items) { boolean modified = false; for (TItem item : items) modified |= this.add(item); return modified; } public boolean removeAll(Collection keys) { boolean modified = false; for (Object key : keys) modified |= this.remove(key); return modified; } public boolean retainAll(Collection keys) { boolean modified = false; for (TKey key : this.items.keySet()) { if (!keys.contains(key)) modified |= this.remove(key); } return modified; } public void clear() { this.items.clear(); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append('['); TItem item; Iterator iterator = this.iterator(); if (iterator.hasNext()) { item = iterator.next(); builder.append(item == this ? "(this Collection)" : item); } while (iterator.hasNext()) { item = iterator.next(); builder.append(", ").append(item == this ? "(this Collection)" : item); } builder.append(']'); return builder.toString(); } //endregion } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224/Person.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224; public class Person { private String idNo; private String name; public String getIdNo() { return this.idNo; } public void setIdNo(String idNo) { this.idNo = idNo; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224/PersonCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224; public class PersonCollection extends KeyedCollection { protected String getKeyForItem(Person person) { return person.getIdNo(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_2/GroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_2; import com.alibaba.json.bvt.issue_2200.issue2224.KeyedCollection; import java.util.List; abstract class GroupedCollection extends KeyedCollection> { } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_2/PersonGroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_2; import com.alibaba.json.bvt.issue_2200.issue2224.Person; import java.util.List; public class PersonGroupedCollection extends StringGroupedCollection { @Override protected String getKeyForItem(List list) { if (list == null || list.isEmpty()) return null; return list.get(0).getName(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_2/StringGroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_2; abstract class StringGroupedCollection extends GroupedCollection { } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_3/ArrayGroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_3; import com.alibaba.json.bvt.issue_2200.issue2224.KeyedCollection; abstract class ArrayGroupedCollection extends KeyedCollection { } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_3/ArrayPersonGroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_3; import com.alibaba.json.bvt.issue_2200.issue2224.Person; public class ArrayPersonGroupedCollection extends ArrayStringGroupedCollection { @Override protected String getKeyForItem(Person[] array) { if (array == null || array.length == 0) return null; return array[0].getName(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_3/ArrayStringGroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_3; abstract class ArrayStringGroupedCollection extends ArrayGroupedCollection { } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_4/MAGroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_4; import com.alibaba.json.bvt.issue_2200.issue2224.KeyedCollection; abstract class MAGroupedCollection extends KeyedCollection { } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_4/MAPersonGroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_4; import java.util.Map; public class MAPersonGroupedCollection extends MAStringGroupedCollection> { @Override protected String getKeyForItem(Map[] array) { if (array == null || array.length == 0) return null; Object name = array[0].get("name"); return name == null ? null : name.toString(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_4/MAStringGroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_4; abstract class MAStringGroupedCollection extends MAGroupedCollection { } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_5/MA2GroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_5; import com.alibaba.json.bvt.issue_2200.issue2224.KeyedCollection; abstract class MA2GroupedCollection extends KeyedCollection { } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_5/MA2PersonGroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_5; import java.util.Map; public class MA2PersonGroupedCollection extends MA2StringGroupedCollection { @Override protected String getKeyForItem(Map[] array) { if (array == null || array.length == 0) return null; final String[] names = array[0].get("name"); return names == null || names.length == 0 ? null : names[0]; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_5/MA2StringGroupedCollection.java ================================================ package com.alibaba.json.bvt.issue_2200.issue2224_5; import java.util.Map; abstract class MA2StringGroupedCollection extends MA2GroupedCollection> { } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2300.java ================================================ package com.alibaba.json.bvt.issue_2300; 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 Issue2300 extends TestCase { public void test_for_issue() throws Exception { String text = "{\"createTime\":1548166745}"; Order o = JSON.parseObject(text, Order.class); assertEquals(1548166745000L, o.createTime.getTime()); String json = JSON.toJSONString(o); assertEquals("{\"createTime\":1548166745}", json); //新增校验1 JSONObject jsonObject = JSONObject.parseObject(text); Order order1 = JSONObject.toJavaObject(jsonObject, Order.class); //校验不通过 assertEquals(1548166745000L, order1.createTime.getTime()); //新增校验2 Order order2 = jsonObject.toJavaObject(Order.class); //校验不通过 assertEquals(1548166745000L, order2.createTime.getTime()); } public static class Order { @JSONField(format = "unixtime") public Date createTime; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2306.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue2306 extends TestCase { public void test_for_issue() throws Exception { JSONObject object = new JSONObject(); object.put("help_score_avg.cbm", 123); assertEquals(123 , JSONPath.extract( object.toJSONString(), "['help_score_avg.cbm']")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2311.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSONPath; import com.jayway.jsonpath.JsonPath; import junit.framework.TestCase; public class Issue2311 extends TestCase { public void test_for_issue() throws Exception { String t = "{\"groups\":[{\"timers\":[{\"date\":\"00000001\",\"dps\":{\"1\":true},\"loops\":\"1111111\",\"timezoneId\":\"Asia/Shanghai\",\"time\":\"13:06\",\"status\":1},{\"date\":\"00000010\",\"dps\":{\"1\":true},\"loops\":\"1111111\",\"timezoneId\":\"Asia/Shanghai\",\"time\":\"13:07\",\"status\":1}],\"id\":\"1:\"},{\"timers\":[{\"date\":\"00000100\",\"dps\":{\"1\":true},\"loops\":\"1111111\",\"timezoneId\":\"Asia/Shanghai\",\"time\":\"13:06\",\"status\":1},{\"date\":\"00001000\",\"dps\":{\"1\":true},\"loops\":\"1111111\",\"timezoneId\":\"Asia/Shanghai\",\"time\":\"13:07\",\"status\":1}],\"id\":\"2:\"}],\"category\":{\"category\":\"xxxxxx\",\"status\":1}}"; System.out.println((Object) JsonPath.read(t, "$.groups[*].timers[*].dps.1")); System.out.println(JSONPath.extract(t, "$.groups[*].timers[*].dps['1']")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2334.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue2334 extends TestCase { public void test_for_issue() throws Exception { String json = "{\n" + "\"EXTINFO\":{\n" + "\"bct_loan_account_status[15]\":\"aaa\",\n" + "\"wc_bank_num_of_trans_last_3_mon[6]\":-9999,\n" + "\"fahai_shixin_post_time[46]\":\"bbb\",\n" + "\"zs_punishbreak_regdateclean[22]\":\"ccc\"\n" + "}\n" + "}"; JSONObject object = JSON.parseObject(json); assertEquals("aaa" , JSONPath.eval(object, "$.EXTINFO.bct_loan_account_status\\[15\\]")); Object result = JSONPath.extract(json, "$.EXTINFO.bct_loan_account_status\\[15\\]"); assertEquals("aaa", result.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2341.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; public class Issue2341 extends TestCase { public void test_for_issue() throws Exception { String ss = "{\"@type\":\"1234\"}"; JSONObject object = JSON.parseObject(ss); assertEquals("1234", object.get("@type")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2343.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class Issue2343 extends TestCase { public void test_for_issue() throws Exception { A a = new A(); a.f1 = 101; a.f2 = 102; a.f3 = 103; String str = JSON.toJSONString(a); assertEquals("{\"f2\":102,\"f1\":101,\"f3\":103}", str); JSONObject object = JSON.parseObject(str); A a1 = object.toJavaObject(A.class); assertEquals(a.f1, a1.f1); assertEquals(a.f2, a1.f2); assertEquals(a.f3, a1.f3); } public static class A { @JSONField(ordinal = 1) public int f1; @JSONField(ordinal = 0) public int f2; @JSONField(ordinal = 2) public int f3; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2344.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.json.bvtVO.basic.LongPrimitiveEntity; import junit.framework.TestCase; public class Issue2344 extends TestCase { public void test_for_issue() throws Exception { LongPrimitiveEntity vo = new LongPrimitiveEntity(9007199254741992L); assertEquals("{\"value\":\"9007199254741992\"}" , JSON.toJSONString(vo, SerializerFeature.BrowserCompatible)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2346.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONPOJOBuilder; import com.alibaba.fastjson.annotation.JSONType; import junit.framework.TestCase; import lombok.Builder; import lombok.Getter; public class Issue2346 extends TestCase { public void test_for_issue() throws Exception { String jsonStr = "{\"age\":1,\"name\":\"aa\"}"; TestEntity testEntity = JSON.parseObject(jsonStr, TestEntity.class); assertEquals(jsonStr, JSON.toJSONString(testEntity)); } @Builder(builderClassName = "TestEntityBuilder") @Getter @JSONType(builder = TestEntity.TestEntityBuilder.class) public static class TestEntity { private String name; private int age; @JSONPOJOBuilder(withPrefix = "") public static class TestEntityBuilder{ } } @JSONType(builder = TestEntity2.TestEntity2Builder.class) @Getter public static class TestEntity2 { private String name; private int age; @JSONPOJOBuilder(withPrefix = "www") public static class TestEntity2Builder{ private TestEntity2 testEntity2 = new TestEntity2(); public TestEntity2 build(){ return testEntity2; } public TestEntity2Builder wwwAge(int age) { testEntity2.age = age; return this; } public TestEntity2Builder wwwName(String name) { testEntity2.name = name; return this; } } } @JSONType(builder = TestEntity3.TestEntity3Builder.class) @Getter public static class TestEntity3 { private String name; private int age; public static class TestEntity3Builder{ private TestEntity3 testEntity3 = new TestEntity3(); public TestEntity3 build(){ return testEntity3; } public TestEntity3Builder withAge(int age) { testEntity3.age = age; return this; } public TestEntity3Builder withName(String name) { testEntity3.name = name; return this; } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2348.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; import java.io.Serializable; import java.util.List; public class Issue2348 extends TestCase { public void test_for_issue() throws Exception { String json = "{\n" + "\"ID\": null,\n" + "\"XM\": \"陈XX\",\n" + "\"XB\": \"1\",\n" + "\"XB_\": \"男\",\n" + "\"ZJH\": \"522401198310176625\",\n" + "\"JSH\": \"0101\",\n" + "\"GJ\": \"156\",\n" + "\"GJ_\": \"中国\",\n" + "\"MZ\": \"01\",\n" + "\"MZ_\": \"汉族\",\n" + "\"WHCD\": \"48\",\n" + "\"WHCD_\": \"相当中专或中技毕业\",\n" + "\"ZY\": null,\n" + "\"ZY_\": null,\n" + "\"CSRQ\": \"1532448000000\",\n" + "\"CBZ\": null,\n" + "\"LFFH\": \"370100111201807250001\",\n" + "\"NL\": \"0\",\n" + "\"RSRQ\": \"1537167900000\",\n" + "\"AY\": \"010180\",\n" + "\"AY_\": \"资助活动案\",\n" + "\"ZZ\": \"AAAA\",\n" + "\"BAHJ\": \"11\",\n" + "\"BAHJ_\": \"事留\",\n" + "\"JYQX\": null,\n" + "\"ZSZT\": \"11\",\n" + "\"ZSZT_\": null,\n" + "\"PWH\": \"16\",\n" + "\"WXDJ\": \"3\",\n" + "\"WXDJ_\": \"二级\",\n" + "\"JKZK\": null,\n" + "\"JKZK_\": null,\n" + "\"FZJJ\": \"阿德\",\n" + "\"ZDRY\": \"0\",\n" + "\"ZDRY_\": \"非重点\",\n" + "\"Photo\": \"\",\n" + "\"TZZ\": \"\",\n" + "\"TZZ2\": \"\",\n" + "\"GYQX\": \"2018/8/30 0:00:00\",\n" + "\"ZZD\": \"QQQQ\",\n" + "\"RSAQ\": \"阿德\",\n" + "\"SG\": 22,\n" + "\"TZ\": 22,\n" + "\"HYZK\": null,\n" + "\"HYZK_\": null,\n" + "\"BHLX\": \"1\",\n" + "\"BHLX_\": null,\n" + "\"RFID\": \"23\",\n" + "\"RFID_\": \"理发\",\n" + "\"ZBZT\": null,\n" + "\"JDXJ\": null,\n" + "\"WCNR\": null,\n" + "\"BYZDE\": \"3\",\n" + "\"BYZDE_\": null,\n" + "\"GL\": null,\n" + "\"GZDW\": \"无单位\",\n" + "\"ZJLX\": \"居民身份证\",\n" + "\"CARDID\": \"D0CB8F1B\",\n" + "\"JBR\": null,\n" + "\"SKSJ\": null,\n" + "\"SKYY\": null,\n" + "\"YE\": 7427.87,\n" + "\"BADW\": \"市看\",\n" + "\"RSXZ\": \"事留\",\n" + "\"ZB\": null,\n" + "\"TYPE\": \"1\",\n" + "\"CSSJ\": null,\n" + "\"CSYY\": null,\n" + "\"YXGW\": \"1\"\n" + "}"; PersonnelModel p = JSON.parseObject(json, PersonnelModel.class); assertEquals("23", p.getRfid()); assertEquals("1", p.getBhlx()); assertEquals(null, p.getJdxj()); } public static class RoomPersonnel { private String code; private List data; private int count; static RoomPersonnel roompersonnel; public static RoomPersonnel getRoomPersonnel(){ if(roompersonnel==null){ roompersonnel=new RoomPersonnel(); } return roompersonnel; } public void setCode(String code) { this.code = code; } public String getCode() { return code; } public void setData(List data) { this.data = data; } public List getData() { return data; } public void setCount(int count) { this.count = count; } public int getCount() { return count; } } public static class PersonnelModel implements Serializable { private String xm; private String xb; private String xb_; private String zjh; private String jsh; private String gj; private String gj_; private String mz; private String mz_; private String whcd; private String whcd_; private String zy; private String zy_; private String csrq; private String cbz; private String lffh; private String nl; private String rsrq; private String ay; private String ay_; private String zz; private String bahj; private String bahj_; private String jyqx; private String zszt; private String zszt_; private String pwh; private String wxdj; private String wxdj_; private String jkzk; private String fzjj; private String zdry; private String zdry_; private String photo; private String tzz; private String tzz2; private String gyqx; private String zzd; private String rsaq; private String sg; private String tz; private String hyzk; private String hyzk_; private String bhlx; private String rfid; private String jkzk_; private String gzdw; private String zjlx; private String zbzt; private String jdxj; private String wcnr; private String byzde; private String byzde_; private String badw; private String type; private String rsxz; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getBadw() { return badw; } public void setBadw(String badw) { this.badw = badw; } public String getByzde() { return byzde; } public void setByzde(String byzde) { this.byzde = byzde; } public String getByzde_() { return byzde_; } public void setByzde_(String byzde_) { this.byzde_ = byzde_; } public String getJdxj() { return jdxj; } public void setJdxj(String jdxj) { this.jdxj = jdxj; } public String getWcnr() { return wcnr; } public void setWcnr(String wcnr) { this.wcnr = wcnr; } public String getGzdw() { return gzdw; } public String getZbzt() { return zbzt; } public void setZbzt(String zbzt) { this.zbzt = zbzt; } public void setGzdw(String gzdw) { this.gzdw = gzdw; } public String getZjlx() { return zjlx; } public void setZjlx(String zjlx) { this.zjlx = zjlx; } public String getJkzk_() { return jkzk_; } public void setJkzk_(String jkzk_) { this.jkzk_ = jkzk_; } public String getHyzk() { return hyzk; } public void setHyzk(String hyzk) { this.hyzk = hyzk; } public String getHyzk_() { return hyzk_; } public void setHyzk_(String hyzk_) { this.hyzk_ = hyzk_; } public String getBhlx() { return bhlx; } public void setBhlx(String bhlx) { this.bhlx = bhlx; } public String getRfid() { return rfid; } public void setRfid(String rfid) { this.rfid = rfid; } public void setXm(String xm) { this.xm = xm; } public String getGyqx() { return gyqx; } public void setGyqx(String gyqx) { this.gyqx = gyqx; } public String getZzd() { return zzd; } public void setZzd(String zzd) { this.zzd = zzd; } public String getRsaq() { return rsaq; } public void setRsaq(String rsaq) { this.rsaq = rsaq; } public String getSg() { return sg; } public void setSg(String sg) { this.sg = sg; } public String getTz() { return tz; } public void setTz(String tz) { this.tz = tz; } public String getXm() { return xm; } public void setXb(String xb) { this.xb = xb; } public String getXb() { return xb; } public void setXb_(String xb_) { this.xb_ = xb_; } public String getXb_() { return xb_; } public void setZjh(String zjh) { this.zjh = zjh; } public String getZjh() { return zjh; } public void setJsh(String jsh) { this.jsh = jsh; } public String getJsh() { return jsh; } public void setGj(String gj) { this.gj = gj; } public String getGj() { return gj; } public void setGj_(String gj_) { this.gj_ = gj_; } public String getGj_() { return gj_; } public void setMz(String mz) { this.mz = mz; } public String getMz() { return mz; } public void setMz_(String mz_) { this.mz_ = mz_; } public String getMz_() { return mz_; } public void setWhcd(String whcd) { this.whcd = whcd; } public String getWhcd() { return whcd; } public void setWhcd_(String whcd_) { this.whcd_ = whcd_; } public String getWhcd_() { return whcd_; } public void setZy(String zy) { this.zy = zy; } public String getZy() { return zy; } public void setZy_(String zy_) { this.zy_ = zy_; } public String getZy_() { return zy_; } public void setCsrq(String csrq) { this.csrq = csrq; } public String getCsrq() { return csrq; } public void setCbz(String cbz) { this.cbz = cbz; } public String getCbz() { return cbz; } public void setLffh(String lffh) { this.lffh = lffh; } public String getLffh() { return lffh; } public void setNl(String nl) { this.nl = nl; } public String getNl() { return nl; } public void setRsrq(String rsrq) { this.rsrq = rsrq; } public String getRsrq() { return rsrq; } public void setAy(String ay) { this.ay = ay; } public String getAy() { return ay; } public void setAy_(String ay_) { this.ay_ = ay_; } public String getAy_() { return ay_; } public void setZz(String zz) { this.zz = zz; } public String getZz() { return zz; } public void setBahj(String bahj) { this.bahj = bahj; } public String getBahj() { return bahj; } public void setBahj_(String bahj_) { this.bahj_ = bahj_; } public String getBahj_() { return bahj_; } public void setJyqx(String jyqx) { this.jyqx = jyqx; } public String getJyqx() { return jyqx; } public void setZszt(String zszt) { this.zszt = zszt; } public String getZszt() { return zszt; } public void setZszt_(String zszt_) { this.zszt_ = zszt_; } public String getZszt_() { return zszt_; } public void setPwh(String pwh) { this.pwh = pwh; } public String getPwh() { return pwh; } public void setWxdj(String wxdj) { this.wxdj = wxdj; } public String getWxdj() { return wxdj; } public void setWxdj_(String wxdj_) { this.wxdj_ = wxdj_; } public String getWxdj_() { return wxdj_; } public void setJkzk(String jkzk) { this.jkzk = jkzk; } public String getJkzk() { return jkzk; } public void setFzjj(String fzjj) { this.fzjj = fzjj; } public String getFzjj() { return fzjj; } public void setZdry(String zdry) { this.zdry = zdry; } public String getZdry() { return zdry; } public void setZdry_(String zdry_) { this.zdry_ = zdry_; } public String getZdry_() { return zdry_; } public void setPhoto(String photo) { this.photo = photo; } public String getPhoto() { return photo; } public void setTzz(String tzz) { this.tzz = tzz; } public String getTzz() { return tzz; } public void setTzz2(String tzz2) { this.tzz2 = tzz2; } public String getTzz2() { return tzz2; } public void setRsxz(String rsxz) { this.rsxz = rsxz; } public String getRsxz() { return rsxz; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2351.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; public class Issue2351 extends TestCase { public void test_for_issue() throws Exception { // ParserConfig.getGlobalInstance().setAsmEnable(false); // 创建空白对象 Bean1 c = new Bean1(); c.a = ""; // 序列化 // 输出[null,null] String s = JSON.toJSONString(c, SerializerFeature.BeanToArray); assertEquals("[\"\",null]", s); // 反序列化报错 // Exception in thread "main" com.alibaba.fastjson.JSONException: syntax error, expect [, actual [ JSON.parseObject(s, Bean1.class, Feature.SupportArrayToBean); } public static class Bean1 { public String a; public List b; } public static class Bean2 { private String c; public String getC() { return c; } public void setC(String c) { this.c = c; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2355.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.math.BigDecimal; public class Issue2355 extends TestCase { public void test_for_issue() throws Exception { VO vo = new VO(); BigDecimal num = new BigDecimal("0.00000001"); vo.setNum(num); String json = JSON.toJSONString(vo); assertEquals("{\"num\":0.00000001}", json); } static class VO { @JSONField(serialzeFeatures = {SerializerFeature.WriteBigDecimalAsPlain}) private BigDecimal num; public BigDecimal getNum() { return num; } public void setNum(BigDecimal num) { this.num = num; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2357.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.nio.ByteBuffer; public class Issue2357 extends TestCase { public void test_for_issue() throws Exception { ByteBuffer buff = ByteBuffer.allocate(32); buff.putInt(100); buff.flip(); String result = JSON.toJSONString(buff); System.out.println(result); assertEquals("{\"array\":\"AAAAZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\",\"limit\":4,\"position\":0}", result); ByteBuffer buf1 = JSON.parseObject(result, ByteBuffer.class); assertEquals(buff.capacity(), buf1.capacity()); assertEquals(buff.limit(), buf1.limit()); assertEquals(buff.position(), buf1.position()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2358.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.List; public class Issue2358 extends TestCase { public void test_for_issue() throws Exception { String str = "[{\n" + " \"test1\":\"1\",\n" + " \"test2\":\"2\"\n" + "},\n" + " {\n" + " \"test1\":\"1\",\n" + " \"test2\":\"2\"\n" + " }]"; Exception error = null; try { List testJsons = JSONObject.parseArray(str, TestJson2.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertEquals("can't create non-static inner class instance.", error.getMessage()); } class TestJson { private String test1; private String test2; public String getTest1() { return test1; } public void setTest1(String test1) { this.test1 = test1; } public String getTest2() { return test2; } public void setTest2(String test2) { this.test2 = test2; } } class TestJson2 { private String test1; private String test2; public String getTest1() { return test1; } public void setTest1(String test1) { this.test1 = test1; } public String getTest2() { return test2; } public void setTest2(String test2) { this.test2 = test2; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2371.java ================================================ package com.alibaba.json.bvt.issue_2300; 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 Issue2371 extends TestCase { public void test_for_issue() throws Exception { RpcRespObj> resources = convertResult(Resource.class); assertEquals(2, resources.data.get(0).resourceId.intValue()); assertEquals("own佛恩", resources.data.get(0).resourceName); } public static RpcRespObj> convertResult(Class type) { String str = "{\"status\":0,\"data\":[{\"resourceId\":2,\"resourceName\":\"own佛恩\",\"systemCode\":\"ad\"}]}"; RpcRespObj> result = JSON.parseObject(str, new TypeReference>>(type) {}); return result; } public static class RpcRespObj { public Integer status; public Integer errcode; public Integer errno; public T data; } public static class Resource { public Integer resourceId; public String resourceName; public String systemCode; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2387.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; public class Issue2387 extends TestCase { public void test_for_issue() throws Exception { String jsonStr = "{id:\"ss\",ddd:\"sdfsd\",name:\"hh\"}"; TestEntity news = JSON.parseObject(jsonStr, TestEntity.class, Feature.InitStringFieldAsEmpty); assertEquals("{\"ddd\":\"sdfsd\",\"id\":\"ss\",\"name\":\"hh\"}", JSON.toJSONString(news)); } public static class TestEntity { private String id; private String ddd; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDdd() { return ddd; } public void setDdd(String ddd) { this.ddd = ddd; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2300/Issue2397.java ================================================ package com.alibaba.json.bvt.issue_2300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import junit.framework.TestCase; import org.junit.Assert; import java.io.Serializable; import java.util.List; public class Issue2397 extends TestCase { public void test_for_bug(){ String jsonStr = "{\"items\":[{\"id\":1,\"name\":\"kata\"}]}"; TestReply testReply = JSON.parseObject(jsonStr, new TypeReference() { }); Assert.assertEquals(testReply.getItems().get(0).getId() , 1); } public static class SuperBaseReply { private List items; public List getItems() { return items; } public void setItems(List items) { this.items = items; } } public static class BaseReply extends SuperBaseReply { } public static class Msg implements Serializable { 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 Msg(int id, String name) { this.id = id; this.name = name; } } public static class TestReply extends BaseReply { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2400/Issue2428.java ================================================ package com.alibaba.json.bvt.issue_2400; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.PropertyNamingStrategy; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @NoArgsConstructor @Data public class Issue2428 extends TestCase { private String myName; private NestedBean nestedBean; @AllArgsConstructor @Data public static class NestedBean { private String myId; } public void test_for_issue() { Issue2428 demoBean = new Issue2428(); demoBean.setMyName("test name"); demoBean.setNestedBean(new NestedBean("test id")); String text = JSON.toJSONString(JSON.toJSON(demoBean), SerializerFeature.SortField); assertEquals("{\"nestedBean\":{\"myId\":\"test id\"},\"myName\":\"test name\"}", text); SerializeConfig serializeConfig = new SerializeConfig(); serializeConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase; text = JSON.toJSONString(JSON.toJSON(demoBean, serializeConfig), SerializerFeature.SortField); assertEquals("{\"my_name\":\"test name\",\"nested_bean\":{\"my_id\":\"test id\"}}", text); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2400/Issue2429.java ================================================ package com.alibaba.json.bvt.issue_2400; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue2429 extends TestCase { public void testForIssue() { String str = "{\"schema\":{$ref:\"111\"},\"name\":\"ft\",\"age\":12,\"address\":\"杭州\"}"; JSON.parseObject(str); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2400/Issue2430.java ================================================ package com.alibaba.json.bvt.issue_2400; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.google.common.collect.ArrayListMultimap; import junit.framework.TestCase; public class Issue2430 extends TestCase { public void testForIssue() { ArrayListMultimap multimap = ArrayListMultimap.create(); multimap.put("a", "1"); multimap.put("a", "2"); multimap.put("a", "3"); multimap.put("b", "1"); VO vo = new VO(); vo.setMap(multimap); vo.setName("zhangsan"); assertEquals("{\"map\":{\"a\":[\"1\",\"2\",\"3\"],\"b\":[\"1\"]},\"name\":\"zhangsan\"}", JSON.toJSONString(vo, SerializerFeature.MapSortField)); } public void testForIssue2() { String jsonString = "{\"map\":{\"a\":[\"1\",\"2\",\"3\"],\"b\":[\"1\"]},\"name\":\"zhangsan\"}"; VO vo = JSON.parseObject(jsonString, VO.class); assertEquals("{\"map\":{\"a\":[\"1\",\"2\",\"3\"],\"b\":[\"1\"]},\"name\":\"zhangsan\"}", JSON.toJSONString(vo, SerializerFeature.MapSortField)); } public static class VO { private String name; private ArrayListMultimap map; public String getName() { return name; } public void setName(String name) { this.name = name; } public ArrayListMultimap getMap() { return map; } public void setMap(ArrayListMultimap map) { this.map = map; } @Override public String toString() { return String.format("VO:{name->%s,map->%s}", this.name, this.map.toString()); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2400/Issue2447.java ================================================ package com.alibaba.json.bvt.issue_2400; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.util.LinkedHashMap; import java.util.Map; public class Issue2447 extends TestCase { public void test_for_issue() { VO vo = new VO(); vo.id = 123; vo.location = new Location(127, 37); Object obj = JSON.toJSON(vo); String text = JSON.toJSONString(obj, SerializerFeature.SortField); assertEquals("{\"latitude\":37,\"id\":123,\"longitude\":127}", text); } public void test_for_issue2() { VO2 vo = new VO2(); vo.id = 123; vo.properties.put("latitude", 37); vo.properties.put("longitude", 127); Object obj = JSON.toJSON(vo); String text = JSON.toJSONString(obj, SerializerFeature.SortField); assertEquals("{\"latitude\":37,\"id\":123,\"longitude\":127}", text); } public static class VO { public int id; @JSONField(unwrapped = true) public Location location; } public static class VO2 { public int id; @JSONField(unwrapped = true) public Map properties = new LinkedHashMap(); } public static class Location { public int longitude; public int latitude; public Location() {} public Location(int longitude, int latitude) { this.longitude = longitude; this.latitude = latitude; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2400/Issue2464.java ================================================ package com.alibaba.json.bvt.issue_2400; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue2464 extends TestCase { public void test1() throws Exception { String json = "[\"Mjg4NDd8MXxjb20uY2Fpbmlhby5pc2ltdS5xLndvcmtmbG93LmNvbGxlY3Quc2NoZWR1bGUuaW1wbC5UYXNrU3RvcENvbGxlY3RDYWxsQmFja0hhbmRsZXJJbXBsfDB8\",1]"; Object result = JSON.parseArray(json,new Class[]{byte[].class,Integer.class}); assertEquals(json, JSON.toJSONString(result)); result = JSON.parseArray(json,new Class[]{char[].class,Integer.class}); assertEquals(json, JSON.toJSONString(result)); } public void test2() throws Exception { String json = "[1,\"Mjg4NDd8MXxjb20uY2Fpbmlhby5pc2ltdS5xLndvcmtmbG93LmNvbGxlY3Quc2NoZWR1bGUuaW1wbC5UYXNrU3RvcENvbGxlY3RDYWxsQmFja0hhbmRsZXJJbXBsfDB8\"]"; Object result = JSON.parseArray(json,new Class[]{Integer.class,byte[].class}); assertEquals(json, JSON.toJSONString(result)); result = JSON.parseArray(json,new Class[]{Integer.class, char[].class}); assertEquals(json, JSON.toJSONString(result)); } public void test3() throws Exception { String json = "[1,\"aaa\",\"bbb\",\"ccc\"]"; Object result = JSON.parseArray(json, new Class[]{Integer.class, String[].class}); assertEquals("[1,[\"aaa\",\"bbb\",\"ccc\"]]", JSON.toJSONString(result)); } public void test4() throws Exception { String json = "[1,97,98,99]"; Object result = JSON.parseArray(json, new Class[]{Integer.class, byte[].class}); assertEquals("[1,\"YWJj\"]", JSON.toJSONString(result)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2400/Issue2488.java ================================================ package com.alibaba.json.bvt.issue_2400; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; public class Issue2488 extends TestCase { public void testForIssue_1() { String a = "{\"$a_b\":\"a1_b2\",\"_c_d\":\"c3_d4\",\"aaaa\":\"CC\",\"__flag\":\"true\",\"$flag\":\"true\"}"; JSONObject obj = (JSONObject) JSONObject.parse(a); TestJsonObj2 stu = JSONObject.toJavaObject(obj, TestJsonObj2.class); assertEquals("TestJsonObj2{$a_b=\"a1_b2\",_c_d=\"c3_d4\",aaaa=\"CC\",__flag=true,$flag=true}", stu.toString()); } public void testForIssue_2() { String a = "{\"$a_b\":\"aa3_bb4\",\"_c_d\":\"cc1_dd2\",\"aaaa\":\"BB\",\"__flag\":\"true\",\"$flag\":\"true\"}"; TestJsonObj2 stu = JSON.parseObject(a, TestJsonObj2.class); assertEquals("TestJsonObj2{$a_b=\"aa3_bb4\",_c_d=\"cc1_dd2\",aaaa=\"BB\",__flag=true,$flag=true}", stu.toString()); } public void testForIssue_3() { TestJsonObj2 vo = new TestJsonObj2("aa_bb", "cc_dd", "AA", true, true); String text = JSON.toJSONString(vo); assertEquals("{\"$a_b\":\"aa_bb\",\"$flag\":true,\"__flag\":true,\"_c_d\":\"cc_dd\",\"aaaa\":\"AA\"}", text); } public static class TestJsonObj2 { private String $a_b; private String _c_d; private String aaaa; private boolean __flag; private boolean $flag; public TestJsonObj2() { } public TestJsonObj2(String $a_b, String _c_d, String aaaa, boolean __flag, boolean $flag) { this.$a_b = $a_b; this._c_d = _c_d; this.aaaa = aaaa; this.__flag = __flag; this.$flag = $flag; } public String get$a_b() { return $a_b; } public void set$a_b(String $a_b) { this.$a_b = $a_b; } public String get_c_d() { return _c_d; } public void set_c_d(String _c_d) { this._c_d = _c_d; } public String getaaaa() { return aaaa; } public void setaaaa(String aaaa) { this.aaaa = aaaa; } public boolean is__flag() { return __flag; } public void set__flag(boolean __flag) { this.__flag = __flag; } public boolean is$flag() { return $flag; } public void set$flag(boolean $flag) { this.$flag = $flag; } @Override public String toString() { return String.format("TestJsonObj2{$a_b=\"%s\",_c_d=\"%s\",aaaa=\"%s\",__flag=%b,$flag=%b}", this.$a_b, this._c_d, this.aaaa, this.__flag, this.$flag); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2500/Issue2515.java ================================================ package com.alibaba.json.bvt.issue_2500; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue2515 extends TestCase { public void test_for_issue() throws Exception { String json = "{\n" + " \"a\":\"{\\\"b\\\":\\\"cd\\\"}\"\n" + "}"; JSONObject obj = JSON.parseObject(json); assertEquals("cd", JSONPath.eval(obj, "$.a.b")); assertEquals(1, JSONPath.eval(obj, "$.a.size")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2500/Issue2516.java ================================================ package com.alibaba.json.bvt.issue_2500; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.Collection; import java.util.List; public class Issue2516 extends TestCase { public void test_for_issue() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.toJavaObject(JSONObject.class); jsonObject.toJavaObject(JSON.class); new JSONArray().toJavaObject(JSON.class); new JSONArray().toJavaObject(JSONArray.class); new JSONArray().toJavaObject(Collection.class); new JSONArray().toJavaObject(List.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2500/Issue2579.java ================================================ package com.alibaba.json.bvt.issue_2500; import java.awt.Point; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.UUID; 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 junit.framework.TestCase; public class Issue2579 extends TestCase { // 场景:走ASM public void test_for_issue1() throws Exception { run_test("MyPoint1"); } // 场景:不走ASM,通过JSONType(asm=false),关闭了ASM public void test_for_issue2() throws Exception { run_test("MyPoint2"); } // 场景:随机顺序组合JSON字符串测试2000次 private void run_test(String className) { String begin = "{"; String end = "}"; String jsonString; for (int i = 1; i < 2000; i++) { jsonString = getString(i, className); jsonString = begin + jsonString + end; try { Object obj = JSON.parse(jsonString, Feature.SupportAutoType); if ("MyPoint1".equals(className)) { Assert.assertEquals(i, ((MyPoint1) obj).getBatchNumber()); } else { Assert.assertEquals(i, ((MyPoint2) obj).getBatchNumber()); } } catch (JSONException e) { System.out.println(jsonString); e.printStackTrace(); Assert.assertTrue(false); } } } private static String getString(int batchNumber, String className) { List list = new ArrayList(); list.add("\"@type\":\"com.alibaba.json.bvt.issue_2500.Issue2579$" + className + "\""); list.add("\"date\":1563867975335"); list.add("\"id\":\"0f075036-9e52-4821-800a-9c51761a7227b\""); list.add("\"location\":{\"@type\":\"java.awt.Point\",\"x\":11,\"y\":1}"); list.add("\"point\":{\"@type\":\"java.awt.Point\",\"x\":9,\"y\":1}"); list.add( "\"pointArr\":[{\"@type\":\"java.awt.Point\",\"x\":4,\"y\":6},{\"@type\":\"java.awt.Point\",\"x\":7,\"y\":8}]"); list.add("\"strArr\":[\"te-st\",\"tes-t2\"]"); list.add("\"x\":2.0D"); list.add("\"y\":3.0D"); list.add("\"batchNumber\":" + batchNumber); Iterator it = list.iterator(); StringBuffer buffer = new StringBuffer(); int len; int index; while (it.hasNext()) { len = list.size(); index = getRandomIndex(len); buffer.append(list.get(index)); buffer.append(","); list.remove(index); } buffer.deleteCharAt(buffer.length() - 1); return buffer.toString(); } private static int getRandomIndex(int length) { Random random = new Random(); return random.nextInt(length); } @SuppressWarnings("serial") public static class MyPoint1 extends Point { private UUID id; private int batchNumber; private Point point = new Point(); private String[] strArr = { "te-st", "tes-t2" }; private Date date = new Date(); private Point[] pointArr = { new Point(), new Point() }; public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public int getBatchNumber() { return batchNumber; } public void setBatchNumber(int batchNumber) { this.batchNumber = batchNumber; } public Point getPoint() { return point; } public void setPoint(Point point) { this.point = point; } public String[] getStrArr() { return strArr; } public void setStrArr(String[] strArr) { this.strArr = strArr; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Point[] getPointArr() { return pointArr; } public void setPointArr(Point[] pointArr) { this.pointArr = pointArr; } } @SuppressWarnings("serial") @JSONType(asm = false) public static class MyPoint2 extends Point { private UUID id; private int batchNumber; private Point point = new Point(); private String[] strArr = { "te-st", "tes-t2" }; private Date date = new Date(); private Point[] pointArr = { new Point(), new Point() }; public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public int getBatchNumber() { return batchNumber; } public void setBatchNumber(int batchNumber) { this.batchNumber = batchNumber; } public Point getPoint() { return point; } public void setPoint(Point point) { this.point = point; } public String[] getStrArr() { return strArr; } public void setStrArr(String[] strArr) { this.strArr = strArr; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Point[] getPointArr() { return pointArr; } public void setPointArr(Point[] pointArr) { this.pointArr = pointArr; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2600/Issue2606.java ================================================ package com.alibaba.json.bvt.issue_2600; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.util.TypeUtils; import junit.framework.TestCase; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Issue2606 extends TestCase { @Override public void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getDefault(); JSON.defaultLocale = Locale.CHINA; } public void test_for_issue() throws Exception { String str = "2019-07-03 19:34:22,547"; Date d = TypeUtils.castToDate(str); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); sdf.setTimeZone(TimeZone.getDefault()); assertEquals(str, sdf.format(d)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2600/Issue2617.java ================================================ package com.alibaba.json.bvt.issue_2600; import java.lang.reflect.Type; import java.util.Date; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.MapDeserializer; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import junit.framework.TestCase; public class Issue2617 extends TestCase { // 场景:通过@JSONField(deserializeUsing = MyDateDeserializer.class)来自定义解析 public void test_for_issue() throws Exception { String str = "{ \"a\": { \"date\": 6, \"day\": 2, \"hours\": 18, \"minutes\": 37, \"month\": 7, \"seconds\": 1, \"time\": 1565087821607, \"timezoneOffset\": -480, \"year\": 119 } }"; Date date = JSON.parseObject(str, A.class).getA(); Date date2 = new Date(1565087821607L); assertEquals(date2.getDate(), date.getDate()); assertEquals(date2.getDay(), date.getDay()); assertEquals(date2.getHours(), date.getHours()); assertEquals(date2.getMinutes(), date.getMinutes()); assertEquals(date2.getMonth(), date.getMonth()); assertEquals(date2.getSeconds(), date.getSeconds()); assertEquals(date2.getTime(), date.getTime()); assertEquals(date2.getTimezoneOffset(), date.getTimezoneOffset()); assertEquals(date2.getYear(), date.getYear()); } // 场景:通过ParserConfig的putDeserializer自定义解析 public void test_for_issue_2() throws Exception { String str = "{ \"a\": { \"date\": 6, \"day\": 2, \"hours\": 18, \"minutes\": 37, \"month\": 7, \"seconds\": 1, \"time\": 1565087821607, \"timezoneOffset\": -480, \"year\": 119 } }"; ParserConfig config = new ParserConfig(); config.putDeserializer(Date.class, new MyDateDeserializer()); Date date = ((A2) JSON.parseObject(str, A2.class, config)).getA(); assertEquals(date.getDate(), date.getDate()); assertEquals(date.getDay(), date.getDay()); assertEquals(date.getHours(), date.getHours()); assertEquals(date.getMinutes(), date.getMinutes()); assertEquals(date.getMonth(), date.getMonth()); assertEquals(date.getSeconds(), date.getSeconds()); assertEquals(date.getTime(), date.getTime()); assertEquals(date.getTimezoneOffset(), date.getTimezoneOffset()); assertEquals(date.getYear(), date.getYear()); } // 场景:还原楼主提出的报错场景 public void test_for_issue_3() throws Exception { String str = "{ \"a\": { \"date\": 6, \"day\": 2, \"hours\": 18, \"minutes\": 37, \"month\": 7, \"seconds\": 1, \"time\": 1565087821607, \"timezoneOffset\": -480, \"year\": 119 } }"; try { JSON.parseObject(str, A2.class); } catch (JSONException e) { assertEquals("syntax error, expect }, actual ,", e.getMessage()); } } public static class A { @JSONField(deserializeUsing = MyDateDeserializer.class) private Date a; public Date getA() { return a; } public void setA(Date a) { this.a = a; } } public static class A2 { private Date a; public Date getA() { return a; } public void setA(Date a) { this.a = a; } } public static class MyDateDeserializer implements ObjectDeserializer { @SuppressWarnings("unchecked") @Override public Date deserialze(DefaultJSONParser parser, Type type, Object fieldName) { Map map = MapDeserializer.instance.deserialze(parser, Map.class, fieldName); long milliseconds = (Long) map.get("time"); return new Date(milliseconds); } @Override public int getFastMatchToken() { return JSONToken.LBRACE; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2600/Issue2628.java ================================================ package com.alibaba.json.bvt.issue_2600; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.math.BigInteger; public class Issue2628 extends TestCase { public void test_for_issue() throws Exception { long MAX_LONG = Long.MAX_VALUE; //9223372036854775807 long MIN_LONG = Long.MIN_VALUE; //-9223372036854775808 String s1 = "9423372036854775807"; //-9423372036854775808 BigInteger bi1 = JSON.parseObject(s1, BigInteger.class); //没问题 assertEquals("9423372036854775807", bi1.toString()); BigInteger bi2 = new BigInteger(s1); //没问题 assertEquals("9423372036854775807", bi2.toString()); Tobject tobj1 = new Tobject(); tobj1.setBi(bi2); //没问题 assertEquals("9423372036854775807", tobj1.getBi().toString());; String s2 = JSON.toJSONString(tobj1); Tobject tobj2 = JSON.parseObject(s2, Tobject.class); //有问题 assertEquals("9423372036854775807", tobj2.getBi().toString()); } static class Tobject { private BigInteger bi; public BigInteger getBi() { return bi; } public void setBi(BigInteger bi) { this.bi = bi; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2600/Issue2635.java ================================================ package com.alibaba.json.bvt.issue_2600; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue2635 extends TestCase { public void testForIssue() throws Exception { String json = "{\"dt\":\"evt\",\"pr\":{\"_订单金额\":\"100\",\"$AA_epid#_优惠券金额\":848,\"$AA_eptp#_Client_id\":\"string\",\"$AA_eptp#_访客类别\":\"string\",\"$AA_uid\":856,\"$AA_eptp#_优惠券类型\":\"string\",\"$AA_sid\":1565851940554,\"$AA_eptp#_优惠券金额\":\"string\",\"$AA_epid#_订单金额\":855,\"$AA_epid#_订单号\":847,\"_优惠券名称\":\"60元优惠折扣券\",\"$eid\":\"小程序_订单确认\",\"$AA_eptp#_订单渠道\":\"string\",\"$ct\":1565854057608,\"$cuid\":\"YYYY\",\"_Experiment_id\":\"0\",\"$AA_epid#_优惠券类型\":853,\"_优惠券类型\":\"D4\",\"_店主ID\":\"53890475\",\"_优惠券金额\":\"100\",\"$AA_eptp#_Experiment_id\":\"string\",\"$AA_epid#_优惠券名称\":850,\"$AA_eptp#_优惠券名称\":\"string\",\"_优惠券 ID\":\"916090\",\"$AA_epid#_店主ID\":851,\"$tz\":28800000,\"$AA_eptp#_优惠券 ID\":\"string\",\"$AA_eptp#_订单号\":\"string\",\"$AA_AAid\":7097,\"$AA_eptp#_店主ID\":\"string\",\"$AA_eid\":175,\"$AA_epid#_Client_id\":21544,\"$sid\":1569851940554,\"_订单渠道\":\"云购小程序\",\"_Client_id\":\"1e8e82fe-c90f-f363-6693-143677891dfa\",\"$AA_epid#_事件类型\":3073,\"$AA_epid#_分享来源用户\":14694,\"$AA_epid#_Experiment_id\":21543,\"_分享来源用户\":\"53890475\",\"$AA_eptp#_订单金额\":\"string\",\"$AA_epid#_订单渠道\":852,\"$AA_eptp#_分享来源用户\":\"string\",\"$url\":\"http://171.90.15:87/CCTesting/data/toPrivateTest?test=https://u2.CCio.com/CC.js&appkey=b8868018cIO94114ad7a81cd5f1ddafd\",\"_访客类别\":\"ABO\",\"$AA_epid#_优惠券 ID\":854,\"_订单号\":\"PP190830000683\",\"_下单用户\":\"720003734\",\"$AA_epid#_下单用户\":849,\"$AA_eptp#_事件类型\":\"string\",\"$uuid\":\"5c910d893bc341aBHN02119708ec13df\",\"$AA_eptp#_下单用户\":\"string\",\"$AA_epid#_访客类别\":856,\"$AA_did\":6736,\"$referrer_domain\":\"10.33.180.15:8088\",\"_事件类型\":\"订单确认\",\"$ref\":\"http://10.283.100.10:8088/CCTesting/data/toPrivate\"}}\n"; JSON.parseObject(json); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2600/Issue2678.java ================================================ package com.alibaba.json.bvt.issue_2600; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; public class Issue2678 extends TestCase { public void test_field() throws Exception { Person person = new Person(); person.setName("Ariston"); person.setAge(23); String json = JSON.toJSONString(person); assertEquals("{\"age\":23,'name':'Ariston'}", json); } public void test_getter() throws Exception { Person2 person = new Person2(); person.setName("Ariston"); person.setAge(23); String json = JSON.toJSONString(person); assertEquals("{\"age\":23,'name':'Ariston'}", json); } static class Person { @JSONField(serialzeFeatures = SerializerFeature.UseSingleQuotes) private String name; private int age; 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; } } static class Person2 { private String name; private int age; @JSONField(serialzeFeatures = SerializerFeature.UseSingleQuotes) 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2600/Issue2685.java ================================================ package com.alibaba.json.bvt.issue_2600; import java.lang.reflect.Type; import org.marre.sms.SmsMessage; 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.StringCodec; import com.zx.sms.codec.cmpp.msg.CmppSubmitResponseMessage; import com.zx.sms.codec.smgp.msg.SMGPSubmitMessage; import com.zx.sms.common.util.CMPPCommonUtil; import com.zx.sms.common.util.MsgId; import junit.framework.TestCase; public class Issue2685 extends TestCase { public void test_field() throws Exception { SMGPSubmitMessage smgpSubmitMessage = new SMGPSubmitMessage(); smgpSubmitMessage.setSequenceNo(1); smgpSubmitMessage.setServiceId("hell"); smgpSubmitMessage.setMsgContent("hello"); // 注释掉可以正常 smgpSubmitMessage.setChargeTermId("123555"); smgpSubmitMessage.setSrcTermId("10086"); CmppSubmitResponseMessage submitResponseMessage = new CmppSubmitResponseMessage(1); submitResponseMessage.setResult(0); submitResponseMessage.setMsgId(new MsgId()); String smsMsg = JSON.toJSONString(smgpSubmitMessage); // System.out.println(smsMsg); JSON.addMixInAnnotations(SMGPSubmitMessage.class, Mixin.class); smgpSubmitMessage = JSON.parseObject(smsMsg, SMGPSubmitMessage.class); assertEquals("hello", smgpSubmitMessage.getMsgContent()); } public interface Mixin { @JSONField(deserializeUsing = MyDeserializer.class) void setMsgContent(SmsMessage msg); } public static class MyDeserializer implements ObjectDeserializer { public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { String msg = StringCodec.deserialze(parser); return (T) CMPPCommonUtil.buildTextMessage(msg); } public int getFastMatchToken() { return JSONToken.LITERAL_STRING; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2600/Issue2689.java ================================================ package com.alibaba.json.bvt.issue_2600; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import junit.framework.TestCase; public class Issue2689 extends TestCase { public void test_0() throws Exception { Exception error = null; try { JSON.parse("{\"val\":\"\\x~\""); } catch (JSONException ex) { error = ex; } assertTrue( error.getMessage().startsWith("invalid escape character")); } public void test_1() throws Exception { Exception error = null; try { JSON.parse("{\"val\":'\\x~'"); } catch (JSONException ex) { error = ex; } assertTrue( error.getMessage().startsWith("invalid escape character")); } public void test_2() throws Exception { Exception error = null; try { JSON.parse("{\"val\":'\\x1'"); } catch (JSONException ex) { error = ex; } assertTrue( error.getMessage().startsWith("invalid escape character")); } public void test_3() throws Exception { Exception error = null; try { JSON.parse("{\"val\":'\\x'"); } catch (JSONException ex) { error = ex; } assertTrue( error.getMessage().startsWith("invalid escape character")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2703.java ================================================ package com.alibaba.json.bvt.issue_2700; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; public class Issue2703 extends TestCase { public void test_for_issue() { Object a = JSON.toJavaObject(new JSONObject(), JSON.class); assertTrue(a instanceof JSONObject); Object b = new JSONObject().toJavaObject(JSON.class); assertTrue(b instanceof JSONObject); Object c = JSON.toJavaObject(new JSONArray(), JSON.class); assertTrue(c instanceof JSONArray); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2721Test.java ================================================ package com.alibaba.json.bvt.issue_2700; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import org.junit.Assert; import org.junit.Test; import java.util.List; public class Issue2721Test extends TestCase { public void test2721() { String chineseKeyString = "[{\"名称\": \"脆皮青豆\", \"配料\": [\"豌豆\", \"棕榈油\", \"白砂糖\", \"食用盐\", \"玉米淀粉\"]}]"; System.out.println(JSONPath.read(chineseKeyString, "$[名称 = '脆皮青豆']")); // [{"名称":"脆皮青豆","配料":["豌豆","棕榈油","白砂糖","食用盐","玉米淀粉"]}] String normalKeyString = "[{ \"name\": \"脆皮青豆\", \"配料\": [\"豌豆\", \"棕榈油\", \"白砂糖\", \"食用盐\", \"玉米淀粉\"] }]"; System.out.println(JSONPath.read(normalKeyString, "$[name = '脆皮青豆']")); // [{"name":"脆皮青豆","配料":["豌豆","棕榈油","白砂糖","食用盐","玉米淀粉"]}] // Assert.assertFalse("Chinese Key is NOT OK, Array length is 0!", ((List) JSONPath.read(chineseKeyString, "$[名称 = '脆皮青豆']")).isEmpty()); Assert.assertFalse("Chinese Key is NOT OK, Array length is 0!", ((List) JSONPath.read(normalKeyString, "$[name = '脆皮青豆']")).isEmpty()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2736.java ================================================ package com.alibaba.json.bvt.issue_2700; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; public class Issue2736 extends TestCase { public void test_for_issue() throws Exception { JSONObject s = JSONObject.parseObject("{1:2,3:4}"); for(String s1 : s.keySet()){ System.out.println(s1); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2743.java ================================================ package com.alibaba.json.bvt.issue_2700; //import static org.junit.Assert.assertArrayEquals; // //import java.util.regex.Pattern; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue2743 extends TestCase { // 场景:验证字符串数组,楼主提供的用例 public void test_0() throws Exception { String json = "{\"info\":{\"com.xxx.service.xxxServiceForOrder@queryGoodsV2(Long,Long,Long)\":[{\"method\":\"queryPrepayGoodsV2\"}]}}"; Object obj = JSONPath.extract(json, "$['info']['com.xxx.service.xxxServiceForOrder@queryGoodsV2(Long,Long,Long)']"); assertEquals("[{\"method\":\"queryPrepayGoodsV2\"}]", obj.toString()); } // 场景:验证数字数组 public void test_1() throws Exception { String json = "[10,11,12,13,14,15,16,17,18,19,20]"; Object obj = JSONPath.extract(json, "$[3,4]"); assertEquals("[13,14]", obj.toString()); } // // // 场景:验证修复bug用的正则表达式 // public void test_2() throws Exception { // String strArrayRegex = "\'\\s*,\\s*\'"; // Pattern strArrayPattern = Pattern.compile(strArrayRegex); // // assertFalse( // strArrayPattern.matcher("'com.xxx.service.xxxServiceForOrder@queryGoodsV2(Long,Long,Long)'").find()); // assertTrue(strArrayPattern.matcher("'id','name'").find()); // assertTrue(strArrayPattern.matcher("'id' , 'name'").find()); // assertTrue(strArrayPattern.matcher("'id', 'name'").find()); // assertTrue(strArrayPattern.matcher("'id' ,'name'").find()); // // String[] strs = { "'com.xxx.service.xxxServiceForOrder@queryGoodsV2(Long,Long,Long)'" }; // assertArrayEquals(strs, strs[0].split(strArrayRegex)); // // strs = new String[] { "'id", "name'" }; // assertArrayEquals(strs, "'id','name'".split(strArrayRegex)); // assertArrayEquals(strs, "'id' , 'name'".split(strArrayRegex)); // assertArrayEquals(strs, "'id' ,'name'".split(strArrayRegex)); // assertArrayEquals(strs, "'id', 'name'".split(strArrayRegex)); // } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2752.java ================================================ package com.alibaba.json.bvt.issue_2700; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.alibaba.fastjson.serializer.MiscCodec; import com.alibaba.fastjson.serializer.ObjectSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.spi.Module; import junit.framework.TestCase; public class Issue2752 extends TestCase { public void test_for_issue() { Pageable pageRequest = new PageRequest(0, 10, new Sort(new Sort.Order("id, desc"))); SerializeConfig config = new SerializeConfig(); config.register(new MyModule()); String result = JSON.toJSONString(pageRequest, config); assertTrue(result.indexOf("\"property\":\"id, desc\"") != -1); } public class MyModule implements Module { @Override public ObjectDeserializer createDeserializer(ParserConfig config, Class type) { if (type.getName().equals("org.springframework.data.domain.Sort")) { return MiscCodec.instance; } return null; } @Override public ObjectSerializer createSerializer(SerializeConfig config, Class type) { if (type.getName().equals("org.springframework.data.domain.Sort")) { return MiscCodec.instance; } return null; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2754.java ================================================ package com.alibaba.json.bvt.issue_2700; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.TimeZone; public class Issue2754 extends TestCase { public void test_for_issue0() throws Exception { String s = "{\"p1\":\"2019-09-18T20:35:00+12:45\"}"; C c = JSON.parseObject(s, C.class); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); sdf.setTimeZone(TimeZone.getTimeZone("Pacific/Chatham")); assertEquals("2019-09-18T20:35:00+12:45", sdf.format(c.p1.getTime())); } public void test_for_issue1() throws Exception { String s = "{\"p1\":\"2019-09-18T20:35:00+12:45\"}"; C c = JSON.parseObject(s, C.class); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); sdf.setTimeZone(TimeZone.getTimeZone("NZ-CHAT")); assertEquals("2019-09-18T20:35:00+12:45", sdf.format(c.p1.getTime())); } public void test_for_issue2() throws Exception { String s = "{\"p1\":\"2019-09-18T20:35:00+05:45\"}"; C c = JSON.parseObject(s, C.class); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kathmandu")); assertEquals("2019-09-18T20:35:00+05:45", sdf.format(c.p1.getTime())); } public void test_for_issue3() throws Exception { String s = "{\"p1\":\"2019-09-18T20:35:00+05:45\"}"; C c = JSON.parseObject(s, C.class); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); sdf.setTimeZone(TimeZone.getTimeZone("Asia/Katmandu")); assertEquals("2019-09-18T20:35:00+05:45", sdf.format(c.p1.getTime())); } public void test_for_issue4() throws Exception { String s = "{\"p1\":\"2019-09-18T20:35:00+08:45\"}"; C c = JSON.parseObject(s, C.class); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); sdf.setTimeZone(TimeZone.getTimeZone("Australia/Eucla")); assertEquals("2019-09-18T20:35:00+08:45", sdf.format(c.p1.getTime())); } public static class C{ public Calendar p1; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2772.java ================================================ package com.alibaba.json.bvt.issue_2700; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.Date; public class Issue2772 extends TestCase { public void test_for_issue() throws Exception { { java.sql.Time time = java.sql.Time.valueOf("12:13:14"); long millis = time.getTime(); assertEquals(Long.toString(millis/1000), JSON.toJSONStringWithDateFormat(time, "unixtime")); assertEquals(Long.toString(millis), JSON.toJSONStringWithDateFormat(time, "millis")); } long millis = System.currentTimeMillis(); assertEquals(Long.toString(millis), JSON.toJSONStringWithDateFormat(new Date(millis), "millis")); assertEquals(Long.toString(millis/1000), JSON.toJSONStringWithDateFormat(new Date(millis), "unixtime")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2779.java ================================================ package com.alibaba.json.bvt.issue_2700; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.List; public class Issue2779 extends TestCase { public void test_for_issue() throws Exception { String str = JSON.toJSONString(new Model()); JSON.parseObject(str, Model.class); } public static class Model { private List f000; private List f001; private List f002; private List f003; private List f004; private List f005; private List f006; private List f007; private List f008; private List f009; private List f010; private List f011; private List f012; private List f013; private List f014; private List f015; private List f016; private List f017; private List f018; private List f019; private List f020; private List f021; private List f022; private List f023; private List f024; private List f025; private List f026; private List f027; private List f028; private List f029; private List f030; private List f031; private List f032; private List f033; private List f034; private List f035; private List f036; private List f037; private List f038; private List f039; private List f040; private List f041; private List f042; private List f043; private List f044; private List f045; private List f046; private List f047; private List f048; private List f049; private List f050; private List f051; private List f052; private List f053; private List f054; private List f055; private List f056; private List f057; private List f058; private List f059; private List f060; private List f061; private List f062; private List f063; private List f064; private List f065; private List f066; private List f067; private List f068; private List f069; private List f070; private List f071; private List f072; private List f073; private List f074; private List f075; private List f076; private List f077; private List f078; private List f079; private List f080; private List f081; private List f082; private List f083; private List f084; private List f085; private List f086; private List f087; private List f088; private List f089; private List f090; private List f091; private List f092; private List f093; private List f094; private List f095; private List f096; private List f097; private List f098; private List f099; private List f100; private List f101; private List f102; private List f103; private List f104; private List f105; private List f106; private List f107; private List f108; private List f109; private List f110; private List f111; private List f112; private List f113; private List f114; private List f115; private List f116; private List f117; private List f118; private List f119; private List f120; private List f121; private List f122; private List f123; private List f124; private List f125; private List f126; private List f127; private List f128; private List f129; private List f130; private List f131; private List f132; private List f133; private List f134; private List f135; private List f136; private List f137; private List f138; private List f139; private List f140; private List f141; private List f142; private List f143; private List f144; private List f145; private List f146; private List f147; private List f148; private List f149; private List f150; private List f151; private List f152; private List f153; private List f154; private List f155; private List f156; private List f157; private List f158; private List f159; private List f160; private List f161; private List f162; private List f163; private List f164; private List f165; private List f166; private List f167; private List f168; private List f169; private List f170; private List f171; private List f172; private List f173; private List f174; private List f175; private List f176; private List f177; private List f178; private List f179; private List f180; private List f181; private List f182; private List f183; private List f184; private List f185; private List f186; private List f187; private List f188; private List f189; private List f190; private List f191; private List f192; private List f193; private List f194; private List f195; private List f196; private List f197; private List f198; private List f199; public List getF000() { return f000; } public void setF000(List f000) { this.f000 = f000; } public List getF001() { return f001; } public void setF001(List f001) { this.f001 = f001; } public List getF002() { return f002; } public void setF002(List f002) { this.f002 = f002; } public List getF003() { return f003; } public void setF003(List f003) { this.f003 = f003; } public List getF004() { return f004; } public void setF004(List f004) { this.f004 = f004; } public List getF005() { return f005; } public void setF005(List f005) { this.f005 = f005; } public List getF006() { return f006; } public void setF006(List f006) { this.f006 = f006; } public List getF007() { return f007; } public void setF007(List f007) { this.f007 = f007; } public List getF008() { return f008; } public void setF008(List f008) { this.f008 = f008; } public List getF009() { return f009; } public void setF009(List f009) { this.f009 = f009; } public List getF010() { return f010; } public void setF010(List f010) { this.f010 = f010; } public List getF011() { return f011; } public void setF011(List f011) { this.f011 = f011; } public List getF012() { return f012; } public void setF012(List f012) { this.f012 = f012; } public List getF013() { return f013; } public void setF013(List f013) { this.f013 = f013; } public List getF014() { return f014; } public void setF014(List f014) { this.f014 = f014; } public List getF015() { return f015; } public void setF015(List f015) { this.f015 = f015; } public List getF016() { return f016; } public void setF016(List f016) { this.f016 = f016; } public List getF017() { return f017; } public void setF017(List f017) { this.f017 = f017; } public List getF018() { return f018; } public void setF018(List f018) { this.f018 = f018; } public List getF019() { return f019; } public void setF019(List f019) { this.f019 = f019; } public List getF020() { return f020; } public void setF020(List f020) { this.f020 = f020; } public List getF021() { return f021; } public void setF021(List f021) { this.f021 = f021; } public List getF022() { return f022; } public void setF022(List f022) { this.f022 = f022; } public List getF023() { return f023; } public void setF023(List f023) { this.f023 = f023; } public List getF024() { return f024; } public void setF024(List f024) { this.f024 = f024; } public List getF025() { return f025; } public void setF025(List f025) { this.f025 = f025; } public List getF026() { return f026; } public void setF026(List f026) { this.f026 = f026; } public List getF027() { return f027; } public void setF027(List f027) { this.f027 = f027; } public List getF028() { return f028; } public void setF028(List f028) { this.f028 = f028; } public List getF029() { return f029; } public void setF029(List f029) { this.f029 = f029; } public List getF030() { return f030; } public void setF030(List f030) { this.f030 = f030; } public List getF031() { return f031; } public void setF031(List f031) { this.f031 = f031; } public List getF032() { return f032; } public void setF032(List f032) { this.f032 = f032; } public List getF033() { return f033; } public void setF033(List f033) { this.f033 = f033; } public List getF034() { return f034; } public void setF034(List f034) { this.f034 = f034; } public List getF035() { return f035; } public void setF035(List f035) { this.f035 = f035; } public List getF036() { return f036; } public void setF036(List f036) { this.f036 = f036; } public List getF037() { return f037; } public void setF037(List f037) { this.f037 = f037; } public List getF038() { return f038; } public void setF038(List f038) { this.f038 = f038; } public List getF039() { return f039; } public void setF039(List f039) { this.f039 = f039; } public List getF040() { return f040; } public void setF040(List f040) { this.f040 = f040; } public List getF041() { return f041; } public void setF041(List f041) { this.f041 = f041; } public List getF042() { return f042; } public void setF042(List f042) { this.f042 = f042; } public List getF043() { return f043; } public void setF043(List f043) { this.f043 = f043; } public List getF044() { return f044; } public void setF044(List f044) { this.f044 = f044; } public List getF045() { return f045; } public void setF045(List f045) { this.f045 = f045; } public List getF046() { return f046; } public void setF046(List f046) { this.f046 = f046; } public List getF047() { return f047; } public void setF047(List f047) { this.f047 = f047; } public List getF048() { return f048; } public void setF048(List f048) { this.f048 = f048; } public List getF049() { return f049; } public void setF049(List f049) { this.f049 = f049; } public List getF050() { return f050; } public void setF050(List f050) { this.f050 = f050; } public List getF051() { return f051; } public void setF051(List f051) { this.f051 = f051; } public List getF052() { return f052; } public void setF052(List f052) { this.f052 = f052; } public List getF053() { return f053; } public void setF053(List f053) { this.f053 = f053; } public List getF054() { return f054; } public void setF054(List f054) { this.f054 = f054; } public List getF055() { return f055; } public void setF055(List f055) { this.f055 = f055; } public List getF056() { return f056; } public void setF056(List f056) { this.f056 = f056; } public List getF057() { return f057; } public void setF057(List f057) { this.f057 = f057; } public List getF058() { return f058; } public void setF058(List f058) { this.f058 = f058; } public List getF059() { return f059; } public void setF059(List f059) { this.f059 = f059; } public List getF060() { return f060; } public void setF060(List f060) { this.f060 = f060; } public List getF061() { return f061; } public void setF061(List f061) { this.f061 = f061; } public List getF062() { return f062; } public void setF062(List f062) { this.f062 = f062; } public List getF063() { return f063; } public void setF063(List f063) { this.f063 = f063; } public List getF064() { return f064; } public void setF064(List f064) { this.f064 = f064; } public List getF065() { return f065; } public void setF065(List f065) { this.f065 = f065; } public List getF066() { return f066; } public void setF066(List f066) { this.f066 = f066; } public List getF067() { return f067; } public void setF067(List f067) { this.f067 = f067; } public List getF068() { return f068; } public void setF068(List f068) { this.f068 = f068; } public List getF069() { return f069; } public void setF069(List f069) { this.f069 = f069; } public List getF070() { return f070; } public void setF070(List f070) { this.f070 = f070; } public List getF071() { return f071; } public void setF071(List f071) { this.f071 = f071; } public List getF072() { return f072; } public void setF072(List f072) { this.f072 = f072; } public List getF073() { return f073; } public void setF073(List f073) { this.f073 = f073; } public List getF074() { return f074; } public void setF074(List f074) { this.f074 = f074; } public List getF075() { return f075; } public void setF075(List f075) { this.f075 = f075; } public List getF076() { return f076; } public void setF076(List f076) { this.f076 = f076; } public List getF077() { return f077; } public void setF077(List f077) { this.f077 = f077; } public List getF078() { return f078; } public void setF078(List f078) { this.f078 = f078; } public List getF079() { return f079; } public void setF079(List f079) { this.f079 = f079; } public List getF080() { return f080; } public void setF080(List f080) { this.f080 = f080; } public List getF081() { return f081; } public void setF081(List f081) { this.f081 = f081; } public List getF082() { return f082; } public void setF082(List f082) { this.f082 = f082; } public List getF083() { return f083; } public void setF083(List f083) { this.f083 = f083; } public List getF084() { return f084; } public void setF084(List f084) { this.f084 = f084; } public List getF085() { return f085; } public void setF085(List f085) { this.f085 = f085; } public List getF086() { return f086; } public void setF086(List f086) { this.f086 = f086; } public List getF087() { return f087; } public void setF087(List f087) { this.f087 = f087; } public List getF088() { return f088; } public void setF088(List f088) { this.f088 = f088; } public List getF089() { return f089; } public void setF089(List f089) { this.f089 = f089; } public List getF090() { return f090; } public void setF090(List f090) { this.f090 = f090; } public List getF091() { return f091; } public void setF091(List f091) { this.f091 = f091; } public List getF092() { return f092; } public void setF092(List f092) { this.f092 = f092; } public List getF093() { return f093; } public void setF093(List f093) { this.f093 = f093; } public List getF094() { return f094; } public void setF094(List f094) { this.f094 = f094; } public List getF095() { return f095; } public void setF095(List f095) { this.f095 = f095; } public List getF096() { return f096; } public void setF096(List f096) { this.f096 = f096; } public List getF097() { return f097; } public void setF097(List f097) { this.f097 = f097; } public List getF098() { return f098; } public void setF098(List f098) { this.f098 = f098; } public List getF099() { return f099; } public void setF099(List f099) { this.f099 = f099; } public List getF100() { return f100; } public void setF100(List f100) { this.f100 = f100; } public List getF101() { return f101; } public void setF101(List f101) { this.f101 = f101; } public List getF102() { return f102; } public void setF102(List f102) { this.f102 = f102; } public List getF103() { return f103; } public void setF103(List f103) { this.f103 = f103; } public List getF104() { return f104; } public void setF104(List f104) { this.f104 = f104; } public List getF105() { return f105; } public void setF105(List f105) { this.f105 = f105; } public List getF106() { return f106; } public void setF106(List f106) { this.f106 = f106; } public List getF107() { return f107; } public void setF107(List f107) { this.f107 = f107; } public List getF108() { return f108; } public void setF108(List f108) { this.f108 = f108; } public List getF109() { return f109; } public void setF109(List f109) { this.f109 = f109; } public List getF110() { return f110; } public void setF110(List f110) { this.f110 = f110; } public List getF111() { return f111; } public void setF111(List f111) { this.f111 = f111; } public List getF112() { return f112; } public void setF112(List f112) { this.f112 = f112; } public List getF113() { return f113; } public void setF113(List f113) { this.f113 = f113; } public List getF114() { return f114; } public void setF114(List f114) { this.f114 = f114; } public List getF115() { return f115; } public void setF115(List f115) { this.f115 = f115; } public List getF116() { return f116; } public void setF116(List f116) { this.f116 = f116; } public List getF117() { return f117; } public void setF117(List f117) { this.f117 = f117; } public List getF118() { return f118; } public void setF118(List f118) { this.f118 = f118; } public List getF119() { return f119; } public void setF119(List f119) { this.f119 = f119; } public List getF120() { return f120; } public void setF120(List f120) { this.f120 = f120; } public List getF121() { return f121; } public void setF121(List f121) { this.f121 = f121; } public List getF122() { return f122; } public void setF122(List f122) { this.f122 = f122; } public List getF123() { return f123; } public void setF123(List f123) { this.f123 = f123; } public List getF124() { return f124; } public void setF124(List f124) { this.f124 = f124; } public List getF125() { return f125; } public void setF125(List f125) { this.f125 = f125; } public List getF126() { return f126; } public void setF126(List f126) { this.f126 = f126; } public List getF127() { return f127; } public void setF127(List f127) { this.f127 = f127; } public List getF128() { return f128; } public void setF128(List f128) { this.f128 = f128; } public List getF129() { return f129; } public void setF129(List f129) { this.f129 = f129; } public List getF130() { return f130; } public void setF130(List f130) { this.f130 = f130; } public List getF131() { return f131; } public void setF131(List f131) { this.f131 = f131; } public List getF132() { return f132; } public void setF132(List f132) { this.f132 = f132; } public List getF133() { return f133; } public void setF133(List f133) { this.f133 = f133; } public List getF134() { return f134; } public void setF134(List f134) { this.f134 = f134; } public List getF135() { return f135; } public void setF135(List f135) { this.f135 = f135; } public List getF136() { return f136; } public void setF136(List f136) { this.f136 = f136; } public List getF137() { return f137; } public void setF137(List f137) { this.f137 = f137; } public List getF138() { return f138; } public void setF138(List f138) { this.f138 = f138; } public List getF139() { return f139; } public void setF139(List f139) { this.f139 = f139; } public List getF140() { return f140; } public void setF140(List f140) { this.f140 = f140; } public List getF141() { return f141; } public void setF141(List f141) { this.f141 = f141; } public List getF142() { return f142; } public void setF142(List f142) { this.f142 = f142; } public List getF143() { return f143; } public void setF143(List f143) { this.f143 = f143; } public List getF144() { return f144; } public void setF144(List f144) { this.f144 = f144; } public List getF145() { return f145; } public void setF145(List f145) { this.f145 = f145; } public List getF146() { return f146; } public void setF146(List f146) { this.f146 = f146; } public List getF147() { return f147; } public void setF147(List f147) { this.f147 = f147; } public List getF148() { return f148; } public void setF148(List f148) { this.f148 = f148; } public List getF149() { return f149; } public void setF149(List f149) { this.f149 = f149; } public List getF150() { return f150; } public void setF150(List f150) { this.f150 = f150; } public List getF151() { return f151; } public void setF151(List f151) { this.f151 = f151; } public List getF152() { return f152; } public void setF152(List f152) { this.f152 = f152; } public List getF153() { return f153; } public void setF153(List f153) { this.f153 = f153; } public List getF154() { return f154; } public void setF154(List f154) { this.f154 = f154; } public List getF155() { return f155; } public void setF155(List f155) { this.f155 = f155; } public List getF156() { return f156; } public void setF156(List f156) { this.f156 = f156; } public List getF157() { return f157; } public void setF157(List f157) { this.f157 = f157; } public List getF158() { return f158; } public void setF158(List f158) { this.f158 = f158; } public List getF159() { return f159; } public void setF159(List f159) { this.f159 = f159; } public List getF160() { return f160; } public void setF160(List f160) { this.f160 = f160; } public List getF161() { return f161; } public void setF161(List f161) { this.f161 = f161; } public List getF162() { return f162; } public void setF162(List f162) { this.f162 = f162; } public List getF163() { return f163; } public void setF163(List f163) { this.f163 = f163; } public List getF164() { return f164; } public void setF164(List f164) { this.f164 = f164; } public List getF165() { return f165; } public void setF165(List f165) { this.f165 = f165; } public List getF166() { return f166; } public void setF166(List f166) { this.f166 = f166; } public List getF167() { return f167; } public void setF167(List f167) { this.f167 = f167; } public List getF168() { return f168; } public void setF168(List f168) { this.f168 = f168; } public List getF169() { return f169; } public void setF169(List f169) { this.f169 = f169; } public List getF170() { return f170; } public void setF170(List f170) { this.f170 = f170; } public List getF171() { return f171; } public void setF171(List f171) { this.f171 = f171; } public List getF172() { return f172; } public void setF172(List f172) { this.f172 = f172; } public List getF173() { return f173; } public void setF173(List f173) { this.f173 = f173; } public List getF174() { return f174; } public void setF174(List f174) { this.f174 = f174; } public List getF175() { return f175; } public void setF175(List f175) { this.f175 = f175; } public List getF176() { return f176; } public void setF176(List f176) { this.f176 = f176; } public List getF177() { return f177; } public void setF177(List f177) { this.f177 = f177; } public List getF178() { return f178; } public void setF178(List f178) { this.f178 = f178; } public List getF179() { return f179; } public void setF179(List f179) { this.f179 = f179; } public List getF180() { return f180; } public void setF180(List f180) { this.f180 = f180; } public List getF181() { return f181; } public void setF181(List f181) { this.f181 = f181; } public List getF182() { return f182; } public void setF182(List f182) { this.f182 = f182; } public List getF183() { return f183; } public void setF183(List f183) { this.f183 = f183; } public List getF184() { return f184; } public void setF184(List f184) { this.f184 = f184; } public List getF185() { return f185; } public void setF185(List f185) { this.f185 = f185; } public List getF186() { return f186; } public void setF186(List f186) { this.f186 = f186; } public List getF187() { return f187; } public void setF187(List f187) { this.f187 = f187; } public List getF188() { return f188; } public void setF188(List f188) { this.f188 = f188; } public List getF189() { return f189; } public void setF189(List f189) { this.f189 = f189; } public List getF190() { return f190; } public void setF190(List f190) { this.f190 = f190; } public List getF191() { return f191; } public void setF191(List f191) { this.f191 = f191; } public List getF192() { return f192; } public void setF192(List f192) { this.f192 = f192; } public List getF193() { return f193; } public void setF193(List f193) { this.f193 = f193; } public List getF194() { return f194; } public void setF194(List f194) { this.f194 = f194; } public List getF195() { return f195; } public void setF195(List f195) { this.f195 = f195; } public List getF196() { return f196; } public void setF196(List f196) { this.f196 = f196; } public List getF197() { return f197; } public void setF197(List f197) { this.f197 = f197; } public List getF198() { return f198; } public void setF198(List f198) { this.f198 = f198; } public List getF199() { return f199; } public void setF199(List f199) { this.f199 = f199; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2784.java ================================================ package com.alibaba.json.bvt.issue_2700; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.Date; public class Issue2784 extends TestCase { public void test_for_issue() throws Exception { Model m = new Model(); m.time = java.time.LocalDateTime.now(); String str = JSON.toJSONString(m); assertEquals("{\"time\":" + m.time.atZone(JSON.defaultTimeZone.toZoneId()).toInstant().toEpochMilli() + "}", str); Model m1 = JSON.parseObject(str, Model.class); assertEquals(m.time, m1.time); } public void test_for_issue_1() throws Exception { Model m = new Model(); m.ztime = ZonedDateTime.now(); String str = JSON.toJSONString(m); assertEquals("{\"ztime\":" + m.ztime.toInstant().toEpochMilli() + "}", str); Model m1 = JSON.parseObject(str, Model.class); assertEquals(m.ztime.toInstant().toEpochMilli(), m1.ztime.toInstant().toEpochMilli()); } public void test_for_issue_2() throws Exception { Model m = new Model(); m.time1 = java.time.LocalDateTime.now(); String str = JSON.toJSONString(m); assertEquals("{\"time1\":" + m.time1.atZone(JSON.defaultTimeZone.toZoneId()).toEpochSecond() + "}", str); Model m1 = JSON.parseObject(str, Model.class); assertEquals(m.time1.atZone(JSON.defaultTimeZone.toZoneId()).toEpochSecond() , m1.time1.atZone(JSON.defaultTimeZone.toZoneId()).toEpochSecond()); } public void test_for_issue_3() throws Exception { Model m = new Model(); m.ztime1 = ZonedDateTime.now(); String str = JSON.toJSONString(m); assertEquals("{\"ztime1\":" + m.ztime1.toEpochSecond() + "}", str); Model m1 = JSON.parseObject(str, Model.class); assertEquals(m.ztime1.toEpochSecond() , m1.ztime1.toEpochSecond()); } public void test_for_issue_4() throws Exception { Model m = new Model(); m.date = new Date(); String str = JSON.toJSONString(m); assertEquals("{\"date\":" + m.date.getTime() + "}", str); Model m1 = JSON.parseObject(str, Model.class); assertEquals(m.date.getTime() , m1.date.getTime()); } public void test_for_issue_5() throws Exception { Model m = new Model(); m.date1 = new Date(); String str = JSON.toJSONString(m); assertEquals("{\"date1\":" + (m.date1.getTime() / 1000) + "}", str); Model m1 = JSON.parseObject(str, Model.class); assertEquals(m.date1.getTime() / 1000 , m1.date1.getTime() / 1000); } public void test_for_issue_6() throws Exception { Model m = new Model(); m.date1 = new Date(); String str = JSON.toJSONString(m); assertEquals("{\"date1\":" + (m.date1.getTime() / 1000) + "}", str); Model m1 = JSON.parseObject(str, Model.class); assertEquals(m.date1.getTime() / 1000 , m1.date1.getTime() / 1000); } public void test_for_issue_7() throws Exception { Model m = JSON.parseObject("{\"time2\":20190714121314}", Model.class); assertEquals(m.time2, LocalDateTime.of(2019, 7, 14, 12, 13, 14)); } public static class Model { @JSONField(format = "millis") public LocalDateTime time; @JSONField(format = "millis") public ZonedDateTime ztime; @JSONField(format = "unixtime") public LocalDateTime time1; @JSONField(format = "unixtime") public ZonedDateTime ztime1; @JSONField(format = "millis") public Date date; @JSONField(format = "unixtime") public Date date1; @JSONField(format = "yyyyMMddHHmmss") public LocalDateTime time2; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2787.java ================================================ package com.alibaba.json.bvt.issue_2700; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue2787 extends TestCase { public void test_for_issue() throws Exception { Model m = new Model(); String str = JSON.toJSONString(m, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty); assertEquals("{\"value\":[]}", str); } public static class Model { public int[] value; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2791.java ================================================ package com.alibaba.json.bvt.issue_2700; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue2791 extends TestCase { public void test_for_issue() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"dependencies\":[{\"values\":[{\"name\":\"Demo\"}]}]}"); JSONPath.remove(jsonObject, "$.dependencies.values[?(@.name=='Demo')]"); assertEquals("{\"dependencies\":[{\"values\":[]}]}", jsonObject.toString()); } public void test_for_issue1() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"dependencies\":[{\"values\":{\"name\":\"Demo\"}}]}"); JSONPath.remove(jsonObject, "$.dependencies.values[?(@.name=='Demo')]"); assertEquals("{\"dependencies\":[]}", jsonObject.toString()); } public void test_for_issue2() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"values\":[{\"name\":\"Demo\"}]}"); JSONPath.remove(jsonObject, "$.values[?(@.name=='Demo')]"); assertEquals("{\"values\":[]}", jsonObject.toString()); } public void test_for_issue3() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"values\":{\"name\":\"Demo\"}}"); assertTrue(JSONPath.remove(jsonObject, "$.values[?(@.name=='Demo')]")); assertEquals("{}", jsonObject.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2700/Issue2792.java ================================================ package com.alibaba.json.bvt.issue_2700; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue2792 extends TestCase { public void test_for_issue() throws Exception { String jsonpath = "$.sku[?((@.quantity != 0)&&(@.is_onsale == 1))].sku_id"; JSONObject root = JSON.parseObject("{\"sku\":{\"quantity\":12,\"is_onsale\":1,\"sku_id\":42356}}"); assertEquals(42356, JSONPath.eval(root, jsonpath)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2800/Issue2830.java ================================================ package com.alibaba.json.bvt.issue_2800; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; public class Issue2830 extends TestCase { public void test_for_issue() throws Exception { JSONObject jsonObject = JSONObject.parseObject("{\"qty\":\"10\",\"qty1\":\"10.0\",\"qty2\":\"10.000\"}"); assertEquals(10, jsonObject.getIntValue("qty")); assertEquals(10, jsonObject.getIntValue("qty1")); assertEquals(10, jsonObject.getIntValue("qty2")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2800/Issue2866.java ================================================ package com.alibaba.json.bvt.issue_2800; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; public class Issue2866 extends TestCase { public void test_for_issue() throws Exception { String json = "{\"A1\":1,\"A2\":2,\"A3\":3}"; A a = JSON.parseObject(json, A.class, Feature.SupportNonPublicField); assertEquals(1, a.a1); assertEquals(2, a.A2); assertEquals(3, a.a3); } static class A{ @JSONField(name="A1") int a1; int A2; @JSONField(name="A3") public int a3; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2800/Issue2894.java ================================================ package com.alibaba.json.bvt.issue_2800; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import lombok.Data; import java.sql.Timestamp; import java.util.Locale; import java.util.TimeZone; public class Issue2894 extends TestCase { protected void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getDefault(); JSON.defaultLocale = Locale.CHINA; } public void test_for_issue() throws Exception { String json = "{\"timestamp\":\"2019-09-19 08:49:52.350000000\"}"; Pojo pojo = JSONObject.parseObject(json, Pojo.class); int nanos = pojo.timestamp.getNanos(); assertEquals(nanos, 350000000); assertEquals("{\"timestamp\":\"2019-09-19 08:49:52.000000350\"}", JSON.toJSONString(pojo)); } public static class Pojo { @JSONField(name = "timestamp", format = "yyyy-MM-dd HH:mm:ss.SSSSSSSSS") public Timestamp timestamp; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2800/Issue2903.java ================================================ package com.alibaba.json.bvt.issue_2800; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue2903 extends TestCase { public void test_1() { String date1 = "{createTime:\"1570636800000\"}"; String date2 = "{createTime:1570636800000}"; LoginRequestDTO dto = JSON.parseObject(date1, LoginRequestDTO.class); LoginRequestDTO dto2 = JSON.parseObject(date2, LoginRequestDTO.class); assertEquals(dto.createTime, dto2.createTime); } public void test_2() { String date1 = "{createTime:\"1570636800000\"}"; String date2 = "{createTime:1570636800000}"; LoginRequestDTO2 dto = JSON.parseObject(date1, LoginRequestDTO2.class); LoginRequestDTO2 dto2 = JSON.parseObject(date2, LoginRequestDTO2.class); assertEquals(dto.createTime, dto2.createTime); } public void test_3() { String date1 = "{createTime:\"1570636800000\"}"; String date2 = "{createTime:1570636800000}"; LoginRequestDTO3 dto = JSON.parseObject(date1, LoginRequestDTO3.class); LoginRequestDTO3 dto2 = JSON.parseObject(date2, LoginRequestDTO3.class); assertEquals(dto.createTime, dto2.createTime); } public void test_4() { String date1 = "{createTime:\"1570636800000\"}"; String date2 = "{createTime:1570636800000}"; LoginRequestDTO4 dto = JSON.parseObject(date1, LoginRequestDTO4.class); LoginRequestDTO4 dto2 = JSON.parseObject(date2, LoginRequestDTO4.class); assertEquals(dto.createTime, dto2.createTime); } public void test_5() { String date1 = "{createTime:\"1570636800000\"}"; String date2 = "{createTime:1570636800000}"; LoginRequestDTO5 dto = JSON.parseObject(date1, LoginRequestDTO5.class); LoginRequestDTO5 dto2 = JSON.parseObject(date2, LoginRequestDTO5.class); assertEquals(dto.createTime, dto2.createTime); } public void test_6() { String date1 = "{createTime:\"1570636800000\"}"; String date2 = "{createTime:1570636800000}"; LoginRequestDTO6 dto = JSON.parseObject(date1, LoginRequestDTO6.class); LoginRequestDTO6 dto2 = JSON.parseObject(date2, LoginRequestDTO6.class); assertEquals(dto.createTime, dto2.createTime); } public void test_7() { String date1 = "{createTime:\"1570636800000\"}"; String date2 = "{createTime:1570636800000}"; LoginRequestDTO7 dto = JSON.parseObject(date1, LoginRequestDTO7.class); LoginRequestDTO7 dto2 = JSON.parseObject(date2, LoginRequestDTO7.class); assertEquals(dto.createTime, dto2.createTime); } public void test_8() { String date1 = "{createTime:\"1570636800000\"}"; String date2 = "{createTime:1570636800000}"; LoginRequestDTO8 dto = JSON.parseObject(date1, LoginRequestDTO8.class); LoginRequestDTO8 dto2 = JSON.parseObject(date2, LoginRequestDTO8.class); assertEquals(dto.createTime, dto2.createTime); } public static class LoginRequestDTO { public java.time.LocalDateTime createTime; } public static class LoginRequestDTO2 { public java.time.LocalDate createTime; } public static class LoginRequestDTO3 { public java.time.LocalTime createTime; } public static class LoginRequestDTO4 { public java.time.ZonedDateTime createTime; } public static class LoginRequestDTO5 { public org.joda.time.LocalDateTime createTime; } public static class LoginRequestDTO6 { public org.joda.time.LocalDate createTime; } public static class LoginRequestDTO7 { public org.joda.time.Instant createTime; } public static class LoginRequestDTO8 { public java.time.Instant createTime; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2900/Issue2914.java ================================================ package com.alibaba.json.bvt.issue_2900; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; public class Issue2914 extends TestCase { public void test_for_issue() throws Exception { ComplexInt complexInt = new ComplexInt(); Queue blockQueueInt = new ArrayBlockingQueue(5); blockQueueInt.offer(1); blockQueueInt.offer(2); blockQueueInt.offer(3); complexInt.setBlockQueue(blockQueueInt); String jsonInt = JSON.toJSONString(complexInt); assertEquals("{\"blockQueue\":[1,2,3]}",jsonInt); ComplexInt complexInt1 = JSON.parseObject(jsonInt,Issue2914.ComplexInt.class); assertEquals(3, complexInt1.getBlockQueue().size()); Complex complex = new Complex(); Queue blockQueue = new ArrayBlockingQueue(5); blockQueue.offer("BlockQueue 1"); blockQueue.offer("BlockQueue 2"); blockQueue.offer("BlockQueue 3"); complex.setBlockQueue(blockQueue); String json = JSON.toJSONString(complex); assertEquals("{\"blockQueue\":[\"BlockQueue 1\",\"BlockQueue 2\",\"BlockQueue 3\"]}",json); Complex complex1 = JSON.parseObject(json,Issue2914.Complex.class); assertEquals(3, complex1.getBlockQueue().size()); } public static class Complex { private Queue blockQueue; public Queue getBlockQueue() { return blockQueue; } public void setBlockQueue(Queue blockQueue) { this.blockQueue = blockQueue; } } public static class ComplexInt { private Queue blockQueue; public Queue getBlockQueue() { return blockQueue; } public void setBlockQueue(Queue blockQueue) { this.blockQueue = blockQueue; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2900/Issue2939.java ================================================ package com.alibaba.json.bvt.issue_2900; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; public class Issue2939 extends TestCase { public void test_for_issue() throws Exception { LinkedMultiValueMap multiValueMap = new LinkedMultiValueMap(); multiValueMap.add("k1","k11"); multiValueMap.add("k1","k12"); multiValueMap.add("k1","k13"); multiValueMap.add("k2","k21"); String json = JSON.toJSONString(multiValueMap); assertEquals("{\"k1\":[\"k11\",\"k12\",\"k13\"],\"k2\":[\"k21\"]}", json); Object obj = JSON.parseObject(json, LinkedMultiValueMap.class); assertTrue(obj != null); LinkedMultiValueMap map = (LinkedMultiValueMap) obj; assertSame(3, map.get("k1").size()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2900/Issue2952.java ================================================ package com.alibaba.json.bvt.issue_2900; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue2952 extends TestCase { public void test_for_issue() throws Exception { String expected = "{\"l\":null,\"s\":null,\"b\":null,\"i\":null,\"o\":null}"; SerializerFeature[] serializerFeatures = { SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullNumberAsZero }; SerializeConfig asmConfig = new SerializeConfig(); asmConfig.setAsmEnable(true); assertEquals(expected, JSON.toJSONString(new Pojo(), asmConfig, serializerFeatures)); assertEquals(expected, JSON.toJSONString(new Pojo2(), asmConfig, serializerFeatures)); SerializeConfig noasmConfig = new SerializeConfig(); noasmConfig.setAsmEnable(false); assertEquals(expected, JSON.toJSONString(new Pojo(), noasmConfig, serializerFeatures)); assertEquals(expected, JSON.toJSONString(new Pojo2(), noasmConfig, serializerFeatures)); } public static class Pojo { @JSONField(serialzeFeatures=SerializerFeature.WriteMapNullValue, ordinal=0) public Object[] l; @JSONField(serialzeFeatures=SerializerFeature.WriteMapNullValue, ordinal=1) public String s; @JSONField(serialzeFeatures=SerializerFeature.WriteMapNullValue, ordinal=2) public Boolean b; @JSONField(serialzeFeatures=SerializerFeature.WriteMapNullValue, ordinal=3) public Integer i; @JSONField(serialzeFeatures=SerializerFeature.WriteMapNullValue, ordinal=4) public Object o; } @JSONType(serialzeFeatures=SerializerFeature.WriteMapNullValue) public static class Pojo2 { @JSONField(ordinal=0) public Object[] l; @JSONField(ordinal=1) public String s; @JSONField(ordinal=2) public Boolean b; @JSONField(ordinal=3) public Integer i; @JSONField(ordinal=4) public Object o; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2900/Issue2962.java ================================================ package com.alibaba.json.bvt.issue_2900; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue2962 extends TestCase { private TimeZone original = TimeZone.getDefault(); @Override public void tearDown () { TimeZone.setDefault(original); JSON.defaultTimeZone = original; } public void test_dates_different_timeZones() { for (String id : TimeZone.getAvailableIDs()) { TimeZone timeZone = TimeZone.getTimeZone(id); TimeZone.setDefault(timeZone); JSON.defaultTimeZone = timeZone; Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); VO vo = new VO(); vo.date = now; String json = JSON.toJSONString(vo); VO result = JSON.parseObject(json, VO.class); assertEquals(vo.date, result.date); // with iso-format json = JSON.toJSONString(vo, SerializerFeature.UseISO8601DateFormat); System.out.println(id + " " + json); result = JSON.parseObject(json, VO.class); assertEquals(JSON.toJSONString(vo.date), JSON.toJSONString(result.date)); } } public static class VO { public Date date; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_2900/Issue2982.java ================================================ package com.alibaba.json.bvt.issue_2900; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import org.junit.Test; public class Issue2982 extends TestCase { @Test public void test_for_issue() { String jsonStr = "[ { \"activity_type\" : 0, \"activity_id\" : \"***\", \"activity_tip\" : \"***\", \"position\" : \"1\" }, { \"activity_type\" : 0, \"activity_id\" : \"2669\", \"activity_tip\" : \"****\", \"position\" : \"1\" }]"; assertTrue(JSONArray.isValidArray(jsonStr)); assertTrue(JSON.isValidArray(jsonStr)); assertTrue(JSONObject.isValidArray(jsonStr)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3000/Issue3031.java ================================================ package com.alibaba.json.bvt.issue_3000; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue3031 extends TestCase { public void test_for_issue() throws Exception { String str = "{\"success\":true,\"message\":null,\"data\":[{\"tblId\":78,\"partId\":104,\"values\":[\"p001\",\"q001\"],\"dbName\":\"db001\",\"tableName\":\"tbl001\",\"createTime\":1582293531,\"lastAccessTime\":1,\"sd\":{\"sdId\":182,\"cdId\":181,\"cols\":[{\"name\":\"col1\",\"type\":\"string\",\"comment\":null},{\"name\":\"col2\",\"type\":\"int\",\"comment\":\"col2\"},{\"name\":\"col3\",\"type\":\"boolean\",\"comment\":null}],\"location\":\"oss://temp/jianghu/db001/tbl001\",\"inputFormat\":\"org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat\",\"outputFormat\":\"org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat\",\"compressed\":true,\"numBuckets\":2,\"serdeInfo\":{\"serdeId\":182,\"name\":null,\"serializationLib\":\"org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe\",\"parameters\":{\"field.delim\":\"\\t\",\"serialization.format\":\"\\t\"}},\"bucketCols\":[\"col1\"],\"sortCols\":[{\"col\":\"col1\",\"order\":0}],\"parameters\":{},\"skewedInfo\":{\"skewedColNames\":[\"col1\",\"col3\"],\"skewedColValues\":[[\"2\",\"1\"],[\"3\",\"2\"]],\"skewedColValueLocationMaps\":{}},\"storedAsSubDirectories\":false},\"parameters\":{\"totalSize\":\"0\",\"numRows\":\"-1\",\"rawDataSize\":\"-1\",\"COLUMN_STATS_ACCURATE\":\"false\",\"numFiles\":\"0\",\"transient_lastDdlTime\":\"1582293531\"},\"parametersSize\":6},{\"tblId\":78,\"partId\":105,\"values\":[\"p001\",\"q002\"],\"dbName\":\"db001\",\"tableName\":\"tbl001\",\"createTime\":1582293531,\"lastAccessTime\":1,\"sd\":{\"sdId\":183,\"cdId\":181,\"cols\":[{\"name\":\"col1\",\"type\":\"string\",\"comment\":null},{\"name\":\"col2\",\"type\":\"int\",\"comment\":\"col2\"},{\"name\":\"col3\",\"type\":\"boolean\",\"comment\":null}],\"location\":\"oss://temp/jianghu/db001/tbl001\",\"inputFormat\":\"org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat\",\"outputFormat\":\"org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat\",\"compressed\":true,\"numBuckets\":2,\"serdeInfo\":{\"serdeId\":183,\"name\":null,\"serializationLib\":\"org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe\",\"parameters\":{\"field.delim\":\"\\t\",\"serialization.format\":\"\\t\"}},\"bucketCols\":[\"col1\"],\"sortCols\":[{\"col\":\"col1\",\"order\":0}],\"parameters\":{},\"skewedInfo\":{\"skewedColNames\":[\"col1\",\"col3\"],\"skewedColValues\":[[\"2\",\"1\"],[\"3\",\"2\"]],\"skewedColValueLocationMaps\":{}},\"storedAsSubDirectories\":false},\"parameters\":{\"totalSize\":\"0\",\"numRows\":\"-1\",\"rawDataSize\":\"-1\",\"COLUMN_STATS_ACCURATE\":\"false\",\"numFiles\":\"0\",\"transient_lastDdlTime\":\"1582293531\",\"$ref\":\"$[0].parameters\"},\"parametersSize\":7},{\"tblId\":78,\"partId\":106,\"values\":[\"p002\",\"q002\"],\"dbName\":\"db001\",\"tableName\":\"tbl001\",\"createTime\":1582293531,\"lastAccessTime\":1,\"sd\":{\"sdId\":184,\"cdId\":181,\"cols\":[{\"name\":\"col1\",\"type\":\"string\",\"comment\":null},{\"name\":\"col2\",\"type\":\"int\",\"comment\":\"col2\"},{\"name\":\"col3\",\"type\":\"boolean\",\"comment\":null}],\"location\":\"oss://temp/jianghu/db001/tbl001\",\"inputFormat\":\"org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat\",\"outputFormat\":\"org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat\",\"compressed\":true,\"numBuckets\":2,\"serdeInfo\":{\"serdeId\":184,\"name\":null,\"serializationLib\":\"org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe\",\"parameters\":{\"field.delim\":\"\\t\",\"serialization.format\":\"\\t\"}},\"bucketCols\":[\"col1\"],\"sortCols\":[{\"col\":\"col1\",\"order\":0}],\"parameters\":{},\"skewedInfo\":{\"skewedColNames\":[\"col1\",\"col3\"],\"skewedColValues\":[[\"2\",\"1\"],[\"3\",\"2\"]],\"skewedColValueLocationMaps\":{}},\"storedAsSubDirectories\":false},\"parameters\":{\"totalSize\":\"0\",\"numRows\":\"-1\",\"rawDataSize\":\"-1\",\"COLUMN_STATS_ACCURATE\":\"false\",\"numFiles\":\"0\",\"transient_lastDdlTime\":\"1582293531\",\"$ref\":\"$[0].parameters\"},\"parametersSize\":7}]}"; System.out.println(str); ResultData obj = JSON.parseObject(str, ResultData.class); } public static class ResultData { private boolean success; private String message; private Object data; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3000/Issue3049.java ================================================ package com.alibaba.json.bvt.issue_3000; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue3049 extends TestCase { public void test_for_issue() throws Exception { String json1 = "{\"date\":\"2019-11-1 21:45:12\"}"; MyObject myObject1 = JSON.parseObject(json1, MyObject.class); String str2 = JSON.toJSONStringWithDateFormat(myObject1, "yyyy-MM-dd HH:mm:ss"); assertEquals("{\"date\":\"2019-11-01 21:45:12\"}", str2); } public static class MyObject { public java.util.Date date; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3000/Issue3057.java ================================================ package com.alibaba.json.bvt.issue_3000; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue3057 extends TestCase { public void test_for_issue() throws Exception { String str = "{\"q\":[]}"; Bean bean = JSON.parseObject(str, Bean.class); assertEquals(0, bean.q.size()); } public static class Bean { public java.util.Deque q; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3000/Issue3060.java ================================================ package com.alibaba.json.bvt.issue_3000; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class Issue3060 extends TestCase { public void test_for_issue() throws Exception { String str = "{\"type\":1}"; Bean bean = JSON.parseObject(str).toJavaObject(Bean.class); Bean bean1 = JSON.parseObject(str, Bean.class); assertEquals(bean.type, bean1.type); } public static class Bean { public int type; } public enum Type { Small, Big } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3000/Issue3065.java ================================================ package com.alibaba.json.bvt.issue_3000; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; public class Issue3065 extends TestCase { public void test_for_issue() throws Exception { String data = "{\n" + "\t\"code\":\"OK\",\n" + "\t\"data\":[\n" + "\t\t{\n" + "\t\t\t\"createTime\":1584457789,\n" + "\t\t\t\"dbName\":\"basic_test\",\n" + "\t\t\t\"lastAccessTime\":0,\n" + "\t\t\t\"parameters\":{\n" + "\t\t\t\t\"transient_lastDdlTime\":\"1584457789\"\n" + "\t\t\t},\n" + "\t\t\t\"parametersSize\":2,\n" + "\t\t\t\"partId\":2209,\n" + "\t\t\t\"sd\":{\n" + "\t\t\t\t\"bucketCols\":[],\n" + "\t\t\t\t\"cdId\":2719,\n" + "\t\t\t\t\"cols\":[\n" + "\t\t\t\t\t{\n" + "\t\t\t\t\t\t\"name\":\"n_nationkey\",\n" + "\t\t\t\t\t\t\"type\":\"int\"\n" + "\t\t\t\t\t},\n" + "\t\t\t\t\t{\n" + "\t\t\t\t\t\t\"name\":\"n_name\",\n" + "\t\t\t\t\t\t\"type\":\"string\"\n" + "\t\t\t\t\t},\n" + "\t\t\t\t\t{\n" + "\t\t\t\t\t\t\"name\":\"n_regionkey\",\n" + "\t\t\t\t\t\t\"type\":\"int\"\n" + "\t\t\t\t\t},\n" + "\t\t\t\t\t{\n" + "\t\t\t\t\t\t\"name\":\"n_comment\",\n" + "\t\t\t\t\t\t\"type\":\"string\"\n" + "\t\t\t\t\t}\n" + "\t\t\t\t],\n" + "\t\t\t\t\"compressed\":false,\n" + "\t\t\t\t\"inputFormat\":\"org.apache.hadoop.mapred.TextInputFormat\",\n" + "\t\t\t\t\"location\":\"oss://hello/world/\",\n" + "\t\t\t\t\"numBuckets\":0,\n" + "\t\t\t\t\"outputFormat\":\"org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat\",\n" + "\t\t\t\t\"parameters\":{},\n" + "\t\t\t\t\"sdId\":2662,\n" + "\t\t\t\t\"serDeInfo\":{\n" + "\t\t\t\t\t\"name\":\"nation_part_hidden\",\n" + "\t\t\t\t\t\"parameters\":{\n" + "\t\t\t\t\t\t\"field.delim\":\"|\",\n" + "\t\t\t\t\t\t\"serialization.format\":\"|\"\n" + "\t\t\t\t\t},\n" + "\t\t\t\t\t\"serdeId\":2720,\n" + "\t\t\t\t\t\"serializationLib\":\"org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe\"\n" + "\t\t\t\t},\n" + "\t\t\t\t\"skewedInfo\":{\n" + "\t\t\t\t\t\"skewedColNames\":[],\n" + "\t\t\t\t\t\"skewedColValueLocationMaps\":{},\n" + "\t\t\t\t\t\"skewedColValues\":[]\n" + "\t\t\t\t},\n" + "\t\t\t\t\"sortCols\":[],\n" + "\t\t\t\t\"storedAsSubDirectories\":false\n" + "\t\t\t},\n" + "\t\t\t\"tableName\":\"nation_part_hidden\",\n" + "\t\t\t\"tblId\":453,\n" + "\t\t\t\"values\":[\n" + "\t\t\t\t\"2019\",\n" + "\t\t\t\t\"01\",\n" + "\t\t\t\t\"15\"\n" + "\t\t\t]\n" + "\t\t},\n" + "\t\t{\n" + "\t\t\t\"createTime\":1584457789,\n" + "\t\t\t\"dbName\":\"basic_test\",\n" + "\t\t\t\"lastAccessTime\":0,\n" + "\t\t\t\"parameters\":{\n" + "\t\t\t\t\"transient_lastDdlTime\":\"1584457789\"\n" + "\t\t\t},\n" + "\t\t\t\"parametersSize\":2,\n" + "\t\t\t\"partId\":2210,\n" + "\t\t\t\"sd\":{\n" + "\t\t\t\t\"bucketCols\":[],\n" + "\t\t\t\t\"cdId\":2719,\n" + "\t\t\t\t\"cols\":[\n" + "\t\t\t\t\t{\n" + "\t\t\t\t\t\t\"name\":\"n_nationkey\",\n" + "\t\t\t\t\t\t\"type\":\"int\"\n" + "\t\t\t\t\t},\n" + "\t\t\t\t\t{\n" + "\t\t\t\t\t\t\"name\":\"n_name\",\n" + "\t\t\t\t\t\t\"type\":\"string\"\n" + "\t\t\t\t\t},\n" + "\t\t\t\t\t{\n" + "\t\t\t\t\t\t\"name\":\"n_regionkey\",\n" + "\t\t\t\t\t\t\"type\":\"int\"\n" + "\t\t\t\t\t},\n" + "\t\t\t\t\t{\n" + "\t\t\t\t\t\t\"name\":\"n_comment\",\n" + "\t\t\t\t\t\t\"type\":\"string\"\n" + "\t\t\t\t\t}\n" + "\t\t\t\t],\n" + "\t\t\t\t\"compressed\":false,\n" + "\t\t\t\t\"inputFormat\":\"org.apache.hadoop.mapred.TextInputFormat\",\n" + "\t\t\t\t\"location\":\"oss://hello/world/\",\n" + "\t\t\t\t\"numBuckets\":0,\n" + "\t\t\t\t\"outputFormat\":\"org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat\",\n" + "\t\t\t\t\"parameters\":{\n" + "\t\t\t\t\t\"$ref\":\"$[0].sd.parameters\"\n" + "\t\t\t\t},\n" + "\t\t\t\t\"sdId\":2663,\n" + "\t\t\t\t\"serDeInfo\":{\n" + "\t\t\t\t\t\"name\":\"nation_part_hidden\",\n" + "\t\t\t\t\t\"parameters\":{\n" + "\t\t\t\t\t\t\"$ref\":\"$[0].sd.serDeInfo.parameters\"\n" + "\t\t\t\t\t},\n" + "\t\t\t\t\t\"serdeId\":2721,\n" + "\t\t\t\t\t\"serializationLib\":\"org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe\"\n" + "\t\t\t\t},\n" + "\t\t\t\t\"skewedInfo\":{\n" + "\t\t\t\t\t\"skewedColNames\":[],\n" + "\t\t\t\t\t\"skewedColValueLocationMaps\":{},\n" + "\t\t\t\t\t\"skewedColValues\":[]\n" + "\t\t\t\t},\n" + "\t\t\t\t\"sortCols\":[],\n" + "\t\t\t\t\"storedAsSubDirectories\":false\n" + "\t\t\t},\n" + "\t\t\t\"tableName\":\"nation_part_hidden\",\n" + "\t\t\t\"tblId\":453,\n" + "\t\t\t\"values\":[\n" + "\t\t\t\t\"2018\",\n" + "\t\t\t\t\"12\",\n" + "\t\t\t\t\"20\"\n" + "\t\t\t]\n" + "\t\t}\n" + "\t],\n" + "\t\"success\":true\n" + "}"; ResultData resultData = JSON.parseObject(data, ResultData.class); System.out.println(resultData); } public static class ResultData { private boolean success; private String message; private Object data; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3000/Issue3066.java ================================================ package com.alibaba.json.bvt.issue_3000; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class Issue3066 extends TestCase { public void test_for_jsonpath() throws Exception { String str = "{ 'id' : 0, 'items' : [ {'name': 'apple', 'price' : 30 }, {'name': 'pear', 'price' : 40 } ] }"; JSONObject root = JSON.parseObject(str); Object max = JSONPath.eval(root, "$.items[*].price.max()"); assertEquals(40, max); Object min = JSONPath.eval(root, "$.items[*].price.min()"); assertEquals(30, min); Object count = JSONPath.eval(root, "$.items[*].price.size()"); assertEquals(2, count); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3000/Issue3075.java ================================================ package com.alibaba.json.bvt.issue_3000; import com.alibaba.fastjson.JSON; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue3075 extends TestCase { public void test_for_issue() throws Exception { SerializerFeature[] features = { SerializerFeature.BrowserSecure, // 消除对同一对象重复引用的优化 SerializerFeature.DisableCircularReferenceDetect, // 将中文都会序列化为\Uxxxx 格式 // 超过 −9007199254740992 到 9007199254740992 区间使用字符串,如:"9007199254740993" // FIXME: 序列化的时候会导致空指针。 SerializerFeature.BrowserCompatible, // 不隐藏为空的字段 SerializerFeature.IgnoreNonFieldGetter, // map为Null,置为{} SerializerFeature.WriteMapNullValue, // Long、Integer、Short等number类型为Null,置为0 SerializerFeature.WriteNullNumberAsZero, // Boolean为Null,置为false SerializerFeature.WriteNullBooleanAsFalse, // List为Null,置为[] SerializerFeature.WriteNullListAsEmpty, // String为Null,置为"" SerializerFeature.WriteNullStringAsEmpty }; JSON.toJSONString(new TestBasicBO(), features); JSON.toJSONString(new TestBO(), features); } @NoArgsConstructor @Data public static class TestBasicBO { String udgxhkk; String dvbvgtm; String cegnjlhiz; String tmztsttazf; List dszukwrs; String stymi; Float uwobf; Float dcvnlfo; Float bjlrxreby; Float sgljt; Float irqtbtgugfk; Float usnvv; Float gfeqybelageu; Float bccbcqtb; Float znkdwgblhji; Float uktxicvsrxui; Float sujnyvlz; Integer grihhxsxehct; Integer vqyqv; Integer wiipi; Float sxdihakgyuja; Integer xpspehqs; Integer aiysq; Integer zdzbdg; Float pzhjnnvzsujn; Float wdyfoawjsupo; List rtfskvdd; String txwrimwo; List rlsueycznbec; Integer wiboqxnnyjby; Integer tpjgzadsl; Integer ncwzji; Integer gxslparv; Integer zcioiclpkc; Integer esjloj; Integer jrmzi; Integer coqxh; Integer csdylng; Integer fliuk; List rbnbk; String kqclmytapnfm; Integer dqlndt; String ciergywnviyc; Float qffnfbmg; String hzases; Integer yfywdwpckn; String mfhkzjjtac; String egldba; Integer dsnkiipg; String owllvncxwc; String umcnrocpnk; Integer pzjnnkxkpu; String cbepkbipiwy; String sidtoadm; Integer gbebsls; String qdmjhio; String qwhctpjrqzl; Integer asqxntoueop; String diffdush; Integer bkieoangrm; List comyayjvkvw; List ndvjktzzuzzu; List dmncb; List aicnh; List noznm; List mtovpqvrvt; List cyoeso; List xexcw; List nhtdqd; List lqrcqrsuobml; List pbsdnbzzdw; List yxlqyliyqvrg; List tmlmaoycqtuw; Integer ldcirqriayn; Float yiqgeq; Float olqnefjnprtz; Float shkfyrpytfa; Float tzcmipuj; Integer fklflsx; Integer walrdei; Integer qwqtkuqmsla; String nzqduoel; Integer otpza; String cctxjwhjmyi; Integer mzsgtnyfk; String ftskxhjtcb; Integer gbrujvscq; String dzxmmw; Integer rhqdugvayl; Integer aookder; String qscvra; Integer upyubsp; String shzagw; Integer tweniwhxvjjn; Integer tzkuser; Integer vkbutizlvwvv; String qzvhgpew; Integer wwrrphmki; String xsvhkcmil; Integer cyseso; String uaqnzjmxru; Integer ydmvnvwidrb; String xppwn; Integer egamsuczb; String sdgcotcjilz; Integer kxjkjlxllhqm; String ycmkvjnwnxw; Integer dnzba; Integer gtxrnyzeeay; Integer snhxyanxkjd; String qcbcy; List ahiatnsb; String zuetqpbl; Integer dmalnj; String rhvkww; Integer ccipz; String batjsa; Integer xilrdu; String zcddn; Integer savddhvsw; String wpfkrmo; Integer lxwqeglqg; String pzrsbjwftbn; String bksteu; Float uldnytaqnvj; Float tniiqgfvku; Float pojntm; String tfgkvrve; Float lwtesutqb; Float owqfxakmzooj; Float cmmtltk; Float hekkfyhn; Float liedzk; Float yvmiaa; Float kprftdvaqi; Float lqookvn; Float bxpchxhsweq; Float poqkjonoof; Float qaioeuzuohn; Float pifwzgq; Float cdzuozdqwbgm; Float lbifqqimiv; Float pxsgjlv; Float tttkh; Float mbufzjclnhx; Float scxuelvrmxsn; Float bdptli; Float xczxonza; Float ldwssjxb; Float wiouipwwqjbg; Float vniafvt; Float vssktgubhnx; Float kflyvz; Integer aknemh; Integer nidynr; Integer bpwizpukvh; Integer crskvy; String licwnil; Integer ckanqgwvq; Integer bxztcjyhgpw; Integer nplybxzhxtsw; Integer fqdcmqlq; Integer crikxhlpbw; Float ejegbhvhbqkp; Float rhsvcd; Float mtbpgsnbkfa; Float fghdkkdl; Float lvnmyj; Integer bgsakgxawgjh; String nzvgyrodtsr; String abdrwew; Float amvfspvwb; Integer dqvyvmnmj; Float xowqdimpyxmw; Integer fkrdbixfma; Float hhufuxqln; Float uebyr; Float syavzsxriebg; Float zovgafxv; Float ctdcbxbkwoll; Float rinfpkytok; Float gpulotiilxcr; Float aovpmxvxpfg; Float zigtcxcepxc; Float mmavfb; Float mczfhudqhqa; Float nfqdpdkbxt; Float lcjdxon; Float xcmmtzhwraox; Float bajzw; Float fymfzjnu; Float etkfygf; Float dqlepesaxea; Float lwsuvrnsf; Float vbndsascz; Float aoxujoci; Integer jflepnqlqfrc; String crmxb; String lfxwl; Integer aajylvzrzdhf; String upoymzbopmks; String wohec; String eqaqhqbz; Integer oblaryua; String ibjqnseq; String xhwwq; Integer iyoak; String mimgsfedn; String gvoadzr; List zsicdjrekfe; String aghymcgm; List szqwrym; String nzwpcvb; List yaqvf; String oofni; List gywrntf; String vpliqryy; List xghtojazsz; String rlpvlptk; Integer egntvt; String awoqmlx; Integer zpppbvgi; String gaioivdrwz; Integer lqmaz; List tdblj; List mmtavpe; List mzxphtilz; Integer xohrlfdgjq; String surbjsnsnz; String ibcsu; String limfokbgjgr; } @NoArgsConstructor @Data public static class TestBO extends TestBasicBO{ public String mlbkyxy; public List sqhgpd; public List nikawljmoafb; public String rphau; public Integer iwhjp; public String pjevuugkw; public List orpkgtuiz; public String jsbxdscp; public String epnrgnejvfm; public Integer poeihbdfwe; public List mzzaoocfntzn; public List lrvkotdxp; public List udkknpqpey; public Float uibav; public Integer owuwykgifldl; public String cjyxckl; public String lkfkoddqme; public Integer dkcggnjzgdzj; public Float gerjcltp; public String gcfaiwj; public Float bmuniiladuu; public List fsuahyioln; public Integer knpvvsju; public Integer bimvkoauvkdm; public List fnuxllxfcc; public List udkpqjtlhxy; public String xtsrpb; public List pmxbc; public String rtkvfukhtca; public Integer vnxnxg; public Float gipmqit; public Integer dzufoeglnsl; public List wahnlujq; public Float brqaxsksnpqn; public Float mohysv; public String jmodsimfpxp; public Integer ypfimuf; public List mfdmuwlxe; public Float zmgqqr; public List vuofhyfnh; public Float ybizdwlx; public String tfqvadbpzanx; public Float orxtn; public List kifznybnfvo; public String pjsdytj; public Float jobisey; public List cnzsytgsrmh; public List rqjdxemd; public String bfxxethqvyo; public String wgkkexdy; public Integer giyeovmj; public List unhholw; public List anseshsvz; public List ribmewsfzwcp; public List tpwfr; public List pxjsnytfth; public List txsbr; public Integer nrodwidtchl; public List ocugbk; public List cirelkacd; public Integer hpqgpicypp; public List lftecbun; public Float ygewofr; public String tgjcrxk; public Float csujsjzm; public String vxsusbwz; public String rpnafceep; public List ytwxyenb; public String auhvjywewmo; public List bbvsrb; public List vzuftloqaal; public List krjwsd; public String gkihfkuve; public String jikuil; public String rhdmpjyccf; public Integer mhrnx; public String yobhtwzf; public List xeyoj; public Float cojoaar; public Float bjfkxougmw; public String geoilga; public List xllrjzafquyu; public Float xobveiffhsdo; public List dknpewwdh; public String oztdynn; public Integer vgddb; public String apiqmm; public List dwjdwz; public String wurbwztjp; public Integer bseiv; public Float zxlysfuokb; public String qyfowxe; public String iipwsfy; public List owsejqfkehjn; public List ztzcv; public List keygodzfjjmr; public List bfzfijxvwyb; public List idhvg; public Float sgzgfoadud; public String mhzspwrd; public Float yuldcj; public String bjwnfb; public String tlzzjt; public List tgmul; public Float pnsryayelzxt; public Float afmdfca; public String vxbalqkel; public String gaqrvygvjili; public Integer qhvoxqalg; public String hegjib; public String hvbxpgeqek; public List lpkzkgnya; public List tbtickvxvho; public String mvbciywiejs; public String ijcczoqij; public String vddps; public List qomzusabz; public Float xqcsrts; public Float zqafkvntsh; public List byygmcw; public Integer zwysdiaiev; public Float dstftqztrl; public List wvybkavzf; public Integer ujoqlrrgflnf; public List sbsmqzxj; public List lkasladbez; public String ydmgeywpquba; public String vufcvrt; public Integer jzhbuueld; public List nminfrgyts; public Integer rxtpyhghh; public List xvncumabdfhq; public Float ftjrvcptykxx; public String torraglirgs; public Integer jomkavscsf; public String duvhc; public String czxnlbt; public List qloaj; public String wlircmcfea; public String tpbcqj; public String otrjwwnsssd; public String vkofzdftinz; public Float ftinjqovg; public String innprvmyj; public String ynjqvcudywdy; public Float rpdtnenuwr; public List xiywwxjjhlc; public Integer htuwbznbz; public String kzqkncbcdcu; public List xzhor; public String sidrpoy; public Float ltpmidzjd; public List lwyuyni; public List rdsab; public List kmmoxpxw; public Float qtcrtcarxhy; public String nvdqgvebdvxw; public List brvmir; public List lhfsw; public List fobff; public Float wontvjkp; public List vrsegwx; public List mdbyf; public Float anpevc; public String krtrsevahzu; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3000/Issue3082.java ================================================ package com.alibaba.json.bvt.issue_3000; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.lang.reflect.Type; import java.util.AbstractMap; import java.util.HashSet; import java.util.Map; public class Issue3082 extends TestCase { public void test_for_issue_entry() throws Exception { String str = "{\"k\":{\"k\":\"v\"}}"; Map.Entry> entry = JSON.parseObject(str, new TypeReference>>() {}); assertEquals("v", entry.getValue().getValue()); } public void test_for_issue() throws Exception { HashSet>> nestedSet = new HashSet>>(); nestedSet.add(new AbstractMap.SimpleEntry>("a", new AbstractMap.SimpleEntry("b", "c"))); nestedSet.add(new AbstractMap.SimpleEntry>("d", new AbstractMap.SimpleEntry("e", "f"))); String content = JSON.toJSONString(nestedSet); HashSet>> deserializedNestedSet; Type type = new TypeReference>>>() {}.getType(); deserializedNestedSet = JSON.parseObject(content, type); assertEquals(nestedSet, deserializedNestedSet); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3000/Issue3083.kt ================================================ package com.alibaba.json.bvt.issue_3000 import com.alibaba.fastjson.JSON class TestBean { var is_subscribe = 0 var subscribe = 0 var isHave = 0 var _have = 0 var normal = 0 var Abnormal = 0 } fun main(args: Array) { val s = "{'is_subscribe':1,'subscribe':2,'isHave':3, '_have':4, 'normal':5, 'Abnormal':6}" val b = JSON.parseObject(s, TestBean::class.java) println("${b.is_subscribe}--${b.subscribe}--${b.isHave}--${b._have}--${b.normal}--${b.Abnormal}") } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3000/Issue3093.java ================================================ package com.alibaba.json.bvt.issue_3000; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.sql.Timestamp; import java.util.Calendar; public class Issue3093 extends TestCase { public void test_for_issue() throws Exception { Timestamp ts = new Timestamp(Calendar.getInstance().getTimeInMillis()); System.out.println(ts.toString()); String json = JSON.toJSONString(ts, SerializerFeature.UseISO8601DateFormat); System.out.println(json); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3000/Issue3138.java ================================================ package com.alibaba.json.bvt.issue_3000; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; import java.util.Map; public class Issue3138 extends TestCase { public void test_0() throws Exception { VO vo = JSON.parseObject("{\"value\":{\"@type\":\"aa\"}}", VO.class); } public static class VO { @JSONField(parseFeatures = Feature.DisableSpecialKeyDetect) public Map value; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3100/Issue3109.java ================================================ package com.alibaba.json.bvt.issue_3100; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import junit.framework.TestCase; public class Issue3109 extends TestCase { public void test_for_issue() throws Exception { ParserConfig config = new ParserConfig(); config.addAccept("test"); JSON.parseObject("{\"@type\":\"testxx\",\"dogName\":\"dog1001\"}", Dog.class, config); } public static class Dog { public String dogName; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3100/Issue3131.java ================================================ package com.alibaba.json.bvt.issue_3100; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Issue3131 extends TestCase { public void test_for_issue() throws Exception { List orgs = new ArrayList(); UserOrg org = new UserOrg("111","222" ); orgs.add(org); String s = JSON.toJSONString(new Orgs("111", orgs)); System.out.println(s); Orgs userOrgs = JSON.parseObject(s, Orgs.class); System.out.println(JSON.toJSONString(userOrgs)); } public static class Orgs implements Serializable { /** */ private static final long serialVersionUID = -1L; private String name; private List orgs; public Orgs() { } public Orgs(String name, List orgs) { this.name = name; this.orgs = orgs; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getOrgs() { return orgs; } public void setOrgs(List orgs) { this.orgs = orgs; } public void add(T org) { if (orgs == null) { orgs = new ArrayList(); } orgs.add(org); } } public static class UserOrg extends Org implements Serializable{ private String name; private String idcard; public UserOrg() { } public UserOrg(String name, String idcard) { super (name); this.name = name; this.idcard = idcard; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } } public static abstract class Org implements Serializable{ private String name; public Org() { } public Org(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3100/Issue3132.java ================================================ package com.alibaba.json.bvt.issue_3100; import com.alibaba.fastjson.JSONObject; import com.alibaba.json.bvtVO.一个中文名字的包.User; import junit.framework.TestCase; public class Issue3132 extends TestCase { public void test_for_issue() throws Exception { User user = new User(); user.setId(9); user.setName("asdffsf"); System.out.println(JSONObject.toJSONString(user)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3100/Issue3150.java ================================================ package com.alibaba.json.bvt.issue_3100; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.AfterFilter; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; public class Issue3150 extends TestCase { public void test_for_issue() throws Exception { MyRefAfterFilter refAfterFilterTest = new MyRefAfterFilter(); List items = new ArrayList(2); Category category = new Category("category"); items.add(new Item("item1",category)); items.add(new Item("item2",category)); // System.out.println(JSON.toJSONString(items)); System.out.println(JSON.toJSONString(items, refAfterFilterTest)); } public static class MyRefAfterFilter extends AfterFilter { private Category category = new Category("afterFilterCategory"); @Override public void writeAfter(Object object) { if(object instanceof Item){ this.writeKeyValue("afterFilterCategory", category); } } } public static class Item { private String name; private Category category; public Item(String name,Category category){ this.name = name; this.category = category; } public String getName() { return name; } public Category getcategory() { return category; } } public static class Category { private String name; public Category(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3100/Issue3160.java ================================================ package com.alibaba.json.bvt.issue_3100; import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.util.IOUtils; import junit.framework.TestCase; import org.junit.Assert; import java.lang.reflect.Field; public class Issue3160 extends TestCase { public void test_for_issue() throws Exception { String str = createLargeBasicStr(); SerializeWriter writer = new SerializeWriter(); //写入大于12K的字符串 writer.writeString(str); writer.writeString(str); byte[] bytes = writer.toBytes("UTF-8"); writer.close(); //检查bytesLocal大小,如果缓存成功应该大于等于输出的bytes长度 Field bytesBufLocalField = SerializeWriter.class.getDeclaredField("bytesBufLocal"); bytesBufLocalField.setAccessible(true); ThreadLocal bytesBufLocal = (ThreadLocal) bytesBufLocalField.get(null); byte[] bytesLocal = bytesBufLocal.get(); Assert.assertNotNull("bytesLocal is null", bytesLocal); Assert.assertTrue("bytesLocal is smaller than expected", bytesLocal.length >= bytes.length); } private String createLargeBasicStr() { String tmp = new String(IOUtils.DIGITS); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 400; i++) { builder.append(tmp); } return builder.toString(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3206.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.NameFilter; import junit.framework.TestCase; public class Issue3206 extends TestCase { public void test_for_issue() throws Exception { VO vo = new VO(); vo.date = new java.util.Date(1590819204293L); assertEquals(JSON.toJSONString(vo), "{\"date\":\"2020-05-30\"}"); String str = JSON.toJSONString(vo, new NameFilter() { public String process(Object object, String name, Object value) { return name; } }); assertEquals(str, "{\"date\":\"2020-05-30\"}"); } public static class VO { @JSONField(format="yyyy-MM-dd") public java.util.Date date; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3217.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue3217 extends TestCase { public void testException(){ MyException myException = new MyException(); myException.enumTest = EnumTest.FIRST; TestClass testClass = new TestClass(); testClass.setMyException(myException); String jsonString = JSON.toJSONString(testClass, SerializerFeature.NotWriteDefaultValue); System.out.println(jsonString); TestClass testClass1 = JSON.parseObject(jsonString, TestClass.class); System.out.println(testClass1); } public static enum EnumTest{ FIRST("111","111"), SECOND("222","222"); private String key; private String value; EnumTest(String key, String value) { this.key = key; this.value = 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; } } public static class MyException extends Exception { private EnumTest enumTest; public EnumTest getEnumTest() { return enumTest; } public void setEnumTest(EnumTest enumTest) { this.enumTest = enumTest; } } public static class TestClass{ private MyException myException; public MyException getMyException() { return myException; } public void setMyException(MyException myException) { this.myException = myException; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3227.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.junit.Assert; /** * @Author :Nanqi * @Date :Created in 20:38 2020/6/27 */ public class Issue3227 extends TestCase { public void test_for_issue() { String json = "{\"code\":\"123\"}"; if (!Child.class.getMethods()[0].getReturnType().getName().contains("Object")) { System.out.println(Child.class.getMethods()[0].getReturnType().getName()); } Child child = JSON.parseObject(json, Child.class); Assert.assertNotNull(child); } static class Parent { protected String name; public String getName() { return name; } public void setName(String name) { this.name = name; } protected T code; public T getCode() { return code; } public void setCode(T code) { this.code = code; } } static class Child extends Parent{ @Override public Integer getCode() { return code; } @Override public void setCode(Integer code) { this.code = code; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3245.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSONValidator; import junit.framework.TestCase; public class Issue3245 extends TestCase { public void test_for_issue() throws Exception { JSONValidator v = JSONValidator.from("[]"); v.validate(); assertEquals(JSONValidator.Type.Array, v.getType()); } public void test_for_issue_1() throws Exception { assertEquals(JSONValidator.Type.Array, JSONValidator.from("[]").getType()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3246.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import lombok.Data; public class Issue3246 extends TestCase { public void test_for_issue() throws Exception { String jsonStr = "{\"d_id\":\"bphyean01\",\"isOpenMergeCode\":0,\"offlineOrder\":false,\"offlineOrderType\":-1,\"og\":0,\"pushIdFromRemote\":false,\"qrisAmountPrice\":22000,\"s_req\":0,\"s_t\":1,\"skr_id\":0,\"type\":1,\"c_id\":471,\"o_$\":5500.0,\"am\":4,\"$_tp\":\"bp\",\"o_t\":1,\"a_m\":3}"; Order parseOrder = JSON.parseObject(jsonStr,Order.class); assertEquals(Integer.valueOf(4), parseOrder.getAmount()); assertEquals("3", parseOrder.getAddMoney()); } @Data public static class Order { @JSONField(name = "d_id", ordinal = 0) private String deviceId; @JSONField(name = "c_id", ordinal = 1) private Integer commodityId; @JSONField(name = "o_$", ordinal = 2) private Double orderPrice; @JSONField(name = "am", ordinal = 3) private Integer amount; @JSONField(name = "$_tp", ordinal = 4) private String payType; @JSONField(name = "wx_p_id", ordinal = 5) private Long productId; @JSONField(name = "ext_p_id", ordinal = 6) private Long extraProductId; @JSONField(name = "u_id", ordinal = 7) private String userId; @JSONField(name = "p_id", ordinal = 8) private Long parentId; @JSONField(name = "o_t", ordinal = 9) private Integer orderType; @JSONField(name = "ts", ordinal = 10) private Integer tradeStatus; @JSONField(name = "pn", ordinal = 11) private String phoneNum; @JSONField(name = "conf_id", ordinal = 12) private Long configId; @JSONField(name = "sku_id", ordinal = 13) private Long skuCommodityId; @JSONField(name = "c_ids", ordinal = 14) private String commodityIds; @JSONField(name = "a_m", ordinal = 15) private String addMoney; @JSONField(name = "skr_id", ordinal = 15) private Long secKillRecordId; @JSONField(name = "c_n", ordinal = 16) private String clientOrderNum; @JSONField(name = "s_t", ordinal = 16) private Integer sceneType; @JSONField(name = "t_t", ordinal = 16) private Integer tradingType; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3264.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import org.junit.Assert; /** * @Author :Nanqi * @Date :Created in 21:25 2020/6/22 */ public class Issue3264 extends TestCase { public void test_for_issue() throws Exception { MyData data = MyData.builder().isTest(true).build(); String string = JSON.toJSONString(data); Assert.assertTrue(string.contains("is_test")); } @Data @Builder @AllArgsConstructor public static class MyData { @JSONField(name = "is_test") private Boolean isTest; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3266.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONCreator; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class Issue3266 extends TestCase { public void test_for_issue() throws Exception { VO vo = new VO(); vo.type = Color.Black; String str = JSON.toJSONString(vo); assertEquals("{\"type\":1003}", str); VO vo2 = JSON.parseObject(str, VO.class); } public static class VO { public Color type; } public enum Color { Red(1001), White(1002), Black(1003), Blue(1004); private final int code; private Color(int code) { this.code = code; } @JSONField public int getCode() { return code; } @JSONCreator public static Color from(int code) { for (Color v : values()) { if (v.code == code) { return v; } } throw new IllegalArgumentException("code " + code); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3266_mixedin.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONCreator; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class Issue3266_mixedin extends TestCase { public void test_for_issue() throws Exception { JSON.addMixInAnnotations(Color.class, ColorMixedIn.class); VO vo = new VO(); vo.type = Color.Black; String str = JSON.toJSONString(vo); assertEquals("{\"type\":1003}", str); VO vo2 = JSON.parseObject(str, VO.class); } public static class VO { public Color type; } public enum Color { Red(1001), White(1002), Black(1003), Blue(1004); private final int code; private Color(int code) { this.code = code; } public int getCode() { return code; } public static Color from(int code) { for (Color v : values()) { if (v.code == code) { return v; } } throw new IllegalArgumentException("code " + code); } } public static class ColorMixedIn { @JSONField public int getCode() { return 0; } @JSONCreator public static Color from(int code) { return null; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3267.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSONValidator; import junit.framework.TestCase; public class Issue3267 extends TestCase { public void test_for_issue() throws Exception { JSONValidator v = JSONValidator.from("113{}[]"); v.setSupportMultiValue(false); assertFalse( v.validate()); assertEquals(JSONValidator.Type.Value, v.getType()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3274.kt ================================================ package com.alibaba.json.bvt.issue_3200 import com.alibaba.fastjson.JSON import junit.framework.Assert.assertEquals import org.junit.Test import java.util.* class TestFJ { @Test fun test() { val str = """ {"data": {"id": "1", "name":"n1"}} """.trimIndent() val d1 = JSON.parseObject(str, Data2::class.java) val data = JSON.parseObject(str) val d2 = data.getObject("data", Data::class.java) assertEquals(1, d1.data.id) assertEquals(1, d2.id) } } data class Data( val id: Int = 0, val name: String = "", val date: Date? = null ) data class Data2( val data: Data ) ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3279.java ================================================ package com.alibaba.json.bvt.issue_3200; 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 Issue3279 extends TestCase { public void test_for_issue() throws Exception { V0 v = JSON.parseObject("{\"id\":\" 1001 \"}", V0.class, Feature.TrimStringFieldValue); assertEquals("1001", v.id); v = JSON.parseObject("{\"id\":\" 1001 \"}", V0.class); assertEquals(" 1001 ", v.id); } public void test_for_issue_1() throws Exception { V1 v = JSON.parseObject("{\"id\":\" 1001 \"}", V1.class); assertEquals("1001", v.id); } public void test_for_issue_2() throws Exception { V2 v = JSON.parseObject("{\"id\":\" 1001 \"}", V2.class); assertEquals("1001", v.id); } public static class V0 { public String id; } public static class V1 { @JSONField(parseFeatures = Feature.TrimStringFieldValue) public String id; } @JSONType(parseFeatures = Feature.TrimStringFieldValue) public static class V2 { public String id; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3281.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import org.junit.Assert; import java.util.Date; import java.util.HashMap; /** * @Author :Nanqi * @Date :Created in 10:47 2020/6/22 * @Description:补充测试用例 */ public class Issue3281 extends TestCase { public void test_for_issue() { ModelState modelBack = JSON.parseObject("{\"counterMap\":{\"0\":0,\"100\":0,\"200\":0,\"300\":0,\"400\":0," + "\"500\":0,\"600\":0,\"700\":0,\"800\":0,\"900\":0,\"1000\":0},\"formatDate\":null," + "\"modelName\":\"test\",\"modelScores\":{\"Test1-1000\":{\"max\":1.0997832999999515,\"min\":0.0," + "\"recording\":false}},\"modelVersion\":\"1\",\"pit\":1592470429399,\"useCaseName\":\"test\"," + "\"variableName\":\"v2\"}", ModelState.class); Assert.assertNotNull(modelBack.getCounterMap()); Assert.assertNotNull(modelBack.getModelScores()); } @Builder @Data @AllArgsConstructor public static class ModelState { private HashMap counterMap; private Date formatDate; private HashMap modelScores; private String modelName; private Long modelVersion; private Long pit; private String useCaseName; private String variableName; } @Builder @Data @AllArgsConstructor public static class TGigest { private Double max; private Double min; private Boolean recording; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3282.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue3282 extends TestCase { public void test_for_issue() { Demo demo = JSON.parseObject("{'date':'2020-01-01 00:00:00 000'}", Demo.class); assertNotNull(demo.date); } public static class Demo { public java.util.Date date; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3283.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue3283 extends TestCase { public void test_for_issue() throws Exception { VO v = new VO(); v.v0 = 1001L; v.v1 = 101; String str = JSON.toJSONString(v, SerializerFeature.WriteNonStringValueAsString); JSONObject object = JSON.parseObject(str); assertEquals("1001", object.get("v0")); assertEquals("101", object.get("v1")); } public void test_for_issue_1() throws Exception { VO v = new VO(); v.v0 = 19007199254740991L; String str = JSON.toJSONString(v, SerializerFeature.BrowserCompatible); assertEquals("{\"v0\":\"19007199254740991\"}", str); } public static class VO { public Long v0; public Integer v1; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/Issue3293.java ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSONValidator; import junit.framework.TestCase; import org.junit.Assert; /** * @Author :Nanqi * @Date :Created in 09:59 2020/6/24 */ public class Issue3293 extends TestCase { public void test_for_issue() throws Exception { JSONValidator jv = JSONValidator.from("{\"a\"}"); Assert.assertFalse(jv.validate()); jv = JSONValidator.from("113{}[]"); jv.setSupportMultiValue(false); Assert.assertFalse(jv.validate()); Assert.assertEquals(JSONValidator.Type.Value, jv.getType()); jv = JSONValidator.from("{\"a\":\"12333\"}"); Assert.assertTrue(jv.validate()); jv = JSONValidator.from("{}"); Assert.assertTrue(jv.validate()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3200/TestIssue3223.kt ================================================ package com.alibaba.json.bvt.issue_3200; import com.alibaba.fastjson.JSON import com.alibaba.fastjson.JSONObject import com.alibaba.fastjson.parser.ParserConfig import com.alibaba.fastjson.serializer.SerializerFeature import org.junit.Assert import org.junit.Test import java.util.concurrent.atomic.AtomicInteger import kotlin.properties.Delegates /** * kotlin集合测试 * @author 佐井 * @since 2020-06-05 20:35 */ class TestIssue3223 { @Test fun test() { val cfg = ParserConfig.getGlobalInstance() cfg.addAccept("com.") cfg.addAccept("net.") cfg.addAccept("java.") cfg.addAccept("kotlin.") cfg.addAccept("org.") val n = NullableKotlin() //nullable n.nullableList = listOf("nullableList") n.nullableMap = mapOf("nullableMap" to "nullableMap") n.nullableSet = setOf("nullableSet") //empty n.emptyList = listOf("emptyList") n.emptyMap = mapOf("emptyMap" to "emptyMap") n.emptySet = setOf("emptySet") //delegate n.delegateList = listOf("delegateList") n.delegateMap = mapOf("delegateMap" to "delegateMap") n.delegateSet = setOf("delegateSet") //basic n.atomicInt = AtomicInteger(10) n.longValue = 1 n.json = JSON.parseObject(JSON.toJSONString(mapOf("a" to "b"))) val raw = JSON.toJSONString(n, SerializerFeature.WriteClassName) val d = JSON.parseObject(raw, NullableKotlin::class.java) Assert.assertTrue(n == d) } } class NullableKotlin { //map var nullableMap: Map? = null var emptyMap: Map = emptyMap() var delegateMap by Delegates.notNull>() //set var nullableSet: Set? = null var emptySet: Set = emptySet() var delegateSet by Delegates.notNull>() //list var nullableList: List? = null var emptyList: List = emptyList() var delegateList by Delegates.notNull>() //basic var atomicInt: AtomicInteger? = null var longValue: Long? = null var json: JSONObject? = null override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as NullableKotlin if (nullableMap != other.nullableMap) return false if (emptyMap != other.emptyMap) return false if (nullableSet != other.nullableSet) return false if (emptySet != other.emptySet) return false if (nullableList != other.nullableList) return false if (emptyList != other.emptyList) return false if (atomicInt?.get() != other.atomicInt?.get()) return false if (longValue != other.longValue) return false if (json != other.json) return false return true } override fun hashCode(): Int { var result = nullableMap?.hashCode() ?: 0 result = 31 * result + emptyMap.hashCode() result = 31 * result + (nullableSet?.hashCode() ?: 0) result = 31 * result + emptySet.hashCode() result = 31 * result + (nullableList?.hashCode() ?: 0) result = 31 * result + emptyList.hashCode() result = 31 * result + (atomicInt?.hashCode() ?: 0) result = 31 * result + (longValue?.hashCode() ?: 0) result = 31 * result + (json?.hashCode() ?: 0) return result } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3217.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.AfterFilter; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; public class Issue3217 extends TestCase { public void test_for_issue() throws Exception { RefAfterFilterTest refAfterFilterTest = new RefAfterFilterTest(); List items = new ArrayList(2); Category category = new Category("category"); items.add(new Item("item1",category)); items.add(new Item("item2",category)); System.out.println(JSON.toJSONString(items,refAfterFilterTest)); } public static class RefAfterFilterTest extends AfterFilter { private Category category = new Category("afterFilterCategory"); @Override public void writeAfter(Object object) { if (object instanceof Item) { this.writeKeyValue("afterFilterCategory", category); /*多加一个属性报错,原因是category是object也触发了writeAfter,当前线程变量serializer被设置为null了serializerLocal.set(null); *这两个write换个顺序就不会报错 */ this.writeKeyValue("afterFilterTwo", "two"); } } } public static class Category { private String name; public Category(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static class Item { private String name; private Category category; private String barcode; public Item(String name,Category category){ this.name = name; this.category = category; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3309.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.util.Date; /** * @Author :Nanqi * @Date :Created in 16:27 2020/6/29 */ public class Issue3309 extends TestCase { public void test_for_issue() throws Exception { JSONObject jsonObj = new JSONObject(); jsonObj.put("formatDate","20200623 15:20:01"); DateFormatTest dateFormatTest = jsonObj.toJavaObject(DateFormatTest.class); JSON.toJSONString(dateFormatTest); } static class DateFormatTest { @JSONField(format = "yyyyMMdd HH:mm:ss") private Date formatDate; public Date getFormatDate() { return formatDate; } public void setFormatDate(Date formatDate) { this.formatDate = formatDate; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3313.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import lombok.Data; import org.springframework.util.Assert; /** * @Author :Nanqi * @Date :Created in 21:54 2020/6/30 */ public class Issue3313 extends TestCase { public void test_for_issue() throws Exception { String jsonStr = "{\"NAME\":\"nanqi\",\"age\":18}"; Model model = JSONObject.parseObject(jsonStr, Model.class); Assert.notNull(model.getAGe()); Assert.notNull(model.getName()); } @Data static class Model { @JSONField(name = "NaMe") private String name; @JSONField(name = "age") private Integer aGe; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3326.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import junit.framework.TestCase; import java.util.HashMap; public class Issue3326 extends TestCase { public void test_for_issue() throws Exception { HashMap map = JSON.parseObject("{\"id\":10.0}" , new TypeReference>() { }.getType() , 0); assertEquals(10.0, map.get("id")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3329.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.alibaba.fastjson.util.IdentityHashMap; import com.alibaba.fastjson.util.ParameterizedTypeImpl; import junit.framework.TestCase; import java.util.List; import java.lang.reflect.Type; public class Issue3329 extends TestCase { public void test_for_issue() throws Exception { ParserConfig config = new ParserConfig(); IdentityHashMap deserializers = config.getDeserializers(); int initSize = deserializers.size(); for (int i = 0; i < 1000 * 10; ++i) { assertEquals(123, ((VO) JSON.parseObject("{\"value\":{\"id\":123}}", new ParameterizedTypeImpl(new Type[] {User.class}, null, VO.class), config )).value.id ); } assertEquals(2, deserializers.size() - initSize); } public static class VO { public T value; } public static class User { public int id; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3334.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue3334 extends TestCase { public void test_for_issue() throws Exception { assertEquals(0, JSON.parseObject("{\"id\":false}", VO.class).id); assertEquals(1, JSON.parseObject("{\"id\":true}", VO.class).id); assertEquals(0, JSON.parseObject("{\"id64\":false}", VO.class).id64); assertEquals(1, JSON.parseObject("{\"id64\":true}", VO.class).id64); assertEquals(0, JSON.parseObject("{\"id16\":false}", VO.class).id16); assertEquals(1, JSON.parseObject("{\"id16\":true}", VO.class).id16); assertEquals(0, JSON.parseObject("{\"id8\":false}", VO.class).id8); assertEquals(1, JSON.parseObject("{\"id8\":true}", VO.class).id8); assertEquals(0F, JSON.parseObject("{\"floatValue\":false}", VO.class).floatValue); assertEquals(1F, JSON.parseObject("{\"floatValue\":true}", VO.class).floatValue); assertEquals(0D, JSON.parseObject("{\"doubleValue\":false}", VO.class).doubleValue); assertEquals(1D, JSON.parseObject("{\"doubleValue\":true}", VO.class).doubleValue); } public static class VO { private byte id8; private short id16; private int id; private long id64; private Float floatValue; private Double doubleValue; public int getId() { return id; } public void setId(int id) { this.id = id; } public long getId64() { return id64; } public void setId64(long id64) { this.id64 = id64; } public short getId16() { return id16; } public void setId16(short id16) { this.id16 = id16; } public byte getId8() { return id8; } public void setId8(byte id8) { this.id8 = id8; } public Float getFloatValue() { return floatValue; } public void setFloatValue(Float floatValue) { this.floatValue = floatValue; } public Double getDoubleValue() { return doubleValue; } public void setDoubleValue(Double doubleValue) { this.doubleValue = doubleValue; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3336.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue3336 extends TestCase { public void test_for_issue() throws Exception { String s = "{\"schema\":{\"$ref\":\"#/definitions/URLJumpConfig\"}}"; assertEquals(s, JSON.parseObject(s) .toJSONString()); String s1 = "{\"schema\":{\"ref\":\"#/definitions/URLJumpConfig\"}}"; assertEquals(s1, JSON.parseObject(s1) .toJSONString()); String s2 = "{\"schema\":{\"$ref\":\"#/definitions/URLJumpConfig\"}}"; assertEquals(s2, JSON.parseObject(s2) .toJSONString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3338.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; /** * @Author :Nanqi * @Date :Created in 17:11 2020/7/11 */ public class Issue3338 extends TestCase { public void test_for_issue() throws Exception { Model model = new Model(); Map map = new HashMap(); map.put("nanqi", "因为相信,所以看见。"); model.setMap(map); String jsonString = JSONObject.toJSONString(model); assertTrue(jsonString.contains("因为相信,所以看见。")); Model modelBack = JSONObject.parseObject(jsonString, Model.class); assertEquals("因为相信,所以看见。", modelBack.getMap().get("nanqi")); } static class Model { private Map map; public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3343.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSONValidator; import junit.framework.TestCase; public class Issue3343 extends TestCase { public void test_for_issue() throws Exception { assertFalse( JSONValidator.from("{\"name\":\"999}") .validate()); assertTrue( JSONValidator.from("false") .validate()); assertEquals(JSONValidator.Type.Value, JSONValidator.from("false") .getType()); assertTrue( JSONValidator.from("999").validate()); assertEquals(JSONValidator.Type.Value, JSONValidator.from("999") .getType()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3344.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.Date; import java.util.TimeZone; /** * @Author :Nanqi * @Date :Created in 18:28 2020/7/19 */ public class Issue3344 extends TestCase { public void test_for_issue_timeZone() throws Exception { TimeZone.setDefault(TimeZone.getTimeZone("GMT+1")); String jsonStr = "{\"date\":1595154768}"; Model model = JSONObject.parseObject(jsonStr, Model.class); assertEquals("Mon Jan 19 12:05:54 GMT+01:00 1970", model.getDate().toString()); } static class Model { private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3347.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; /** * @Author :Nanqi * @Date :Created in 22:29 2020/7/15 */ public class Issue3347 extends TestCase { public void test_for_issue() throws Exception { Map map = new HashMap(); map.put(1, "hello"); String mapJSONString = JSON.toJSONString(map); Map mapValues = JSONObject.parseObject(mapJSONString, Map.class); Object mapKey = mapValues.keySet().iterator().next(); assertTrue(mapKey instanceof Integer); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3351.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSONValidator; import junit.framework.TestCase; /** * @Author :Nanqi * @Date :Created in 00:14 2020/7/18 */ public class Issue3351 extends TestCase { public void test_for_issue() throws Exception { String cString = "c110"; boolean cValid = JSONValidator.from(cString).validate(); assertFalse(cValid); String jsonString = "{\"forecast\":\"sss\"}"; boolean jsonValid = JSONValidator.from(jsonString).validate(); assertTrue(jsonValid); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3352.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.Map; import java.util.UUID; public class Issue3352 extends TestCase { public void test_for_issue() throws Exception { UUID uuid = UUID.randomUUID(); JSONObject object = new JSONObject(); Map map = object.getInnerMap(); map.put("1", "1"); map.put("A", "A"); map.put("true", "true"); map.put(uuid.toString(), uuid); assertTrue(object.containsKey(1)); assertTrue(object.containsKey("1")); assertTrue(object.containsKey('A')); assertTrue(object.containsKey("A")); assertTrue(object.containsKey(true)); assertTrue(object.containsKey("true")); assertTrue(object.containsKey(uuid)); assertTrue(object.containsKey(uuid.toString())); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3356.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.util.UUID; public class Issue3356 extends TestCase { public void test_for_issue() throws Exception { UUID uuid = UUID.randomUUID(); JSONObject object = new JSONObject(); object.put("1", "1"); object.put(uuid.toString(), uuid.toString()); object.put("A", "A"); object.put("true", "true"); assertEquals("1", object.get(1)); assertEquals("true", object.get(true)); assertEquals("A", object.get('A')); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3358.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONCreator; import junit.framework.TestCase; import org.joda.time.LocalDateTime; /** * @Author :Nanqi * @Date :Created in 19:07 2020/7/21 */ public class Issue3358 extends TestCase { public void test_for_issue() throws Exception { Model validateCode = new Model("111", 600); String jsonString = JSON.toJSONString(validateCode); Model backModel = JSON.parseObject(jsonString, Model.class); assertEquals(validateCode.getExpireTime(), backModel.getExpireTime()); jsonString = "{\"code\":\"111\"}"; backModel = JSON.parseObject(jsonString, Model.class); assertNull(backModel.getExpireTime()); } public static class Model { private String code; private LocalDateTime expireTime; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public LocalDateTime getExpireTime() { return expireTime; } public void setExpireTime(LocalDateTime expireTime) { this.expireTime = expireTime; } public Model(String code, int expireIn) { this.code = code; this.expireTime = LocalDateTime.now().plusSeconds(expireIn); } @JSONCreator public Model(String code, LocalDateTime expireTime) { this.code = code; this.expireTime = expireTime; } public boolean isExpried() { return LocalDateTime.now().isAfter(getExpireTime()); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3361.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import junit.framework.TestCase; import java.util.Date; @Slf4j public class Issue3361 extends TestCase { private static String ORIGIN_JSON_DEFAULT_DATE_FORMAT; @Override public void setUp() throws Exception { ORIGIN_JSON_DEFAULT_DATE_FORMAT = JSON.DEFFAULT_DATE_FORMAT; } public void test_for_issue() throws Exception { Model model = new Model(); model.setOldDate(new Date()); log.info("{}", model); FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures(SerializerFeature.WriteMapNullValue); config.setWriteContentLength(false); JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS"; config.setDateFormat(JSON.DEFFAULT_DATE_FORMAT); String string = JSON.toJSONString(model, config.getSerializeConfig(), config.getSerializeFilters(), config.getDateFormat(), JSON.DEFAULT_GENERATE_FEATURE, config.getSerializerFeatures()); log.info("{}", string); Model model2 = JSON.parseObject(string, Model.class); log.info("{}", model2); Model model3 = JSON.parseObject(string, new TypeReference() { }.getType()); log.info("{}", model3); } @Override public void tearDown() throws Exception { JSON.DEFFAULT_DATE_FORMAT = ORIGIN_JSON_DEFAULT_DATE_FORMAT; } @Getter @Setter @ToString public static class Model { private Date oldDate; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3373.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.BeforeFilter; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; public class Issue3373 extends TestCase { public void test_for_issue() throws Exception { RefBeforeFilterTest refAfterFilterTest = new RefBeforeFilterTest(); List items = new ArrayList(2); Category category = new Category("category"); items.add(new Item("item1",category)); items.add(new Item("item2",category)); System.out.println(JSON.toJSONString(items,refAfterFilterTest)); } public static class RefBeforeFilterTest extends BeforeFilter { private Category category = new Category("afterFilterCategory"); @Override public void writeBefore(Object object) { if (object instanceof Item) { this.writeKeyValue("afterFilterCategory", category); /*多加一个属性报错,原因是category是object也触发了writeAfter,当前线程变量serializer被设置为null了serializerLocal.set(null); *这两个write换个顺序就不会报错 */ this.writeKeyValue("afterFilterTwo", "two"); } } } public static class Category { private String name; public Category(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static class Item { private String name; private Category category; private String barcode; public Item(String name, Category category){ this.name = name; this.category = category; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3375.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Author :Nanqi * @Date :Created in 01:09 2020/8/2 */ public class Issue3375 extends TestCase { public void test_for_issue() throws Exception { List> models = new ArrayList>(); Map map1 = new HashMap(); map1.put("name", "nanqi01"); models.add(map1); Map map2 = new HashMap(); map2.put("name", "nanqi02"); models.add(map2); for (Map model : models) { String modelStr = JSON.toJSONString(model); Model modelObj = JSON.parseObject(modelStr, Model.class); assertTrue(modelObj.getName().contains("nanqi")); } } public static class Model { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3376.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; /** * @Author :Nanqi * @Date :Created in 01:25 2020/8/2 */ public class Issue3376 extends TestCase { public void test_for_issue() throws Exception { Model model = new Model(1, 1); String modelString = JSON.toJSONString(model); assertEquals("{}", modelString); Model2 model2 = new Model2(1, 1); String model2String = JSON.toJSONString(model2); assertEquals("{\"offset\":1,\"timestamp\":1}", model2String); Model3 model3 = new Model3(1, 1); String model3String = JSON.toJSONString(model3); assertEquals("{\"off\":1,\"timeStamp\":true,\"timestamp\":1}", model3String); } public static class Model { private final long offset; private final long timestamp; public Model(long offset, long timestamp) { this.offset = offset; this.timestamp = timestamp; } /** * 这种 类似的 get 方法不正规,没办法确定那个方法才算是获取参数的接口,可以参考例子 3 */ public long timestamp() { return timestamp; } public long offset() { return this.offset; } } public static class Model2 { private final long offset; private final long timestamp; public Model2(long offset, long timestamp) { this.offset = offset; this.timestamp = timestamp; } public long getOffset() { return offset; } public long getTimestamp() { return timestamp; } } public static class Model3 { private final long offset; public final long timestamp; public Model3(long offset, long timestamp) { this.offset = offset; this.timestamp = timestamp; } public long getOff() { return offset; } public Boolean isTimeStamp() { return true; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3397.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.time.LocalDateTime; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * @Author :Nanqi * @Date :Created in 16:32 2020/8/16 */ public class Issue3397 extends TestCase { @Override public void setUp() throws Exception { JSON.defaultTimeZone = TimeZone.getDefault(); JSON.defaultLocale = Locale.CHINA; } public void test_for_issue() throws Exception { String text = "{\"date\":\"2020-08-16 16:35:18.188\"}"; VO vo = JSON.parseObject(text, VO.class); JSONObject json = (JSONObject) JSONObject.toJSON(vo); Date date = json.getDate("date"); // assertEquals("Sun Aug 16 16:35:18 CST 2020", date.toString()); } public static class VO { @JSONField(format = "yyyy-MM-dd HH:mm:ss.SSS") private LocalDateTime date; public LocalDateTime getDate() { return date; } public void setDate(LocalDateTime date) { this.date = date; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3443.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.serializer.*; import junit.framework.TestCase; public class Issue3443 extends TestCase { public void testCustomJsonSerializerAndAfterFilter() throws Exception { SerializeWriter serializeWriter = new SerializeWriter(); try { JSONSerializer jsonSerializer = new JSONSerializer(serializeWriter, new SerializeConfig()); Parameter parameter = new Parameter(); parameter.setParameterDesc(new ParameterDesc("vipExpireDate", "VIP expire date.")); jsonSerializer.config(SerializerFeature.DisableCircularReferenceDetect, true); jsonSerializer.getAfterFilters().add(new CustomFilter()); jsonSerializer.write(parameter); assertEquals("{\"parameterDesc\":{\"ParameterDesc\":\"VIP expire date.\"}}", serializeWriter.toString()); } finally { serializeWriter.close(); } } static class Parameter { private ParameterDesc parameterDesc; public ParameterDesc getParameterDesc() { return parameterDesc; } public void setParameterDesc(ParameterDesc parameterType) { this.parameterDesc = parameterType; } } static class ParameterDesc { private String parameterName; private String parameterUsage; // do some work... public ParameterDesc(String parameterName, String parameterUsage) { this.parameterName = parameterName; this.parameterUsage = parameterUsage; } } static class CustomFilter extends AfterFilter { @Override public void writeAfter(Object object) { if (object instanceof ParameterDesc) { writeKeyValue("ParameterDesc", "VIP expire date."); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/Issue3448.java ================================================ package com.alibaba.json.bvt.issue_3300; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import junit.framework.TestCase; import org.junit.Test; /** * @author yumin.pym */ public class Issue3448 extends TestCase { public static class SelfTypeReference { } @Test public void test() { List>> list = new ArrayList(4); list.add(Collections.singletonMap("key1", Collections.singletonList("item"))); String text = JSON.toJSONString(list); System.out.println("text = " + text); List>> result = parseObject(text, new SelfTypeReference>>() {}); System.out.println("result = " + result); TestCase.assertTrue(result.get(0) instanceof Map); TestCase.assertTrue(result.get(0).get("key1").get(0) instanceof String); } public List parseObject(String text, SelfTypeReference selfTypeReference) { Type genericSuperclass = selfTypeReference.getClass().getGenericSuperclass(); Type[] actualTypeArguments = ((ParameterizedType)genericSuperclass).getActualTypeArguments(); return JSON.parseObject(text, new TypeReference>(actualTypeArguments) {}); } @Test public void test_1() { List>> list = new ArrayList(4); list.add(Collections.singletonMap("key1", Collections.singletonList("item"))); String text = JSON.toJSONString(list); System.out.println("text = " + text); List>> result = parseObject2(text, new SelfTypeReference>>() { }); System.out.println("result = " + result); } @Test public void test2() { List> list = new ArrayList(4); list.add(Collections.singletonList("item")); String text = JSON.toJSONString(list); System.out.println("text = " + text); List> result = parseObject2(text, new SelfTypeReference>() { }); System.out.println("result = " + result); } @Test public void test3() { List list = new ArrayList(4); list.add("item"); String text = JSON.toJSONString(list); System.out.println("text = " + text); List result = parseObject2(text, new SelfTypeReference() { }); System.out.println("result = " + result); } public List parseObject2(String text, SelfTypeReference selfTypeReference) { Type genericSuperclass = selfTypeReference.getClass().getGenericSuperclass(); Type[] actualTypeArguments = ((ParameterizedType) genericSuperclass).getActualTypeArguments(); return JSON.parseObject(text, new TypeReference>(actualTypeArguments) { }); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3300/IssueForJSONFieldMatch.java ================================================ package com.alibaba.json.bvt.issue_3300; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class IssueForJSONFieldMatch extends TestCase { public void test_for_issue() throws Exception { assertEquals(123 , JSON.parseObject("{\"user_Id\":123}", VO.class) .userId); assertEquals(123 , JSON.parseObject("{\"userId\":123}", VO.class) .userId); assertEquals(123 , JSON.parseObject("{\"user-id\":123}", VO.class) .userId); } public static class VO { @JSONField(name = "user_id", alternateNames = {"userId", "user-id"}) public int userId; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3400/Issue3436.java ================================================ package com.alibaba.json.bvt.issue_3400; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONCreator; import com.alibaba.fastjson.annotation.JSONType; import junit.framework.TestCase; import org.springframework.core.io.FileSystemResource; public class Issue3436 extends TestCase { public void test_for_issue() throws Exception { JSON.addMixInAnnotations(FileSystemResource.class, FileSystemResourceMixedIn.class); FileSystemResource fileSystemResource = new FileSystemResource("E:\\my-code\\test\\test-fastjson.txt"); String json = JSON.toJSONString(fileSystemResource); assertEquals("{\"path\":\"E:/my-code/test/test-fastjson.txt\"}", json); FileSystemResource fsr1 = JSON.parseObject(json, FileSystemResource.class); assertEquals(fileSystemResource.getPath(), fsr1.getPath()); System.out.println("file size after Serialize:" + fileSystemResource.getFile().length()); } @JSONType(asm = false, includes = "path") public static class FileSystemResourceMixedIn { @JSONCreator public FileSystemResourceMixedIn(String path) { } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3400/Issue3452.java ================================================ package com.alibaba.json.bvt.issue_3400; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class Issue3452 extends TestCase { public void test_for_issue() throws Exception { String s = "{ \"componentKey\" : \"CMDB_UPDATE_SERVER\"}"; Step step = JSON.parseObject(s, Step.class); assertEquals("CMDB_UPDATE_SERVER",step.getComponentKey()); System.out.println(step.getComponentKey()); } private static class Step { @JSONField(name = "component_key", alternateNames = {"componentKey"}) private String componentKey; public String getComponentKey() { return componentKey; } public void setComponentKey(String componentKey) { this.componentKey = componentKey; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3400/Issue3453.java ================================================ package com.alibaba.json.bvt.issue_3400; import com.alibaba.fastjson.JSONValidator; import junit.framework.TestCase; import org.junit.Assert; /** * Description:
* * @author byw * @create 2020/9/20 */ public class Issue3453 extends TestCase { public void test_for_issue() throws Exception { String str = "[\n" + " {\n" + " \"altitude\": 109.0,\n" + " \"angle\": 5.0,\n" + " \"index\": 1,\n" + " \"type\": 1\n" + " },\n" + " {\n" + " \"altitude\": 1307.0,\n" + " \"angle\": 5.0,\n" + " \"index\": 2,\n" + " \"type\": 1\n" + " },\n" + " {\n" + " \"altitude\": 22.0,\n" + " \"angle\": 7.0,\n" + " \"index\": 3,\n" + " \"type\": 1\n" + " },\n" + " {\n" + " \"altitude\": 22.0,\n" + " \"angle\": 7.0,\n" + " \"index\": 4,\n" + " \"type\": 2\n" + " },\n" + " {\n" + " \"altitude\": 22.0,\n" + " \"angle\": 7.0,\n" + " \"index\": 5,\n" + " \"type\": 2\n" + " },\n" + " {\n" + " \"altitude\": 22.0,\n" + " \"angle\": 7.0,\n" + " \"index\": 6,\n" + " \"type\": 2\n" + " },\n" + " {\n" + " \"altitude\": 22.0,\n" + " \"angle\": 7.0,\n" + " \"index\": 7,\n" + " \"type\": 2\n" + " }\n" + "]"; JSONValidator validator = JSONValidator.from(str); Assert.assertTrue(validator.validate()); JSONValidator.Type type = validator.getType(); Assert.assertEquals("Array",type.name()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3400/Issue3460.java ================================================ package com.alibaba.json.bvt.issue_3400; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONValidator; import com.alibaba.json.bvt.issue_3200.Issue3293; import junit.framework.TestCase; import org.junit.Assert; /** * Description:
* * @author byw * @create 2020/9/20 */ public class Issue3460 extends TestCase { public void test_for_issue() throws Exception { String body = "11{\"time\":" + System.currentTimeMillis() + "}"; assertFalse( JSONValidator.from(body) .validate()); assertTrue( JSONValidator.from(body) .setSupportMultiValue(true) .validate()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3400/Issue3465.java ================================================ package com.alibaba.json.bvt.issue_3400; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue3465 extends TestCase { public void test_for_issue() throws Exception { JSONObject jsonObj1 = new JSONObject(); JSONObject sonJsonObj1 = new JSONObject(); sonJsonObj1.put("dca0898f74b4cc6d0174b4cc77fd0005", "2ca0898f74b4cc6d0174b4cc77fd0005"); jsonObj1.put("issue", sonJsonObj1); String rst1 = JSON.toJSONString(jsonObj1, JSON.DEFAULT_GENERATE_FEATURE | SerializerFeature.WRITE_MAP_NULL_FEATURES); System.out.println(rst1); JSONObject parse1 = JSON.parseObject(rst1); System.out.println(parse1.toJSONString()); JSONObject jsonObj = new JSONObject(); JSONObject sonJsonObj = new JSONObject(); sonJsonObj.put("2ca0898f74b4cc6d0174b4cc77fd0005", "2ca0898f74b4cc6d0174b4cc77fd0005"); jsonObj.put("issue", sonJsonObj); String rst = JSON.toJSONString(jsonObj, JSON.DEFAULT_GENERATE_FEATURE | SerializerFeature.WRITE_MAP_NULL_FEATURES); System.out.println(rst); JSONObject parse = JSON.parseObject(rst); System.out.println(parse.toJSONString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3400/Issue3470.java ================================================ package com.alibaba.json.bvt.issue_3400; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue3470 extends TestCase { public void test_for_issue() throws Exception { String str = JSON.toJSONString(new Privacy().setPassword("test")); assertEquals("{\"__password\":\"test\"}", str); } public static class Privacy { private String phone; //手机 private String password; //登录密码,隐藏字段 public Privacy() { super(); } public String getPhone() { return phone; } public Privacy setPhone(String phone) { this.phone = phone; return this; } public String get__password() { return password; } public Privacy setPassword(String password) { this.password = password; return this; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3400/Issue_20201016_01.java ================================================ package com.alibaba.json.bvt.issue_3400; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue_20201016_01 extends TestCase { public void testToString() { UserConfig user = new UserConfig(); user.setAccount("account"); user.setName("name"); Config config = new Config(); config.setCreator(user); config.setOwner(user); String s = JSON.toJSONString(config, SerializerFeature.WriteMapNullValue, SerializerFeature.QuoteFieldNames, SerializerFeature.WriteNullListAsEmpty); System.out.println(s); } public void testFastJson() { String s = "{\"agent\":null,\"creator\":{\"account\":\"account\",\"name\":\"name\",\"workid\":null},\"owner\":{\"$ref\":\"$.creator\"}}"; System.out.println( JSON.parseObject(s, Config.class)); } public static class Config { private UserConfig creator; private UserConfig owner; private UserConfig agent; public UserConfig getCreator() { return creator; } public void setCreator(UserConfig creator) { this.creator = creator; } public UserConfig getOwner() { return owner; } public void setOwner(UserConfig owner) { this.owner = owner; } public UserConfig getAgent() { return agent; } public void setAgent(UserConfig agent) { this.agent = agent; } } public static class UserConfig { private String workid; private String name; private String account; public String getWorkid() { return workid; } public void setWorkid(String workid) { this.workid = workid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3500/Issue3516.java ================================================ package com.alibaba.json.bvt.issue_3500; import com.alibaba.fastjson.JSONValidator; import junit.framework.TestCase; public class Issue3516 extends TestCase { public void test_for_issue() throws Exception { JSONValidator validator = JSONValidator.from("{}"); assertEquals(JSONValidator.Type.Object, validator.getType()); assertTrue(validator.validate()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3500/Issue3539.java ================================================ package com.alibaba.json.bvt.issue_3500; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.time.Instant; public class Issue3539 extends TestCase { public void test_for_issue() throws Exception { String str = "{\"date\":{\"nano\":140000000,\"epochSecond\":1605106869}}"; Bean bean = JSON.parseObject(str, Bean.class); assertNotNull(bean.date); JSON.toJSONString(bean); JSON.parseObject(str) .toJavaObject(Bean.class); } public void test_for_issue_joda() throws Exception { String str = "{\"date\":{\"epochSecond\":1605106869}}"; JodaBean bean = JSON.parseObject(str, JodaBean.class); assertNotNull(bean.date); JSON.toJSONString(bean); JSON.parseObject(str) .toJavaObject(JodaBean.class); } public void test_for_issue_joda2() throws Exception { String str = "{\"date\":{\"millis\":1605364826724}}"; JodaBean bean = JSON.parseObject(str, JodaBean.class); assertNotNull(bean.date); JSON.toJSONString(bean); JSON.parseObject(str) .toJavaObject(JodaBean.class); } public static class Bean { public Instant date; } public static class JodaBean { public org.joda.time.Instant date; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3500/Issue3544.java ================================================ package com.alibaba.json.bvt.issue_3500; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import lombok.Getter; import lombok.Setter; import java.util.Map; public class Issue3544 extends TestCase { public void test_errorType() { assertNull("", JSON.toJavaObject( JSON.parseObject("{\"result\":\"\"}"), TestVO.class).result); assertNull("", JSON.toJavaObject( JSON.parseObject("{\"result\":\"null\"}"), TestVO.class).result); } @Getter @Setter static class TestVO { Map result; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3500/Issue3571.java ================================================ package com.alibaba.json.bvt.issue_3500; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class Issue3571 extends TestCase { public void test_for_issue() throws Exception { Bean1 bean = new Bean1(); bean.id1 = 101; bean.id2 = 102; bean.id3 = 103; assertEquals("{\"id1\":101,\"id2\":102,\"id3\":103}", JSON.toJSON(bean).toString()); } public void test_for_issue_2() throws Exception { Bean2 bean = new Bean2(); bean.id1 = 101; bean.id2 = 102; bean.id3 = 103; assertEquals("{\"id1\":101,\"id2\":102,\"id3\":103}", JSON.toJSON(bean).toString()); } @JSONType(serialzeFeatures = SerializerFeature.SortField) public static class Bean1 { public int id2; public int id1; public int id3; } @JSONType(serialzeFeatures = SerializerFeature.MapSortField) public static class Bean2 { public int id2; public int id1; public int id3; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3500/Issue3579.java ================================================ package com.alibaba.json.bvt.issue_3500; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.math.BigDecimal; public class Issue3579 extends TestCase { public void test_for_issue() throws Exception { assertEquals("1", JSON.toJSONString(new BigDecimal("1")) ); assertEquals("1.", JSON.toJSONString(new BigDecimal("1"), SerializerFeature.WriteClassName) ); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3614.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.*; import java.util.Collections; import java.util.zip.GZIPOutputStream; public class Issue3614 extends TestCase { public void test_for_issue() throws Exception { byte[] gzipBytes = gzip(JSON.toJSONString(Collections.singletonMap("key", "value")).getBytes()); Object o = JSON.parseObject(gzipBytes, JSONObject.class); assertEquals("{\"key\":\"value\"}", JSON.toJSONString(o)); } private static byte[] gzip(byte[] source) throws IOException { if (source == null) return null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(bos); gzip.write(source); gzip.finish(); byte[] bytes = bos.toByteArray(); gzip.close(); return bytes; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3628.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Issue3628 extends TestCase { public void test_for_issue() throws Exception { String json = "{\"admin\":3483706632,\"admins\":[],\"black\":{\"blackList\":[]},\"enable\":true,\"messages\":{\"adminChangeDown\":\"[mirai:at:%target%] 被撤销了管理~\",\"adminChangeUp\":\"恭喜 [mirai:at:%target%] 被升为管理员~\",\"blacelist\":\"[mirai:at:%target%]你被加入此群黑名单,不允许你进入本群\",\"clearnScreen\":\"清屏ing~~~\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n清屏完毕~~~\",\"join\":\"欢迎 [mirai:at:%target%] 进入本群~\",\"kick\":\"[mirai:at:%target%] 被 [mirai:at:%operator%] 踢出本群\",\"leave\":\"很遗憾, [mirai:at:%target%] 离开了本群\",\"mute\":\"[mirai:at:%target%] 被 [mirai:at:%operator%] 禁言 %time%\",\"talkative\":\"恭喜 [mirai:at:%target%] 成为本群龙王!\",\"title\":\"恭喜 [mirai:at:%target%] 获得群主授予的 %title% 头衔!\",\"unmute\":\"[mirai:at:%target%] 被 [mirai:at:%operator%] 解除禁言\",\"warn\":\"\"},\"requestConfig\":{\"keyWordRegex\":\"SINGLE\",\"keyWords\":[\"栗子\"],\"type\":\"PASS\"},\"select\":{\"adminChange\":true,\"autoParseRequest\":true,\"join\":true,\"kick\":true,\"leave\":true,\"mute\":true,\"talkative\":true,\"title\":true,\"unmute\":true},\"warn\":{\"count\":10,\"countBlack\":30,\"warnList\":[{\"count\":-9999,\"id\":123456}]}}"; JSON.parse(json); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3629.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSONPath; import java.util.List; import junit.framework.TestCase; public class Issue3629 extends TestCase { public void test_for_issue() throws Exception { String text1 = "[\n" + " {\n" + " \"author\": \"Nigel Rees\",\n" + " \"category\": \"reference\",\n" + " \"price\": 8.95,\n" + " \"title\": \"Sayings of the Century\"\n" + " },\n" + " {\n" + " \"author\": \"Evelyn Waugh\",\n" + " \"category\": \"fiction\",\n" + " \"price\": 12.99,\n" + " \"title\": \"Sword of Honour\"\n" + " },\n" + " {\n" + " \"author\": \"Herman Melville\",\n" + " \"category\": \"fiction\",\n" + " \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.99,\n" + " \"title\": \"Moby Dick\"\n" + " },\n" + " {\n" + " \"author\": \"J. R. R. Tolkien\",\n" + " \"category\": \"fiction\",\n" + " \"isbn\": \"0-395-19395-8\",\n" + " \"price\": 22.99,\n" + " \"title\": \"The Lord of the Rings\"\n" + " }\n" + "]"; List extract = (List) JSONPath.extract(text1, "$..[?(@.price < 10)]"); assertEquals(2, extract.size()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3631.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import junit.framework.TestCase; import java.util.Base64; public class Issue3631 extends TestCase { public void test_issue_1() throws Exception { try { JSON.parse("{[-"); } catch (JSONException unused) { // skip } } public void test_issue_2() throws Exception { try { JSON.parse("TreeSet[[]"); } catch (JSONException unused) { // skip } } public void test_issue_3() throws Exception { try { JSON.parse(btoa("WywsIiIMLCIAAAAMAAAgAAAAdWUgdAAAAA1ubHUlbDMyMjIABAAAADIyMjISMjNbW1ukHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHiBUZA17W3tbCTg0DQooIHRleHQuIEFuZCAgNDRUBDQ0LCwoLCwsLCwsKSwsLCwsLCwsLCwsLCwsnf8sLCwsLCwsMiwsLG51bA9sLCwqLCwsLCwsLCwsLCwsLCwsLCwoLCwsLCwsKSx077+9LCwsLBAsLCwsLCwoLCwsLCwsKSx077+9LCwsLCwyLCwsLCwsLCwsLFtbW1uhpJ3/GiwsLCwsLDIsLCwsLCwsQSw8LCwsLHtbW1sAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHtbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHsnw4QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWw1dLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAW10AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABdAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAW6Gknf8sLCwsLCwsLCwsLCwsWywsLCwsLCwsLCwsLCwsLCwsKCwsLCwsLCksLCwsLCwsLCwsLCwsLJ3/LCwsLCwsLDIsLCxudWxsLCwqLCwsLCwsLCwsLCwsLCwsLCwoLCwsLCwsKSx077+9LCwsLCwsLCwsLCwoLCwsLCwsKSx07zV1bmRlZmluZW5kACwsLCwsLFtbW1uhpJ3/GiwsLCwsLDIsLCwsLCwsQSw8LCwsLHtbW1tboaSd/ywsLCwsLCwsLCwsLCxbLCwsLCwsLCwsLCwsLCwsLCwsLEEsPCwsLCx7W1tbW6Gknf8sLCwsLCwsLCwsLCwsLCwsLCgsLCwsLCwpLCwsLCwsLCwsLCwsLCyd/ywsLCwsLCwyLCwsbnVsbCwsKiwsLCwsLCwsLCwsLCwsLCwsKCwsLCwsLCksdO+/vSwsLCwsMSwsLCwsLCwsLCxbW1tboaSd/xosLCwsLCwyLCwsLCwsLCwsLCws")); } catch (JSONException unused) { // skip } } public static String btoa(String base64) { return new String(Base64.getDecoder().decode(base64)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3637.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.util.TypeUtils; import junit.framework.TestCase; import java.sql.Timestamp; public class Issue3637 extends TestCase { public void test_for_issue() throws Exception { // java.sql.Time.valueOf("01:00:00"); JSON.parseObject("\"01:00:00\"", java.sql.Time.class); TypeUtils.castToJavaBean("01:00:00", java.sql.Time.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3652.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.PropertyNamingStrategy; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.serializer.SerializeConfig; import lombok.AllArgsConstructor; import lombok.Data; import org.junit.Assert; import org.junit.Test; public class Issue3652 { @Test public void test_SerializeConfig_different_Class_Annotation() { Object[] models = new Object[]{ new Model1("hello,world"), new Model2("hello,world"), new Model3("hello,world"), new Model4("hello,world"), }; for (int i = 0; i < 4; i++) { String[] toStrings = new String[PropertyNamingStrategy.values().length]; for (int j = 0; j < toStrings.length; j++) { SerializeConfig config = new SerializeConfig(); config.propertyNamingStrategy = PropertyNamingStrategy.values()[j]; toStrings[j] = JSON.toJSONString(models[i], config); } for (int j = 1; j < toStrings.length; j++) { Assert.assertEquals(toStrings[j], toStrings[j - 1]); System.out.println(toStrings[j - 1]); } } } @Test public void test_different_Class_Annotation() { Object[] models = new Object[]{ new Model1("hello,world"), new Model2("hello,world"), new Model3("hello,world"), new Model4("hello,world"), }; String[] JsonStrings = new String[]{ "{\"goodBoy\":\"hello,world\"}", "{\"GoodBoy\":\"hello,world\"}", "{\"good_boy\":\"hello,world\"}", "{\"good-boy\":\"hello,world\"}"}; /* PS: Order is CamelCase, PascalCase, SnakeCase, KebabCase,*/ for (int i = 0; i < models.length; i++) { String[] toStrings = new String[PropertyNamingStrategy.values().length]; toStrings[i] = JSON.toJSONString(models[i]); Assert.assertEquals(JsonStrings[i], toStrings[i]); } } @JSONType(naming = PropertyNamingStrategy.CamelCase) @Data @AllArgsConstructor public class Model1 { private String goodBoy; } @JSONType(naming = PropertyNamingStrategy.PascalCase) @Data @AllArgsConstructor public class Model2 { private String goodBoy; } @JSONType(naming = PropertyNamingStrategy.SnakeCase) @Data @AllArgsConstructor public class Model3 { private String goodBoy; } @JSONType(naming = PropertyNamingStrategy.KebabCase) @Data @AllArgsConstructor public class Model4 { private String goodBoy; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3655.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import org.junit.Assert; import org.junit.Test; public class Issue3655 { private final static String jsonStr = "{\"data\":\"\",\"data2\":\"\",\"data3\":\"\",\"data4\":\"\",\"data5\":\"\",\"data6\":\"\",\"data7\":\"\",\"data8\":\"\",\"data9\":\"\"}"; @Test public void test_inherit_from_abstract_class_1() { issue3655_b b = new issue3655_b(null, null, null, null, null, null, null, null, null); String result = JSON.toJSONString(b, SerializerFeature.WriteNullStringAsEmpty); System.out.println(result); Assert.assertEquals(jsonStr, result); } @Test public void test_inherit_from_abstract_class_2() { issue3655_c c = new issue3655_c(null, null, null, null, null, null, null, null, null); String result = JSON.toJSONString(c, SerializerFeature.WriteNullStringAsEmpty); System.out.println(result); Assert.assertEquals(jsonStr, result); } public static class issue3655_b extends issue3655_a { private String data; private String data2; private String data3; private String data4; private String data5; private String data6; private String data7; private String data8; private String data9; public String getData() { return data; } public String getData2() { return data2; } public String getData3() { return data3; } public String getData4() { return data4; } public String getData5() { return data5; } public String getData6() { return data6; } public String getData7() { return data7; } public String getData8() { return data8; } public String getData9() { return data9; } public void setData(String data) { this.data = data; } public void setData2(String data2) { this.data2 = data2; } public void setData3(String data3) { this.data3 = data3; } public void setData4(String data4) { this.data4 = data4; } public void setData5(String data5) { this.data5 = data5; } public void setData6(String data6) { this.data6 = data6; } public void setData7(String data7) { this.data7 = data7; } public void setData8(String data8) { this.data8 = data8; } public void setData9(String data9) { this.data9 = data9; } public issue3655_b( String data, String data2, String data3, String data4, String data5, String data6, String data7, String data8, String data9) { this.data = data; this.data2 = data2; this.data3 = data3; this.data4 = data4; this.data5 = data5; this.data6 = data6; this.data7 = data7; this.data8 = data8; this.data9 = data9; } } @Getter @Setter @AllArgsConstructor public static class issue3655_c extends issue3655_a { private String data; private String data2; private String data3; private String data4; private String data5; private String data6; private String data7; private String data8; private String data9; } public static abstract class issue3655_a { public abstract Object getData(); public abstract Object getData2(); public abstract Object getData3(); public abstract Object getData4(); public abstract Object getData5(); public abstract Object getData6(); public abstract Object getData7(); public abstract Object getData8(); public abstract Object getData9(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3671.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONValidator; import junit.framework.TestCase; public class Issue3671 extends TestCase { public void test_for_issue() throws Exception { String json = "[{\n" + " \"filters\": [],\n" + " \"id\": \"baidu_route2\",\n" + " \"order\": 0,\n" + " \"predicates\": [{\n" + " \"args\": {\n" + " \"pattern\": \"/baidu/**\"\n" + " },\n" + " \"name\": \"Path\"\n" + " }],\n" + " \"uri\": \"https://www.baidu.com\"\n" + "}]\n"; assertTrue(JSONValidator.from(json).validate()); assertTrue(JSON.isValid(json)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3672.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.google.common.collect.Lists; import lombok.Data; import org.junit.Test; import java.util.ArrayList; import junit.framework.TestCase; public class Issue3672 extends TestCase { public void test_for_issue() throws Exception { Issue3672Root root = new Issue3672Root(); Issue3672A a = new Issue3672A(); Issue3672B b = new Issue3672B(); Issue3672C c = new Issue3672C(); Issue3672D d = new Issue3672D(); root.setA(a); a.setB(Lists.newArrayList(b).toArray()); b.setC(c); c.setD(d); d.setE(Lists.newArrayList(c)); String str1 = JSON.toJSONString(root, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue); String str2 = JSON.toJSONString(root); JSONObject obj1 = JSON.parseObject(str1); JSONObject obj2 = JSON.parseObject(str2); assertEquals(obj1.toString(), obj2.toString()); } @Data private class Issue3672Root { private Issue3672A a; } @Data private class Issue3672A { private Object[] b; } @Data private class Issue3672B { private Issue3672C c; } @Data private class Issue3672C { private Issue3672D d; } @Data private class Issue3672D { private ArrayList e; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3682.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import lombok.Data; public class Issue3682 extends TestCase { public void test_for_issue() throws Exception { Cid cid = JSON.parseObject(SOURCE, Cid.class); System.out.println(cid); } @Data static public class Cid { @JSONField(name = "/") private String hash; } static final String SOURCE = "{\n" + " \"jsonrpc\": \"2.0\",\n" + " \"result\": {\n" + " \"Version\": 0,\n" + " \"To\": \"t1iceld4fv44xgjqfcx5lwz45pubheu3c7c2nmlua\",\n" + " \"From\": \"t152xual7ze57jnnioucuv4lmtxarewtzhkqojboy\",\n" + " \"Nonce\": 4,\n" + " \"Value\": \"9999999938462317355\",\n" + " \"GasLimit\": 609960,\n" + " \"GasFeeCap\": \"101083\",\n" + " \"GasPremium\": \"100029\",\n" + " \"Method\": 0,\n" + " \"Params\": null,\n" + " \"CID\": {\n" + " \"/\": \"bafy2bzacedgpr5pmkvu4rkq26uv4hidpfrn3gdvtgkp3hpxss3bgmodrgqtk6\"\n" + " }\n" + " },\n" + " \"id\": 1\n" + "}"; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3689.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import org.junit.Test; public class Issue3689 { @Test(expected = JSONException.class) public void test_without_type_0_meaningles_char() { JSONArray.parseArray("dfdfdf"); } @Test(expected = JSONException.class) public void test_without_type_1_meaningles_char() { JSONArray.parseArray("/dfdfdf"); } @Test(expected = JSONException.class) public void test_without_type_2_meaningles_char() { JSONArray.parseArray("//dfdfdf"); } @Test(expected = JSONException.class) public void test_without_type_3_meaningles_char() { JSONArray.parseArray("///dfdfdf"); } @Test(expected = JSONException.class) public void test_without_type_4_meaningles_char() { JSONArray.parseArray("////dfdfdf"); } @Test(expected = JSONException.class) public void test_without_type_5_meaningles_char() { JSONArray.parseArray("/////dfdfdf"); } @Test(expected = JSONException.class) public void test_without_type_6_meaningles_char() { JSONArray.parseArray("//////dfdfdf"); } @Test(expected = JSONException.class) public void test_with_type_0_meaningles_char() { JSONArray.parseArray("dfdfdf", String.class); } @Test(expected = JSONException.class) public void test_with_type_1_meaningles_char() { JSONArray.parseArray("/dfdfdf", String.class); } @Test(expected = JSONException.class) public void test_with_type_2_meaningles_char() { JSONArray.parseArray("//dfdfdf", String.class); } @Test(expected = JSONException.class) public void test_with_type_3_meaningles_char() { JSONArray.parseArray("///dfdfdf", String.class); } @Test(expected = JSONException.class) public void test_with_type_4_meaningles_char() { JSONArray.parseArray("////dfdfdf", String.class); } @Test(expected = JSONException.class) public void test_with_type_5_meaningles_char() { JSONArray.parseArray("/////dfdfdf", String.class); } @Test(expected = JSONException.class) public void test_with_type_6_meaningles_char() { JSONArray.parseArray("//////dfdfdf", String.class); } @Test public void test_for_issue() { JSONArray.parseArray("[\"////dfdfdf\"]"); //不会抛异常 JSONArray objects = JSONArray.parseArray("[\"dfdfdf\"]");//不会抛异常 System.out.println(JSONArray.parseArray("[\"////dfdfdf\"]")); System.out.println(JSONArray.parseArray("[\"dfdfdf\"]")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3600/Issue3693.java ================================================ package com.alibaba.json.bvt.issue_3600; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; 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; import java.lang.reflect.Type; public class Issue3693 extends TestCase { public void test_for_issue() throws Exception { Model model = new Model("hello 世界", new ModelProperties("红色", 66)); String json = JSON.toJSONString(model); assertEquals("{\"name\":\"hello 世界\",\"properties\":\"{\\\"color\\\":\\\"红色\\\",\\\"size\\\":66}\"}", json); Model deserializedModel = JSON.parseObject(json, new TypeReference>() { }); assertNotNull(deserializedModel); assertEquals("hello 世界", deserializedModel.getName()); assertNotNull(deserializedModel.getProperties()); assertEquals("红色", deserializedModel.getProperties().getColor()); assertEquals(66, deserializedModel.getProperties().getSize()); } static class Model { private String name; @JSONField(serializeUsing = MyCodec.class, deserializeUsing = MyCodec.class) private T properties; Model() { } Model(String name, T properties) { this.name = name; this.properties = properties; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public T getProperties() { return this.properties; } public void setProperties(T properties) { this.properties = properties; } } static class ModelProperties { private String color; private int size; ModelProperties() { } ModelProperties(String color, int size) { this.color = color; this.size = size; } public String getColor() { return this.color; } public void setColor(String color) { this.color = color; } public int getSize() { return this.size; } public void setSize(int size) { this.size = size; } } public static class MyCodec implements ObjectSerializer, ObjectDeserializer { @Override public int getFastMatchToken() { return 0; } @Override public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) { serializer.write(JSON.toJSONString(object)); } @Override public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { String json = parser.parseObject(String.class); return JSON.parseObject(json, type); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/issue_3800/Issue3810.java ================================================ package com.alibaba.json.bvt.issue_3800; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.util.ParameterizedTypeImpl; import junit.framework.TestCase; import lombok.Data; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * https://github.com/alibaba/fastjson/issues/3810 * * @author hnyyghk * @date 2021/06/30 18:40 */ public class Issue3810 extends TestCase { @Data static class TestA { T a; } @Data static class TestB { String b; } private final static String json = "{\"a\":[{\"b\":\"b\"}]}"; public void test_for_issue() throws Exception { ParameterizedTypeImpl inner = new ParameterizedTypeImpl(new Type[]{TestB.class}, List.class, List.class); ParameterizedTypeImpl outer = new ParameterizedTypeImpl(new Type[]{inner}, TestA.class, TestA.class); JSONObject jo = JSONObject.parseObject(json); TestA> ret = jo.toJavaObject(outer); assertEquals(ArrayList.class.getName(), ret.getA().getClass().getName()); assertEquals(TestB.class.getName(), ret.getA().get(0).getClass().getName()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk7/PathTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/DoubleAdderTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/DurationTest.java ================================================ 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 void test_for_issue_1() throws Exception { String text = "{\"zero\":false,\"seconds\":5184000,\"negative\":false,\"nano\":0,\"units\":[\"SECONDS\",\"NANOS\"]}"; Duration duration = JSON.parseObject(text, Duration.class); assertEquals("PT1440H", duration.toString()); } public static class VO { private Duration date; public Duration getDate() { return date; } public void setDate(Duration date) { this.date = date; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/InstantTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest3.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest4.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest5.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest.java ================================================ 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()); VO vo1 = JSON.parseObject("{\"date\":1511334591189}", 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 void test_for_issue_1() throws Exception { String text = "{\"date\":\"2018-08-03 22:38:33.145\"}"; VO vo1 = JSON.parseObject(text, VO.class); assertNotNull(vo1.date); } public static class VO { private LocalDateTime date; public LocalDateTime getDate() { return date; } public void setDate(LocalDateTime date) { this.date = date; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest3.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest3_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest4.java ================================================ 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-06T09: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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTimeTest5.java ================================================ package com.alibaba.json.bvt.jdk8; import java.time.Instant; import java.time.LocalDateTime; import java.util.Locale; import java.util.Random; import java.util.TimeZone; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class LocalDateTimeTest5 extends TestCase { private static Random random = new Random(); private Locale origin; private TimeZone original = TimeZone.getDefault(); private String[] zoneIds = TimeZone.getAvailableIDs(); @Override protected void setUp() throws Exception { int index = random.nextInt(zoneIds.length); TimeZone timeZone = TimeZone.getTimeZone(zoneIds[index]); TimeZone.setDefault(timeZone); JSON.defaultTimeZone = timeZone; // While running mvn tests defaultTimeZone might already be initialized origin = Locale.getDefault(); } @Override protected void tearDown() throws Exception { TimeZone.setDefault(original); JSON.defaultTimeZone = original; Locale.setDefault(origin); } public void test_for_long() throws Exception { long millis = 1322874196000L; // using localDataTime instance so that different timeZones are tested LocalDateTime localDateTime = LocalDateTime.ofInstant( Instant.ofEpochMilli(millis), TimeZone.getDefault().toZoneId()); VO vo = JSON.parseObject("{\"date\":" + millis + "}", VO.class); assertEquals("Not Matching year", localDateTime.getYear(), vo.date.getYear()); assertEquals("Not Matching month", localDateTime.getMonthValue(), vo.date.getMonthValue()); assertEquals("Not Matching day", localDateTime.getDayOfMonth(), vo.date.getDayOfMonth()); assertEquals("Not Matching hour", localDateTime.getHour(), vo.date.getHour()); assertEquals("Not Matching minute", localDateTime.getMinute(), vo.date.getMinute()); assertEquals("Not Matching second", localDateTime.getSecond(), vo.date.getSecond()); assertEquals("Not Matching nano", localDateTime.getNano(), vo.date.getNano()); } public void test_for_normal() throws Exception { VO vo = JSON.parseObject("{\"date\":\"2011-12-03 09:03:16\"}", VO.class); assertEquals(2011, vo.date.getYear()); assertEquals(12, vo.date.getMonthValue()); assertEquals(3, vo.date.getDayOfMonth()); assertEquals(9, vo.date.getHour()); assertEquals(3, vo.date.getMinute()); assertEquals(16, vo.date.getSecond()); assertEquals(0, vo.date.getNano()); } public void test_for_iso() throws Exception { VO vo = JSON.parseObject("{\"date\":\"2011-12-03T09:03:16\"}", VO.class); assertEquals(2011, vo.date.getYear()); assertEquals(12, vo.date.getMonthValue()); assertEquals(3, vo.date.getDayOfMonth()); assertEquals(9, vo.date.getHour()); assertEquals(3, vo.date.getMinute()); assertEquals(16, vo.date.getSecond()); 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); assertEquals(2016, vo.date.getYear()); assertEquals(5, vo.date.getMonthValue()); 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); assertEquals(2016, vo.date.getYear()); assertEquals(5, vo.date.getMonthValue()); 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); assertEquals(2016, vo.date.getYear()); assertEquals(5, vo.date.getMonthValue()); 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); assertEquals(2016, vo.date.getYear()); assertEquals(5, vo.date.getMonthValue()); 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); assertEquals(2016, vo.date.getYear()); assertEquals(5, vo.date.getMonthValue()); 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); assertEquals(2016, vo.date.getYear()); assertEquals(5, vo.date.getMonthValue()); 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); assertEquals(2016, vo.date.getYear()); assertEquals(5, vo.date.getMonthValue()); 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); assertEquals(2016, vo.date.getYear()); assertEquals(5, vo.date.getMonthValue()); 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); assertEquals(2016, vo.date.getYear()); assertEquals(5, vo.date.getMonthValue()); 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); assertEquals(2016, vo.date.getYear()); assertEquals(5, vo.date.getMonthValue()); assertEquals(6, vo.date.getDayOfMonth()); assertEquals(9, vo.date.getHour()); assertEquals(3, vo.date.getMinute()); assertEquals(16, vo.date.getSecond()); 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); assertEquals(2016, vo.date.getYear()); assertEquals(5, vo.date.getMonthValue()); assertEquals(6, vo.date.getDayOfMonth()); assertEquals(9, vo.date.getHour()); assertEquals(3, vo.date.getMinute()); assertEquals(16, vo.date.getSecond()); assertEquals(0, vo.date.getNano()); } public static class VO { public LocalDateTime date; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest3.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/LongAdderTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/OffseTimeTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/OffsetDateTimeTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/OptionalDouble_Test.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/OptionalInt_Test.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/OptionalLong_Test.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest.java ================================================ 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())); } public void test_optional_parseNull() throws Exception { assertSame(Optional.empty() , JSON.parseObject("null", Optional.class)); } public void test_optional_parseNull_2() throws Exception { assertSame(Optional.empty() , JSON.parseObject("null", new TypeReference>() {})); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest4.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest_empty.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/PeriodTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/ZoneIdTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/ZonedDateTimeTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jdk8/ZonedDateTimeTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/joda/JodaTest_0.java ================================================ package com.alibaba.json.bvt.joda; import com.alibaba.fastjson.JSON; import com.alibaba.json.bvt.jdk8.LocalDateTest2; import junit.framework.TestCase; import org.junit.Assert; import org.joda.time.LocalDate; import java.util.Locale; import java.util.TimeZone; public class JodaTest_0 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()); } public void test_for_issue_1() 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.getMonthOfYear()); Assert.assertEquals(6, vo.date.getDayOfMonth()); } public void test_for_issue_2() throws Exception { VO vo = JSON.parseObject("{\"date\":\"20160506\"}", VO.class); Assert.assertEquals(2016, vo.date.getYear()); Assert.assertEquals(5, vo.date.getMonthOfYear()); Assert.assertEquals(6, vo.date.getDayOfMonth()); } /** * 方法描述: 测试时间戳转换为 日期 * @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.getMonthOfYear()); 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/joda/JodaTest_1_LocalDateTime.java ================================================ package com.alibaba.json.bvt.joda; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import org.junit.Assert; import org.joda.time.LocalDateTime; public class JodaTest_1_LocalDateTime extends TestCase { public void test_for_issue() throws Exception { VO vo = new VO(); vo.setDate(LocalDateTime.now()); 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()); VO vo1 = JSON.parseObject("{\"date\":1511334591189}", 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 void test_for_issue_1() throws Exception { String text = "{\"date\":\"2018-08-03 22:38:33.145\"}"; VO vo1 = JSON.parseObject(text, VO.class); assertNotNull(vo1.date); } public static class VO { private LocalDateTime date; public LocalDateTime getDate() { return date; } public void setDate(LocalDateTime date) { this.date = date; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/joda/JodaTest_2_LocalDateTimeTest3_private.java ================================================ package com.alibaba.json.bvt.joda; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import org.junit.Assert; import org.joda.time.LocalDateTime; public class JodaTest_2_LocalDateTimeTest3_private extends TestCase { public void test_for_issue() throws Exception { String text = "{\"date\":\"20111203\"}"; VO vo = JSON.parseObject(text, VO.class); assertEquals(2011, vo.date.getYear()); assertEquals(12, vo.date.getMonthOfYear()); assertEquals(03, vo.date.getDayOfMonth()); assertEquals(0, vo.date.getHourOfDay()); assertEquals(0, vo.date.getMinuteOfHour()); assertEquals(0, vo.date.getSecondOfMinute()); assertEquals(text, JSON.toJSONString(vo)); } private static class VO { @JSONField(format="yyyyMMdd") public LocalDateTime date; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/joda/JodaTest_3_LocalTimeTest.java ================================================ package com.alibaba.json.bvt.joda; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.junit.Assert; import org.joda.time.LocalTime; import java.util.Locale; import java.util.TimeZone; public class JodaTest_3_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.getHourOfDay()); Assert.assertEquals(14, vo.date.getMinuteOfHour()); Assert.assertEquals(07, vo.date.getSecondOfMinute()); } public static class VO { private LocalTime date; public LocalTime getDate() { return date; } public void setDate(LocalTime date) { this.date = date; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/joda/JodaTest_4_InstantTest.java ================================================ package com.alibaba.json.bvt.joda; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.junit.Assert; import org.joda.time.Instant; public class JodaTest_4_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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/joda/JodaTest_5_DateTimeFormatter.java ================================================ package com.alibaba.json.bvt.joda; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.joda.time.format.*; public class JodaTest_5_DateTimeFormatter extends TestCase { public void test_for_joda_0() throws Exception { String json = "{\"formatter\":\"yyyyMMdd\"}"; Model m = JSON.parseObject(json, Model.class); assertEquals(DateTimeFormat.forPattern("yyyyMMdd"), m.formatter); } public static class Model { public DateTimeFormatter formatter; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/joda/JodaTest_6_Duration.java ================================================ package com.alibaba.json.bvt.joda; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.joda.time.Duration; import org.joda.time.Period; public class JodaTest_6_Duration extends TestCase { public void test_for_joda_0() throws Exception { Model m = new Model(); m.duration = new Duration(24L*60L*60L*1000L); String json = JSON.toJSONString(m); assertEquals("{\"duration\":\"PT86400S\"}", json); Model m1 = JSON.parseObject(json, Model.class); assertEquals(m.duration, m1.duration); } public static class Model { public Duration duration; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/joda/JodaTest_6_Period.java ================================================ package com.alibaba.json.bvt.joda; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.joda.time.Period; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class JodaTest_6_Period extends TestCase { public void test_for_joda_0() throws Exception { Model m = new Model(); m.period = Period.days(3); String json = JSON.toJSONString(m); assertEquals("{\"period\":\"P3D\"}", json); Model m1 = JSON.parseObject(json, Model.class); assertEquals(m.period, m1.period); } public static class Model { public Period period; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/joda/JodaTest_7_DateTimeZone.java ================================================ package com.alibaba.json.bvt.joda; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.joda.time.DateTimeZone; public class JodaTest_7_DateTimeZone extends TestCase { public void test_for_joda_0() throws Exception { Model m = new Model(); m.zone = DateTimeZone.forID("Asia/Shanghai"); String json = JSON.toJSONString(m); assertEquals("{\"zone\":\"Asia/Shanghai\"}", json); Model m1 = JSON.parseObject(json, Model.class); assertEquals(m.zone, m1.zone); } public static class Model { public DateTimeZone zone; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/joda/JodaTest_8_DateTimeTest.java ================================================ package com.alibaba.json.bvt.joda; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.joda.time.DateTime; import org.joda.time.LocalTime; import org.junit.Assert; import java.util.Locale; import java.util.TimeZone; public class JodaTest_8_DateTimeTest 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.date = DateTime.now(); String text = JSON.toJSONString(vo); VO vo1 = JSON.parseObject(text, VO.class); Assert.assertEquals(vo.date.toDate(), vo1.date.toDate()); } /** * 方法描述: 测试时间戳转换为 时间 * @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("timeZone " + TimeZone.getDefault(), 15, vo.date.getHourOfDay()); Assert.assertEquals(14, vo.date.getMinuteOfHour()); Assert.assertEquals(07, vo.date.getSecondOfMinute()); } public static class VO { private DateTime date; public DateTime getDate() { return date; } public void setDate(DateTime date) { this.date = date; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jsonfield/JSONFieldTest_0.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jsonfield/JSONFieldTest_1.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest1.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest2.java ================================================ 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, SerializerFeature.MapSortField); assertEquals("parent.callback({\"id\":1,\"name\":\"idonans\"})", json); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest3.java ================================================ 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, SerializerFeature.MapSortField); assertEquals("/**/parent.callback({\"id\":1,\"name\":\"ido\\u0029nans\"},1,2)", json); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jsonp/JSONPParseTest4.java ================================================ 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 JSONPParseTest4 extends TestCase { public void test_f() throws Exception { JSONPObject p = new JSONPObject(); p.setFunction("f"); assertEquals("f()", p.toJSONString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/jsonpatch/JSONPatchTest_0.java ================================================ package com.alibaba.json.bvt.jsonpatch; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONPatch; import junit.framework.TestCase; public class JSONPatchTest_0 extends TestCase { public void test_for_multi_0() throws Exception { String original = "{\n" + " \"baz\": \"qux\",\n" + " \"foo\": \"bar\"\n" + "}"; String patch = "[\n" + " { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n" + " { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n" + " { \"op\": \"remove\", \"path\": \"/foo\" }\n" + "]"; String result = JSONPatch.apply(original, patch); assertEquals("{\"baz\":\"boo\",\"hello\":[\"world\"]}", result); } public void test_for_add_1() throws Exception { String original = "{}"; String patch = "{ \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": [ \"foo\", \"bar\" ] }"; String result = JSONPatch.apply(original, patch); assertEquals("{\"a\":{\"b\":{\"c\":[\"foo\",\"bar\"]}}}", result); } public void test_for_remove_0() throws Exception { String original = "{}"; String patch = "{ \"op\": \"remove\", \"path\": \"/a/b/c\" }\n"; String result = JSONPatch.apply(original, patch); assertEquals("{}", result); } public void test_for_remove_1() throws Exception { String original = "{\"a\":{\"b\":{\"c\":[\"foo\",\"bar\"]}}}"; String patch = "{ \"op\": \"remove\", \"path\": \"/a/b/c\" }\n"; String result = JSONPatch.apply(original, patch); assertEquals("{\"a\":{\"b\":{}}}", result); } public void test_for_replace_1() throws Exception { String original = "{\"a\":{\"b\":{\"c\":[\"foo\",\"bar\"]}}}"; String patch = "{ \"op\": \"replace\", \"path\": \"/a/b/c\", \"value\": 42 }"; String result = JSONPatch.apply(original, patch); assertEquals("{\"a\":{\"b\":{\"c\":42}}}", result); } public void test_for_move_0() throws Exception { String original = "{\"a\":{\"b\":{\"c\":[\"foo\",\"bar\"]}}}"; String patch = "{ \"op\": \"move\", \"from\": \"/a/b/c\", \"path\": \"/a/b/d\" }"; String result = JSONPatch.apply(original, patch); assertEquals("{\"a\":{\"b\":{\"d\":[\"foo\",\"bar\"]}}}", result); } public void test_for_copy_0() throws Exception { String original = "{\"a\":{\"b\":{\"c\":[\"foo\",\"bar\"]}}}"; String patch = "{ \"op\": \"copy\", \"from\": \"/a/b/c\", \"path\": \"/a/b/e\" }"; String result = JSONPatch.apply(original, patch); assertEquals("{\"a\":{\"b\":{\"c\":[\"foo\",\"bar\"],\"e\":[\"foo\",\"bar\"]}}}", result); } public void test_for_test_0() throws Exception { String original = "{\"a\":{\"b\":{\"c\":[\"foo\",\"bar\"]}}}"; String patch = "{ \"op\": \"test\", \"path\": \"/a/b/c\", \"value\": \"foo\" }"; String result = JSONPatch.apply(original, patch); assertEquals("false", result); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/ClassWithPairMixedTypesTest.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/ClassWithPairTest.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/ClassWithRangesTest.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/ClassWithTripleTest.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/Class_WithPrimaryAndSecondaryConstructorTest.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/DataClassSimpleTest.java ================================================ package com.alibaba.json.bvt.kotlin; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.util.ASMUtils; import junit.framework.TestCase; 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/DataClassTest.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/Issue1420.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/Issue1462.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/Issue1483.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/Issue1524.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/Issue1543.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/Issue1547.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/Issue1569.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/Issue1750.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/Issue_for_kotlin_20181203.java ================================================ package com.alibaba.json.bvt.kotlin; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; public class Issue_for_kotlin_20181203 extends TestCase { public void test_user() throws Exception { ExtClassLoader classLoader = new ExtClassLoader(); Class clazz = classLoader.loadClass("com.autonavi.falcon.data.service.vulpeData.ProjectItemCheckItemRelation1"); String str = " [{\n" + " \"project_item\": \"1105067\",\n" + " \"project_name\": \"明明想\",\n" + " \"product_id_3\": \"0210202\",\n" + " \"task_type_name\": \"黎明X\",\n" + " \"product_id_2\": \"02102\",\n" + " \"product_id_1\": \"021\",\n" + " \"job_item_type\": \"高中\",\n" + " \"product_name_1\": \"犀利\",\n" + " \"product_name_2\": \"基础路网\",\n" + " \"unit\": \"条\",\n" + " \"product_name_3\": \"到底\",\n" + " \"unitremark\": \"任务条数\",\n" + " \"task_type\": \"57205\"\n" + " }]"; System.out.println(JSON.VERSION); Object obj = JSONArray.parseArray(str, clazz); String result = JSON.toJSONString(obj); System.out.println(result); assertEquals("[{\"job_item_type\":\"高中\",\"product_id_1\":\"021\",\"product_id_2\":\"02102\",\"product_id_3\":\"0210202\",\"product_name_1\":\"犀利\",\"product_name_2\":\"基础路网\",\"product_name_3\":\"到底\",\"project_item\":\"1105067\",\"project_name\":\"明明想\",\"task_type\":\"57205\",\"task_type_name\":\"黎明X\",\"unit\":\"条\",\"unitremark\":\"任务条数\"}]", result); } private static class ExtClassLoader extends ClassLoader { public ExtClassLoader() throws IOException { super(Thread.currentThread().getContextClassLoader()); { byte[] bytes; InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/ProjectItemCheckItemRelation1.clazz"); bytes = IOUtils.toByteArray(is); is.close(); super.defineClass("com.autonavi.falcon.data.service.vulpeData.ProjectItemCheckItemRelation1", bytes, 0, bytes.length); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/ResponseKotlin2Test.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/ResponseKotlinTest.java ================================================ 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); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/kotlin/Zoujing.java ================================================ 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 Zoujing extends TestCase { public void test_user() throws Exception { ExtClassLoader classLoader = new ExtClassLoader(); Class clazz = classLoader.loadClass("com.alidme.xrecharge.platform.common.data.NoticeData"); String json = "{\"benefitNoticeState\":1}"; Object obj = JSON.parseObject(json, clazz); String result = JSON.toJSONString(obj); System.out.println(result); assertEquals("{\"benefitNoticeState\":1,\"outId\":\"\"}", result); } private static class ExtClassLoader extends ClassLoader { public ExtClassLoader() throws IOException { super(Thread.currentThread().getContextClassLoader()); { byte[] bytes; InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/zuojing/NoticeData.clazz"); bytes = IOUtils.toByteArray(is); is.close(); super.defineClass("com.alidme.xrecharge.platform.common.data.NoticeData", bytes, 0, bytes.length); } { byte[] bytes; InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/zuojing/NoticeDataKt.clazz"); bytes = IOUtils.toByteArray(is); is.close(); super.defineClass("com.alidme.xrecharge.platform.common.data.NoticeDataKt", bytes, 0, bytes.length); } { byte[] bytes; InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/zuojing/NoticeData_Companion.clazz"); bytes = IOUtils.toByteArray(is); is.close(); super.defineClass("com.alidme.xrecharge.platform.common.data.NoticeData$Companion", bytes, 0, bytes.length); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/lombok/LomBokTest.java ================================================ package com.alibaba.json.bvt.lombok; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.ParserConfig; import junit.framework.TestCase; public class LomBokTest extends TestCase { public void test_for_issue() throws Exception { String str = "{\n" + "\t\"target\": 1,\n" + "\t\"current\": 0,\n" + "\t\"step\": 1,\n" + "\t\"uqcRule\": {\n" + "\t\t\"ruleCode\": \"IND#PAY1212#NP1D#1\"\n" + "\t},\n" + "\t\"cycleRule\": {\n" + "\t\t\"decision\": {\"@type\": \"com.alibaba.json.bvt.lombok.LomBokTest$DaysCycleExeDecision\",\"days\": 1\n" + "\t\t}\n" + "\t},\n" + "\t\"dataSource\": {\n" + "\t\t\"PAYLINK\": {\n" + "\t\t\t\"target\": 0\n" + "\t\t}\n" + "\t}\n" + "}"; ParserConfig.getGlobalInstance().addAccept("com.alibaba.json.bvt.lombok.LomBokTest.DaysCycleExeDecision"); JSONObject obj = JSON.parseObject(str); IndicatorCycleRule cycleRule = obj.getObject("cycleRule", IndicatorCycleRule.class); System.out.println(((DaysCycleExeDecision) cycleRule.decision).days); } @lombok.Data public static class DaysCycleExeDecision implements ExeDecision { private int days; } public static interface ExeDecision { } @lombok.Data public static class IndicatorCycleRule { /** * 周期决策器 */ private ExeDecision decision; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/mixins/MixInRemovalTest.java ================================================ package com.alibaba.json.bvt.mixins; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import org.junit.Assert; public class MixInRemovalTest extends TestCase { static class BaseClass { public int a; public int b; public BaseClass() { } public BaseClass(int a, int b) { this.a = a; this.b = b; } } class MixIn1 { @JSONField(name = "apple") public int a; @JSONField(name = "banana") public int b; } class MixIn2 { @JSONField(name = "ariston") public int a; @JSONField(name = "brilliant") public int b; } public void test_mixInRemoval_serialize() throws Exception { BaseClass base = new BaseClass(1, 2); Assert.assertEquals("{\"a\":1,\"b\":2}", JSON.toJSONString(base)); JSON.addMixInAnnotations(BaseClass.class, MixIn1.class); Assert.assertEquals("{\"apple\":1,\"banana\":2}", JSON.toJSONString(base)); JSON.removeMixInAnnotations(BaseClass.class); JSON.addMixInAnnotations(BaseClass.class, MixIn2.class); Assert.assertEquals("{\"ariston\":1,\"brilliant\":2}", JSON.toJSONString(base)); JSON.removeMixInAnnotations(BaseClass.class); Assert.assertEquals("{\"a\":1,\"b\":2}", JSON.toJSONString(base)); } public void test_mixInRemoval_deserialize() throws Exception { BaseClass base = JSON.parseObject("{\"a\":1,\"b\":2}", BaseClass.class); Assert.assertEquals(1, base.a); Assert.assertEquals(2, base.b); JSON.addMixInAnnotations(BaseClass.class, MixIn1.class); BaseClass base2 = JSON.parseObject("{\"apple\":3,\"banana\":4}", BaseClass.class); Assert.assertEquals(3, base2.a); Assert.assertEquals(4, base2.b); JSON.removeMixInAnnotations(BaseClass.class); JSON.addMixInAnnotations(BaseClass.class, MixIn2.class); BaseClass base3 = JSON.parseObject("{\"ariston\":5,\"brilliant\":6}", BaseClass.class); Assert.assertEquals(5, base3.a); Assert.assertEquals(6, base3.b); JSON.removeMixInAnnotations(BaseClass.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/mixins/MixinAPITest.java ================================================ package com.alibaba.json.bvt.mixins; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import org.junit.Assert; public class MixinAPITest extends TestCase { static class BaseClass { public int a; public int b; public BaseClass() { } public BaseClass(int a, int b) { this.a = a; this.b = b; } } class MixIn1 { @JSONField(name = "apple") public int a; @JSONField(name = "banana") public int b; } public void test_mixIn_get_methods() throws Exception { BaseClass base = new BaseClass(1, 2); JSON.addMixInAnnotations(BaseClass.class, MixIn1.class); Assert.assertEquals("{\"apple\":1,\"banana\":2}", JSON.toJSONString(base)); Assert.assertTrue(MixIn1.class == JSON.getMixInAnnotations(BaseClass.class)); JSON.clearMixInAnnotations(); Assert.assertTrue(null == JSON.getMixInAnnotations(BaseClass.class)); JSON.removeMixInAnnotations(BaseClass.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/mixins/MixinDeserForClassTest.java ================================================ package com.alibaba.json.bvt.mixins; import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class MixinDeserForClassTest extends TestCase { static class BaseClass { @JSONField( deserialize = true ) public String a; @JSONField( deserialize = false, name = "a" ) public void setA( String v ) { a = "XXX" + v; } } static class BaseClass1 { @JSONField( deserialize = false ) public String a; @JSONField( deserialize = true, name = "a" ) public void setA( String v ) { a = "XXX" + v; } } static class Mixin { @JSONField( deserialize = false ) public String a; @JSONField( deserialize = true, name = "a" ) public void setA( String v ) { } } public void test_1() throws Exception { BaseClass1 base = JSON.parseObject( "{\"a\":\"132\"}", BaseClass1.class ); Assert.assertEquals( "XXX132", base.a ); } public void test_2() throws Exception { JSON.addMixInAnnotations(BaseClass.class, Mixin.class); BaseClass base = JSON.parseObject( "{\"a\":\"132\"}", BaseClass.class ); Assert.assertEquals( "XXX132", base.a ); JSON.removeMixInAnnotations(BaseClass.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/mixins/MixinDeserForMethodsTest.java ================================================ package com.alibaba.json.bvt.mixins; import java.util.HashMap; 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 MixinDeserForMethodsTest extends TestCase { static class BaseClass { protected HashMap values = new HashMap(); @JSONCreator public BaseClass( @JSONField( name = "name" ) String name,@JSONField( name = "age" ) String age, @JSONField( name = "student" ) Object student ) { values.put( "name", name ); values.put( "age", age ); values.put( "student", student ); } } static class BaseClass2 { protected HashMap values = new HashMap(); public BaseClass2( String name,String age,Object student ) { values.put( "name", name ); values.put( "age", age ); values.put( "student", student ); } } class MixIn { @JSONCreator MixIn( @JSONField( name = "name" ) String name,@JSONField( name = "age" ) String age, @JSONField( name = "student" ) Object student ) { }; } public void test_0() throws Exception { BaseClass result = JSON.parseObject( "{ \"name\" : \"David\", \"age\" : 13, \"student\" : true }", BaseClass.class ); Assert.assertNotNull( result ); Assert.assertEquals( 3, result.values.size() ); Assert.assertEquals( "David", result.values.get( "name" ) ); Assert.assertEquals( "13", result.values.get( "age" ) ); Assert.assertEquals( Boolean.TRUE, result.values.get( "student" ) ); } public void test_1() throws Exception { JSON.addMixInAnnotations(BaseClass2.class, MixIn.class); BaseClass2 result = JSON.parseObject( "{ \"name\" : \"David\", \"age\" : 13, \"student\" : true }", BaseClass2.class ); Assert.assertNotNull( result ); Assert.assertEquals( 3, result.values.size() ); Assert.assertEquals( "David", result.values.get( "name" ) ); Assert.assertEquals( "13", result.values.get( "age" ) ); Assert.assertEquals( Boolean.TRUE, result.values.get( "student" ) ); JSON.removeMixInAnnotations(BaseClass2.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/mixins/MixinInheritanceTest.java ================================================ package com.alibaba.json.bvt.mixins; 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 MixinInheritanceTest extends TestCase { static class Beano { public int ido = 42; public String nameo = "Bob"; } static class BeanoMixinSuper { @JSONField(name = "name") public String nameo; } static class BeanoMixinSub extends BeanoMixinSuper { @JSONField(name = "id") public int ido; } static class Beano2 { public int getIdo() { return 13; } public String getNameo() { return "Bill"; } } static abstract class BeanoMixinSuper2 extends Beano2 { @Override @JSONField(name = "name") public abstract String getNameo(); } static abstract class BeanoMixinSub2 extends BeanoMixinSuper2 { @Override @JSONField(name = "id") public abstract int getIdo(); } public void test_field() throws Exception { JSON.addMixInAnnotations(Beano.class, BeanoMixinSub.class); String str = JSON.toJSONString(new Beano()); JSONObject result = JSONObject.parseObject(str); assertEquals(2, result.size()); if (!result.containsKey("id") || !result.containsKey("name")) { fail("Should have both 'id' and 'name', but content = " + result); } JSON.removeMixInAnnotations(Beano.class); } public void test_method() throws Exception { JSON.addMixInAnnotations(Beano2.class, BeanoMixinSub2.class); String str = JSON.toJSONString(new Beano2()); JSONObject result = JSONObject.parseObject(str); assertEquals(2, result.size()); assertTrue(result.containsKey("id")); assertTrue(result.containsKey("name")); JSON.removeMixInAnnotations(Beano2.class); } static class BaseClass { public int a; public int b; public int c; public BaseClass() { } public BaseClass(int a, int b,int c) { this.a = a; this.b = b; this.c = c; } } class BaseMixIn { @JSONField(name = "apple") public int a; @JSONField(name = "banana") public int b; } class SubMixIn extends BaseMixIn { @JSONField(name = "pear") public int c; } class SubMixIn1 extends SubMixIn { @JSONField(name = "watermelon") public int b; } public void test_mixIn_extend() throws Exception { BaseClass base = new BaseClass(1, 2,3); Assert.assertEquals("{\"a\":1,\"b\":2,\"c\":3}", JSON.toJSONString(base)); JSON.addMixInAnnotations(BaseClass.class, SubMixIn.class); Assert.assertEquals("{\"apple\":1,\"banana\":2,\"pear\":3}", JSON.toJSONString(base)); JSON.removeMixInAnnotations(BaseClass.class); } public void test_mixIn_extend1() throws Exception { BaseClass base = new BaseClass(1, 2,3); Assert.assertEquals("{\"a\":1,\"b\":2,\"c\":3}", JSON.toJSONString(base)); JSON.addMixInAnnotations(BaseClass.class, SubMixIn1.class); Assert.assertEquals("{\"apple\":1,\"pear\":3,\"watermelon\":2}", JSON.toJSONString(base)); JSON.removeMixInAnnotations(BaseClass.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/mixins/MixinJSONTypeTest.java ================================================ package com.alibaba.json.bvt.mixins; import com.alibaba.fastjson.annotation.JSONPOJOBuilder; 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 MixinJSONTypeTest extends TestCase { public void test_1() { User user1 = new User("zhangsan", "male", 19); Assert.assertEquals("{\"age\":19,\"sex\":\"male\",\"userName\":\"zhangsan\"}", JSON.toJSONString(user1)); JSON.addMixInAnnotations(user1.getClass(), Mixin.class); Assert.assertEquals("{\"age\":19,\"userName\":\"zhangsan\",\"sex\":\"male\"}", JSON.toJSONString(user1)); JSON.removeMixInAnnotations(user1.getClass()); } public void test_2() { User user1 = new User("lisi", "male", 20); Assert.assertEquals("{\"age\":20,\"sex\":\"male\",\"userName\":\"lisi\"}", JSON.toJSONString(user1)); JSON.addMixInAnnotations(user1.getClass(), Mixin2.class); Assert.assertEquals("{\"userName\":\"lisi\"}", JSON.toJSONString(user1)); JSON.removeMixInAnnotations(user1.getClass()); } public void test_3() { User user1 = new User("wangwu", "male", 31); Assert.assertEquals("{\"age\":31,\"sex\":\"male\",\"userName\":\"wangwu\"}", JSON.toJSONString(user1)); JSON.addMixInAnnotations(user1.getClass(), Mixin3.class); Assert.assertEquals("{\"age\":31,\"sex\":\"male\"}", JSON.toJSONString(user1)); JSON.removeMixInAnnotations(user1.getClass()); } public void test_4() throws Exception { JSON.addMixInAnnotations(VO.class, Mixin5.class); JSON.addMixInAnnotations(VOBuilder.class, Mixin6.class); VO vo = JSON.parseObject("{\"id\":12304,\"name\":\"ljw\"}", VO.class); Assert.assertEquals(12304, vo.getId()); Assert.assertEquals("ljw", vo.getName()); JSON.removeMixInAnnotations(VO.class); JSON.removeMixInAnnotations(VOBuilder.class); } @JSONType(serialzeFeatures = { SerializerFeature.QuoteFieldNames }) public class User { private String userName; private String sex; private int age; public User(String userName, String sex, int age) { this.userName = userName; this.sex = sex; this.age = age; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } 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; } } @JSONType(orders = { "age", "userName", "sex" }) interface Mixin { } @JSONType(includes = { "userName" }) interface Mixin2 { } @JSONType(ignores = { "userName" }) interface Mixin3 { } @JSONType(serialzeFeatures = { SerializerFeature.PrettyFormat }) interface Mixin4 { } 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 xxx() { return vo; } public VOBuilder withId(int id) { vo.id = id; return this; } public VOBuilder withName(String name) { vo.name = name; return this; } } @JSONType(builder= VOBuilder.class) class Mixin5{ } @JSONPOJOBuilder(buildMethod="xxx") class Mixin6{ } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/mixins/MixinMergingTest.java ================================================ package com.alibaba.json.bvt.mixins; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class MixinMergingTest extends TestCase { public interface Contact { String getCity(); } static class ContactImpl implements Contact { @Override public String getCity() { return "Seattle"; } } static class ContactMixin implements Contact { @Override @JSONField public String getCity() { return null; } } public interface Person extends Contact {} static class PersonImpl extends ContactImpl implements Person {} static class PersonMixin extends ContactMixin implements Person {} public void test() throws Exception { JSON.addMixInAnnotations(Person.class, PersonMixin.class); assertEquals("{\"city\":\"Seattle\"}", JSON.toJSONString(new PersonImpl())); JSON.removeMixInAnnotations(Person.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/mixins/MixinSerForFieldsTest.java ================================================ package com.alibaba.json.bvt.mixins; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class MixinSerForFieldsTest extends TestCase { static class BeanClass { public String a; public String b; public BeanClass(String a, String b) { this.a = a; this.b = b; } } abstract class MixIn { @JSONField(serialize = false) public String a; @JSONField(name = "banana") public String b; } public void test() throws Exception{ BeanClass bean = new BeanClass("1", "2"); JSON.addMixInAnnotations(BeanClass.class, MixIn.class); String jsonString = JSON.toJSONString(bean); JSONObject result = JSON.parseObject(jsonString); assertEquals(1, result.size()); assertEquals("2", result.get("banana")); JSON.removeMixInAnnotations(BeanClass.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/mixins/MixinSerForMethodsTest.java ================================================ package com.alibaba.json.bvt.mixins; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class MixinSerForMethodsTest extends TestCase { @SuppressWarnings( "unused" ) static class BaseClass { private String a; private String b; protected BaseClass() { } public BaseClass( String a,String b ) { this.a = a; this.b = b; } @JSONField( name = "b" ) public String takeB() { return b; } } static class BaseClass2 { private String a; private String b; protected BaseClass2() { } public BaseClass2( String a,String b ) { this.a = a; this.b = b; } @JSONField( name = "b" ) public String takeB() { return b; } @JSONField( name = "a" ) public String takeA() { return a; } } abstract static class MixIn { String a; @JSONField( name = "b2" ) public abstract String takeB(); abstract String takeA(); } public void test() throws Exception{ BaseClass bean = new BaseClass( "a1", "b2" ); String jsonString = JSON.toJSONString( bean ); JSONObject result = JSON.parseObject( jsonString ); assertEquals( 1, result.size() ); assertEquals( "b2", result.get( "b" ) ); BaseClass2 bean2 = new BaseClass2( "a1", "b2" ); JSON.addMixInAnnotations( BaseClass2.class, MixIn.class ); jsonString = JSON.toJSONString( bean2 ); result = JSON.parseObject( jsonString ); assertEquals( 2, result.size() ); assertEquals( "b2", result.get( "b2" ) ); assertEquals( "a1", result.get( "a" ) ); JSON.removeMixInAnnotations( BaseClass.class ); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/naming/ListCaseTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/naming/NamingSerTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/AEHuangliang2Test.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/AETest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/Alipay1213.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/AmbiguousTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/AsmParserTest0.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/AsmParserTest1.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/AtomicIntegerComptableAndroidTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/AtomicLongComptableAndroidTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/AutoTypeCheckHandlerTest.java ================================================ package com.alibaba.json.bvt.parser; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.ParserConfig; import junit.framework.TestCase; public class AutoTypeCheckHandlerTest extends TestCase { public void test_for_issue() throws Exception { ParserConfig config = new ParserConfig(); String str = "{\"@type\":\"com.alibaba.json.bvt.parser.autoType.AutoTypeCheckHandlerTest$Model\"}"; JSONException error = null; try { JSON.parse(str, config); } catch (JSONException ex) { error = ex; } assertNotNull(error); config.addAutoTypeCheckHandler(new ParserConfig.AutoTypeCheckHandler() { public Class handler(String typeName, Class expectClass, int features) { if ("com.alibaba.json.bvt.parser.autoType.AutoTypeCheckHandlerTest$Model".equals(typeName)) { return Model.class; } return null; } }); JSON.parse(str, config); } public static class Model { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/BigDecimalKeyFieldTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/BigListStringFieldTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/BigListStringFieldTest_private.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/BigSpecailKeyTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/BigSpecailKeyTest2.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/BigSpecailStringTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ClassConstructorTest1.java ================================================ package com.alibaba.json.bvt.parser; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import org.junit.Test; import org.springframework.util.Assert; public class ClassConstructorTest1 extends TestCase { public void test_error() throws Exception { String modelJSON = "{\"age\":12, \"name\":\"nanqi\"}"; Model model = JSON.parseObject(modelJSON, Model.class); // Assert.notNull(model.getName()); //skip } public static class Model { public Model(int age) { this.age = age; } private String name; private int age; 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ClassTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/CommentTest.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/CreateInstanceErrorTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/CreateInstanceErrorTest2.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DateParserTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DateParserTest_sql.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DateParserTest_sql_timestamp.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DateTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest.java ================================================ /* * 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.parser; import static com.alibaba.fastjson.util.TypeUtils.castToBigDecimal; 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.castToDate; import static com.alibaba.fastjson.util.TypeUtils.castToDouble; import static com.alibaba.fastjson.util.TypeUtils.castToFloat; import static com.alibaba.fastjson.util.TypeUtils.castToInt; import static com.alibaba.fastjson.util.TypeUtils.castToLong; import static com.alibaba.fastjson.util.TypeUtils.castToShort; import static com.alibaba.fastjson.util.TypeUtils.castToString; import java.io.Reader; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import org.junit.Assert; import com.alibaba.fastjson.JSON; 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); user.setSalary(new BigDecimal("123456789.0123")); String jsonString = JSON.toJSONString(user); System.out.println(jsonString); JSON.parseObject(jsonString); DefaultJSONParser parser = new DefaultJSONParser(jsonString); User user1 = new User(); parser.parseObject(user1); Assert.assertEquals(user.getAge(), user1.getAge()); Assert.assertEquals(user.getName(), user1.getName()); Assert.assertEquals(user.getSalary(), user1.getSalary()); } public void testCastCalendar() throws Exception { Calendar c = Calendar.getInstance(); Date d = TypeUtils.castToDate(c); Assert.assertEquals(c.getTime(), d); } public void testCast() throws Exception { new TypeUtils(); DefaultJSONParser parser = new DefaultJSONParser(""); Assert.assertNull(castToByte(null)); Assert.assertNull(castToShort(null)); Assert.assertNull(castToInt(null)); Assert.assertNull(castToLong(null)); Assert.assertNull(castToBigInteger(null)); Assert.assertNull(castToBigDecimal(null)); Assert.assertNull(castToFloat(null)); Assert.assertNull(castToDouble(null)); Assert.assertNull(castToBoolean(null)); Assert.assertNull(castToDate(null)); Assert.assertNull(castToString(null)); Assert.assertEquals(12, castToByte("12").intValue()); Assert.assertEquals(1234, castToShort("1234").intValue()); Assert.assertEquals(1234, castToInt("1234").intValue()); Assert.assertEquals(1234, castToLong("1234").intValue()); Assert.assertEquals(1234, castToBigInteger("1234").intValue()); Assert.assertEquals(1234, castToBigDecimal("1234").intValue()); Assert.assertEquals(1234, castToFloat("1234").intValue()); Assert.assertEquals(1234, castToDouble("1234").intValue()); Assert.assertEquals(12, castToByte(12).intValue()); Assert.assertEquals(1234, castToShort(1234).intValue()); Assert.assertEquals(1234, castToInt(1234).intValue()); Assert.assertEquals(1234, castToLong(1234).intValue()); Assert.assertEquals(1234, castToBigInteger(1234).intValue()); Assert.assertEquals(1234, castToBigDecimal(1234).intValue()); Assert.assertEquals(1234, castToFloat(1234).intValue()); Assert.assertEquals(1234, castToDouble(1234).intValue()); Assert.assertEquals(Boolean.TRUE, castToBoolean(true)); Assert.assertEquals(Boolean.FALSE, castToBoolean(false)); Assert.assertEquals(Boolean.TRUE, castToBoolean(1)); Assert.assertEquals(Boolean.FALSE, castToBoolean(0)); Assert.assertEquals(Boolean.TRUE, castToBoolean("true")); Assert.assertEquals(Boolean.FALSE, castToBoolean("false")); long time = System.currentTimeMillis(); Assert.assertEquals(time, castToDate(new Date(time)).getTime()); Assert.assertEquals(time, castToDate(time).getTime()); Assert.assertEquals(time, castToDate(Long.toString(time)).getTime()); Assert.assertEquals("true", castToString("true")); Assert.assertEquals("true", castToString(true)); Assert.assertEquals("123", castToString(123)); Assert.assertEquals(new BigDecimal("2"), castToBigDecimal("2")); Assert.assertEquals(new BigDecimal("2"), castToBigDecimal(new BigInteger("2"))); } public void test_casterror2() { DefaultJSONParser parser = new DefaultJSONParser(""); { Exception error = null; try { castToByte(new Object()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToShort(new Object()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToInt(new Object()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToLong(new Object()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToFloat(new Object()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToDouble(new Object()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToBigInteger(new Object()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToBigDecimal(new Object()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToDate(new Object()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToBoolean(new Object()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } } public void test_casterror() { DefaultJSONParser parser = new DefaultJSONParser(""); { Exception error = null; try { castToByte("xx"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToShort("xx"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToInt("xx"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToLong("xx"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToFloat("xx"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToDouble("xx"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToBigInteger("xx"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToBigDecimal("xx"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToDate("xx"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { castToBoolean("xx"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } } @SuppressWarnings("rawtypes") public void test_parseArrayWithType() throws Exception { Method method = DefaultExtJSONParserTest.class.getMethod("f", Collection.class, Collection.class, Collection.class, Collection.class, Collection.class, Collection.class, Collection.class); Type[] types = method.getGenericParameterTypes(); { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; 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}]"; 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}]"; DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseArrayWithType(types[2]); ; } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; 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}]"; DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseArrayWithType(types[4]); ; } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; DefaultJSONParser parser = new DefaultJSONParser(text); Assert.assertEquals(true, ((List) parser.parseArrayWithType(types[5])).get(0) instanceof User); } { Exception error = null; try { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseArrayWithType(types[6]); ; } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } } public void test_parseArrayWithType_error_1() throws Exception { Method method = DefaultExtJSONParserTest.class.getMethod("f", Collection.class, Collection.class, Collection.class, Collection.class, Collection.class, Collection.class, Collection.class); Type[] types = method.getGenericParameterTypes(); Exception error = null; try { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123}]"; DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseArrayWithType(types[6]); ; } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public static , T1 extends User> void f(Collection p0, Collection p1, Collection p2, Collection p3, Collection p4, Collection p5, Collection p6) { } public void test_not_match() throws Exception { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123, \"kxxx\":33}]"; DefaultJSONParser parser = new DefaultJSONParser(text); Assert.assertEquals(true, (parser.parseArray(User.class).get(0) instanceof User)); } public void test_not_match_error() throws Exception { Exception error = null; try { String text = "[{\"old\":false,\"name\":\"校长\",\"age\":3,\"salary\":123456789.0123, \"kxxx\":33}]"; DefaultJSONParser parser = new DefaultJSONParser(text); parser.config(Feature.IgnoreNotMatch, false); Assert.assertEquals(true, (parser.parseArray(User.class).get(0) instanceof User)); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error() 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); } { Exception error = null; try { String text = "{\"reader\":3}"; DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseObject(ErrorObject.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } { Exception error = null; try { String text = "{\"name\":3}"; DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseObject(ErrorObject2.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } } public static class ErrorObject { private Reader reader; public Reader getReader() { return reader; } public void setReader(Reader reader) { this.reader = reader; } } public static class ErrorObject2 { private String name; public String getName() { return name; } public void setName(String name) { throw new UnsupportedOperationException(); } } public void test_error2() throws Exception { { Exception error = null; try { String text = "{}"; DefaultJSONParser parser = new DefaultJSONParser(text); parser.parseArray(User.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } } public static class User { private String name; private int age; private BigDecimal salary; private Date birthdate; private boolean old; public boolean isOld() { return old; } public void setOld(boolean old) { this.old = old; } public Date getBirthdate() { return birthdate; } public void setBirthdate(Date birthdate) { this.birthdate = birthdate; } 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 void setage(int age) { this.age = age; } public void set(int age) { throw new UnsupportedOperationException(); } public void get(int age) { throw new UnsupportedOperationException(); } public void is(int age) { throw new UnsupportedOperationException(); } public BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } public static void setFF() { } void setXX() { } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_0.java ================================================ package com.alibaba.json.bvt.parser; import java.math.BigDecimal; import java.util.Date; 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; public class DefaultExtJSONParserTest_0 extends TestCase { protected void setUp() throws Exception { } public void test_0() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("123"); Assert.assertEquals(new Integer(123), (Integer) parser.parse()); parser.config(Feature.IgnoreNotMatch, false); } public void test_1() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[]"); parser.parseArray(Class.class); } public void test_2() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{}"); parser.parseObject(Object.class); } public void test_3() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{}"); parser.parseObject(User.class); } public void test_error_0() throws Exception { JSONException error = null; try { DefaultJSONParser parser = new DefaultJSONParser("123"); parser.parseObject(Class.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_1() throws Exception { JSONException error = null; try { DefaultJSONParser parser = new DefaultJSONParser("[{}]"); parser.parseArray(Class.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_2() throws Exception { JSONException error = null; try { DefaultJSONParser parser = new DefaultJSONParser( "{\"errorValue\":33}"); parser.parseArray(User.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_3() throws Exception { JSONException error = null; try { DefaultJSONParser parser = new DefaultJSONParser( "{\"age\"33}"); parser.parseArray(User.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_4() throws Exception { JSONException error = null; try { DefaultJSONParser parser = new DefaultJSONParser( "[\"age\":33}"); parser.parseObject(new User()); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public static class User { private String name; private int age; private BigDecimal salary; private Date birthdate; private boolean old; public boolean isOld() { return old; } public void setOld(boolean old) { this.old = old; } public Date getBirthdate() { return birthdate; } public void setBirthdate(Date birthdate) { this.birthdate = birthdate; } 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 void setage(int age) { throw new UnsupportedOperationException(); } public void set(int age) { throw new UnsupportedOperationException(); } public void get(int age) { throw new UnsupportedOperationException(); } public void is(int age) { throw new UnsupportedOperationException(); } public BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } public static void setFF() { } public void setErrorValue(int value) { throw new RuntimeException(); } void setXX() { } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_1.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_3.java ================================================ package com.alibaba.json.bvt.parser; import java.math.BigDecimal; 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; public class DefaultExtJSONParserTest_3 extends TestCase { public void test_0() throws Exception { 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 { DefaultJSONParser parser = new DefaultJSONParser("{v1:'3'}"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.config(Feature.AllowSingleQuotes, true); A a = parser.parseObject(A.class); Assert.assertEquals(3, a.getV1()); } public void test_2() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{v1:\"3\"}"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.config(Feature.AllowSingleQuotes, true); A a = parser.parseObject(A.class); Assert.assertEquals(3, a.getV1()); } public void test_3() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{o1:{}}"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.config(Feature.AllowSingleQuotes, true); A a = parser.parseObject(A.class); Assert.assertEquals(true, a.getO1() != null); } public void test_4() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{v5:'3'}"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.config(Feature.AllowSingleQuotes, true); A a = parser.parseObject(A.class); Assert.assertEquals(3L, a.getV5().longValue()); } public void test_5() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{v5:\"3\"}"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.config(Feature.AllowSingleQuotes, true); A a = parser.parseObject(A.class); Assert.assertEquals(3L, a.getV5().longValue()); } public void test_6() throws Exception { int features = JSON.DEFAULT_PARSER_FEATURE; features = Feature.config(features, Feature.AllowSingleQuotes, true); Assert.assertEquals(true, Feature.isEnabled(features, Feature.AllowSingleQuotes)); DefaultJSONParser parser = new DefaultJSONParser("'abc'", ParserConfig.getGlobalInstance(), features); Assert.assertEquals("abc", parser.parse()); } public void test_7() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("123"); ParserConfig mapping = new ParserConfig(); parser.setConfig(mapping); Assert.assertEquals(mapping, parser.getConfig()); } public static class A { private int v1; private String v2; private boolean v3; private BigDecimal v4; private Long v5; private B o1; public A(){ } public Long getV5() { return v5; } public void setV5(Long v5) { this.v5 = v5; } public B getO1() { return o1; } public void setO1(B o1) { this.o1 = o1; } public int getV1() { return v1; } public void setV1(int v1) { this.v1 = v1; } public String getV2() { return v2; } public void setV2(String v2) { this.v2 = v2; } public boolean isV3() { return v3; } public void setV3(boolean v3) { this.v3 = v3; } public BigDecimal getV4() { return v4; } public void setV4(BigDecimal v4) { this.v4 = v4; } } public static class B { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_4.java ================================================ package com.alibaba.json.bvt.parser; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; public class DefaultExtJSONParserTest_4 extends TestCase { public void test_0() throws Exception { List res = Arrays.asList(1, 2, 3); 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) { DefaultJSONParser ext = new DefaultJSONParser(t); ext.config(Feature.AllowArbitraryCommas, true); List extRes = ext.parseArray(Object.class); Assert.assertEquals(res, extRes); DefaultJSONParser basic = new DefaultJSONParser(t); basic.config(Feature.AllowArbitraryCommas, true); List basicRes = new ArrayList(); basic.parseArray(basicRes); Assert.assertEquals(res, basicRes); } } public void test_1() throws Exception { JSONObject res = new JSONObject(); res.put("a", 1); res.put("b", 2); res.put("c", 3); String[] tests = { "{ 'a':1, 'b':2, 'c':3 }", "{ 'a':1,,'b':2, 'c':3 }", "{,'a':1, 'b':2, 'c':3 }", "{'a':1, 'b':2, 'c':3,,}", "{,,'a':1,,,,'b':2,'c':3,,,,,}", }; for (String t : tests) { DefaultJSONParser ext = new DefaultJSONParser(t); ext.config(Feature.AllowArbitraryCommas, true); JSONObject extRes = ext.parseObject(); Assert.assertEquals(res, extRes); DefaultJSONParser basic = new DefaultJSONParser(t); basic.config(Feature.AllowArbitraryCommas, true); JSONObject basicRes = basic.parseObject(); Assert.assertEquals(res, basicRes); } } public void test_2() throws Exception { A res = new A(); res.setA(1); res.setB(2); res.setC(3); String[] tests = { "{ 'a':1, 'b':2, 'c':3 }", "{ 'a':1,,'b':2, 'c':3 }", "{,'a':1, 'b':2, 'c':3 }", "{'a':1, 'b':2, 'c':3,,}", "{,,'a':1,,,,'b':2,,'c':3,,,,,}", }; for (String t : tests) { DefaultJSONParser ext = new DefaultJSONParser(t); ext.config(Feature.AllowArbitraryCommas, true); A extRes = ext.parseObject(A.class); Assert.assertEquals(res, extRes); } } public static class A { private int a, b, c; public A(){ } public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } @Override public boolean equals(Object obj) { A o = (A) obj; return a == o.a && b == o.b && c == o.c; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_5.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_6.java ================================================ 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_6 extends TestCase { public void test_0() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{value:{,,,,\"value\":3,\"id\":1}}"); parser.config(Feature.AllowArbitraryCommas, true); Entity entity = new Entity(); parser.parseObject(entity); Assert.assertEquals(3, entity.getValue().getValue()); } public void test_1() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{'value':{\"value\":3,\"id\":1}}"); parser.config(Feature.AllowArbitraryCommas, false); Entity entity = new Entity(); parser.parseObject(entity); Assert.assertEquals(3, entity.getValue().getValue()); } public static class Entity { private V1 value; public V1 getValue() { return value; } public void setValue(V1 value) { this.value = value; } } public static class V1 { private int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_7.java ================================================ 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.JSONException; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; public class DefaultExtJSONParserTest_7 extends TestCase { public void test_parse() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("1"); Assert.assertEquals(Integer.valueOf(1), parser.parse()); Exception error = null; try { parser.parse(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_parse_str() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("\"1\""); parser.config(Feature.AllowISO8601DateFormat, true); Assert.assertEquals("1", parser.parse()); } public void test_parseArray() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1]"); parser.config(Feature.AllowArbitraryCommas, false); List list = new ArrayList(); parser.parseArray(String.class, list); Assert.assertEquals(1, list.size()); } public void test_parseArray_error() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2}"); parser.config(Feature.AllowArbitraryCommas, false); List list = new ArrayList(); Exception error = null; try { parser.parseArray(String.class, list); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParser_parseArray.java ================================================ package com.alibaba.json.bvt.parser; import java.lang.reflect.Type; import java.math.BigDecimal; 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.JSONObject; import com.alibaba.fastjson.TypeReference; 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 { 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 { DefaultJSONParser parser = new DefaultJSONParser("[1,2,3]"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(int.class, list); Assert.assertEquals("[1, 2, 3]", list.toString()); } public void test_2() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("['1','2','3']"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(String.class, list); Assert.assertEquals("[1, 2, 3]", list.toString()); Assert.assertEquals("1", list.get(0)); } public void test_3() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,3]"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(BigDecimal.class, list); Assert.assertEquals("[1, 2, 3]", list.toString()); Assert.assertEquals(new BigDecimal("1"), list.get(0)); } public void test_4() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,3,null]"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(BigDecimal.class, list); Assert.assertEquals("[1, 2, 3, null]", list.toString()); Assert.assertEquals(new BigDecimal("1"), list.get(0)); } public void test_5() throws Exception { 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]); Assert.assertEquals(new Long(3), array[2]); Assert.assertEquals(null, array[3]); } public void test_error() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{}"); Exception error = null; try { parser.parseArray(new ArrayList()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_6() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1.2]"); parser.config(Feature.UseBigDecimal, false); ArrayList list = new ArrayList(); parser.parseArray(list); Assert.assertEquals(Double.valueOf(1.2), list.get(0)); } public void test_7() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); 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); Assert.assertEquals(new Date(1294552193254L), list.get(0)); Assert.assertEquals("xxx", list.get(1)); Assert.assertEquals(Boolean.TRUE, list.get(2)); Assert.assertEquals(Boolean.FALSE, list.get(3)); Assert.assertEquals(null, list.get(4)); Assert.assertEquals(new JSONObject(), list.get(5)); } public void test_8() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); 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 { DefaultJSONParser parser = new DefaultJSONParser(""); parser.config(Feature.AllowISO8601DateFormat, true); Object value = parser.parse(); Assert.assertEquals(null, value); } public void test_error_2() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{}"); Exception error = null; try { parser.accept(JSONToken.NULL); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_10() throws Exception { 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]); Assert.assertEquals(new Integer(2), values[1]); Assert.assertEquals(new Integer(3), values[2]); } public void test_11() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1]"); Object[] array = parser.parseArray(new Type[] { String.class }); Assert.assertEquals("1", array[0]); } public void test_12() throws Exception { 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 { 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 { DefaultJSONParser parser = new DefaultJSONParser("[]"); Object[] array = parser.parseArray(new Type[] {}); Assert.assertEquals(0, array.length); } public void test_15() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,null]"); ArrayList list = new ArrayList(); parser.config(Feature.AllowISO8601DateFormat, false); parser.parseArray(String.class, list); Assert.assertEquals("1", list.get(0)); Assert.assertEquals(null, list.get(1)); } public void test_16() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[[1]]"); parser.config(Feature.AllowISO8601DateFormat, false); Object[] array = parser.parseArray(new Type[] { new TypeReference>() { }.getType() }); Assert.assertEquals(new Integer(1), ((List) (array[0])).get(0)); } public void test_17() throws Exception { 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 { DefaultJSONParser parser = new DefaultJSONParser("null"); parser.config(Feature.AllowISO8601DateFormat, false); List list = (List) parser.parseArrayWithType(new TypeReference>() { }.getType()); Assert.assertEquals(null, list); } public void test_error_var() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,null }"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { Object[] array = parser.parseArray(new Type[] { Integer[].class }); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_3() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,null }"); ArrayList list = new ArrayList(); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(String.class, list); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_4() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,null }"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(new Type[] { String.class }); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_5() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,null }"); ArrayList list = new ArrayList(); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(String.class, list); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_6() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{1,null }"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(new Type[] { String.class }); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_7() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{1}"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(new Type[] {}); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_8() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,3 4]"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(new Type[] { Integer.class }); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParser_parseArray_2.java ================================================ package com.alibaba.json.bvt.parser; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.TypeReference; 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 { DefaultJSONParser parser = new DefaultJSONParser("[['1']]"); parser.config(Feature.AllowISO8601DateFormat, false); List> list = (List>) parser.parseArrayWithType(new TypeReference>>() { }.getType()); Assert.assertEquals(new Integer(1), list.get(0).get(0)); } public void test_1() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("['1','2']"); parser.config(Feature.AllowISO8601DateFormat, false); List list = new ArrayList(); parser.parseArray(Integer.class, list); Assert.assertEquals(new Integer(1), list.get(0)); Assert.assertEquals(new Integer(2), list.get(1)); } public void test_error_0() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("['1','2'}"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { List list = new ArrayList(); parser.parseArray(Integer.class, list); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_1() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[['1']]"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArrayWithType(new TypeReference>() { }.getType()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_2() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[new X()]"); parser.config(Feature.AllowISO8601DateFormat, false); List list = new ArrayList(); Exception error = null; try { parser.parseArray(list); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_3() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[] a"); parser.config(Feature.AllowISO8601DateFormat, false); List list = new ArrayList(); Exception error = null; try { parser.parseArray(list); parser.close(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_4() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("['1','2'}"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(new Type[] {}); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_5() throws Exception { 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 { DefaultJSONParser parser = new DefaultJSONParser("['1' 1 '2'}"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(new Type[] {Integer.class}); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest2.java ================================================ package com.alibaba.json.bvt.parser; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; public class DefaultJSONParserTest2 extends TestCase { public void test_empty() throws Exception { String text = ""; assertNull(JSON.parse(text)); assertNull(JSON.parseObject(text)); assertNull(JSON.parseObject(text, Object.class)); assertNull(JSON.parseObject(text, Map.class)); assertNull(JSON.parseObject(text, Entity.class)); } public static class Entity { } public void test_0() throws Exception { String text = "{}"; Map map = (Map) JSON.parse(text); Assert.assertEquals(0, map.size()); } public void test_1() throws Exception { JSONException error = null; try { String text = "{}a"; Map map = (Map) JSON.parse(text); Assert.assertEquals(0, map.size()); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_2() throws Exception { JSONException error = null; try { DefaultJSONParser parser = new DefaultJSONParser("{'a'3}"); parser.config(Feature.AllowSingleQuotes, true); parser.parse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_3() throws Exception { JSONException error = null; try { DefaultJSONParser parser = new DefaultJSONParser("{a 3}"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.parse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_4() throws Exception { JSONException error = null; try { DefaultJSONParser parser = new DefaultJSONParser("{"); parser.config(Feature.AllowUnQuotedFieldNames, true); parser.parse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_5() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{}"); Map map = parser.parseObject(); Assert.assertEquals(0, map.size()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_charArray.java ================================================ 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.ParserConfig; public class DefaultJSONParserTest_charArray extends TestCase { public void test_getInput() { String text = "{}"; char[] chars = text.toCharArray(); DefaultJSONParser parser = new DefaultJSONParser(chars, chars.length, ParserConfig.getGlobalInstance(), 0); Assert.assertEquals(text, parser.getInput()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_comma.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.ParserConfig; public class DefaultJSONParserTest_comma extends TestCase { public void test_getInput() { String text = "{,,}"; char[] chars = text.toCharArray(); DefaultJSONParser parser = new DefaultJSONParser(chars, chars.length, ParserConfig.getGlobalInstance(), 0); JSONException error = null; try { parser.parseObject(); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_date.java ================================================ 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.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(); DefaultJSONParser parser = new DefaultJSONParser(chars, chars.length, ParserConfig.getGlobalInstance(), 0); parser.config(Feature.AllowISO8601DateFormat, true); JSONObject json = parser.parseObject(); Assert.assertEquals(new Date(1294552193254L), json.get("date")); } public void test_date2() { String text = "{\"date\":\"xxxxx\"}"; char[] chars = text.toCharArray(); DefaultJSONParser parser = new DefaultJSONParser(chars, chars.length, ParserConfig.getGlobalInstance(), 0); parser.config(Feature.AllowISO8601DateFormat, true); JSONObject json = parser.parseObject(); Assert.assertEquals("xxxxx", json.get("date")); } public void test_date3() { String text = "{\"1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst\\t\":\"xxxxx\"}"; char[] chars = text.toCharArray(); DefaultJSONParser parser = new DefaultJSONParser(chars, chars.length, ParserConfig.getGlobalInstance(), 0); parser.config(Feature.AllowISO8601DateFormat, true); JSONObject json = parser.parseObject(); Assert.assertEquals("xxxxx", json.get("1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst\t")); } public void test_date4() { String text = "{\"1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst1234567890abcdefghijklmnopqrst\\t\":\"xxxxx\"}"; char[] chars = text.toCharArray(); DefaultJSONParser parser = new DefaultJSONParser(chars, chars.length, ParserConfig.getGlobalInstance(), 0); parser.config(Feature.AllowISO8601DateFormat, true); 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.setDateFormat(format); parser.getDateFomartPattern(); parser.getDateFormat(); parser.parse(); parser.close(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/DefaultJSONParserTest_error.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.ParserConfig; public class DefaultJSONParserTest_error extends TestCase { public void test_error_1() { String text = "{\"obj\":{}]}"; char[] chars = text.toCharArray(); DefaultJSONParser parser = new DefaultJSONParser(chars, chars.length, ParserConfig.getGlobalInstance(), 0); JSONException error = null; try { parser.parseObject(); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_2() { String text = "{\"obj\":[]]}"; char[] chars = text.toCharArray(); DefaultJSONParser parser = new DefaultJSONParser(chars, chars.length, ParserConfig.getGlobalInstance(), 0); JSONException error = null; try { parser.parseObject(); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_3() { String text = "{\"obj\":true]}"; char[] chars = text.toCharArray(); DefaultJSONParser parser = new DefaultJSONParser(chars, chars.length, ParserConfig.getGlobalInstance(), 0); JSONException error = null; try { parser.parseObject(); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/EmptyImmutableTest.java ================================================ package com.alibaba.json.bvt.parser; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.io.Serializable; import java.util.*; public class EmptyImmutableTest extends TestCase { public void test_0() throws Exception { VO vo = JSON.parseObject("{\"values\":[],\"map\":{}}", VO.class); } public static class VO { private List values = new EmptyList(); private Map map = new EmptyMap(); public List getValues() { return values; } public Map getMap() { return map; } } private static class EmptyMap extends HashMap { public void putAll(Map m) { throw new UnsupportedOperationException(); } } private static class EmptyList extends AbstractList implements RandomAccess, Serializable { private static final long serialVersionUID = 8842843931221139166L; public Iterator iterator() { throw new UnsupportedOperationException(); } public ListIterator listIterator() { throw new UnsupportedOperationException(); } public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } public int size() {return 0;} public boolean isEmpty() {return true;} public boolean contains(Object obj) {return false;} public boolean containsAll(Collection c) { return c.isEmpty(); } public Object[] toArray() { return new Object[0]; } public T[] toArray(T[] a) { if (a.length > 0) a[0] = null; return a; } public E get(int index) { throw new IndexOutOfBoundsException("Index: "+index); } public boolean equals(Object o) { return (o instanceof List) && ((List)o).isEmpty(); } public int hashCode() { return 1; } public void sort(Comparator c) { } // Preserves singleton property private Object readResolve() { throw new UnsupportedOperationException(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/EnumParserTest.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/FastMatchCheckTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/FeatureCountTest.java ================================================ package com.alibaba.json.bvt.parser; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; public class FeatureCountTest extends TestCase { public void testZ_0() throws Exception { Feature[] features = Feature.class.getEnumConstants(); System.out.println(features.length); assertTrue(features.length < 32); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/FeatureParserTest.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; public class FeatureParserTest extends TestCase { public void test_AllowSingleQuotes_0() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{'a':3}"); parser.config(Feature.AllowSingleQuotes, true); JSONObject json = (JSONObject) parser.parse(); Assert.assertEquals(1, json.size()); Assert.assertEquals(new Integer(3), (Integer) json.getInteger("a")); } public void test_AllowSingleQuotes_1() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{'a':'3'}"); parser.config(Feature.AllowSingleQuotes, true); JSONObject json = (JSONObject) parser.parse(); Assert.assertEquals(1, json.size()); Assert.assertEquals("3", (String) json.get("a")); } public void test_AllowUnQuotedFieldNames_0() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{a:3}"); parser.config(Feature.AllowUnQuotedFieldNames, true); JSONObject json = (JSONObject) parser.parse(); Assert.assertEquals(1, json.size()); Assert.assertEquals(new Integer(3), (Integer) json.getInteger("a")); } public void test_error_0() throws Exception { JSONException error = null; try { DefaultJSONParser parser = new DefaultJSONParser("{'a':3}"); parser.config(Feature.AllowSingleQuotes, false); parser.parse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_1() throws Exception { JSONException error = null; try { DefaultJSONParser parser = new DefaultJSONParser("{\"a\":'3'}"); parser.config(Feature.AllowSingleQuotes, false); parser.parse(); } 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, false); parser.parse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/FeatureTest.java ================================================ package com.alibaba.json.bvt.parser; import junit.framework.TestCase; 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 { public void test_default() throws Exception { DefaultJSONParser parser = new DefaultJSONParser(""); Assert.assertEquals(false, parser.isEnabled(Feature.AllowComment)); Assert.assertEquals(true, parser.isEnabled(Feature.AllowSingleQuotes)); Assert.assertEquals(true, parser.isEnabled(Feature.AllowUnQuotedFieldNames)); Assert.assertEquals(true, parser.isEnabled(Feature.AutoCloseSource)); Assert.assertEquals(true, parser.isEnabled(Feature.InternFieldNames)); } public void test_config() throws Exception { new IOUtils(); DefaultJSONParser parser = new DefaultJSONParser(""); Assert.assertEquals(false, parser.isEnabled(Feature.AllowComment)); Assert.assertEquals(true, parser.isEnabled(Feature.AllowSingleQuotes)); Assert.assertEquals(true, parser.isEnabled(Feature.AllowUnQuotedFieldNames)); Assert.assertEquals(true, parser.isEnabled(Feature.AutoCloseSource)); Assert.assertEquals(true, parser.isEnabled(Feature.InternFieldNames)); parser.config(Feature.AllowComment, true); Assert.assertEquals(true, parser.isEnabled(Feature.AllowComment)); parser.config(Feature.InternFieldNames, false); Assert.assertEquals(false, parser.isEnabled(Feature.InternFieldNames)); } public void test_count() throws Exception { assertTrue(Feature.values().length < 32); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/InetSocketAddressTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONArrayParseTest.java ================================================ package com.alibaba.json.bvt.parser; import java.util.List; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; public class JSONArrayParseTest extends TestCase { public void test_array() throws Exception { String text = "[{id:123}]"; List> array = JSON.parseObject(text, new TypeReference>>() {}); Assert.assertEquals(1, array.size()); Map map = array.get(0); Assert.assertEquals(123, map.get("id").intValue()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerAllowCommentTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_10.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_11.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_12.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_13.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_14.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_15.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_16.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_3.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_5.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_6.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_7.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_8.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_9.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONLexerTest_set.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_boolean.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_double.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_double_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_enum.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_float.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_int.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_long.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_string.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__entity_stringList.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest__map_string.java ================================================ 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")); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_array_string.java ================================================ 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)); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_bytes.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_decimal.java ================================================ 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)); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_enum.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error.java ================================================ 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 } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error5.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_int.java ================================================ 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()); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_jsonobject.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_long.java ================================================ 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()); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_array.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_array_2.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_object.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_object_2.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_int.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_int_unquote.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_long.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_object.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_string.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReader_error.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONReader_top.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_ISO8601.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.JSONScanner; import com.alibaba.fastjson.parser.JSONToken; public class JSONScannerTest_ISO8601 extends TestCase { 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(true, new JSONScanner("3000-10-02").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("4000-10-02").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("5000-10-02").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("6000-10-02").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("7000-10-02").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("8000-10-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("A000-10-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("a000-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()); Assert.assertEquals(false, new JSONScanner("1997:02-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("1997-02:02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2A00-02-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2!00-02-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("20A0-02-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("20!0-02-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("200A-02-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("200!-02-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-32-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-1A-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-1!-02").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-10-02").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-11-02").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-12-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-13-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-20-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-0A-02").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-0!-02").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-00").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-0!").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-0A").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-20").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-2A").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-2!").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-30").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-31").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-32").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-42").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T").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(true, new JSONScanner("2000-02-10T01:01:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T0A:01:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T0!:01:01").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T00:10:01").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T00:11:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T10011:01").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T10:11:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T1!:11:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T1a:11:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:1A:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:1!:01").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T20:20:01").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T21:21:01").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T22:22:01").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T23:23:01").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T24:24:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T25:25:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T2!:20:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T30:20:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00A22:01").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T00:22:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:!2:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:A2:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:2A:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:2!:01").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T00:60:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:61:01").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T00:00:01").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:0!").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:0A").scanISO8601DateIfMatch()); Assert.assertEquals(true, new JSONScanner("2000-02-10T00:00:60").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:61").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:70").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:!0").scanISO8601DateIfMatch()); 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(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()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:00.0A0").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:00.0!0").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:00.00!").scanISO8601DateIfMatch()); Assert.assertEquals(false, new JSONScanner("2000-02-10T00:00:00.00a").scanISO8601DateIfMatch()); } public void test_2() throws Exception { JSONScanner lexer = new JSONScanner("2000-02-10T00:00:00.000"); lexer.config(Feature.AllowISO8601DateFormat, true); Assert.assertEquals(true, lexer.scanISO8601DateIfMatch()); Assert.assertEquals(JSONToken.LITERAL_ISO8601_DATE, lexer.token()); lexer.nextToken(); Assert.assertEquals(JSONToken.EOF, lexer.token()); } public void test_3() throws Exception { JSONScanner lexer = new JSONScanner("2000-2"); lexer.config(Feature.AllowISO8601DateFormat, true); lexer.nextToken(); Assert.assertEquals(JSONToken.LITERAL_INT, lexer.token()); lexer.nextToken(); Assert.assertEquals(JSONToken.LITERAL_INT, lexer.token()); lexer.nextToken(); Assert.assertEquals(JSONToken.EOF, lexer.token()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest__nextToken.java ================================================ 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; public class JSONScannerTest__nextToken extends TestCase { public void test_next() throws Exception { String text = "\"aaa\""; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(JSONToken.LITERAL_INT); Assert.assertEquals(JSONToken.LITERAL_STRING, lexer.token()); } public void test_next_1() throws Exception { String text = "["; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(JSONToken.LITERAL_INT); Assert.assertEquals(JSONToken.LBRACKET, lexer.token()); } public void test_next_2() throws Exception { String text = "{"; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(JSONToken.LITERAL_INT); Assert.assertEquals(JSONToken.LBRACE, lexer.token()); } public void test_next_3() throws Exception { String text = "{"; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(JSONToken.LBRACKET); Assert.assertEquals(JSONToken.LBRACE, lexer.token()); } public void test_next_4() throws Exception { String text = ""; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(JSONToken.LBRACKET); Assert.assertEquals(JSONToken.EOF, lexer.token()); } public void test_next_5() throws Exception { String text = " \n\r\t\f\b 1"; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(JSONToken.LBRACKET); Assert.assertEquals(JSONToken.LITERAL_INT, lexer.token()); } public void test_next_6() throws Exception { String text = ""; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(JSONToken.EOF); Assert.assertEquals(JSONToken.EOF, lexer.token()); } public void test_next_7() throws Exception { String text = "{"; JSONScanner lexer = new JSONScanner(text); lexer.nextToken(JSONToken.EOF); Assert.assertEquals(JSONToken.LBRACE, lexer.token()); } public void test_next_8() throws Exception { String text = "\n\r\t\f\b :{"; JSONScanner lexer = new JSONScanner(text); lexer.nextTokenWithColon(JSONToken.LBRACE); Assert.assertEquals(JSONToken.LBRACE, lexer.token()); } public void test_next_9() throws Exception { String text = "\n\r\t\f\b :["; JSONScanner lexer = new JSONScanner(text); lexer.nextTokenWithColon(JSONToken.LBRACE); Assert.assertEquals(JSONToken.LBRACKET, lexer.token()); } public void test_next_10() throws Exception { String text = "\n\r\t\f\b :"; JSONScanner lexer = new JSONScanner(text); lexer.nextTokenWithColon(JSONToken.LBRACE); Assert.assertEquals(JSONToken.EOF, lexer.token()); } public void test_next_11() throws Exception { String text = "\n\r\t\f\b :{"; JSONScanner lexer = new JSONScanner(text); lexer.nextTokenWithColon(JSONToken.LBRACKET); Assert.assertEquals(JSONToken.LBRACE, lexer.token()); } public void test_next_12() throws Exception { String text = "\n\r\t\f\b :"; JSONScanner lexer = new JSONScanner(text); lexer.nextTokenWithColon(JSONToken.LBRACKET); Assert.assertEquals(JSONToken.EOF, lexer.token()); } public void test_next_13() throws Exception { String text = "\n\r\t\f\b :\n\r\t\f\b "; JSONScanner lexer = new JSONScanner(text); lexer.nextTokenWithColon(JSONToken.LBRACKET); Assert.assertEquals(JSONToken.EOF, lexer.token()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest__x.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class JSONScannerTest__x extends TestCase { public void test_x() throws Exception { StringBuilder buf = new StringBuilder(); buf.append("\""); for (int i = 0; i < 16; ++i) { for (int j = 0; j < 16; ++j) { buf.append("\\x"); buf.append(Integer.toHexString(i)); buf.append(Integer.toHexString(j)); } } buf.append("\""); String jsonString = (String) JSON.parse(buf.toString()); Assert.assertEquals(16 * 16, jsonString.length()); for (int i = 0; i < 16 * 16; ++i) { char c = jsonString.charAt(i); if ((int) c != i) { Assert.fail(); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_colon.java ================================================ 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.JSONToken; /** * 测试字符':'的处理 * * @author wenshao[szujobs@hotmail.com] */ public class JSONScannerTest_colon extends TestCase { public void test_0() throws Exception { JSONScanner lexer = new JSONScanner(":true"); lexer.nextTokenWithColon(); Assert.assertEquals(JSONToken.TRUE, lexer.token()); } public void test_1() throws Exception { JSONScanner lexer = new JSONScanner(" : true"); lexer.nextTokenWithColon(); Assert.assertEquals(JSONToken.TRUE, lexer.token()); } public void test_2() throws Exception { JSONScanner lexer = new JSONScanner("\n:\ntrue"); lexer.nextTokenWithColon(); Assert.assertEquals(JSONToken.TRUE, lexer.token()); } public void test_3() throws Exception { JSONScanner lexer = new JSONScanner("\r:\rtrue"); lexer.nextTokenWithColon(); Assert.assertEquals(JSONToken.TRUE, lexer.token()); } public void test_4() throws Exception { JSONScanner lexer = new JSONScanner("\t:\ttrue"); lexer.nextTokenWithColon(); Assert.assertEquals(JSONToken.TRUE, lexer.token()); } public void test_5() throws Exception { JSONScanner lexer = new JSONScanner("\t:\ftrue"); lexer.nextTokenWithColon(); Assert.assertEquals(JSONToken.TRUE, lexer.token()); } public void test_6() throws Exception { JSONScanner lexer = new JSONScanner("\b:\btrue"); lexer.nextTokenWithColon(); Assert.assertEquals(JSONToken.TRUE, lexer.token()); } public void test_f() throws Exception { JSONScanner lexer = new JSONScanner("\f:\btrue"); lexer.nextTokenWithColon(); Assert.assertEquals(JSONToken.TRUE, lexer.token()); } public void test_7() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("true"); lexer.nextTokenWithColon(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_8() throws Exception { JSONScanner lexer = new JSONScanner("\b:\btrue"); lexer.nextToken(); Assert.assertEquals(JSONToken.COLON, lexer.token()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_false.java ================================================ 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; public class JSONScannerTest_false extends TestCase { public void test_scan_false_0() throws Exception { JSONScanner lexer = new JSONScanner("false"); lexer.scanFalse(); } public void test_scan_false_1() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("zalse"); lexer.scanFalse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_false_2() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("fzlse"); lexer.scanFalse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_false_3() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("fazse"); lexer.scanFalse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_false_4() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("falze"); lexer.scanFalse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_false_5() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("falsz"); lexer.scanFalse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_false_6_1() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("falsee"); lexer.scanFalse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_false_6() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("false\""); lexer.scanFalse(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_false_7() throws Exception { JSONScanner lexer = new JSONScanner("false a"); lexer.scanFalse(); } public void test_scan_false_8() throws Exception { JSONScanner lexer = new JSONScanner("false,"); lexer.scanFalse(); } public void test_scan_false_9() throws Exception { JSONScanner lexer = new JSONScanner("false\na"); lexer.scanFalse(); } public void test_scan_false_10() throws Exception { JSONScanner lexer = new JSONScanner("false\ra"); lexer.scanFalse(); } public void test_scan_false_11() throws Exception { JSONScanner lexer = new JSONScanner("false\ta"); lexer.scanFalse(); } public void test_scan_false_12() throws Exception { JSONScanner lexer = new JSONScanner("false\fa"); lexer.scanFalse(); } public void test_scan_false_13() throws Exception { JSONScanner lexer = new JSONScanner("false\ba"); lexer.scanFalse(); } public void test_scan_false_14() throws Exception { JSONScanner lexer = new JSONScanner("false}"); lexer.scanFalse(); } public void test_scan_false_15() throws Exception { JSONScanner lexer = new JSONScanner("false]"); lexer.scanFalse(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_ident.java ================================================ 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; public class JSONScannerTest_ident extends TestCase { public void test_true() throws Exception { JSONScanner lexer = new JSONScanner("true"); lexer.scanIdent(); Assert.assertEquals(JSONToken.TRUE, lexer.token()); } public void test_false() throws Exception { JSONScanner lexer = new JSONScanner("false"); lexer.scanIdent(); Assert.assertEquals(JSONToken.FALSE, lexer.token()); } public void test_null() throws Exception { JSONScanner lexer = new JSONScanner("null"); lexer.scanIdent(); Assert.assertEquals(JSONToken.NULL, lexer.token()); } public void test_new() throws Exception { JSONScanner lexer = new JSONScanner("new"); lexer.scanIdent(); Assert.assertEquals(JSONToken.NEW, lexer.token()); } public void test_Date() throws Exception { String text = "Date"; JSONScanner lexer = new JSONScanner(text); lexer.scanIdent(); Assert.assertEquals(JSONToken.IDENTIFIER, lexer.token()); Assert.assertEquals(text, lexer.stringVal()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_int.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.JSONScanner; /** * parseInt * * @author wenshao[szujobs@hotmail.com] */ public class JSONScannerTest_int extends TestCase { public void ftest_parse_long() throws Exception { System.out.println(System.currentTimeMillis()); JSONScanner lexer = new JSONScanner("1293770846"); lexer.scanNumber(); Assert.assertEquals(new Integer(1293770846), (Integer) lexer.integerValue()); Assert.assertEquals(1293770846, lexer.intValue()); } public void ftest_parse_long_1() throws Exception { System.out.println(System.currentTimeMillis()); JSONScanner lexer = new JSONScanner(Integer.toString(Integer.MAX_VALUE)); lexer.scanNumber(); Assert.assertEquals(new Integer(Integer.MAX_VALUE), (Integer) lexer.integerValue()); Assert.assertEquals(Integer.MAX_VALUE, lexer.intValue()); } public void test_parse_long_2() throws Exception { System.out.println(System.currentTimeMillis()); JSONScanner lexer = new JSONScanner(Long.toString(Integer.MIN_VALUE)); lexer.scanNumber(); Assert.assertEquals(new Integer(Integer.MIN_VALUE), (Integer) lexer.integerValue()); Assert.assertEquals(Integer.MIN_VALUE, lexer.intValue()); } public void test_error_0() { Exception error = null; try { JSONScanner lexer = new JSONScanner("--"); lexer.scanNumber(); lexer.intValue(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_1() { Exception error = null; try { String text = Integer.MAX_VALUE + "1234"; JSONScanner lexer = new JSONScanner(text); lexer.scanNumber(); lexer.intValue(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_2() { Exception error = null; try { String text = Integer.MIN_VALUE + "1234"; JSONScanner lexer = new JSONScanner(text); lexer.scanNumber(); lexer.intValue(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_3() { Exception error = null; try { String text = "2147483648"; JSONScanner lexer = new JSONScanner(text); lexer.scanNumber(); lexer.intValue(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_isEOF.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_long.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.parser.JSONScanner; /** * parseLong * * @author wenshao[szujobs@hotmail.com] */ public class JSONScannerTest_long extends TestCase { public void ftest_parse_long() throws Exception { System.out.println(System.currentTimeMillis()); JSONScanner lexer = new JSONScanner("1293770846476"); lexer.scanNumber(); Assert.assertEquals(new Long(1293770846476L), (Long) lexer.integerValue()); Assert.assertEquals(1293770846476L, lexer.longValue()); } public void ftest_parse_long_1() throws Exception { System.out.println(System.currentTimeMillis()); JSONScanner lexer = new JSONScanner(Long.toString(Long.MAX_VALUE)); lexer.scanNumber(); Assert.assertEquals(new Long(Long.MAX_VALUE), (Long) lexer.integerValue()); Assert.assertEquals(Long.MAX_VALUE, lexer.longValue()); } public void test_parse_long_2() throws Exception { System.out.println(System.currentTimeMillis()); JSONScanner lexer = new JSONScanner(Long.toString(Long.MIN_VALUE)); lexer.scanNumber(); Assert.assertEquals(new Long(Long.MIN_VALUE), (Long) lexer.integerValue()); Assert.assertEquals(Long.MIN_VALUE, lexer.longValue()); } public void test_error_0() { Exception error = null; try { JSONScanner lexer = new JSONScanner("--"); lexer.scanNumber(); lexer.longValue(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_1() { Exception error = null; try { String text = Long.MAX_VALUE + "1234"; JSONScanner lexer = new JSONScanner(text); lexer.scanNumber(); lexer.longValue(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_2() { Exception error = null; try { String text = Long.MIN_VALUE + "1234"; JSONScanner lexer = new JSONScanner(text); lexer.scanNumber(); lexer.longValue(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_3() { Exception error = null; try { String text = "9223372036854775809"; JSONScanner lexer = new JSONScanner(text); lexer.scanNumber(); lexer.longValue(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_new.java ================================================ 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; public class JSONScannerTest_new extends TestCase { public void test_scan_new_0() throws Exception { JSONScanner lexer = new JSONScanner("new"); lexer.scanNullOrNew(); } public void test_scan_new_1() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("nww"); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_new_2() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("nee"); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_new_3() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("neel"); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_new_4() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("neww"); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_new_5() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("newe"); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_new_6() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("new\""); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_new_7() throws Exception { JSONScanner lexer = new JSONScanner("new a"); lexer.scanNullOrNew(); } public void test_scan_new_8() throws Exception { JSONScanner lexer = new JSONScanner("new,"); lexer.scanNullOrNew(); } public void test_scan_new_9() throws Exception { JSONScanner lexer = new JSONScanner("new\na"); lexer.scanNullOrNew(); } public void test_scan_new_10() throws Exception { JSONScanner lexer = new JSONScanner("new\ra"); lexer.scanNullOrNew(); } public void test_scan_new_11() throws Exception { JSONScanner lexer = new JSONScanner("new\ta"); lexer.scanNullOrNew(); } public void test_scan_new_12() throws Exception { JSONScanner lexer = new JSONScanner("new\fa"); lexer.scanNullOrNew(); } public void test_scan_new_13() throws Exception { JSONScanner lexer = new JSONScanner("new\ba"); lexer.scanNullOrNew(); } public void test_scan_new_14() throws Exception { JSONScanner lexer = new JSONScanner("new}"); lexer.scanNullOrNew(); } public void test_scan_new_15() throws Exception { JSONScanner lexer = new JSONScanner("new]"); lexer.scanNullOrNew(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_null.java ================================================ 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; public class JSONScannerTest_null extends TestCase { public void test_scan_null_0() throws Exception { JSONScanner lexer = new JSONScanner("null"); lexer.scanNullOrNew(); } public void test_scan_null_1() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("zull"); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_null_2() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("nzll"); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_null_3() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("nuzl"); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_null_4() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("nulz"); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_null_5() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("nulle"); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_null_6() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("null\""); lexer.scanNullOrNew(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_null_7() throws Exception { JSONScanner lexer = new JSONScanner("null a"); lexer.scanNullOrNew(); } public void test_scan_null_8() throws Exception { JSONScanner lexer = new JSONScanner("null,"); lexer.scanNullOrNew(); } public void test_scan_null_9() throws Exception { JSONScanner lexer = new JSONScanner("null\na"); lexer.scanNullOrNew(); } public void test_scan_null_10() throws Exception { JSONScanner lexer = new JSONScanner("null\ra"); lexer.scanNullOrNew(); } public void test_scan_null_11() throws Exception { JSONScanner lexer = new JSONScanner("null\ta"); lexer.scanNullOrNew(); } public void test_scan_null_12() throws Exception { JSONScanner lexer = new JSONScanner("null\fa"); lexer.scanNullOrNew(); } public void test_scan_null_13() throws Exception { JSONScanner lexer = new JSONScanner("null\ba"); lexer.scanNullOrNew(); } public void test_scan_false_14() throws Exception { JSONScanner lexer = new JSONScanner("null}"); lexer.scanNullOrNew(); } public void test_scan_false_15() throws Exception { JSONScanner lexer = new JSONScanner("null]"); lexer.scanNullOrNew(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldBoolean.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class JSONScannerTest_scanFieldBoolean extends TestCase { public void test_true() throws Exception { String text = "{\"value\":true}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertEquals(true, obj.getValue()); } public void test_false() throws Exception { String text = "{\"value\":false}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertEquals(false, obj.getValue()); } public void test_1() throws Exception { String text = "{\"value\":\"true\"}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertEquals(true, obj.getValue()); } public void test_2() throws Exception { String text = "{\"value\":\"false\"}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertEquals(false, obj.getValue()); } public void test_3() throws Exception { String text = "{\"value\":\"1\"}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertEquals(true, obj.getValue()); } public void test_5() throws Exception { String text = "{\"value\":false}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertEquals(false, obj.getValue()); } public void test_error_0() { Exception error = null; try { String text = "{\"value\":true\\n\""; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_1() { Exception error = null; try { String text = "{\"value\":a"; 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\":teue}"; 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\":tree}"; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_4() { Exception error = null; try { String text = "{\"value\":truu}"; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_5() { Exception error = null; try { String text = "{\"value\":fflse}"; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_6() { Exception error = null; try { String text = "{\"value\":fasse}"; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_7() { Exception error = null; try { String text = "{\"value\":falee}"; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_8() { Exception error = null; try { String text = "{\"value\":falss}"; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_9() { Exception error = null; try { String text = "{\"value\":false]"; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_10() { Exception error = null; try { String text = "{\"value\":false}{"; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_11() { Exception error = null; try { String text = "{\"value\":false}}"; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_12() { Exception error = null; try { String text = "{\"value\":false}]"; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_13() { Exception error = null; try { String text = "{\"value\":false},"; JSON.parseObject(text, VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public static class VO { private boolean value; public boolean getValue() { return value; } public void setValue(boolean value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldBoolean_unquote.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldDouble.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; 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.assertTrue(1D == obj.getValue()); } public void test_1() throws Exception { String text = "{\"value\":\"1\"}"; VO obj = JSON.parseObject(text, VO.class); 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.assertTrue(1D == obj.getValue()); } public void test_3() throws Exception { String text = "{\"value\":1.01}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertTrue(1.01D == obj.getValue()); } public void test_4() throws Exception { String text = "{\"value\":1.}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertTrue(1D == obj.getValue()); } public void test_5() throws Exception { String text = "{\"value\":922337203685477580723}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertTrue(922337203685477580723D == obj.getValue()); } public void test_error_2() throws Exception { JSONException error = null; try { String text = "{\"value\":32K}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_3() throws Exception { JSONException error = null; try { String text = "{\"value\":32}{"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_4() throws Exception { JSONException error = null; try { String text = "{\"value\":中}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_5() throws Exception { JSONException error = null; try { String text = "{\"value\":3.F"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_6() throws Exception { JSONException error = null; try { String text = "{\"value\":3.2]"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_7() throws Exception { JSONException error = null; try { String text = "{\"value\":3.2}]"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_8() throws Exception { JSONException error = null; try { String text = "{\"value\":3.2}}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_9() throws Exception { JSONException error = null; try { String text = "{\"value\":3.2},"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_10() throws Exception { JSONException error = null; try { String text = "{\"value\":3.\\0}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_11() throws Exception { JSONException error = null; try { String text = "{\"value\":3.中}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public static class VO { private double value; public double getValue() { return value; } public void setValue(double value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldFloat.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.JSONScanner; 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.assertTrue(1F == obj.getValue()); } @SuppressWarnings("resource") public void test_isBlank() throws Exception { String text = " {\"value\":1.0}"; Assert.assertTrue(!new JSONScanner(text).isBlankInput()); } public void test_1() throws Exception { String text = "{\"value\":\"1\"}"; VO obj = JSON.parseObject(text, VO.class); 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.assertTrue(1F == obj.getValue()); } public void test_3() throws Exception { String text = "{\"value\":1.01}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertTrue(1.01F == obj.getValue()); } public void test_4() throws Exception { String text = "{\"value\":1.}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertTrue(1F == obj.getValue()); } public void test_error_1() throws Exception { String text = "{\"value\":922337203685477580723}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertTrue(922337203685477580723F == obj.getValue()); } public void test_error_2() throws Exception { JSONException error = null; try { String text = "{\"value\":32M}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_3() throws Exception { JSONException error = null; try { String text = "{\"value\":32}{"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_4() throws Exception { JSONException error = null; try { String text = "{\"value\":中}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_5() throws Exception { JSONException error = null; try { String text = "{\"value\":3.F"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_6() throws Exception { JSONException error = null; try { String text = "{\"value\":3.2]"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_7() throws Exception { JSONException error = null; try { String text = "{\"value\":3.2}]"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_8() throws Exception { JSONException error = null; try { String text = "{\"value\":3.2}}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_9() throws Exception { JSONException error = null; try { String text = "{\"value\":3.2},"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_10() throws Exception { JSONException error = null; try { String text = "{\"value\":3.\\0}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_11() throws Exception { JSONException error = null; try { String text = "{\"value\":3.中}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public static class VO { private float value; public float getValue() { return value; } public void setValue(float value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldInt.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; public class JSONScannerTest_scanFieldInt extends TestCase { public void test_0() throws Exception { String text = "{\"value\":1.0}"; 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_error_1() throws Exception { JSONException error = null; try { String text = "{\"value\":922337203685477580723}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_2() throws Exception { JSONException error = null; try { String text = "{\"value\":32O}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_3() throws Exception { JSONException error = null; try { String text = "{\"value\":32}{"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_4() throws Exception { JSONException error = null; try { String text = "{\"value\":中}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_5() throws Exception { JSONException error = null; try { String text = "{\"value\":\0}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public static class VO { private int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldLong.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; public class JSONScannerTest_scanFieldLong extends TestCase { public void test_0() throws Exception { String text = "{\"value\":1.0}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertEquals(1, obj.getValue()); } /** public void test_1() throws Exception { JSONException error = null; try { String text = "{\"value\":922337203685477580723}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_2() throws Exception { JSONException error = null; try { String text = "{\"value\":32RR}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_3() throws Exception { JSONException error = null; try { String text = "{\"value\":中}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_4() throws Exception { JSONException error = null; try { String text = "{\"value\":3}}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_5() throws Exception { JSONException error = null; try { String text = "{\"value\":3}F"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_6() throws Exception { JSONException error = null; try { String text = "{\"value\":3{"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_7() throws Exception { JSONException error = null; try { String text = "{\"value\":\0}"; JSON.parseObject(text, VO.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } */ public static class VO { private long value; public long getValue() { return value; } public void setValue(long value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldString.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldStringArray.java ================================================ 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.JSONException; public class JSONScannerTest_scanFieldStringArray extends TestCase { public void test_string() throws Exception { String text = "{\"value\":[1]}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertEquals("[1]", obj.getValue().toString()); } public void test_string_1() throws Exception { String text = "{\"value\":[\"1\"]}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertEquals("[1]", obj.getValue().toString()); } public void test_string_2() throws Exception { String text = "{\"value\":['1']}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertEquals("[1]", obj.getValue().toString()); } public void test_string_3() throws Exception { String text = "{\"value\":[\"1\\t2\"]}"; VO obj = JSON.parseObject(text, VO.class); Assert.assertEquals("[1\t2]", obj.getValue().toString()); } public void test_string_4() throws Exception { String text = "[{\"value\":[\"1\"]}]"; List list = JSON.parseArray(text, VO.class); Assert.assertEquals("[1]", list.get(0).getValue().toString()); } public void test_string_5() throws Exception { String text = "[{\"value\":[\"1\"]},{\"value\":[\"2\"]}]"; List list = JSON.parseArray(text, VO.class); Assert.assertEquals("[1]", list.get(0).getValue().toString()); Assert.assertEquals("[2]", list.get(1).getValue().toString()); } public void test_string_error() throws Exception { JSONException error = null; try { String text = "{\"value\":{}}"; JSON.parseObject(text, VO.class); } catch (JSONException e) { error = e; } //Assert.assertNotNull(error); } public void test_string_error_2() throws Exception { JSONException error = null; try { String text = "{\"value\":[\"1\"}"; JSON.parseObject(text, VO.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_string_error_3() throws Exception { JSONException error = null; try { String text = "{\"value\":[\"1\"]}}"; JSON.parseObject(text, VO.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_string_error_4() throws Exception { JSONException error = null; try { String text = "{\"value\":[\"1\"]]"; JSON.parseObject(text, VO.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_string_error_5() throws Exception { JSONException error = null; try { String text = "{\"value\":[\"1\"]}{"; JSON.parseObject(text, VO.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public static class VO { private List value; public List getValue() { return value; } public void setValue(List value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanFieldString_error.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_scanSymbol.java ================================================ package com.alibaba.json.bvt.parser; import com.alibaba.fastjson.util.TypeUtils; 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; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_hashcode; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_prime; /** * 测试字符':'的处理 * * @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()); } public void test_8() throws Exception { JSONScanner lexer = new JSONScanner("\"value\": \"MINUTES\","); long hashCode = lexer.scanFieldSymbol("\"value\":".toCharArray()); assertEquals(189130438399835214L, hashCode); Assert.assertEquals(JSONScanner.VALUE, lexer.matchStat()); } public void test_9() throws Exception { JSONScanner lexer = new JSONScanner("\"value\":\"MINUTES\","); long hashCode = lexer.scanFieldSymbol("\"value\":".toCharArray()); assertEquals(189130438399835214L, hashCode); Assert.assertEquals(JSONScanner.VALUE, lexer.matchStat()); } public void test_10() throws Exception { JSONScanner lexer = new JSONScanner(" \"value\":\"MINUTES\","); long hashCode = lexer.scanFieldSymbol("\"value\":".toCharArray()); assertEquals(189130438399835214L, hashCode); Assert.assertEquals(JSONScanner.VALUE, lexer.matchStat()); } public void test_11() throws Exception { JSONScanner lexer = new JSONScanner(" \"value\":\"A\","); long hashCode = lexer.scanFieldSymbol("\"value\":".toCharArray()); assertEquals(TypeUtils.fnv1a_64("A"), hashCode); Assert.assertEquals(JSONScanner.VALUE, lexer.matchStat()); } static long fnv_hash(String text) { long hash = fnv1a_64_magic_hashcode; for (int i = 0; i < text.length(); ++i) { char c = text.charAt(i); hash ^= c; hash *= fnv1a_64_magic_prime; } return hash; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_singQuoteString.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.JSONScanner; import com.alibaba.fastjson.parser.JSONToken; public class JSONScannerTest_singQuoteString extends TestCase { public void test_string() throws Exception { { JSONScanner lexer = new JSONScanner("\'中国\'"); lexer.config(Feature.AllowSingleQuotes, true); lexer.nextToken(); Assert.assertEquals("中国", lexer.stringVal()); } { JSONScanner lexer = new JSONScanner("'中国\t\\'\\\"'"); lexer.config(Feature.AllowSingleQuotes, true); lexer.nextToken(); Assert.assertEquals("中国\t'\"", lexer.stringVal()); } { JSONScanner lexer = new JSONScanner("\'中国\tV5\'"); lexer.config(Feature.AllowSingleQuotes, true); lexer.nextToken(); Assert.assertEquals("中国\tV5", lexer.stringVal()); } StringBuilder buf = new StringBuilder(); buf.append('\''); buf.append("\\\\\\/\\b\\f\\n\\r\t\\u" + Integer.toHexString('中')); buf.append('\''); buf.append('\u2001'); String text = buf.toString(); JSONScanner lexer = new JSONScanner(text.toCharArray(), text.length() - 1); lexer.config(Feature.AllowSingleQuotes, true); lexer.nextToken(); Assert.assertEquals(0, lexer.pos()); String stringVal = lexer.stringVal(); Assert.assertEquals("\"\\\\/\\b\\f\\n\\r\\t中\"", JSON.toJSONString(stringVal)); JSON.toJSONString(stringVal); } public void test_string2() throws Exception { StringBuilder buf = new StringBuilder(); buf.append('\''); for (int i = 0; i < 200; ++i) { buf.append("\\\\\\/\\b\\f\\n\\r\\t\\u" + Integer.toHexString('中')); } buf.append('\''); String text = buf.toString(); JSONScanner lexer = new JSONScanner(text.toCharArray(), text.length()); lexer.config(Feature.AllowSingleQuotes, true); lexer.nextToken(); Assert.assertEquals(0, lexer.pos()); String stringVal = lexer.stringVal(); // Assert.assertEquals("\"\\\\\\/\\b\\f\\n\\r\\t中\"", // JSON.toJSONString(stringVal)); JSON.toJSONString(stringVal); } public void test_string3() throws Exception { StringBuilder buf = new StringBuilder(); buf.append('\''); for (int i = 0; i < 200; ++i) { buf.append("abcdefghijklmn012345689ABCDEFG"); } buf.append('\''); String text = buf.toString(); JSONScanner lexer = new JSONScanner(text.toCharArray(), text.length()); lexer.config(Feature.AllowSingleQuotes, true); lexer.nextToken(); Assert.assertEquals(0, lexer.pos()); String stringVal = lexer.stringVal(); // Assert.assertEquals("\"\\\\\\/\\b\\f\\n\\r\\t中\"", // JSON.toJSONString(stringVal)); JSON.toJSONString(stringVal); } public void test_string4() throws Exception { StringBuilder buf = new StringBuilder(); buf.append('\''); for (int i = 0; i < 200; ++i) { buf.append("\\tabcdefghijklmn012345689ABCDEFG"); } buf.append('\''); String text = buf.toString(); JSONScanner lexer = new JSONScanner(text.toCharArray(), text.length()); lexer.config(Feature.AllowSingleQuotes, true); lexer.nextToken(); Assert.assertEquals(0, lexer.pos()); String stringVal = lexer.stringVal(); // Assert.assertEquals("\"\\\\\\/\\b\\f\\n\\r\\t中\"", // JSON.toJSONString(stringVal)); JSON.toJSONString(stringVal); } public void test_error() throws Exception { Exception error = null; try { JSONScanner lexer = new JSONScanner("'k"); lexer.config(Feature.AllowSingleQuotes, true); lexer.nextToken(); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_1() throws Exception { Exception error = null; try { JSONScanner lexer = new JSONScanner("'k\\k'"); lexer.config(Feature.AllowSingleQuotes, true); lexer.nextToken(); Assert.assertEquals(JSONToken.ERROR, lexer.token()); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_symbol.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/JSONScannerTest_true.java ================================================ 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; public class JSONScannerTest_true extends TestCase { public void test_scan_true_0() throws Exception { JSONScanner lexer = new JSONScanner("true"); lexer.scanTrue(); } public void test_scan_true_1() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("frue"); lexer.scanTrue(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_true_2() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("ttue"); lexer.scanTrue(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_true_3() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("trze"); lexer.scanTrue(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_true_4() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("truz"); lexer.scanTrue(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_true_5() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("truee"); lexer.scanTrue(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_true_6() throws Exception { JSONException error = null; try { JSONScanner lexer = new JSONScanner("true\""); lexer.scanTrue(); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_scan_true_7() throws Exception { JSONScanner lexer = new JSONScanner("true a"); lexer.scanTrue(); } public void test_scan_true_8() throws Exception { JSONScanner lexer = new JSONScanner("true,"); lexer.scanTrue(); } public void test_scan_true_9() throws Exception { JSONScanner lexer = new JSONScanner("true\na"); lexer.scanTrue(); } public void test_scan_true_10() throws Exception { JSONScanner lexer = new JSONScanner("true\ra"); lexer.scanTrue(); } public void test_scan_true_11() throws Exception { JSONScanner lexer = new JSONScanner("true\ta"); lexer.scanTrue(); } public void test_scan_true_12() throws Exception { JSONScanner lexer = new JSONScanner("true\fa"); lexer.scanTrue(); } public void test_scan_true_13() throws Exception { JSONScanner lexer = new JSONScanner("true\ba"); lexer.scanTrue(); } public void test_scan_false_14() throws Exception { JSONScanner lexer = new JSONScanner("true}"); lexer.scanTrue(); } public void test_scan_false_15() throws Exception { JSONScanner lexer = new JSONScanner("true]"); lexer.scanTrue(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/MapResetTest.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/MaximumLevelTest.java ================================================ package com.alibaba.json.bvt.parser; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import junit.framework.TestCase; public class MaximumLevelTest extends TestCase { public void test_for_maximum() throws Exception { int[] chars = new int[] {0x5b, 0x7b}; for (int ch : chars) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 500; ++i) { sb.append((char) ch); } Exception error = null; try { JSON.parseObject(sb.toString()); } catch (JSONException ex) { error = ex; } assertNotNull(error); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/NullCheckTest.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class NullCheckTest extends TestCase { public void test_0() throws Exception { Assert.assertEquals(null, JSON.parse(null)); Assert.assertEquals(null, JSON.parse("")); Assert.assertEquals(null, JSON.parse(" ")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/OrderedFieldTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ParseContextTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ParseRestTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest_map.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ParserSpecialCharTest_map_singleQuote.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/PrivateConstrunctorTest.java ================================================ 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() {} } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ProductViewTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicBooleanTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicBooleanTest_field.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicIntegerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicIntegerTest_field.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicLongTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyAtomicLongTest_field.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest_final_field.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyCollectionTest_final_field_null.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest.java ================================================ 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() { } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest2.java ================================================ 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.assertNotNull(entity.values); } public static class Entity { private Map values; public Map getValues() { return values; } } public static class A { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest2_final_field.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest_final_field.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/RedundantTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/SafeModeTest.java ================================================ package com.alibaba.json.bvt.parser; 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.parser.ParserConfig; import junit.framework.TestCase; public class SafeModeTest extends TestCase { public void test_for_safeMode() throws Exception { ParserConfig config = new ParserConfig(); String str = "{\"@type\":\"com.alibaba.json.bvt.parser.SafeModeTest$Entity\"}"; JSON.parse(str); { Exception error = null; try { JSON.parse(str, config, Feature.SafeMode); } catch (JSONException ex) { error = ex; } assertNotNull(error); } { Exception error = null; try { config.setSafeMode(true); JSON.parse(str, config); } catch (JSONException ex) { error = ex; } assertNotNull(error); } } @JSONType public static class Entity { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TestException.java ================================================ package com.alibaba.json.bvt.parser; import java.util.List; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestException extends TestCase { public void test_0() throws Exception { Exception error = null; try { f(); } catch (Exception ex) { error = ex; } String text = JSON.toJSONString(new Exception[] { error }); List list = JSON.parseArray(text, RuntimeException.class); JSON.toJSONString(list); } public void f() { throw new RuntimeException(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TestInitStringFieldAsEmpty.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TestInitStringFieldAsEmpty2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TestUTF8.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class TestUTF8 extends TestCase { public void test_utf() throws Exception { JSONObject obj = (JSONObject) JSON.parse("{'name':'刘大'}".getBytes("UTF-8")); Assert.assertEquals(1, obj.size()); Assert.assertEquals("刘大", obj.get("name")); } public void test_utf_cn() throws Exception { String content = "首先来到村委会,走进农家书屋,认真翻看各种图书和报刊。他拿起一份藏文版《人民日报》,询问村民读书读报的情况,并和正在读书的几位藏族青年亲切交谈,勉励他们好好学习,学以致用,培养致富本领。在党支部活动室,村支部书记桑杰介绍了支部建设情况。当听到全村36名党员发挥先锋模范作用"; JSONObject json = new JSONObject(); json.put("content", content); JSONObject obj = (JSONObject) JSON.parse(json.toJSONString().getBytes("UTF-8")); Assert.assertEquals(1, obj.size()); Assert.assertEquals(content, obj.get("content")); } public void test_utf_de() throws Exception { String content = "Beim Griechenland-Gipfel gibt es viele Gewinner. Kanzlerin Merkel bekommt die Bankenbeteiligung, Frankreichs Präsident Sarkozy den Aufkauf von Staatsanleihen. \\nEinzig EZB-Präsident Jean-Claude Trichet gilt als Verlierer. Er zog im Machtkampf den Kürzeren"; JSONObject json = new JSONObject(); json.put("content", content); JSONObject obj = (JSONObject) JSON.parse(json.toJSONString().getBytes("UTF-8")); Assert.assertEquals(1, obj.size()); Assert.assertEquals(content, obj.get("content")); } public void test_utf_jp() throws Exception { String content = "菅首相がマニフェストで陳謝"; JSONObject json = new JSONObject(); json.put("content", content); JSONObject obj = (JSONObject) JSON.parse(json.toJSONString().getBytes("UTF-8")); Assert.assertEquals(1, obj.size()); Assert.assertEquals(content, obj.get("content")); } public void test_utf_() throws Exception { String content = "Viel Spaß mit Java 7 und Eclipse!"; JSONObject json = new JSONObject(); json.put("content", content); JSONObject obj = (JSONObject) JSON.parse(json.toJSONString().getBytes("UTF-8")); Assert.assertEquals(1, obj.size()); Assert.assertEquals(content, obj.get("content")); } public void test_utf_7() throws Exception { String content = "薄扶林水塘,《香港雜記》叫百步林水塘,係香港一水塘,亦係全港第一個水塘。水塘喺香港島西嘅薄扶林,近薄扶林村。佢集有薄扶林谷地中咁多條河涌嘅水。涌水出自扯旗山、西高山、爐峯峽、歌賦山、奇力山。水塘分上下兩塘,儲水量約為廿六萬立方米,約莫六千八百萬加侖。水塘溢水會經薄扶林村流入瀑布灣"; JSONObject json = new JSONObject(); json.put("content", content); JSONObject obj = (JSONObject) JSON.parse(json.toJSONString().getBytes("UTF-8")); Assert.assertEquals(1, obj.size()); Assert.assertEquals(content, obj.get("content")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TestUTF8_2.java ================================================ package com.alibaba.json.bvt.parser; import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.json.bvt.util.ThreadLocalCacheTest; import junit.framework.TestCase; public class TestUTF8_2 extends TestCase { public void test_utf_1() throws Exception { String content = new String(decodeHex("F0A4ADA2".toCharArray()), "UTF-8"); JSONObject json = new JSONObject(); json.put("content", content); JSONObject obj = (JSONObject) JSON.parse(json.toJSONString().getBytes("UTF-8")); Assert.assertEquals(1, obj.size()); Assert.assertEquals(content, obj.get("content")); } public void test_utf_2() throws Exception { String content = new String(decodeHex("E282AC".toCharArray()), "UTF-8"); JSONObject json = new JSONObject(); json.put("content", content); JSONObject obj = (JSONObject) JSON.parse(json.toJSONString().getBytes("UTF-8")); Assert.assertEquals(1, obj.size()); Assert.assertEquals(content, obj.get("content")); } public void test_utf_3() throws Exception { byte[] bytes = decodeHex("C2A2".toCharArray()); String content = new String(bytes, "UTF-8"); JSONObject json = new JSONObject(); json.put("content", content); JSONObject obj = (JSONObject) JSON.parse(json.toJSONString().getBytes("UTF-8")); Assert.assertEquals(1, obj.size()); Assert.assertEquals(content, obj.get("content")); } public void test_utf_4() throws Exception { ThreadLocalCacheTest.clearChars(); byte[] bytes = decodeHex("C2FF".toCharArray()); String content = new String(bytes, "UTF-8"); JSONObject json = new JSONObject(); json.put("content", content); JSONObject obj = (JSONObject) JSON.parse(json.toJSONString().getBytes("UTF-8")); Assert.assertEquals(1, obj.size()); Assert.assertEquals(content, obj.get("content")); } public static byte[] decodeHex(char[] data) throws Exception { int len = data.length; if ((len & 0x01) != 0) { throw new Exception("Odd number of characters."); } byte[] out = new byte[len >> 1]; // two characters form the hex value. for (int i = 0, j = 0; j < len; i++) { int f = toDigit(data[j], j) << 4; j++; f = f | toDigit(data[j], j); j++; out[i] = (byte) (f & 0xFF); } return out; } protected static int toDigit(char ch, int index) throws Exception { int digit = Character.digit(ch, 16); if (digit == -1) { throw new Exception("Illegal hexadecimal character " + ch + " at index " + index); } return digit; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeReferenceTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest.java ================================================ package com.alibaba.json.bvt.parser; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; 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.ParserConfig; import com.alibaba.fastjson.util.TypeUtils; @SuppressWarnings("rawtypes") public class TypeUtilsTest extends TestCase { public void test_0() throws Exception { HashMap map = new HashMap(); Assert.assertTrue(map == TypeUtils.castToJavaBean(map, Map.class)); } public void test_1() throws Exception { JSONObject map = new JSONObject(); Assert.assertTrue(map == TypeUtils.castToJavaBean(map, Map.class)); } public void test_2() throws Exception { JSONObject map = new JSONObject(); map.put("id", 1); map.put("name", "panlei"); User user = TypeUtils.castToJavaBean(map, User.class); Assert.assertEquals(1L, user.getId()); Assert.assertEquals("panlei", user.getName()); } public void test_cast_Integer() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1L); Assert.assertEquals(new Integer(1), json.getObject("id", int.class)); } public void test_cast_Integer_2() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1L); Assert.assertEquals(new Integer(1), json.getObject("id", Integer.class)); } public void test_cast_to_long() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Assert.assertEquals(new Long(1), json.getObject("id", long.class)); } public void test_cast_to_Long() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Assert.assertEquals(new Long(1), json.getObject("id", Long.class)); } public void test_cast_to_short() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Assert.assertEquals(new Short((short) 1), json.getObject("id", short.class)); } public void test_cast_to_Short() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Assert.assertEquals(new Short((short) 1), json.getObject("id", Short.class)); } public void test_cast_to_byte() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Assert.assertEquals(new Byte((byte) 1), json.getObject("id", byte.class)); } public void test_cast_to_Byte() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Assert.assertEquals(new Byte((byte) 1), json.getObject("id", Byte.class)); } public void test_cast_to_BigInteger() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Assert.assertEquals(new BigInteger("1"), json.getObject("id", BigInteger.class)); } public void test_cast_to_BigDecimal() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Assert.assertEquals(new BigDecimal("1"), json.getObject("id", BigDecimal.class)); } public void test_cast_to_boolean() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Assert.assertEquals(Boolean.TRUE, json.getObject("id", boolean.class)); } public void test_cast_to_Boolean() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Assert.assertEquals(Boolean.TRUE, json.getObject("id", Boolean.class)); } public void test_cast_null() throws Exception { JSONObject json = new JSONObject(); json.put("id", null); Assert.assertEquals(null, json.getObject("id", Boolean.class)); } public void test_cast_to_String() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Assert.assertEquals("1", json.getObject("id", String.class)); } public void test_cast_to_Date() throws Exception { long millis = System.currentTimeMillis(); JSONObject json = new JSONObject(); json.put("date", millis); Assert.assertEquals(new Date(millis), json.getObject("date", Date.class)); } public void test_cast_to_SqlDate() throws Exception { long millis = System.currentTimeMillis(); JSONObject json = new JSONObject(); json.put("date", millis); Assert.assertEquals(new java.sql.Date(millis), json.getObject("date", java.sql.Date.class)); } public void test_cast_to_SqlDate_string() throws Exception { long millis = System.currentTimeMillis(); JSONObject json = new JSONObject(); json.put("date", Long.toString(millis)); Assert.assertEquals(new java.sql.Date(millis), json.getObject("date", java.sql.Date.class)); } public void test_cast_to_SqlDate_null() throws Exception { JSONObject json = new JSONObject(); json.put("date", null); Assert.assertEquals(null, json.getObject("date", java.sql.Date.class)); } public void test_cast_to_SqlDate_null2() throws Exception { Assert.assertEquals(null, TypeUtils.castToSqlDate(null)); } public void test_cast_to_SqlDate_util_Date() throws Exception { long millis = System.currentTimeMillis(); JSONObject json = new JSONObject(); json.put("date", new Date(millis)); Assert.assertEquals(new java.sql.Date(millis), json.getObject("date", java.sql.Date.class)); } public void test_cast_to_SqlDate_sql_Date() throws Exception { long millis = System.currentTimeMillis(); JSONObject json = new JSONObject(); json.put("date", new java.sql.Date(millis)); Assert.assertEquals(new java.sql.Date(millis), json.getObject("date", java.sql.Date.class)); } public void test_cast_to_SqlDate_sql_Date2() throws Exception { long millis = System.currentTimeMillis(); java.sql.Date date = new java.sql.Date(millis); Assert.assertEquals(date, TypeUtils.castToSqlDate(date)); } public void test_cast_to_SqlDate_calendar() throws Exception { long millis = System.currentTimeMillis(); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(millis); JSONObject json = new JSONObject(); json.put("date", calendar); Assert.assertEquals(new java.sql.Date(millis), json.getObject("date", java.sql.Date.class)); } public void test_cast_to_SqlDate_error() throws Exception { JSONObject json = new JSONObject(); json.put("date", 0); JSONException error = null; try { json.getObject("date", java.sql.Date.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_cast_to_Timestamp() throws Exception { long millis = System.currentTimeMillis(); JSONObject json = new JSONObject(); json.put("date", millis); Assert.assertEquals(new java.sql.Timestamp(millis), json.getObject("date", java.sql.Timestamp.class)); } public void test_cast_to_Timestamp_string() throws Exception { long millis = System.currentTimeMillis(); JSONObject json = new JSONObject(); json.put("date", Long.toString(millis)); Assert.assertEquals(new java.sql.Timestamp(millis), json.getObject("date", java.sql.Timestamp.class)); } public void test_cast_to_Timestamp_number() throws Exception { long millis = System.currentTimeMillis(); JSONObject json = new JSONObject(); json.put("date", new BigDecimal(Long.toString(millis))); Assert.assertEquals(new java.sql.Timestamp(millis), json.getObject("date", java.sql.Timestamp.class)); } public void test_cast_to_Timestamp_null() throws Exception { JSONObject json = new JSONObject(); json.put("date", null); Assert.assertEquals(null, json.getObject("date", java.sql.Timestamp.class)); } public void test_cast_to_Timestamp_null2() throws Exception { Assert.assertEquals(null, TypeUtils.castToTimestamp(null)); } public void test_cast_to_Timestamp_1970_01_01_00_00_00() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); Assert.assertEquals(new Timestamp(0), TypeUtils.castToTimestamp("1970-01-01 08:00:00")); } 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()); } public void test_cast_to_Timestamp_util_Date() throws Exception { long millis = System.currentTimeMillis(); JSONObject json = new JSONObject(); json.put("date", new Date(millis)); Assert.assertEquals(new java.sql.Timestamp(millis), json.getObject("date", java.sql.Timestamp.class)); } public void test_cast_to_Timestamp_sql_Date() throws Exception { long millis = System.currentTimeMillis(); JSONObject json = new JSONObject(); json.put("date", new java.sql.Date(millis)); Assert.assertEquals(new java.sql.Timestamp(millis), json.getObject("date", java.sql.Timestamp.class)); } public void test_cast_to_Timestamp_sql_Timestamp() throws Exception { long millis = System.currentTimeMillis(); java.sql.Timestamp date = new java.sql.Timestamp(millis); Assert.assertEquals(date, TypeUtils.castToTimestamp(date)); } public void test_cast_to_Timestamp_calendar() throws Exception { long millis = System.currentTimeMillis(); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(millis); JSONObject json = new JSONObject(); json.put("date", calendar); Assert.assertEquals(new java.sql.Timestamp(millis), json.getObject("date", java.sql.Timestamp.class)); } public void test_cast_to_Timestamp_not_error() throws Exception { JSONObject json = new JSONObject(); json.put("date", -1); JSONException error = null; try { json.getObject("date", java.sql.Timestamp.class); } catch (JSONException e) { error = e; } Assert.assertNull(error); Assert.assertEquals(new Timestamp(-1L), (java.sql.Timestamp) json.getObject("date", java.sql.Timestamp.class)); } public void test_cast_ab() throws Exception { B b = new B(); JSONObject json = new JSONObject(); json.put("value", b); Assert.assertEquals(b, json.getObject("value", A.class)); } public void test_cast_ab_1() throws Exception { B b = new B(); JSONObject json = new JSONObject(); json.put("value", b); Assert.assertEquals(b, json.getObject("value", IA.class)); } public void test_cast_ab_error() throws Exception { A a = new A(); JSONObject json = new JSONObject(); json.put("value", a); JSONException error = null; try { json.getObject("value", B.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); JSONException error = null; try { TypeUtils.castToJavaBean(json, C.class, ParserConfig.getGlobalInstance()); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_2() throws Exception { JSONObject json = new JSONObject(); json.put("id", 1); Method method = TypeUtilsTest.class.getMethod("f", List.class); Throwable error = null; try { TypeUtils.cast(json, method.getGenericParameterTypes()[0], ParserConfig.getGlobalInstance()); } catch (JSONException ex) { error = ex; } assertNotNull(error); } public void test_3() throws Exception { JSONObject map = new JSONObject(); map.put("id", 1); map.put("name", "panlei"); User user = JSON.toJavaObject(map, User.class); Assert.assertEquals(1L, user.getId()); Assert.assertEquals("panlei", user.getName()); } public static class User { 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; } } public static class A implements IA { } public static interface IA { } public static class B extends A { } public static class C extends B { public int getId() { throw new UnsupportedOperationException(); } public void setId(int id) { throw new UnsupportedOperationException(); } } public static void f(List list) { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest2.java ================================================ package com.alibaba.json.bvt.parser; import java.lang.reflect.ParameterizedType; import java.util.List; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.util.TypeUtils; public class TypeUtilsTest2 extends TestCase { public void test_0() throws Exception { Assert.assertNull(TypeUtils.cast("", Entity.class, null)); Assert.assertNull(TypeUtils.cast("", Type.class, null)); Assert.assertNull(TypeUtils.cast("", Byte.class, null)); Assert.assertNull(TypeUtils.cast("", Short.class, null)); Assert.assertNull(TypeUtils.cast("", Integer.class, null)); Assert.assertNull(TypeUtils.cast("", Long.class, null)); Assert.assertNull(TypeUtils.cast("", Float.class, null)); Assert.assertNull(TypeUtils.cast("", Double.class, null)); Assert.assertNull(TypeUtils.cast("", Character.class, null)); Assert.assertNull(TypeUtils.cast("", java.util.Date.class, null)); Assert.assertNull(TypeUtils.cast("", java.sql.Date.class, null)); Assert.assertNull(TypeUtils.cast("", java.sql.Timestamp.class, null)); Assert.assertNull(TypeUtils.castToChar("")); Assert.assertNull(TypeUtils.castToChar(null)); Assert.assertEquals('A', TypeUtils.castToChar('A').charValue()); Assert.assertEquals('A', TypeUtils.castToChar("A").charValue()); Assert.assertNull(TypeUtils.castToBigDecimal("")); Assert.assertNull(TypeUtils.castToBigInteger("")); Assert.assertNull(TypeUtils.castToBoolean("")); Assert.assertNull(TypeUtils.castToEnum("", Type.class, null)); Assert.assertEquals(null, TypeUtils.cast("", new TypeReference>() { }.getType(), null)); } public void test_1() throws Exception { Assert.assertEquals(null, TypeUtils.cast("", new TypeReference>() { }.getType(), null)); } public void test_error_2() throws Exception { Exception error = null; try { Assert.assertEquals(null, TypeUtils.cast("a", new TypeReference>() { }.getType(), null)); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_3() throws Exception { Exception error = null; try { Assert.assertEquals(null, TypeUtils.cast("a", new TypeReference>() { }.getType(), null)); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_4() throws Exception { Exception error = null; try { Assert.assertEquals(null, TypeUtils.cast("a", ((ParameterizedType) new TypeReference>() { }.getType()).getActualTypeArguments()[0], null)); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_0() throws Exception { Exception error = null; try { TypeUtils.castToChar("abc"); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_1() throws Exception { Exception error = null; try { TypeUtils.castToChar(true); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public static class Entity { } public static class Pair { } public static enum Type { A, B, C } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest3.java ================================================ 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.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.util.TypeUtils; public class TypeUtilsTest3 extends TestCase { public void test_enum() throws Exception { Assert.assertEquals(Type.A, JSON.parseObject("\"A\"", Type.class)); Assert.assertEquals(Type.A, JSON.parseObject("" + Type.A.ordinal(), Type.class)); Assert.assertEquals(Type.B, JSON.parseObject("" + Type.B.ordinal(), Type.class)); Assert.assertEquals(Type.C, JSON.parseObject("" + Type.C.ordinal(), Type.class)); } public void test_enum_2() throws Exception { Assert.assertEquals(Type.A, TypeUtils.cast("A", Type.class, null)); Assert.assertEquals(Type.A, TypeUtils.cast(Type.A.ordinal(), Type.class, null)); Assert.assertEquals(Type.B, TypeUtils.cast(Type.B.ordinal(), Type.class, null)); } public void test_error() throws Exception { assertNull(TypeUtils.castToEnum("\"A1\"", Type.class, null)); } public void test_error_1() throws Exception { Exception error = null; try { TypeUtils.castToEnum(Boolean.TRUE, Type.class, null); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_2() throws Exception { Exception error = null; try { TypeUtils.castToEnum(1000, Type.class, null); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_null() throws Exception { Assert.assertEquals(null, TypeUtils.cast(null, new TypeReference() { }.getType(), null)); } public void test_null_1() throws Exception { Assert.assertEquals(null, TypeUtils.cast("", new TypeReference>() { }.getType(), null)); } public void test_null_2() throws Exception { Assert.assertEquals(null, TypeUtils.cast("", new TypeReference() { }.getType(), null)); } public void test_error_3() throws Exception { Exception error = null; try { TypeUtils.cast("xxx", new TypeReference() { }.getType(), null); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_ex() throws Exception { RuntimeException ex = new RuntimeException(); JSONObject object = (JSONObject) JSON.toJSON(ex); JSONArray array = object.getJSONArray("stackTrace"); array.getJSONObject(0).put("lineNumber", null); JSON.parseObject(object.toJSONString(), Exception.class); } public static enum Type { A, B, C } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest4.java ================================================ package com.alibaba.json.bvt.parser; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; 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 { Assert.assertEquals(0, TypeUtils.cast(new Entity[0], Object[].class, null).length); } public void test_ParameterizedType() throws Exception { Assert.assertEquals(Integer.valueOf(123), ((ArrayList) TypeUtils.cast(Collections.singleton(123), new TypeReference>() { }.getType(), null)).get(0)); } public void test_ParameterizedType2() throws Exception { Assert.assertEquals("123", ((HashMap) TypeUtils.cast(Collections.singletonMap("name", 123), new TypeReference>() { }.getType(), null)).get("name")); } public void test_ParameterizedType_error() throws Exception { Exception error = null; try { TypeUtils.cast(Collections.singleton(123), new TypeReference>() { }.getType(), null); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error() throws Exception { Exception error = null; try { TypeUtils.cast("xxx", Object[].class, null); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_2() throws Exception { Exception error = null; try { TypeUtils.cast(123, new TypeReference() { }.getType(), null); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_exception() throws Exception { JSONObject object = (JSONObject) JSON.toJSON(new RuntimeException()); object.put("class", "xxx"); Assert.assertEquals(Exception.class, JSON.parseObject(object.toJSONString(), Exception.class).getClass()); } public static class Entity { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_cast.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToBigDecimal.java ================================================ package com.alibaba.json.bvt.parser; import com.alibaba.fastjson.util.TypeUtils; import junit.framework.TestCase; import org.junit.Assert; /** * 强转BigDecimal测试用例 */ public class TypeUtilsTest_castToBigDecimal extends TestCase { /** * NaN和正负无穷大的时候转BigDecimal都会报转换异常,修改为返回null */ public void test_FloatNanInfinite() throws Exception { // 正无穷大 assertNull(TypeUtils.castToBigDecimal(1.0f / 0.0f)); // 负无穷大 assertNull(TypeUtils.castToBigDecimal(-1.0f / 0.0f)); // NaN assertNull(TypeUtils.castToBigDecimal(0.0f / 0.0f)); } /** * NaN和正负无穷大的时候转BigDecimal都会报转换异常,修改为返回null */ public void test_DoubleNanInfinite() throws Exception { // 正无穷大 assertNull(TypeUtils.castToBigDecimal(1.0d / 0.0d)); // 负无穷大 assertNull(TypeUtils.castToBigDecimal(-1.0d / 0.0d)); // NaN assertNull(TypeUtils.castToBigDecimal(0.0d / 0.0d)); } /** * NaN和正负无穷大的时候转BigDecimal都会报转换异常,修改为返回null */ public void test_FloatNanInfinite_BigInteger() throws Exception { // 正无穷大 assertNull(TypeUtils.castToBigInteger(1.0f / 0.0f)); // 负无穷大 assertNull(TypeUtils.castToBigInteger(-1.0f / 0.0f)); // NaN assertNull(TypeUtils.castToBigInteger(0.0f / 0.0f)); } /** * NaN和正负无穷大的时候转BigDecimal都会报转换异常,修改为返回null */ public void test_DoubleNanInfinite_BigInteger() throws Exception { // 正无穷大 assertNull(TypeUtils.castToBigInteger(1.0d / 0.0d)); // 负无穷大 assertNull(TypeUtils.castToBigInteger(-1.0d / 0.0d)); // NaN assertNull(TypeUtils.castToBigInteger(0.0d / 0.0d)); } public void test_nullString_biginteger() throws Exception { assertNull(TypeUtils.castToBigInteger("")); assertNull(TypeUtils.castToBigInteger("null")); } public void test_nullString_bigdecimal() throws Exception { assertNull(TypeUtils.castToBigDecimal("")); assertNull(TypeUtils.castToBigDecimal("null")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToBigInteger.java ================================================ package com.alibaba.json.bvt.parser; import com.alibaba.fastjson.util.TypeUtils; import junit.framework.TestCase; import org.junit.Assert; /** * 强转BigInteger测试用例 */ public class TypeUtilsTest_castToBigInteger extends TestCase { /** * NaN和正负无穷大的时候转BigInteger都会报转换异常,修改为返回null */ public void test_FloatNanInfinite() throws Exception { // 正无穷大 Assert.assertNull(TypeUtils.castToBigInteger(1.0f / 0.0f)); // 负无穷大 Assert.assertNull(TypeUtils.castToBigInteger(-1.0f / 0.0f)); // NaN Assert.assertNull(TypeUtils.castToBigInteger(0.0f / 0.0f)); } /** * NaN和正负无穷大的时候转BigInteger都会报转换异常,修改为返回null */ public void test_DoubleNanInfinite() throws Exception { // 正无穷大 Assert.assertNull(TypeUtils.castToBigInteger(1.0d / 0.0d)); // 负无穷大 Assert.assertNull(TypeUtils.castToBigInteger(-1.0d / 0.0d)); // NaN Assert.assertNull(TypeUtils.castToBigInteger(0.0d / 0.0d)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToBytes.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToDate.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToJavaBean.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToJavaBean_JSONType.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_compatibleWithJavaBean.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_compatibleWithJavaBean_boolean.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_interface.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_loadClass.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtilsToJSONTest.java ================================================ package com.alibaba.json.bvt.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; @SuppressWarnings("rawtypes") public class TypeUtilsToJSONTest extends TestCase { public void test_0() throws Exception { HashMap map = new HashMap(); JSONObject json = (JSONObject) JSON.toJSON(map); Assert.assertEquals(map.size(), json.size()); } public void test_1() throws Exception { List list = new ArrayList(); JSONArray json = (JSONArray) JSON.toJSON(list); Assert.assertEquals(list.size(), json.size()); } public void test_null() throws Exception { Assert.assertEquals(null, JSON.toJSON(null)); } public static class User { 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtils_parseDouble_Test.java ================================================ package com.alibaba.json.bvt.parser; import com.alibaba.fastjson.util.TypeUtils; import junit.framework.TestCase; import java.util.Random; public class TypeUtils_parseDouble_Test extends TestCase { public void test_0() throws Exception { Random r = new Random(); for (int i = 0; i < 1000 * 1000; ++i) { String str = Float.toString(r.nextFloat()); assertEquals(Double.parseDouble(str), TypeUtils.parseDouble(str)); } } public void test_0_d() throws Exception { Random r = new Random(); for (int i = 0; i < 1000 * 1000; ++i) { String str = Double.toString(r.nextDouble()); assertEquals(Double.parseDouble(str), TypeUtils.parseDouble(str)); } } public void test_1() throws Exception { Random r = new Random(); for (int i = 0; i < 1000 * 1000; ++i) { String str = Integer.toString(r.nextInt()); assertEquals(Double.parseDouble(str), TypeUtils.parseDouble(str)); } } public void test_2() throws Exception { Random r = new Random(); for (int i = 0; i < 1000 * 1000; ++i) { String str = Integer.toString(r.nextInt(1000000000)); assertEquals(Double.parseDouble(str), TypeUtils.parseDouble(str)); } } public void test_3() throws Exception { Random r = new Random(); for (int i = 0; i < 1000 * 1000; ++i) { String str = Long.toString(r.nextLong()); assertEquals(Double.parseDouble(str), TypeUtils.parseDouble(str)); } } public void test_4() throws Exception { String[] array = new String[] { "0.34856254", "1", "12", "123", "1234", "12345", "123456", "1234567", "12345678", "123456789", "1234567890", ".1" ,"1.1" ,"12.1" , "123.1" , "1234.1" , "12345.1" , "123456.1" , "1234567.1" , "12345678.1" , "0.1" , "0.12" , "0.123" , "0.1234" , "0.12345" , "0.123456" , "0.1234567" , "0.12345678" , "0.123456789" , "0.1234567891" , "0.12345678901" , "0.123456789012" }; for (String str : array) { assertEquals(Double.parseDouble(str), TypeUtils.parseDouble(str)); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/TypeUtils_parseFloat_Test.java ================================================ package com.alibaba.json.bvt.parser; import com.alibaba.fastjson.util.TypeUtils; import junit.framework.TestCase; import java.util.Random; public class TypeUtils_parseFloat_Test extends TestCase { public void test_0() throws Exception { Random r = new Random(); for (int i = 0; i < 1000 * 1000; ++i) { String str = Float.toString(r.nextFloat()); assertEquals(Float.parseFloat(str), TypeUtils.parseFloat(str)); } } public void test_1() throws Exception { Random r = new Random(); for (int i = 0; i < 1000 * 1000; ++i) { String str = Integer.toString(r.nextInt()); assertEquals(Float.parseFloat(str), TypeUtils.parseFloat(str)); } } public void test_2() throws Exception { Random r = new Random(); for (int i = 0; i < 1000 * 1000; ++i) { String str = Integer.toString(r.nextInt(1000000000)); assertEquals(Float.parseFloat(str), TypeUtils.parseFloat(str)); } } public void test_3() throws Exception { Random r = new Random(); for (int i = 0; i < 1000 * 1000; ++i) { String str = Long.toString(r.nextLong()); assertEquals(Float.parseFloat(str), TypeUtils.parseFloat(str)); } } public void test_4() throws Exception { String[] array = new String[] { "0.34856254", "1", "12", "123", "1234", "12345", "123456", "1234567", "12345678", "123456789", "1234567890", ".1" ,"1.1" ,"12.1" , "123.1" , "1234.1" , "12345.1" , "123456.1" , "1234567.1" , "12345678.1" , "0.1" , "0.12" , "0.123" , "0.1234" , "0.12345" , "0.123456" , "0.1234567" , "0.12345678" , "0.123456789" , "0.1234567891" , "0.12345678901" , "0.123456789012" }; for (String str : array) { assertEquals(Float.parseFloat(str), TypeUtils.parseFloat(str)); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/UTF8ByteArrayLexerTest_symbol.java ================================================ package com.alibaba.json.bvt.parser; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class UTF8ByteArrayLexerTest_symbol extends TestCase { public void test_utf8() throws Exception { byte[] bytes = "{\"name\":\"温家宝\", \"name\":\"xx\"}".getBytes("UTF-8"); JSONObject json = JSON.parseObject(bytes, JSONObject.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/UTF8ByteArrayParseTest.java ================================================ package com.alibaba.json.bvt.parser; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class UTF8ByteArrayParseTest extends TestCase { public void test_utf8() throws Exception { byte[] bytes = "{'name':'xxx', age:3, birthday:\"2009-09-05\"}".getBytes("UTF-8"); JSON.parseObject(bytes, JSONObject.class); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/UnquoteNameTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayAutoTypeTest.java ================================================ package com.alibaba.json.bvt.parser.array; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class BeanToArrayAutoTypeTest extends TestCase { public void test_for_issue_x() throws Exception { String json = "[\"@type\":\"B\",\"chengchao\",1001]"; A a = JSON.parseObject(json, A.class, Feature.SupportAutoType, Feature.SupportArrayToBean); B b = (B) a; } public void test_for_issue() throws Exception { Model m = new Model(); m.value = new B(1001, "chengchao"); String json = JSON.toJSONString(m); assertEquals("{\"value\":[\"@type\":\"B\",\"chengchao\",1001]}", json); Model m1 = JSON.parseObject(json, Model.class, Feature.SupportAutoType); assertEquals(m.value.getClass(), m1.value.getClass()); assertEquals(json, JSON.toJSONString(m1)); } public void test_for_issue_1() throws Exception { Model m = new Model(); m.value = new C(1001, 58); String json = JSON.toJSONString(m); assertEquals("{\"value\":[\"@type\":\"C\",58,1001]}", json); Model m1 = JSON.parseObject(json, Model.class, Feature.SupportAutoType); assertEquals(m.value.getClass(), m1.value.getClass()); assertEquals(json, JSON.toJSONString(m1)); } @JSONType(seeAlso = {B.class, C.class}) public static class A { protected int id; public int getId() { return id; } public void setId(int id) { this.id = id; } } @JSONType(typeName = "B", orders = {"name", "id"}) public static class B extends A { private String name; public B() { } public B(int id, String name) { this.id = id; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @JSONType(typeName = "C", orders = {"age", "id"}) public static class C extends A { public int age; public C() { } public C(int id, int age) { this.id = id; this.age = age; } } public static class Model { @JSONField(serialzeFeatures = {SerializerFeature.BeanToArray, SerializerFeature.WriteClassName} , parseFeatures = Feature.SupportArrayToBean) public A value; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayAutoTypeTest2.java ================================================ package com.alibaba.json.bvt.parser.array; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class BeanToArrayAutoTypeTest2 extends TestCase { public void test_for_issue() throws Exception { Model m = new Model(); m.value = new B(1001, "chengchao"); String json = JSON.toJSONString(m); assertEquals("{\"value\":[\"@type\":\"B\",\"chengchao\",1001]}", json); Model m1 = JSON.parseObject(json, Model.class, Feature.SupportAutoType); assertEquals(m.value.getClass(), m1.value.getClass()); assertEquals(json, JSON.toJSONString(m1)); } public void test_for_issue_1() throws Exception { Model m = new Model(); m.value = new C(1001, 58); String json = JSON.toJSONString(m); assertEquals("{\"value\":[\"@type\":\"C\",58,1001]}", json); Model m1 = JSON.parseObject(json, Model.class, Feature.SupportAutoType); assertEquals(m.value.getClass(), m1.value.getClass()); assertEquals(json, JSON.toJSONString(m1)); } @JSONType(seeAlso = {B.class, C.class} , serialzeFeatures = {SerializerFeature.BeanToArray, SerializerFeature.WriteClassName} , parseFeatures = Feature.SupportArrayToBean) public static class A { public int id; } @JSONType(typeName = "B", orders = {"name", "id"} , serialzeFeatures = {SerializerFeature.BeanToArray, SerializerFeature.WriteClassName} , parseFeatures = Feature.SupportArrayToBean) public static class B extends A { public String name; public B() { } public B(int id, String name) { this.id = id; this.name = name; } } @JSONType(typeName = "C", orders = {"age", "id"} , serialzeFeatures = {SerializerFeature.BeanToArray, SerializerFeature.WriteClassName} , parseFeatures = Feature.SupportArrayToBean) public static class C extends A { public int age; public C() { } public C(int id, int age) { this.id = id; this.age = age; } } public static class Model { public A value; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayAutoTypeTest3.java ================================================ package com.alibaba.json.bvt.parser.array; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; import java.util.List; public class BeanToArrayAutoTypeTest3 extends TestCase { public void test_beanToArray() throws Exception { Topology topology = JSON.parseObject("{\"maps\":[[\"@type\":\"Log\"]]}", Topology.class); assertEquals(LogSourceMeta.class, topology.maps.get(0).getClass()); } public void test_beanToArray1() throws Exception { Topology topology = JSON.parseObject("{\"maps\":[[\"@type\":\"Log\",123]]}", Topology.class); assertEquals(LogSourceMeta.class, topology.maps.get(0).getClass()); assertEquals(123, ((LogSourceMeta) topology.maps.get(0)).id); } @JSONType(typeName = "Log") public static class LogSourceMeta extends MapTaskMeta { public int id; } @JSONType(seeAlso = {LogSourceMeta.class, OtherMeta.class}, parseFeatures = Feature.SupportArrayToBean) public static class MapTaskMeta { } @JSONType(typeName = "Other") public static class OtherMeta extends MapTaskMeta { } public static class Topology { public List maps; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest3.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest3_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_date.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_date_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_enum.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_enum_private.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_int.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_long.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/Bug0.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/Bug2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_changhao.java ================================================ package com.alibaba.json.bvt.parser.bug; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.PropertyNamingStrategy; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; import junit.framework.TestCase; public class Bug_for_changhao extends TestCase { public void test_for_bug() throws Exception { String s = "{\"intValue\":1,\"stringValue\":\"abc\"}"; ParserConfig parseConfig = new ParserConfig(); parseConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase; TestClass t = JSON.parseObject(s, TestClass.class, parseConfig, Feature.DisableFieldSmartMatch); System.out.println(JSON.toJSONString(t)); } static class TestClass { String stringValue; int intValue; /** * Getter method for property stringValue. * * @return property value of stringValue */ public String getStringValue() { return stringValue; } /** * Setter method for property stringValue. * * @param stringValue value to be assigned to property stringValue */ public TestClass setStringValue(String stringValue) { this.stringValue = stringValue; return this; } /** * Getter method for property intValue. * * @return property value of intValue */ public int getIntValue() { return intValue; } /** * Setter method for property intValue. * * @param intValue value to be assigned to property intValue */ public TestClass setIntValue(int intValue) { this.intValue = intValue; return this; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_dingzhu.java ================================================ package com.alibaba.json.bvt.parser.bug; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.*; import junit.framework.TestCase; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class Bug_for_dingzhu extends TestCase { public void test_0() throws Exception { HashMap params = new HashMap(); params.put("notExitAfterVid", false); params.put("VIData", "{\"config\":{\"noTokens\":\"Y\",\"stopReport\":\"Y\"}"); StupidObject so = new StupidObject(); so.setParams(params); SerializeFilter[] filters = new SerializeFilter[] { new DumbValueFilter()}; String jsonString = JSON.toJSONString(so, new SerializeConfig(), filters, SerializerFeature.NotWriteDefaultValue, SerializerFeature.IgnoreErrorGetter, SerializerFeature.QuoteFieldNames); } private class DumbValueFilter implements ContextValueFilter { public Object process(BeanContext context, Object object, String name, Object value) { if (context == null) { return object; } Field field = context.getField(); return value; } } private class StupidObject { private Map params; public Map getParams() { return params; } public void setParams(Map params) { this.params = params; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_guanxiu.java ================================================ package com.alibaba.json.bvt.parser.bug; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.util.List; /** * 这个bug由李先锋反馈 * @author wenshao * */ public class Bug_for_guanxiu extends TestCase { public void test_long_list() throws Exception { String str = "{\"tnt_inst_id\":\"MYBKC1CN\",\"interface_id\":\"ant.mybank.loantrade.existvalidloan.query @1.0.0\",\"template_id\":\"EX-SYNC-IN-\n" + "\n" + "OPEN-API\"}"; JSON.parseObject(str); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_kongmu.java ================================================ package com.alibaba.json.bvt.parser.bug; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Bug_for_kongmu extends TestCase { public void test_for_bug() throws Exception { String JSON_STRING = "{\n" + "\t\"body\":\"parentBody\",\n" + "\t\"name\":\"child-1\",\n" + "\t\"result\":{\n" + "\t\t\"code\":11\n" + "\t},\n" + "\t\"toy\":{\n" + "\t\t\"type\":\"toytype\"\n" + "\t}\n" + "}"; JSON.parseObject(JSON_STRING, Child.class); } public static class BaseDO { private String body; private Result result; public String getBody() { return body; } public void setBody(String body) { this.body = body; } public Result getResult() { return result; } public void setResult(Result result) { this.result = result; } // 在1.2.27中能过,在1.2.48不能过 public class Result { // 在1.2.48中,必须为static //public static class Result { public Result() { this.code = 11; } private int code; public int getCode() { return code; } public void setCode(int code) { this.code = code; } } } public static class Child extends BaseDO { public String name; public Toy toy; public String getName() { return name; } public void setName(String name) { this.name = name; } public Toy getToy() { return toy; } public void setToy(Toy toy) { this.toy = toy; } // 这儿不是static,在1.2.27、1.2.48都能过 public class Toy { private String type; public Toy() { this.type = "toyType"; } public String getType() { return type; } public void setType(String type) { this.type = type; } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_lingzhi.java ================================================ package com.alibaba.json.bvt.parser.bug; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import java.util.List; public class Bug_for_lingzhi extends TestCase { public void test_0() throws Exception { String str = "[\n" + "{\n" + "\"isDefault\":false,\n" + "\"msgId\": \"expireTransitionChange\",\n" + "\"msgText\": \"xxx\",\n" + "\"extMsgId\": \"promptInformation\",\n" + "\"extMsgText\": \"xxx\",\n" + "\"instChangeType\": 1,\n" + "\"rule\": {\n" + "\"aliUid\":[39314],\n" + "\"regionNo\":[]\n" + "}\n" + "},\n" + "{\n" + "\"isDefault\":true,\n" + "\"msgId\": \"expireTransitionUnChange\",\n" + "\"msgText\": \"xxx\",\n" + "\"extMsgId\": \"Prompt information\",\n" + "\"extMsgText\": \"xxx\",\n" + "\"instChangeType\": 0,\n" + "\"rule\": {\n" + "\"aliUid\":[],\n" + "\"regionNo\":[]\n" + "}\n" + "},\n" + "{\n" + "\"isDefault\":false,\n" + "\"msgId\": \"expireTransitionChange\",\n" + "\"msgText\": \"xxx\",\n" + "\"extMsgId\": \"Prompt information\",\n" + "\"extMsgText\": \"你好B\",\n" + "\"instChangeType\": 1,\n" + "\"rule\": {\n" + "\"aliUid\":[111],\n" + "\"regionNo\":[]\n" + "}\n" + "}\n" + "]"; // String pstr = JSON.toJSONString(JSON.parse(str), SerializerFeature.PrettyFormat); // System.out.println(pstr); JSON.parseObject(str, new TypeReference>(){}); } public static class EcsTransitionDisplayedMsgConfig { /** * 是否默认文案 */ private Boolean isDefault; /** * 展示的文案Id */ private String msgId; /** * 展示的文案信息 */ private String msgText; /** * 扩展文案Id */ private String extMsgId; /** * 扩展文案信息 */ private String extMsgText; private Integer instChangeType; /** * 文案对应的规则 */ private EcsTransitionConfigRule rule; public String getMsgText() { return msgText; } public void setMsgText(String msgText) { this.msgText = msgText; } public String getMsgId() { return msgId; } public void setMsgId(String msgId) { this.msgId = msgId; } public EcsTransitionConfigRule getRule() { return rule; } public void setRule(EcsTransitionConfigRule rule) { this.rule = rule; } public Integer getInstChangeType() { return instChangeType; } public void setInstChangeType(Integer instChangeType) { this.instChangeType = instChangeType; } public Boolean getIsDefault() { return this.isDefault; } public void setIsDefault(Boolean isDefault) { this.isDefault = isDefault; } public String getExtMsgId() { return extMsgId; } public void setExtMsgId(String extMsgId) { this.extMsgId = extMsgId; } public String getExtMsgText() { return extMsgText; } public void setExtMsgText(String extMsgText) { this.extMsgText = extMsgText; } } public static class EcsTransitionConfigRule { /** 0 过保迁移, 1 非过保迁移 **/ private List transType; /** 比如:cn-qingdao-cm5-a01 **/ private List regionNo; private List aliUid; private List bid; /** ecs,disk **/ private List resourceType; private List zoneId; private List targetZoneId; private List networkTransType; /** instance type 实例规格 **/ private List instanceType; /** 磁盘类型 ioX **/ private List ioX; private List instanceId; public List getTransType() { return transType; } public void setTransType(List transType) { this.transType = transType; } public List getRegionNo() { return regionNo; } public void setRegionNo(List regionNo) { this.regionNo = regionNo; } public List getAliUid() { return aliUid; } public void setAliUid(List aliUid) { this.aliUid = aliUid; } public List getBid() { return bid; } public void setBid(List bid) { this.bid = bid; } public List getResourceType() { return resourceType; } public void setResourceType(List resourceType) { this.resourceType = resourceType; } public List getZoneId() { return zoneId; } public void setZoneId(List zoneId) { this.zoneId = zoneId; } public List getTargetZoneId() { return targetZoneId; } public void setTargetZoneId(List targetZoneId) { this.targetZoneId = targetZoneId; } public List getNetworkTransType() { return networkTransType; } public void setNetworkTransType(List networkTransType) { this.networkTransType = networkTransType; } public List getInstanceType() { return instanceType; } public void setInstanceType(List instanceType) { this.instanceType = instanceType; } public List getIoX() { return ioX; } public void setIoX(List ioX) { this.ioX = ioX; } public List getInstanceId() { return instanceId; } public void setInstanceId(List instanceId) { this.instanceId = instanceId; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_lixianfeng.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_yihaodian.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_zitao.java ================================================ package com.alibaba.json.bvt.parser.bug; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.BeanContext; import com.alibaba.fastjson.serializer.ContextValueFilter; import junit.framework.TestCase; public class Bug_for_zitao extends TestCase { public void test_for_issue() throws Exception { Model m = new Model(); ContextValueFilter v = new ContextValueFilter() { public Object process(BeanContext context, Object object, String name, Object value) { if (value == null && context != null && Number.class.isAssignableFrom(context.getFieldClass())) { return -1; } return null; } }; String json = JSON.toJSONString(m, v); assertEquals("{\"value\":-1}", json); } public static class Model { public Number value; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/EmptyParseArrayTest.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/bug/JSONObectNullTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorFactoryTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest10.java ================================================ package com.alibaba.json.bvt.parser.creator; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONCreator; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; public class JSONCreatorTest10 extends TestCase { public void test_for_yk() throws Exception { String jsonString = "{\"link\":\"http://lqgzs.org/fsqhwlnf\",\"text\":\"乐动力专享\"}"; JSONObject headerJSON = JSONObject.parseObject(jsonString); HeaderDTO headerDTO = headerJSON.toJavaObject(HeaderDTO.class); assertEquals("http://lqgzs.org/fsqhwlnf", headerDTO.link); assertEquals("乐动力专享", headerDTO.title); } public static class HeaderDTO { private String title; private String link; @JSONCreator public HeaderDTO(@JSONField(name = "text") String title,@JSONField(name = "link") String link) { this.title = title; this.link = link; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest11.java ================================================ package com.alibaba.json.bvt.parser.creator; 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 junit.framework.TestCase; import java.util.List; public class JSONCreatorTest11 extends TestCase { public void test_for_yk() throws Exception { String jsonString = "[{\"image\":\"https://gw.alicdn.com/tfs/TB1Dtk.ay6guuRjy1XdXXaAwpXa-204-154.png\"," + "\"labelNot\":\"zh*179753,zh*179745,zh*179743,zh*178230,zh*180695\",\"link\":\"https://alimarket.m.taobao" + ".com/markets/alisports/3_1weeklist\",\"title\":\"热卖榜单\",\"desc\":\"大家都在买\"}]"; JSONArray array = JSON.parseArray(jsonString); List dtoList = array.toJavaList(RecommendDTO.class); assertEquals("热卖榜单", dtoList.get(0).title); System.out.println(JSON.VERSION); } public static class RecommendDTO { private String image; private String link; private String title; private String desc; private String labels; private String labelNot; @JSONCreator public RecommendDTO(@JSONField(name = "image") String image, @JSONField(name = "link") String link, @JSONField(name = "title") String title, @JSONField(name = "desc") String desc, @JSONField(name = "labels") String labels, @JSONField(name = "labelNot") String labelNot) { final String PREFIX = "//"; this.desc = desc; this.title = title; this.labelNot = labelNot; this.labels = labels; if (image.startsWith(PREFIX)) { this.image = image.substring(2); } if (link.startsWith(PREFIX)) { this.link = link.substring(2); } } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getLabels() { return labels; } public void setLabels(String labels) { this.labels = labels; } public String getLabelNot() { return labelNot; } public void setLabelNot(String labelNot) { this.labelNot = labelNot; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest5.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest6.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest7.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest8.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest9.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_boolean.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_byte.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_double.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_float.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_int.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_long.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_default_short.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_double.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_double_obj.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_error3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_float.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_float_obj.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/AbstractSerializeTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/AbstractSerializeTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/BigDecimalDeserializerTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/BigDecimalTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/BigIntegerDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/BooleanDeserializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/BooleanFieldDeserializerTest.java ================================================ package com.alibaba.json.bvt.parser.deser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class BooleanFieldDeserializerTest extends TestCase { public void test_0() throws Exception { Entity a = JSON.parseObject("{f1:null, f2:null}", Entity.class); Assert.assertEquals(true, a.isF1()); Assert.assertEquals(null, a.getF2()); } public static class Entity { private boolean f1 = true; private Boolean f2 = Boolean.TRUE; public boolean isF1() { return f1; } public void setF1(boolean f1) { this.f1 = f1; } public Boolean getF2() { return f2; } public void setF2(Boolean f2) { this.f2 = f2; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/BooleanFieldDeserializerTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/CharArrayDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ClassTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/CollectionFieldTest.java ================================================ package com.alibaba.json.bvt.parser.deser; import java.util.Collection; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class CollectionFieldTest 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 Collection value; public Collection getValue() { return value; } public void setValue(Collection value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ConcurrentHashMapDeserializerTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_initError.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_initError_private.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_inner.java ================================================ 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(); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_private.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest10.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest11.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest12.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest2.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest3.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest5.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest6.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest7.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest8.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest9.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DefaultObjectDeserializerTest_collection.java ================================================ package com.alibaba.json.bvt.parser.deser; import java.util.HashMap; import java.util.List; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; public class DefaultObjectDeserializerTest_collection extends TestCase { public void test_0() throws Exception { String input = "[{}]"; List map = JSON.parseObject(input, new TypeReference>() { }.getType()); Assert.assertEquals(HashMap.class, map.get(0).getClass()); } public void test_1() throws Exception { String input = "{}"; BO map = JSON.parseObject(input, new TypeReference>() { }.getType()); } public void test_2() throws Exception { Exception error = null; try { String input = "{'map':{}}"; MyMap map = JSON.parseObject(input, new TypeReference>() { }.getType()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public static class BO { } public static class MyMap extends HashMap { public MyMap() { throw new RuntimeException(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DoubleArrayFieldDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DoubleDeserializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DoubleFieldDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/DupTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/EnumMapTest.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/EnumTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FactoryTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FactoryTest_error.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest.java ================================================ 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 FieldDeserializerTest extends TestCase { public void test_deser() throws Exception { Exception error = null; try { JSON.parseObject("{'value':{}}", Entity.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } private static class Entity { private V1 value; public V1 getValue() { return value; } public void setValue(V1 value) { throw new RuntimeException(); } } private static class V1 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest1.java ================================================ 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; import com.alibaba.fastjson.parser.Feature; public class FieldDeserializerTest1 extends TestCase { public void test_error() throws Exception { Exception error = null; try { JSON.parseObject("{\"value\":[-}", Entity.class, 0); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_1() throws Exception { Exception error = null; try { JSON.parseObject("{,,,\"value\":null}", Entity.class, 0); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_2() throws Exception { Exception error = null; try { JSON.parseObject("{\"value\":null,\"id\":123}", Entity.class, 0); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_null() throws Exception { Entity object = JSON.parseObject("{\"value\":null}", Entity.class, 0); Assert.assertNull(object.getValue()); } public void test_null_2() throws Exception { Entity object = JSON.parseObject("{\"value\":null,\"id\":123}", Entity.class, 0, Feature.IgnoreNotMatch); Assert.assertNull(object.getValue()); } private static class Entity { private V1 value; public V1 getValue() { return value; } public void setValue(V1 value) { this.value = value; } } private static class V1 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest10.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest2.java ================================================ 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; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.ParserConfig; public class FieldDeserializerTest2 extends TestCase { public void test_0() throws Exception { String input = "{,,,\"value\":null,,,,}"; int featureValues = 0; featureValues |= Feature.AllowArbitraryCommas.getMask(); DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); Entity object = new Entity(); parser.parseObject(object); } public void test_1() throws Exception { String input = "{,,,\"value\":null,\"id\":123,,,,}"; int featureValues = 0; featureValues |= Feature.AllowArbitraryCommas.getMask(); featureValues |= Feature.IgnoreNotMatch.getMask(); DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); Entity object = new Entity(); parser.parseObject(object); } public void test_error_1() throws Exception { Exception error = null; try { String input = "{\"value\":null,\"id\":123}"; 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) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest3.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest4.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest5.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest6.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest7.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest8.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest9.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest.java ================================================ 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.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; public class FieldSerializerTest extends TestCase { public void test_writeNull() throws Exception { String text = JSON.toJSONString(new Entity()); Assert.assertEquals("{\"v\":null}", text); } private static class Entity { private transient int id; @JSONField(name = "v", serialzeFeatures = { SerializerFeature.WriteMapNullValue }) private String value; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest2.java ================================================ package com.alibaba.json.bvt.parser.deser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.NameFilter; import com.alibaba.fastjson.serializer.PropertyFilter; import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.ValueFilter; public class FieldSerializerTest2 extends TestCase { public void test_writeNull() throws Exception { String text = toJSONString(new Entity()); Assert.assertEquals("{\"value\":\"xxx\"}", text); } public static final String toJSONString(Object object, SerializerFeature... features) { SerializeWriter out = new SerializeWriter(); try { JSONSerializer serializer = new JSONSerializer(out); serializer.getPropertyFilters().add(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if ("id".equals(name)) { return false; } return true; } }); serializer.getNameFilters().add(new NameFilter() { public String process(Object source, String name, Object value) { if ("v".equals(name)) { return "value"; } return name; } }); serializer.getValueFilters().add(new ValueFilter() { public Object process(Object source, String name, Object value) { if ("v".endsWith(name)) { return "xxx"; } return value; } }); 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(); } } private static class Entity { private int id; @JSONField(name = "v", serialzeFeatures = { SerializerFeature.WriteMapNullValue }) private String value; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest3.java ================================================ package com.alibaba.json.bvt.parser.deser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.NameFilter; import com.alibaba.fastjson.serializer.PropertyFilter; import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.ValueFilter; public class FieldSerializerTest3 extends TestCase { public void test_writeNull() throws Exception { String text = toJSONString(new Entity()); Assert.assertEquals("{\"v\":\"xxx\"}", text); } public static final String toJSONString(Object object, SerializerFeature... features) { SerializeWriter out = new SerializeWriter(); try { JSONSerializer serializer = new JSONSerializer(out); serializer.getPropertyFilters().add(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if ("id".equals(name)) { return false; } return true; } }); serializer.getNameFilters().add(new NameFilter() { public String process(Object source, String name, Object value) { return name; } }); serializer.getValueFilters().add(new ValueFilter() { public Object process(Object source, String name, Object value) { if ("v".endsWith(name)) { return "xxx"; } return value; } }); 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(); } } private static class Entity { private int id; @JSONField(name = "v", serialzeFeatures = { SerializerFeature.WriteMapNullValue }) private String value; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FieldSerializerTest4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/FloatDeserializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/GetOnlyCollectionTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/HashtableFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/InetAddressDeserializerTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/IntegerDeserializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest.java ================================================ package com.alibaba.json.bvt.parser.deser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class IntegerFieldDeserializerTest extends TestCase { public void test_0() throws Exception { Entity a = JSON.parseObject("{f1:null, f2:null}", Entity.class); Assert.assertEquals(124, 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; public int getF1() { return f1; } public void setF1(int f1) { this.f1 = f1; } public Integer getF2() { return f2; } public void setF2(Integer f2) { this.f2 = f2; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest2.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/IntegerFieldDeserializerTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/IntegerParseTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/InterfaceParseTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/JSONFieldSetterTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/LocaleFieldTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/LocaleTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/LongDeserializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest.java ================================================ package com.alibaba.json.bvt.parser.deser; import java.util.UUID; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; public class LongFieldDeserializerTest extends TestCase { public void test_0() throws Exception { Entity a = JSON.parseObject("{f1:null, f2:null}", Entity.class); Assert.assertEquals(124, 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().longValue()); } public void test_error() throws Exception { JSONException ex = null; try { JSON.parseObject("{f3:44}", UUID.class); } catch (JSONException e) { ex = e; } Assert.assertNotNull(ex); } public static class Entity { private long f1 = 124; private Long f2 = 123L; public long getF1() { return f1; } public void setF1(long f1) { this.f1 = f1; } public Long getF2() { return f2; } public void setF2(Long f2) { this.f2 = f2; } public void setF3(Long v) { throw new RuntimeException(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/LongFieldDeserializerTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/MapDeserializerTest.java ================================================ 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 () { } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/MapTest.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/MultiArrayTest.java ================================================ package com.alibaba.json.bvt.parser.deser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class MultiArrayTest extends TestCase { public void test_0() throws Exception { String[][] array = new String[][] { new String[] { "a", "b" }, new String[] { "c", "d", "e" } }; String text = JSON.toJSONString(array); String[][] array2 = JSON.parseObject(text, String[][].class); Assert.assertEquals("a", array2[0][0]); Assert.assertEquals("b", array2[0][1]); Assert.assertEquals("c", array2[1][0]); Assert.assertEquals("d", array2[1][1]); Assert.assertEquals("e", array2[1][2]); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/MyMapFieldTest.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/NumberDeserializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/NumberDeserializerTest2.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ParseNullTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/PatternDeserializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/PropertyProcessableTest_0.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ResolveFieldDeserializerTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ShortFieldDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_boolean_is.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_snake.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/SmartMatchTest_snake2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/SortedSetFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/SqlDateDeserializerTest.java ================================================ package com.alibaba.json.bvt.parser.deser; import org.junit.Assert; import junit.framework.TestCase; 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.SqlDateDeserializer; public class SqlDateDeserializerTest extends TestCase { public void test_bigdecimal() throws Exception { Assert.assertEquals(1309861159710L, JSON.parseObject("1309861159710", java.sql.Date.class).getTime()); Assert.assertEquals(1309861159710L, JSON.parseObject("1309861159710.0", java.sql.Date.class).getTime()); Assert.assertEquals(1309861159710L, JSON.parseObject("'1309861159710'", java.sql.Date.class).getTime()); Assert.assertEquals(null, JSON.parseObject("null", Integer.class)); 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/SqlDateDeserializerTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/StackTraceElementDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/TestEnum.java ================================================ package com.alibaba.json.bvt.parser.deser; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestEnum extends TestCase { public static enum Type { Big, Medium, Small } public void test_enum() throws Exception { Assert.assertEquals(Type.Big, JSON.parseObject("{value:\"Big\"}", VO.class).getValue()); Assert.assertEquals(Type.Big, JSON.parseObject("{\"value\":\"Big\"}", VO.class).getValue()); Assert.assertEquals(Type.Big, JSON.parseObject("{value:0}", VO.class).getValue()); Assert.assertEquals(Type.Big, JSON.parseObject("{\"value\":0}", VO.class).getValue()); } public static class VO { private Type value; public Type getValue() { return value; } public void setValue(Type value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/TestNull.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ThrowableDeserializerTest.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/ThrowableDeserializerTest_2.java ================================================ 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(){ } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/TimeDeserializerTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/TimeZoneDeserializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/TreeMapDeserializerTest.java ================================================ package com.alibaba.json.bvt.parser.deser; import java.util.TreeMap; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TreeMapDeserializerTest extends TestCase { public void test_0 () throws Exception { TreeMap treeMap = JSON.parseObject("{}", TreeMap.class); Assert.assertEquals(0, treeMap.size()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/TreeSetFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/URIDeserializerTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/URLDeserializerTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/UUIDDeserializerTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldBoolArrayTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldByteArrayTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldDoubleArrayTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArray2Test.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArray2Test_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldFloatArrayTest_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldIntArrayTest_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldLongArrayTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/array/FieldShortArrayTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMappingErrorTest3.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_bool.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_double.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_float.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_long.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_long_stream.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.json.test.benchmark.encode.EishayEncode; public class TestASM extends TestCase { public void test_asm() throws Exception { String text = JSON.toJSONString(EishayEncode.mediaContent); System.out.println(text); } public void test_0() throws Exception { Department department = new Department(); Person person = new Person(); person.setId(123); person.setName("刘伟加"); person.setAge(40); person.setSalary(new BigDecimal("123456")); person.getValues().add("A"); person.getValues().add("B"); person.getValues().add("C"); department.getPersons().add(person); department.getPersons().add(new Person()); department.getPersons().add(new Person()); { String text = JSON.toJSONString(department); System.out.println(text); } { String text = JSON.toJSONString(department, SerializerFeature.WriteMapNullValue); System.out.println(text); } } public static class Person { private int id; private String name; private int age; private BigDecimal salary; private List childrens = new ArrayList(); private List values = new ArrayList(); public List getValues() { return values; } public void setValues(List values) { this.values = values; } 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 BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } public List getChildrens() { return childrens; } public void setChildrens(List childrens) { this.childrens = childrens; } } public static class Department { private int id; private String name; private List persons = new ArrayList(); 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 List getPersons() { return persons; } public void setPersons(List persons) { this.persons = persons; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM2.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; 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.serializer.SerializerFeature; public class TestASM2 extends TestCase { public void test_0() throws Exception { String text = JSON.toJSONString(new V0()); Assert.assertEquals("{}", text); } public void test_1() throws Exception { String text = JSON.toJSONString(new V1()); Assert.assertEquals("{\"list\":[]}", text); } public void test_2() throws Exception { V1 v = new V1(); v.getList().add(3); v.getList().add(4); String text = JSON.toJSONString(v); Assert.assertEquals("{\"list\":[3,4]}", text); } public void test_3() throws Exception { V2 v = new V2(); v.setId(123); v.setName("刘加大"); String text = JSON.toJSONString(v); Assert.assertEquals("{\"id\":123,\"name\":\"刘加大\"}", text); } public void test_4() throws Exception { V2 v = new V2(); v.setId(123); String text = JSON.toJSONString(v); Assert.assertEquals("{\"id\":123}", text); } public void test_7() throws Exception { V2 v = new V2(); v.setId(123); String text = JSON.toJSONString(v, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"id\":123,\"name\":null}", text); } public void test_8() throws Exception { V3 v = new V3(); v.setText("xxx"); String text = JSON.toJSONString(v, SerializerFeature.UseSingleQuotes); Assert.assertEquals("{'text':'xxx'}", text); } public void test_9() throws Exception { V3 v = new V3(); v.setText("xxx"); String text = JSON.toJSONString(v, SerializerFeature.UseSingleQuotes, SerializerFeature.WriteMapNullValue); System.out.println(text); Assert.assertEquals(true, "{'list':null,'text':'xxx'}".equals(text) || "{'text':'xxx','list':null}".equals(text)); } public void f_test_3() throws Exception { V1 v = new V1(); v.getList().add(3); String text = JSON.toJSONString(v, SerializerFeature.UseSingleQuotes); System.out.println(text); } public static class V0 { } public static class V1 { private List list = new ArrayList(); public List getList() { return list; } public void setList(List list) { this.list = list; } } 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; } } public static class V3 { private List list; private String text; public List getList() { return list; } public void setList(List list) { this.list = list; } public String getText() { return text; } public void setText(String text) { this.text = text; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASMEishay.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.json.test.benchmark.encode.EishayEncode; import data.media.MediaContent; public class TestASMEishay extends TestCase { public void test_asm() throws Exception { String text = JSON.toJSONString(EishayEncode.mediaContent, SerializerFeature.WriteEnumUsingToString); System.out.println(text); System.out.println(text.getBytes().length); MediaContent object = JSON.parseObject(text, MediaContent.class); String text2 = JSON.toJSONString(object, SerializerFeature.WriteEnumUsingToString); System.out.println(text2); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_BigDecimal.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; 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 TestASM_BigDecimal extends TestCase { public void test_decimal() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v, SerializerFeature.UseSingleQuotes); Assert.assertEquals("{}", text); } public void test_decimal_1() throws Exception { V0 v = new V0(); v.setDecimal(new BigDecimal("123")); String text = JSON.toJSONString(v, SerializerFeature.UseSingleQuotes); Assert.assertEquals("{'decimal':123}", text); } public void test_decimal_2() throws Exception { V1 v = new V1(); v.setId(123); String text = JSON.toJSONString(v, SerializerFeature.UseSingleQuotes); Assert.assertEquals("{'id':123}", text); } public void test_decimal_3() throws Exception { V1 v = new V1(); v.setId(123); String text = JSON.toJSONString(v, SerializerFeature.UseSingleQuotes, SerializerFeature.WriteMapNullValue); System.out.println(text); Assert.assertEquals("{'decimal':null,'id':123}", text); } public static class V0 { private BigDecimal decimal; public BigDecimal getDecimal() { return decimal; } public void setDecimal(BigDecimal decimal) { this.decimal = decimal; } } public static class V1 { private int id; private BigDecimal decimal; public int getId() { return id; } public void setId(int id) { this.id = id; } public BigDecimal getDecimal() { return decimal; } public void setDecimal(BigDecimal decimal) { this.decimal = decimal; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Byte_0.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_Byte_0 extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v.getI(), v1.getI()); } public static class V0 { private Byte i = 12; public Byte getI() { return i; } public void setI(Byte i) { this.i = i; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Date.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import java.util.Date; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; public class TestASM_Date extends TestCase { public void test_date() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new V0()); Assert.assertEquals("{}", serializer.getWriter().toString()); } public static class V0 { private Date d; public V0(){ } public V0(long value){ super(); this.d = new Date(value); } public Date getD() { return d; } public void setD(Date d) { this.d = d; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Integer.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_Integer extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v.getI(), v1.getI()); } public static class V0 { private Integer i = 12; public Integer getI() { return i; } public void setI(Integer i) { this.i = i; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_List.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; public class TestASM_List extends TestCase { public void test_decimal_3() throws Exception { V0 v = new V0(); v.getList().add(new V1()); v.getList().add(new V1()); String text = JSON.toJSONString(v, SerializerFeature.UseSingleQuotes, SerializerFeature.WriteMapNullValue); System.out.println(text); // Assert.assertEquals("{'list':[{},{}]}", text); } public static class V0 { private List list = new ArrayList(); public List getList() { return list; } public void setList(List list) { this.list = list; } } public static class V1 { private int id; private TimeUnit unit = TimeUnit.SECONDS; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public TimeUnit getUnit() { return unit; } public void setUnit(TimeUnit unit) { this.unit = unit; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Long_0.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_Long_0 extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v.getI(), v1.getI()); } public static class V0 { private Long i = 12L; public Long getI() { return i; } public void setI(Long i) { this.i = i; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Short_0.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_Short_0 extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v.getI(), v1.getI()); } public static class V0 { private Short i = 12; public Short getI() { return i; } public void setI(Short i) { this.i = i; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_boolean.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_boolean extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v.isValue(), v1.isValue()); } public static class V0 { private boolean value = true; public boolean isValue() { return value; } public void setValue(boolean value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_byte.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_byte extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v.getI(), v1.getI()); } public static class V0 { private byte i = 12; public byte getI() { return i; } public void setI(byte i) { this.i = i; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_char.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_char extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v.getValue(), v1.getValue()); } public static class V0 { private char value = '中'; public char getValue() { return value; } public void setValue(char i) { this.value = i; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_double.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_double extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertTrue(v.getValue() == v1.getValue()); } public static class V0 { private double value = 32.5F; public double getValue() { return value; } public void setValue(double i) { this.value = i; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_float.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.fastjson.JSON; public class TestASM_float extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertTrue(v.getValue() == v1.getValue()); } public static class V0 { private float value = 32.5F; public float getValue() { return value; } public void setValue(float i) { this.value = i; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_int.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_int extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v.getI(), v1.getI()); } public static class V0 { private int i = 12; public int getI() { return i; } public V0 setI(int i) { this.i = i; return this; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_long.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_long extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v.getI(), v1.getI()); } public static class V0 { private long i = 12; public long getI() { return i; } public void setI(long i) { this.i = i; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_null.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; 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 TestASM_null extends TestCase { public void test_null() throws Exception { List list = JSON.parseArray("[{\"f1\":\"v1\",\"f2\":\"v2\"},{\"f2\":\"v2\",\"f3\":\"v3\"},{\"f2\":\"v2\",\"f3\":\"v3\"},{\"f1\":\"v1\",\"f3\":\"v3\"}]", VO.class); String text = JSON.toJSONString(list, SerializerFeature.UseSingleQuotes); Assert.assertEquals("[{'f1':'v1','f2':'v2'},{'f2':'v2','f3':'v3'},{'f2':'v2','f3':'v3'},{'f1':'v1','f3':'v3'}]", text); // System.out.println(text); } public void test_null_notmatch() throws Exception { List list = JSON.parseArray("[{\"f3\":\"v3\",\"f2\":\"v2\",\"f1\":\"v1\"}]", VO.class); String text = JSON.toJSONString(list, SerializerFeature.UseSingleQuotes); Assert.assertEquals("[{'f1':'v1','f2':'v2','f3':'v3'}]", text); // System.out.println(text); } public static class VO { private String f1; private String f2; private String f3; public VO(){ } public VO(String f1, String f2, String f3){ super(); this.f1 = f1; this.f2 = f2; this.f3 = f3; } public String getF1() { return f1; } public void setF1(String f1) { this.f1 = f1; } public String getF2() { return f2; } public void setF2(String f2) { this.f2 = f2; } public String getF3() { return f3; } public void setF3(String f3) { this.f3 = f3; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_object.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_object extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v.getValue().getValue(), v1.getValue().getValue()); } public static class V0 { private V1 value = new V1(); public V1 getValue() { return value; } public void setValue(V1 value) { this.value = value; } } public static class V1 { private int value = 1234; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_primitive.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_short.java ================================================ package com.alibaba.json.bvt.parser.deser.asm; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class TestASM_short extends TestCase { public void test_asm() throws Exception { V0 v = new V0(); String text = JSON.toJSONString(v); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v.getI(), v1.getI()); } public static class V0 { private short i = 12; public short getI() { return i; } public void setI(short i) { this.i = i; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/awt/ColorDeserializerTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/awt/FontDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/awt/PointDeserializerTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/awt/PointDeserializerTest2.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/awt/RectangleDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateDeserializerTest.java ================================================ package com.alibaba.json.bvt.parser.deser.date; import java.util.Date; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class DateDeserializerTest extends TestCase { public void test_date() throws Exception { long millis = System.currentTimeMillis(); Assert.assertEquals(new Date(millis), JSON.parseObject("'" + millis + "'", Date.class)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateFormatDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest1.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest10.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest11.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest12.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest13.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest14.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest2.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest3.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest4.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest5.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest6.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest7.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest8.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateParseTest9.java ================================================ package com.alibaba.json.bvt.parser.deser.date; import java.util.Calendar; import java.util.Date; import java.util.Random; import java.util.TimeZone; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.serializer.CalendarCodec; import com.alibaba.fastjson.serializer.SerializerFeature; public class DateParseTest9 extends TestCase { private static Random random = new Random(); private TimeZone original = TimeZone.getDefault(); private String[] zoneIds = TimeZone.getAvailableIDs(); @Override public void setUp() { int index = random.nextInt(zoneIds.length); TimeZone timeZone = TimeZone.getTimeZone(zoneIds[index]); TimeZone.setDefault(timeZone); JSON.defaultTimeZone = timeZone; } @Override public void tearDown () { TimeZone.setDefault(original); JSON.defaultTimeZone = original; } public void test_date() throws Exception { String text = "\"/Date(1242357713797+0800)/\""; Date date = JSON.parseObject(text, Date.class); assertEquals(date.getTime(), 1242357713797L); assertEquals(JSONToken.LITERAL_INT, CalendarCodec.instance.getFastMatchToken()); text = "\"/Date(1242357713797+0545)/\""; date = JSON.parseObject(text, Date.class); assertEquals(date.getTime(), 1242357713797L); 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; } 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; } assertNotNull(error); } public void test_dates_different_timeZones() { Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); VO vo = new VO(); vo.date = now; String json = JSON.toJSONString(vo); VO result = JSON.parseObject(json, VO.class); assertEquals(vo.date, result.date); // with iso-format json = JSON.toJSONString(vo, SerializerFeature.UseISO8601DateFormat); result = JSON.parseObject(json, VO.class); assertEquals(JSON.toJSONString(vo.date), JSON.toJSONString(result.date)); } public static class VO { public Date date; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/date/DateTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest10.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest11.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest12.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest13.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest14.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest15.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest16.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest2.java ================================================ 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); error.printStackTrace(); JSON.parseObject(text, B.class, config, JSON.DEFAULT_PARSER_FEATURE); } public static class B { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest3.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest4.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest5.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest6.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest7.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest8.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/DenyTest9.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/deny/InitJavaBeanDeserializerTest.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/extra/ExtraTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/ByteListTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest2.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest3.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest4.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericArrayTest5.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericMap.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest3.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/GenericTest5.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/generic/ListStrFieldTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayLisMapDeserializerTest.java ================================================ package com.alibaba.json.bvt.parser.deser.list; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; public class ArrayLisMapDeserializerTest extends TestCase { public void test_list() throws Exception { Entity a = JSON.parseObject("{items:[{}, {a:1}, null]}", Entity.class); Assert.assertEquals(0, a.getItems().get(0).size()); Assert.assertEquals(1, a.getItems().get(1).size()); Assert.assertEquals(null, a.getItems().get(2)); } public void test_list_2() throws Exception { List list = JSON.parseObject("[{}, {a:1}, null]", new TypeReference>() {}); Assert.assertEquals(0, list.get(0).size()); Assert.assertEquals(1, list.get(1).size()); Assert.assertEquals(null, list.get(2)); } public static class Entity { private List items = new ArrayList(); public List getItems() { return items; } public void setItems(List items) { this.items = items; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListEnumFieldDeserializerTest.java ================================================ package com.alibaba.json.bvt.parser.deser.list; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class ArrayListEnumFieldDeserializerTest extends TestCase { public void test_enums() throws Exception { Entity a = JSON.parseObject("{units:['NANOSECONDS', 'SECONDS', 3, null]}", Entity.class); Assert.assertEquals(TimeUnit.NANOSECONDS, a.getUnits().get(0)); } public static class Entity { private List units = new ArrayList(); public List getUnits() { return units; } public void setUnits(List units) { this.units = units; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListStringDeserializerTest.java ================================================ package com.alibaba.json.bvt.parser.deser.list; import java.lang.reflect.Type; 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.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.TypeReference; 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); Assert.assertEquals("NANOSECONDS", a.getUnits().get(0)); Assert.assertEquals("SECONDS", a.getUnits().get(1)); Assert.assertEquals("3", a.getUnits().get(2)); Assert.assertEquals(null, a.getUnits().get(3)); } public void test_strings_() throws Exception { Entity a = JSON.parseObject("{units:['NANOSECONDS',,,, 'SECONDS', 3, null]}", Entity.class); Assert.assertEquals("NANOSECONDS", a.getUnits().get(0)); Assert.assertEquals("SECONDS", a.getUnits().get(1)); Assert.assertEquals("3", a.getUnits().get(2)); Assert.assertEquals(null, a.getUnits().get(3)); } public void test_strings_2() throws Exception { List list = JSON.parseObject("['NANOSECONDS', 'SECONDS', 3, null]", new TypeReference>() { }); Assert.assertEquals("NANOSECONDS", list.get(0)); Assert.assertEquals("SECONDS", list.get(1)); Assert.assertEquals("3", list.get(2)); Assert.assertEquals(null, list.get(3)); } public void test_strings_3() throws Exception { List list = JSON.parseObject("['NANOSECONDS', 'SECONDS', 3, null]", new TypeReference>() { }.getType(), 0, Feature.AllowSingleQuotes); Assert.assertEquals("NANOSECONDS", list.get(0)); Assert.assertEquals("SECONDS", list.get(1)); Assert.assertEquals("3", list.get(2)); Assert.assertEquals(null, list.get(3)); } public void test_string_error_not_eof() throws Exception { JSONException ex = null; try { JSON.parseObject("[}", new TypeReference>() { }.getType(), 0, Feature.AllowSingleQuotes); } catch (JSONException e) { ex = e; } Assert.assertNotNull(ex); } public void test_string_error() throws Exception { JSONException ex = null; try { JSON.parseObject("'123'", new TypeReference>() { }); } catch (JSONException e) { ex = e; } Assert.assertNotNull(ex); } public void test_string_error_1() throws Exception { JSONException ex = null; try { parseObject("{units:['NANOSECONDS',,,, 'SECONDS', 3, null]}", Entity.class); } catch (JSONException e) { ex = e; } Assert.assertNotNull(ex); } public static final T parseObject(String input, Type clazz, Feature... features) { if (input == null) { return null; } int featureValues = 0; for (Feature feature : features) { featureValues = Feature.config(featureValues, feature, true); } DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues); T value = (T) parser.parseObject(clazz); if (clazz != JSONArray.class) { parser.close(); } return (T) value; } public static class Entity { private List units = new ArrayList(); public List getUnits() { return units; } public void setUnits(List units) { this.units = units; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListTypeDeserializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ArrayListTypeFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListFieldTest.java ================================================ package com.alibaba.json.bvt.parser.deser.list; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class ListFieldTest extends TestCase { public void test_for_list() throws Exception { JSON.parseObject("{'data':['a','b']}", TestPojo.class); } public static class TestPojo{ public java.util.List getData(){ return null; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_array_big.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_createError.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_array.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_array_2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_hashSet.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_dom_treeSet.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_TreeSet.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_array.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_array_2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/list/ListStringFieldTest_stream_hashSet.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/nonctor/NonDefaultConstructorTest0.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderBooleanFieldTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderIntFieldTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/stream/ReaderLongFieldTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/deser/var/TwoTypeTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/JSONReaderError.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_10.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_11.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_12.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_13.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_14.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_15.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_16.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_17.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_18.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_19.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_20.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_21.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_8.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_9.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/ParseErrorTest_date.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/error/TypeNotMatchError.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/fieldTypeResolver/FieldTypeResolverTest.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberEmtpyObjectTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest2.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest3.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest4.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_0.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_1.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_10.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_11.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_12.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_13.java ================================================ package com.alibaba.json.bvt.parser.number; import com.alibaba.fastjson.*; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; import org.junit.Assert; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Timestamp; import java.util.concurrent.TimeUnit; public class NumberValueTest_error_13 extends TestCase { public void test_0() throws Exception { Exception error = null; try { JSON.parseObject("{\"v0\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertTrue(error.getCause() instanceof ArithmeticException); } public void test_1() throws Exception { Exception error = null; try { JSON.parseObject("{\"v1\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertTrue(error.getCause() instanceof ArithmeticException); } public void test_2() throws Exception { Exception error = null; try { JSON.parseObject("{\"v2\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertTrue(error.getCause() instanceof ArithmeticException); } public void test_3() throws Exception { Exception error = null; try { JSON.parseObject("{\"v3\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertTrue(error.getCause() instanceof ArithmeticException); } public void test_4() throws Exception { BigDecimal b = new BigDecimal("49e999999999"); assertEquals("4.9E+1000000000", JSON.toJSONString(b, SerializerFeature.WriteBigDecimalAsPlain)); assertEquals("{\"val\":4.9E+1000000000}", JSON.toJSONString(new M1(b), SerializerFeature.WriteBigDecimalAsPlain)); } public void test_5() throws Exception { Exception error = null; try { JSON.parseObject("{\"v5\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertTrue(error.getCause() instanceof ArithmeticException); } public void test_6() throws Exception { Exception error = null; try { JSON.parseObject("{\"v6\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertTrue(error.getCause() instanceof ArithmeticException); } public void test_7() throws Exception { Exception error = null; try { JSON.parseObject("{\"v7\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertTrue(error.getCause() instanceof ArithmeticException); } public void test_8() throws Exception { Exception error = null; try { JSON.parseObject("{\"v8\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertEquals(NumberFormatException.class, error.getCause().getClass()); } public void test_9() throws Exception { Exception error = null; try { JSON.parseObject("{\"v9\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertEquals(ArithmeticException.class, error.getCause().getClass()); } public void test_10() throws Exception { Exception error = null; try { JSON.parseObject("{\"v10\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertEquals(ArithmeticException.class, error.getCause().getClass()); } public void test_11() throws Exception { Exception error = null; try { JSON.parseObject("{\"v11\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertEquals(ArithmeticException.class, error.getCause().getClass()); } public void test_11_new() throws Exception { Exception error = null; try { JSON.parseObject("{\"v11\":new Date(49e99999999)}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); } public void test_12() throws Exception { Exception error = null; try { JSON.parseObject("{\"v12\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertEquals(ArithmeticException.class, error.getCause().getClass()); } public void test_13() throws Exception { Exception error = null; try { JSON.parseObject("{\"v13\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertEquals(ArithmeticException.class, error.getCause().getClass()); } public void test_14() throws Exception { Exception error = null; try { JSON.parseObject("{\"v14\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); assertEquals(UnsupportedOperationException.class, error.getCause().getClass()); } public void test_15() throws Exception { Exception error = null; try { JSON.parseObject("{\"v15\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); } public void test_16() throws Exception { Exception error = null; try { JSON.parseObject("{\"v16\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); } public void test_17() throws Exception { Exception error = null; try { JSON.parseObject("{\"v17\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); } public void test_17_1() throws Exception { Exception error = null; try { JSONObject jsonObject = JSON.parseObject("{\"v17\":49e99999999}"); jsonObject.getObject("v17", TimeUnit.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); } public void test_18() throws Exception { Exception error = null; try { JSON.parseObject("{\"v18\":49e99999999}", Model.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); } public void test_20() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"v\":49e99999999}"); Exception error = null; try { jsonObject.getIntValue("v"); } catch (ArithmeticException ex) { error = ex; } assertNotNull(error); } public void test_21() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"v\":49e99999999}"); Exception error = null; try { jsonObject.getDate("v"); } catch (ArithmeticException ex) { error = ex; } assertNotNull(error); } public void test_22() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"v\":49e99999999}"); Exception error = null; try { jsonObject.getObject("v", java.sql.Date.class); } catch (ArithmeticException ex) { error = ex; } assertNotNull(error); } public void test_23() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"v\":49e99999999}"); Exception error = null; try { jsonObject.getObject("v", java.sql.Timestamp.class); } catch (ArithmeticException ex) { error = ex; } assertNotNull(error); } public void test_24() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"v\":49e99999999}"); Exception error = null; try { jsonObject.getObject("v", java.time.LocalDateTime.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); } public void test_25() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"lineNumber\":49e99999999}"); Exception error = null; try { jsonObject.toJavaObject(StackTraceElement.class); } catch (JSONException ex) { error = ex; } assertNotNull(error); } public void test_26() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"v\":49e99999999}"); Exception error = null; try { jsonObject.getObject("v", java.sql.Time.class); } catch (ArithmeticException ex) { error = ex; } assertNotNull(error); } public void test_jsonpath() throws Exception { JSONObject jsonObject = JSON.parseObject("{\"v\":0}"); Exception error = null; try { JSONPath.eval(jsonObject, "$.v in (49e99999999)"); } catch (JSONPathException ex) { error = ex; } assertNotNull(error); } public void test_jsonpath_1() throws Exception { JSONArray jsonObject = JSON.parseArray("[{\"v\":49e99999999}]"); JSONPath.eval(jsonObject, "[v=0]"); } public void test_jsonpath_2() throws Exception { Model[] array = JSON.parseObject("[{\"v2\":0}]", Model[].class); JSONPath.eval(array, "[v='49e99999999']"); } public void test_jsonpath_3() throws Exception { Model[] array = JSON.parseObject("[{\"v2\":0}]", Model[].class); Exception error = null; try { JSONPath.read("{\"a\":49e9999999}","[a in (123,2,3)]"); } catch (Exception ex) { error = ex; } assertNotNull(error); } public void test_jsonpath_4() throws Exception { Model[] array = JSON.parseObject("[{\"v2\":0}]", Model[].class); Exception error = null; try { JSONPath.read("{\"a\":49e9999999}","[a between 1 and 3]"); } catch (Exception ex) { error = ex; } assertNotNull(error); } public void test_27() throws Exception { JSONObject object = JSON.parseObject("{\n" + " \"connection_health\": {\"status\": \"good\", \"max_value\": 2.0, \"min_value\": 2.0, \"average_value\": 2.0}, \n" + " \"qps_health\": {\"status\": \"good\", \"max_value\": 5.3, \"min_value\": 4.29, \"average_value\": 4.6},\n" + " \"disksize_health\": {\"status\": \"good\", \"max_value\": 3089.0, \"min_value\": 3089.0, \"average_value\": 3089.0},\n" + " \"cpu_health\": {\"status\": \"good\", \"max_value\": 0.0, \"min_value\": 0.0, \"average_value\": 0.0}, \n" + " \"memory_health\": {\"status\": \"good\", \"max_value\": 17.1, \"min_value\": 17.1, \"average_value\": 17.1}, \n" + " \"iops_health\": {\"status\": \"good\", \"max_value\": 0.09, \"min_value\": 0.07, \"average_value\": 0.08}\n" + "}"); for(String key : object.keySet()) { System.out.println("key = " + key); System.out.println("vaue = " + object.getJSONObject(key).getIntValue("max_value")); } } public static class Model { public byte v0; public short v1; public int v2; public long v3; public Byte v4; public Short v5; public Integer v6; public Long v7; public BigInteger v8; public Timestamp v9; public java.sql.Date v10; public java.util.Date v11; public java.util.Calendar v12; public java.sql.Timestamp v13; public java.time.LocalDateTime v14; public boolean v15; public Boolean v16; public TimeUnit v17; public java.sql.Time v18; } public static class M1 { public BigDecimal val; public M1(BigDecimal val) { this.val = val; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_2.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_3.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_4.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_5.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_6.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_7.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_8.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/number/NumberValueTest_error_9.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/str/EmptyStringTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/str/StringTest_00.java ================================================ 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'); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/str/StringTest_01.java ================================================ 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'); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/str/StringTest_02.java ================================================ 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'); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_boolean.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_chars.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_enum.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_matchField.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_negative.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderScannerTest_type.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_0.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_1.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_2.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_3.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_4.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_5.java ================================================ package com.alibaba.json.bvt.parser.stream; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONReader; import junit.framework.TestCase; import org.junit.Assert; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.util.HashMap; import java.util.Map; public class JSONReaderTest_5 extends TestCase { public void test_read() throws Exception { final int COUNT = 1000 * 10; StringBuilder buf = new StringBuilder(); buf.append('['); for (int i = 0; i < COUNT; ++i) { if (i != 0) { buf.append(','); } buf.append("{\"id\":").append(i).append('}'); } buf.append(']'); JSONReader reader = new JSONReader(new StringReader(buf.toString())); reader.startArray(); Map map = new HashMap(); int count = 0; for (;;) { if (reader.hasNext()) { reader.startObject(); String key = reader.readString(); Long value = reader.readLong(); reader.endObject(); count++; } else { break; } } assertEquals(COUNT, count); reader.endArray(); reader.close(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_error.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_error2.java ================================================ 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(); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_array.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_map.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj_2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_obj_3.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_string.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_string_1.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/stream/JSONReader_typeRef.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/taobao/BooleanObjectFieldTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/taobao/DoubleObjectFieldTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/taobao/FloatObjectFieldTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/taobao/IntAsStringTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/taobao/IntegerAsStringTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/taobao/LongAsStringTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/taobao/LongObjectAsStringTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/parser/taobao/SpecialStringTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/BookEvalTest.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.util.IOUtils; import junit.framework.TestCase; import java.io.InputStream; import java.io.InputStreamReader; public class BookEvalTest extends TestCase { private JSONObject root; protected void setUp() throws Exception { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/book.json"); InputStreamReader reader = new InputStreamReader(is); String json = IOUtils.readAll(reader); IOUtils.close(reader); root = (JSONObject) JSON.parse(json, Feature.OrderedField); } public void test_0() throws Exception { assertEquals(4, JSONPath.eval(root, "$..book.length()")); } public void test_1() throws Exception { assertEquals("[\"reference\",\"Nigel Rees\",\"Sayings of the Century\",8.95,\"fiction\",\"Evelyn Waugh\",\"Sword of Honour\",12.99,\"fiction\",\"Herman Melville\",\"Moby Dick\",\"0-553-21311-3\",8.99,\"fiction\",\"J. R. R. Tolkien\",\"The Lord of the Rings\",\"0-395-19395-8\",22.99,\"red\",19.95,10]" , JSON.toJSONString(JSONPath.eval(root, "$..*"))); } public void test_2() throws Exception { assertEquals("[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]", JSON.toJSONString(JSONPath.eval(root, "$.store.book[*].author"))); } public void test_3() throws Exception { assertEquals("[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]", JSON.toJSONString(JSONPath.eval(root, "$..author"))); } public void test_4() throws Exception { assertEquals("[8.95,12.99,8.99,22.99,19.95]", JSON.toJSONString(JSONPath.eval(root, "$..price"))); } public void test_5() throws Exception { assertEquals("[8.95,12.99,8.99,22.99]", JSON.toJSONString(JSONPath.eval(root, "$..book.price"))); } public void test_6() throws Exception { assertEquals("[[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":22.99}],{\"color\":\"red\",\"price\":19.95}]" , JSON.toJSONString(JSONPath.eval(root, "$.store.*"))); } public void test_7() throws Exception { assertEquals("[8.95,12.99,8.99,22.99,19.95]" , JSON.toJSONString(JSONPath.eval(root, "$.store..price"))); } public void test_8() throws Exception { assertEquals("{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}" , JSON.toJSONString(JSONPath.eval(root, "$..book[2]"))); } public void test_9() throws Exception { assertEquals("{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":22.99}" , JSON.toJSONString(JSONPath.eval(root, "$..book[-1]"))); } public void test_10() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}]" , JSON.toJSONString(JSONPath.eval(root, "$..book[0,1]"))); } public void test_11() throws Exception { assertEquals("[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":22.99}]" , JSON.toJSONString(JSONPath.eval(root, "$..book[?(@.isbn)]"))); } public void test_12() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}]" , JSON.toJSONString(JSONPath.eval(root, "$.store.book[?(@.price < 10)]"))); } public void test_13() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}]" , JSON.toJSONString(JSONPath.eval(root, "$..book[?(@.price <= $['expensive'])]"))); } public void test_14() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95}]" , JSON.toJSONString(JSONPath.eval(root, "$..book[?(@.author =~ /.*REES/i)]"))); } public void test_15() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95}]" , JSON.toJSONString(JSONPath.eval(root, "$..book[?(@.author =~ /.*REES/i)]"))); } public void test_16() throws Exception { assertEquals("[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}]" , JSON.toJSONString(JSONPath.eval(root, "$.store.book[?(@.price < 10 && @.category == 'fiction')]"))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/BookExtractTest.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.util.IOUtils; import junit.framework.TestCase; import java.io.InputStream; import java.io.InputStreamReader; public class BookExtractTest extends TestCase { private String json; protected void setUp() throws Exception { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/book.json"); InputStreamReader reader = new InputStreamReader(is); json = IOUtils.readAll(reader); IOUtils.close(reader); } public void test_0() throws Exception { assertEquals(4, JSONPath.extract(json, "$..book.length()")); } public void test_1() throws Exception { assertEquals("[\"reference\",\"Nigel Rees\",\"Sayings of the Century\",8.95,\"fiction\",\"Evelyn Waugh\",\"Sword of Honour\",12.99,\"fiction\",\"Herman Melville\",\"Moby Dick\",\"0-553-21311-3\",8.99,\"fiction\",\"J. R. R. Tolkien\",\"The Lord of the Rings\",\"0-395-19395-8\",22.99,\"red\",19.95,10]" , JSON.toJSONString(JSONPath.extract(json, "$..*"))); } public void test_2() throws Exception { assertEquals("[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]", JSON.toJSONString(JSONPath.extract(json, "$.store.book[*].author"))); } public void test_3() throws Exception { assertEquals("[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]", JSON.toJSONString(JSONPath.extract(json, "$..author"))); } public void test_4() throws Exception { assertEquals("[8.95,12.99,8.99,22.99,19.95]", JSON.toJSONString(JSONPath.extract(json, "$..price"))); } public void test_5() throws Exception { assertEquals("[8.95,12.99,8.99,22.99]", JSON.toJSONString(JSONPath.extract(json, "$..book.price"))); } public void test_6() throws Exception { assertEquals("[[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":22.99}],{\"color\":\"red\",\"price\":19.95}]" , JSON.toJSONString(JSONPath.extract(json, "$.store.*"))); } public void test_7() throws Exception { assertEquals("[8.95,12.99,8.99,22.99,19.95]" , JSON.toJSONString(JSONPath.extract(json, "$.store..price"))); } public void test_8() throws Exception { assertEquals("{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}" , JSON.toJSONString(JSONPath.extract(json, "$..book[2]"))); } public void test_9() throws Exception { assertEquals("{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":22.99}" , JSON.toJSONString(JSONPath.extract(json, "$..book[-1]"))); } public void test_10() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}]" , JSON.toJSONString(JSONPath.extract(json, "$..book[0,1]"))); } public void test_11() throws Exception { assertEquals("[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":22.99}]" , JSON.toJSONString(JSONPath.extract(json, "$..book[?(@.isbn)]"))); } public void test_12() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}]" , JSON.toJSONString(JSONPath.extract(json, "$.store.book[?(@.price < 10)]"))); } public void test_13() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}]" , JSON.toJSONString(JSONPath.extract(json, "$..book[?(@.price <= $['expensive'])]"))); } public void test_14() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95}]" , JSON.toJSONString(JSONPath.extract(json, "$..book[?(@.author =~ /.*REES/i)]"))); } public void test_15() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95}]" , JSON.toJSONString(JSONPath.extract(json, "$..book[?(@.author =~ /.*REES/i)]"))); } public void test_16() throws Exception { assertEquals("[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}]" , JSON.toJSONString(JSONPath.extract(json, "$.store.book[?(@.price < 10 && @.category == 'fiction')]"))); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/DLATest_0.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.util.IOUtils; import junit.framework.TestCase; import java.io.InputStream; import java.io.InputStreamReader; public class DLATest_0 extends TestCase { public void test_dla() throws Exception { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/dla_01.json"); InputStreamReader reader = new InputStreamReader(is); String json = IOUtils.readAll(reader); Object object = JSON.parse(json, Feature.IgnoreAutoType, Feature.OrderedField); Object result = JSONPath.eval(object, "$..elapsedTime"); assertEquals("[\"1.48s\",1031,1031,1005,1005,1011,1011]", JSON.toJSONString(result)); Object result2 = JSONPath.eval(object, "$..self"); assertEquals("[\"http://172.17.246.55:10001/v1/query/20181024_040507_3_f32vb\",\"http://172.17.246.55:10001/v1/stage/20181024_040507_3_f32vb.0\",\"http://172.17.246.56:14005/v1/task/20181024_040507_3_f32vb.0.0?shufferNettyServerPort=39524&commandNettyServerPort=37207\",\"http://172.17.246.55:10001/v1/stage/20181024_040507_3_f32vb.1\",\"http://172.17.246.55:14005/v1/task/20181024_040507_3_f32vb.1.0?shufferNettyServerPort=33921&commandNettyServerPort=45121\",\"http://172.17.246.56:14005/v1/task/20181024_040507_3_f32vb.1.1?shufferNettyServerPort=39524&commandNettyServerPort=37207\"]", JSON.toJSONString(result2)); } public void test_dla_extract() throws Exception { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/dla_01.json"); InputStreamReader reader = new InputStreamReader(is); String json = IOUtils.readAll(reader); Object result = JSONPath.extract(json, "$..elapsedTime"); assertEquals("[\"1.48s\",1031,1031,1005,1005,1011,1011]", JSON.toJSONString(result)); Object result2 = JSONPath.extract(json, "$..self"); assertEquals("[\"http://172.17.246.55:10001/v1/query/20181024_040507_3_f32vb\",\"http://172.17.246.55:10001/v1/stage/20181024_040507_3_f32vb.0\",\"http://172.17.246.56:14005/v1/task/20181024_040507_3_f32vb.0.0?shufferNettyServerPort=39524&commandNettyServerPort=37207\",\"http://172.17.246.55:10001/v1/stage/20181024_040507_3_f32vb.1\",\"http://172.17.246.55:14005/v1/task/20181024_040507_3_f32vb.1.0?shufferNettyServerPort=33921&commandNettyServerPort=45121\",\"http://172.17.246.56:14005/v1/task/20181024_040507_3_f32vb.1.1?shufferNettyServerPort=39524&commandNettyServerPort=37207\"]", JSON.toJSONString(result2)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/DeepScanTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_0.java ================================================ 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("$").extract(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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_1.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_10_contains.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; public class JSONPath_10_contains extends TestCase { public void test(){ String json = "{\n" + " \"queryScene\":{\n" + " \"scene\":[\n" + " {\n" + " \"innerSceneId\":3,\n" + " \"name\":\"场景绑8测试-笑幽\",\n" + " \"sceneSetId\":8,\n" + " \"formInfo\":\"{}\",\n" + " \"queryDataSet\":{\n" + " \"dataSet\":[\n" + " {\n" + " \"id\":6,\n" + " \"sceneId\":3,\n" + " \"name\":\"测试商品集\",\n" + " \"dataSetRuleCode\":null,\n" + " \"resourceId\":null,\n" + " \"udsOffer\":{\n" + " \"offer\":[\n" + "\n" + " ]\n" + " }\n" + " },\n" + " {\n" + " \"id\":5,\n" + " \"sceneId\":3,\n" + " \"name\":\"测试卖家集\",\n" + " \"dataSetRuleCode\":null,\n" + " \"resourceId\":null,\n" + " \"udsOffer\":{\n" + " \"offer\":[\n" + "\n" + " ]\n" + " }\n" + " }\n" + " ]\n" + " }\n" + " }\n" + " ]\n" + " }\n" + "}"; assertTrue(JSONPath.contains(JSON.parseObject(json), "$.queryScene.scene.queryDataSet.dataSet")); assertFalse(JSONPath.contains(JSON.parseObject(json), "$.queryScene.scene.queryDataSet.dataSet.abcd")); assertTrue(JSONPath.contains(JSON.parseObject(json), "$.queryScene.scene.queryDataSet.dataSet.name")); } // public void test_path_2() throws Exception { //// File file = new File("/Users/wenshao/Downloads/test"); //// String json = FileUtils.readFileToString(file); // String json = "{\"returnObj\":[{\"$ref\":\"$.subInvokes.com\\\\.alipay\\\\.cif\\\\.user\\\\.UserInfoQueryService\\\\@findUserInfosByCardNo\\\\(String[])[0].response[0]\"}]}"; // JSON.parseObject(json); // } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_11.java ================================================ package com.alibaba.json.bvt.path; 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_11 extends TestCase { public void test(){ String json = "[\n" + " [\n" + " {\n" + " \"CN\": \"t1c1CN\",\n" + " \"FP\": \"t1c1FP\"\n" + " },\n" + " {\n" + " \"CN\": \"t1c2CN\",\n" + " \"FP\": \"t1c2FP\"\n" + " }\n" + " ],\n" + " [\n" + " {\n" + " \"CN\": \"t2c1CN\",\n" + " \"FP\": \"t2c1FP\"\n" + " },\n" + " {\n" + " \"CN\": \"t2c2CN\",\n" + " \"FP\": \"t2c2FP\"\n" + " }\n" + " ]\n" + "]"; JSONArray array = JSON.parseArray(json); System.out.println(JSONPath.eval(array, "$[0,1][CN='t1c1CN']")); } // public void test_path_2() throws Exception { //// File file = new File("/Users/wenshao/Downloads/test"); //// String json = FileUtils.readFileToString(file); // String json = "{\"returnObj\":[{\"$ref\":\"$.subInvokes.com\\\\.alipay\\\\.cif\\\\.user\\\\.UserInfoQueryService\\\\@findUserInfosByCardNo\\\\(String[])[0].response[0]\"}]}"; // JSON.parseObject(json); // } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_12.java ================================================ package com.alibaba.json.bvt.path; 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_12 extends TestCase { public void test(){ JSONObject schemaResult = JSON.parseObject("{\n" + " \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n" + " \"title\": \"AE product schema\",\n" + " \"description\": \"AE product schema\",\n" + " \"type\": \"object\",\n" + " \"required\": [\n" + " \"category_attributes\"\n" + " ],\n" + " \"properties\": {\n" + " \"category_attributes\": {\n" + " \"title\": \"category attributes\",\n" + " \"type\": \"object\",\n" + " \"required\": [\n" + " \"Brand Name\"\n" + " ],\n" + " \"properties\":{}\n" + " }\n" + " }\n" + "}"); String jsonPath = "$['properties']['category_attributes']['properties']"; String attributeName = "Brand\\. Name"; // attribute name with dot JSONObject attributeValue = JSON.parseObject("{\n" + " \"title\": \"Brand Name\",\n" + " \"type\": \"String\"\n" + "}"); assertTrue( JSONPath.set(schemaResult, jsonPath + "['" + attributeName + "']" , attributeValue) ); assertTrue(JSONPath.contains(schemaResult, jsonPath + "['" + attributeName + "']")); JSONObject newAttribute = (JSONObject)JSONPath.eval(schemaResult, jsonPath); System.out.println(schemaResult); System.out.println(JSONPath.read(schemaResult.toJSONString(), jsonPath + "['" + attributeName + "']")); assertTrue(newAttribute.containsKey("Brand. Name")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_13.java ================================================ 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; public class JSONPath_13 extends TestCase { public void test_0() { JSONObject root = new JSONObject(); root.put("company", new JSONObject()); root.getJSONObject("company").put("id", 123); root.getJSONObject("company").put("name", "jobs"); JSONPath.remove(root, "$..id"); assertEquals("{\"company\":{\"name\":\"jobs\"}}", root.toJSONString()); } public void test_1() { Root root = new Root(); root.company = new Company(); root.company.id = 123; root.company.name = "jobs"; JSONPath.remove(root, "$..id"); assertEquals("{\"company\":{\"name\":\"jobs\"}}", JSON.toJSONString(root)); } public static class Root { public Company company; } public static class Company { public Integer id; public String name; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_14.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; public class JSONPath_14 extends TestCase { public void test_0() { JSONObject sourceJson = JSON.parseObject("{\n" + "\t\"boolean1\":true,\n" + "\t\"boolean2\":false,\n" + "\t\"boolean3\":true,\n" + "\t\"boolean4\":true,\n" + "\t\"name\":\"str\",\n" + "\t\"name1\":\"str\"\n" + "}"); sourceJson.put("enum1", TimeUnit.SECONDS); sourceJson.put("character1", 'A'); sourceJson.put("uuid1", UUID.randomUUID()); // 初始配置中,新增的字段添加的库中 Map paths = JSONPath.paths(sourceJson); System.out.println(JSON.toJSONString(paths)); assertEquals(10, paths.size()); JSONObject destJson = JSON.parseObject("{\n" + "\t\"boolean1\":true,\n" + "\t\"boolean2\":false,\n" + "\t\"name\":\"str\"\n" + "}"); for (Map.Entry stringObjectEntry : paths.entrySet()) { if(stringObjectEntry.getValue() instanceof JSONObject || stringObjectEntry.getValue() instanceof JSONArray){ continue; } if (!JSONPath.contains(destJson, stringObjectEntry.getKey())) { JSONPath.set(destJson, stringObjectEntry.getKey(), stringObjectEntry.getValue()); System.out.println("key=" + stringObjectEntry.getKey() + " ,value=" + stringObjectEntry.getValue()); } } System.out.println(destJson.toJSONString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_15.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; public class JSONPath_15 extends TestCase { final static String a = "{code:1,msg:'Hello world',data:{list:[1,2,3,4,5], ary2:[{a:2},{a:3,b:{c:'ddd'}}]}}"; final static String b = "[{b:{c:1}}, {b:{d:1}}, {b:{c:2}}, {b:{c:23}}]"; final static String c = "[{c:'aaaa'}, {b:'cccc'}, {c:'cccaa'}]"; public void test_0() { JSONObject object = JSON.parseObject(a); List items = (List) JSONPath.eval(object, "data.ary2[*].b.c"); assertEquals("[\"ddd\"]", JSON.toJSONString(items)); } public void test_1() { Object object = JSON.parse(b); List items = (List) JSONPath.eval(object, "$..b[?(@.c == 23)]"); assertEquals("[{\"c\":23}]", JSON.toJSONString(items)); } public void test_2() { Object object = JSON.parse(b); Object min = JSONPath.eval(object, "$..c.min()"); assertEquals("1", JSON.toJSONString(min)); } public void test_3() { Object object = JSON.parse(c); Object min = JSONPath.eval(object, "$[?(@.c =~ /a+/)]"); assertEquals("[{\"c\":\"aaaa\"}]", JSON.toJSONString(min)); } // // public void test_c() { // Object object = JSON.parse(c); // // Object min = JSONPath.eval(object, "data.list[?(@ in $..ary2[0].a)]"); // assertEquals("[{\"c\":\"aaaa\"}]", JSON.toJSONString(min)); // } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_16.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import java.util.concurrent.TimeUnit; public class JSONPath_16 extends TestCase { public void test_for_jsonpath() throws Exception { String str = "[{\"id\":1001,\"salary\":4000,\"name\":\"jobs\",\"valid\":false},{\"id\":1001,\"salary\":5000}]"; System.out.println(str); assertEquals(2 , JSONPath.extract(str, "$.size()")); assertEquals("array" , JSONPath.extract(str, "$.type()")); assertEquals("object" , JSONPath.extract(str, "$[0].type()")); assertEquals("number" , JSONPath.extract(str, "$[0].id.type()")); assertEquals("string" , JSONPath.extract(str, "$[0].name.type()")); assertEquals("boolean" , JSONPath.extract(str, "$[0].valid.type()")); assertEquals("null" , JSONPath.extract(str, "$[0].xx.type()")); } public void test_for_jsonpath_type() throws Exception { JSONObject root = new JSONObject(); root.put("id", UUID.randomUUID()); root.put("unit", TimeUnit.SECONDS); assertEquals("string" , JSONPath.eval(root, "$.id.type()")); assertEquals("string" , JSONPath.eval(root, "$.unit.type()")); } public void test_for_jsonpath_1() throws Exception { String str = "{\"id\":1001,\"salary\":4000}"; assertNull( JSONPath.extract(str, "$?( @.salary > 100000 )")); assertEquals(JSON.parseObject(str, Feature.OrderedField), JSONPath.extract(str, "$?( @.salary > 1000 )")); } public void test_for_jsonpath_2() throws Exception { String str = "[[10,20],[100],{\"id\":1001}]"; Object object = JSONPath.extract(str, "$.* ? (@.type() == \"array\")"); assertEquals("[[10,20],[100]]", JSON.toJSONString(object)); } public void test_for_jsonpath_3() throws Exception { String str = "[[10,20],[100],{\"id\":1001}]"; Object object = JSONPath.extract(str, "$.* ? (@.type() == \"array\" && @.size() > 1)"); assertEquals("[[10,20]]", JSON.toJSONString(object)); } public void test_for_jsonpath_4() throws Exception { String str = "{ readings: [15.2, -22.3, 45.9] }"; Object object = JSONPath.extract(str, "$.readings.floor()"); assertEquals("[15,-23,45]", JSON.toJSONString(object)); } public void test_for_jsonpath_5() throws Exception { String str = "{ readings: [15.2, 13, -22.3, 45.9] }"; assertEquals(BigDecimal.valueOf(15), JSONPath.extract(str, "$.readings[0].floor()")); assertEquals(13, JSONPath.extract(str, "$.readings[1].floor()")); } public void test_for_jsonpath_6() throws Exception { JSONArray array = new JSONArray(); array.add(1.1F); array.add(2.2D); array.add((byte) 3); array.add((short) 4); array.add(5); array.add(6L); array.add(BigInteger.valueOf(7)); assertEquals(1D, JSONPath.eval(array, "$[0].floor()")); assertEquals(2D, JSONPath.eval(array, "$[1].floor()")); assertEquals((byte) 3, JSONPath.eval(array, "$[2].floor()")); assertEquals((short) 4, JSONPath.eval(array, "$[3].floor()")); assertEquals(5, JSONPath.eval(array, "$[4].floor()")); assertEquals(6L, JSONPath.eval(array, "$[5].floor()")); assertEquals(BigInteger.valueOf(7), JSONPath.eval(array, "$[6].floor()")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_17.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import java.util.UUID; import java.util.concurrent.TimeUnit; public class JSONPath_17 extends TestCase { public void test_for_jsonpath() throws Exception { String input = "{\"b\":[{\"c\":{\"d\":{\"e\":\"978\"}},\"f\":{\"c\":{\"d\":{\"$ref\":\"$.b[0].c.d\"}}}}]}"; Object obj = JSON.parse(input); String oupput = JSON.parse(input).toString(); assertEquals(obj, JSON.parse(oupput)); } public void test_for_jsonpath_1() throws Exception { assertEquals("[5]", JSONPath.extract("[1, 2, 3, 4, 5]", "$[last]").toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_2.java ================================================ 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")); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_3.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_4.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_5.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_6.java ================================================ 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.apache.commons.io.FileUtils; import org.glassfish.jersey.server.JSONP; import java.io.File; import java.util.ArrayList; import java.util.List; public class JSONPath_6 extends TestCase { public void test_path() throws Exception { String json = "{\"hello\":\"world\"}"; JSONObject object = JSON.parseObject(json); assertTrue(JSONPath.contains(object, "$.hello")); assertTrue(JSONPath.contains(object, "hello")); } // public void test_path_2() throws Exception { //// File file = new File("/Users/wenshao/Downloads/test"); //// String json = FileUtils.readFileToString(file); // String json = "{\"returnObj\":[{\"$ref\":\"$.subInvokes.com\\\\.alipay\\\\.cif\\\\.user\\\\.UserInfoQueryService\\\\@findUserInfosByCardNo\\\\(String[])[0].response[0]\"}]}"; // JSON.parseObject(json); // } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_7.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import org.glassfish.jersey.server.JSONP; public class JSONPath_7 extends TestCase { public void test_path() throws Exception { Model[] array = new Model[] {new Model(101), new Model(202), new Model(303)}; JSONArray values = (JSONArray) JSONPath.eval(array, "$.id"); assertEquals(101, values.get(0)); assertEquals(202, values.get(1)); assertEquals(303, values.get(2)); assertEquals(3, JSONPath.eval(array, "$.length")); } public static class Model { public int id; public Model(int id) { this.id = id; } } // public void test_path_2() throws Exception { //// File file = new File("/Users/wenshao/Downloads/test"); //// String json = FileUtils.readFileToString(file); // String json = "{\"returnObj\":[{\"$ref\":\"$.subInvokes.com\\\\.alipay\\\\.cif\\\\.user\\\\.UserInfoQueryService\\\\@findUserInfosByCardNo\\\\(String[])[0].response[0]\"}]}"; // JSON.parseObject(json); // } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_8.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.JSONPathException; import junit.framework.TestCase; import java.util.Map; public class JSONPath_8 extends TestCase { public void test_path() throws Exception { Model m = new Model(); m.f0 = 101; m.f1 = 102; JSONPath.remove(m, "$.f0"); assertNull(m.f0); JSONPath.remove(m, "$.f1"); assertNull(m.f1); JSONPath.remove(m, "$.f2"); JSONPath.eval(m, "$.f2"); } public void test_error() throws Exception { Exception error = null; Model m = new Model(); m.f0 = 101; m.f1 = 102; try { JSONPath.eval(m, "$.id"); } catch (JSONPathException ex) { error = ex; } assertNotNull(error); } public void test_error_1() throws Exception { Exception error = null; Model m = new Model(); m.f0 = 101; m.f1 = 102; try { JSONPath.eval(m, "$..id"); } catch (JSONPathException ex) { error = ex; } assertNotNull(error); } public void test_paths() throws Exception { Model m = new Model(); m.f0 = 101; m.f1 = 102; Exception error = null; try { Map paths = JSONPath.paths(m); } catch (JSONException ex) { error = ex; } assertNotNull(error); } public static class Model { public Integer f0; public Integer f1; public Integer getId() { throw new IllegalStateException(); } } // public void test_path_2() throws Exception { //// File file = new File("/Users/wenshao/Downloads/test"); //// String json = FileUtils.readFileToString(file); // String json = "{\"returnObj\":[{\"$ref\":\"$.subInvokes.com\\\\.alipay\\\\.cif\\\\.user\\\\.UserInfoQueryService\\\\@findUserInfosByCardNo\\\\(String[])[0].response[0]\"}]}"; // JSON.parseObject(json); // } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_9.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.JSONPathException; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; public class JSONPath_9 extends TestCase { public void test_paths() throws Exception { Model m = new Model(); m.f0 = 101; m.f1 = 102; Map paths = JSONPath.paths(m); assertEquals(3, paths.size()); } public void test_paths_1() throws Exception { Map map = new HashMap(); map.put("f0", 1001); map.put("f1", 1002); Map paths = JSONPath.paths(map); assertEquals(3, paths.size()); } public void test_paths_2() throws Exception { Map map = new HashMap(); map.put("f0", 1001); map.put("f1", 1002); JSONPath path = new JSONPath("$.f0"); assertEquals("$.f0", path.getPath()); assertEquals(1001, path.eval(map)); path.remove(null); } public void test_paths_3() throws Exception { JSONPath.paths(null); JSONPath.paths(1); JSONPath.paths("1"); JSONPath.paths(TimeUnit.DAYS); } public static class Model { public Integer f0; public Integer f1; } // public void test_path_2() throws Exception { //// File file = new File("/Users/wenshao/Downloads/test"); //// String json = FileUtils.readFileToString(file); // String json = "{\"returnObj\":[{\"$ref\":\"$.subInvokes.com\\\\.alipay\\\\.cif\\\\.user\\\\.UserInfoQueryService\\\\@findUserInfosByCardNo\\\\(String[])[0].response[0]\"}]}"; // JSON.parseObject(json); // } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_array_length.java ================================================ 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()")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_array_multi.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_array_put.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_array_put_2.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_array_remove_0.java ================================================ 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"); //解析正确 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_between_double.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import org.junit.Assert; import java.util.ArrayList; import java.util.List; public class JSONPath_between_double 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 Double id; private String name; public Entity(int id, String name){ this.id = Double.valueOf(id); this.name = name; } public Double getId() { return id; } public void setId(Double id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_between_int.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_calenar_test.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_conatinas_null.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_bigdecimal.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_biginteger.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_double.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_deepScan_test.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_deepScan_test2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_enum.java ================================================ 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 } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_int.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_int_simple.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_string.java ================================================ package com.alibaba.json.bvt.path; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; 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 void test_eq() throws Exception { JSONPath path = new JSONPath("$.*[?(@.name=='b')].id"); JSONArray array = JSON.parseArray("[{\"id\":\"1\",\"name\":\"a\"},{\"id\":\"2\",\"name\":\"b\"}]"); Object result = path.eval(array); System.out.println(result); } 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_string_simple.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_in_decimal.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import org.junit.Assert; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; public class JSONPath_field_access_filter_in_decimal 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 BigDecimal id; private String name; public Entity(Integer id, String name){ if (id == null) { this.id = null; } else { this.id = BigDecimal.valueOf(id); } this.name = name; } public BigDecimal getId() { return id; } public void setId(BigDecimal id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_in_int.java ================================================ 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_nin() throws Exception { JSONPath path = new JSONPath("[id nin (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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_in_string.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_like.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_like_simple.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_notNull.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_rlike.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_multi.java ================================================ 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 void test_list_map2() throws Exception { Entity entity = new Entity(123, "wenshao"); JSONPath path = new JSONPath("$.entity['id','name']"); Root root = new Root(); root.setEntity(entity); List result = (List) path.eval(root); 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; } } public static class Root { private Entity entity; public Entity getEntity() { return entity; } public void setEntity(Entity entity) { this.entity = entity; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_wildcard.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_wildcard_filter.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; import org.junit.Assert; import java.util.*; public class JSONPath_field_wildcard_filter extends TestCase { public void test_list_map_0() throws Exception { JSONObject jsonObject = JSON.parseObject(text, Feature.OrderedField); Collection array = (Collection) JSONPath.eval(jsonObject, "$.*[score>0]"); assertEquals("[{\"score\":0.89513221556685012},{\"score\":0.7237896928683851},{\"score\":0.3467174233072834}]", JSON.toJSONString(array)); } public void test_list_map_1() throws Exception { JSONObject jsonObject = JSON.parseObject(text, Feature.OrderedField); Collection array = (Collection) JSONPath.eval(jsonObject, "$.*[score<0]"); assertEquals("[{\"score\":-0.3453003960431523}]", JSON.toJSONString(array)); } public void test_list_map_2() throws Exception { JSONObject jsonObject = JSON.parseObject(text, Feature.OrderedField); Collection array = (Collection) JSONPath.eval(jsonObject, "$.*[score=0]"); assertEquals("[{\"score\":0},{\"score\":0},{\"score\":0},{\"score\":0},{\"score\":0},{\"score\":0},{\"score\":0}]", JSON.toJSONString(array)); } public static final String text = "{\n" + "\t\"risk_sexy_trade_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"chemical_medicine_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"gambling_trade_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"politics_stream_plus\": {\n" + "\t\t\"score\": 0.89513221556685012\n" + "\t},\n" + "\t\"risk_tool_gun_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"sex_model_stream_plus\": {\n" + "\t\t\"score\": 0.7237896928683851\n" + "\t},\n" + "\t\"risk_tool_cheat_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"risk_tool_certif_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"gamble_model_stream_plus\": {\n" + "\t\t\"score\": -0.3453003960431523\n" + "\t},\n" + "\t\"risk_tool_vpn_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"vpndetect_stream_plus\": {\n" + "\t\t\"score\": 0.3467174233072834\n" + "\t}\n" + "}"; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_wildcard_filter_double.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; import java.util.Collection; import java.util.Map; public class JSONPath_field_wildcard_filter_double extends TestCase { public void test_list_map_0() throws Exception { Map jsonObject = JSON.parseObject(text, new TypeReference>(){}, Feature.OrderedField); Collection array = (Collection) JSONPath.eval(jsonObject, "$.*[score>0]"); assertEquals("[{\"score\":0.8951322155668501},{\"score\":0.7237896928683851},{\"score\":0.3467174233072834}]", JSON.toJSONString(array)); } public void test_list_map_1() throws Exception { Map jsonObject = JSON.parseObject(text, new TypeReference>(){}, Feature.OrderedField); Collection array = (Collection) JSONPath.eval(jsonObject, "$.*[score<0]"); assertEquals("[{\"score\":-0.3453003960431523}]", JSON.toJSONString(array)); } public void test_list_map_2() throws Exception { Map jsonObject = JSON.parseObject(text, new TypeReference>(){}, Feature.OrderedField); Collection array = (Collection) JSONPath.eval(jsonObject, "$.*[score=0]"); assertEquals("[{\"score\":0.0},{\"score\":0.0},{\"score\":0.0},{\"score\":0.0},{\"score\":0.0},{\"score\":0.0},{\"score\":0.0}]", JSON.toJSONString(array)); } public static class Value { public double score; } public static final String text = "{\n" + "\t\"risk_sexy_trade_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"chemical_medicine_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"gambling_trade_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"politics_stream_plus\": {\n" + "\t\t\"score\": 0.89513221556685012\n" + "\t},\n" + "\t\"risk_tool_gun_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"sex_model_stream_plus\": {\n" + "\t\t\"score\": 0.7237896928683851\n" + "\t},\n" + "\t\"risk_tool_cheat_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"risk_tool_certif_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"gamble_model_stream_plus\": {\n" + "\t\t\"score\": -0.3453003960431523\n" + "\t},\n" + "\t\"risk_tool_vpn_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"vpndetect_stream_plus\": {\n" + "\t\t\"score\": 0.3467174233072834\n" + "\t}\n" + "}"; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_field_wildcard_filter_float.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; import java.util.Collection; import java.util.Map; public class JSONPath_field_wildcard_filter_float extends TestCase { public void test_list_map_0() throws Exception { Map jsonObject = JSON.parseObject(text, new TypeReference>(){}, Feature.OrderedField); Collection array = (Collection) JSONPath.eval(jsonObject, "$.*[score>0]"); assertEquals("[{\"score\":0.89513224},{\"score\":0.7237897},{\"score\":0.34671742}]", JSON.toJSONString(array)); } public void test_list_map_1() throws Exception { Map jsonObject = JSON.parseObject(text, new TypeReference>(){}, Feature.OrderedField); Collection array = (Collection) JSONPath.eval(jsonObject, "$.*[score<0]"); assertEquals("[{\"score\":-0.3453004}]", JSON.toJSONString(array)); } public void test_list_map_2() throws Exception { Map jsonObject = JSON.parseObject(text, new TypeReference>(){}, Feature.OrderedField); Collection array = (Collection) JSONPath.eval(jsonObject, "$.*[score=0]"); assertEquals("[{\"score\":0.0},{\"score\":0.0},{\"score\":0.0},{\"score\":0.0},{\"score\":0.0},{\"score\":0.0},{\"score\":0.0}]", JSON.toJSONString(array)); } public static class Value { public float score; } public static final String text = "{\n" + "\t\"risk_sexy_trade_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"chemical_medicine_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"gambling_trade_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"politics_stream_plus\": {\n" + "\t\t\"score\": 0.89513221556685012\n" + "\t},\n" + "\t\"risk_tool_gun_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"sex_model_stream_plus\": {\n" + "\t\t\"score\": 0.7237896928683851\n" + "\t},\n" + "\t\"risk_tool_cheat_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"risk_tool_certif_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"gamble_model_stream_plus\": {\n" + "\t\t\"score\": -0.3453003960431523\n" + "\t},\n" + "\t\"risk_tool_vpn_stream_plus\": {\n" + "\t\t\"score\": 0\n" + "\t},\n" + "\t\"vpndetect_stream_plus\": {\n" + "\t\t\"score\": 0.3467174233072834\n" + "\t}\n" + "}"; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_issue1208.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_keySet.java ================================================ package com.alibaba.json.bvt.path; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import org.junit.Assert; public class JSONPath_keySet extends TestCase { public static final Set KEY_SET = new HashSet(); static { KEY_SET.add("id"); KEY_SET.add("name"); } @SuppressWarnings("unchecked") public void test_map() { Map map1 = new HashMap(); map1.put("id", 1); map1.put("name", null); // null will be included Assert.assertEquals(KEY_SET, JSONPath.eval(map1, "$.keySet()")); Assert.assertEquals(KEY_SET, JSONPath.keySet(map1, "$")); Map map2 = new HashMap(); map2.put(1L, "a"); map2.put(2L, "b"); Set keys2 = (Set)JSONPath.eval(map2, "$.keySet()"); Assert.assertEquals(2, keys2.size()); Assert.assertTrue(keys2.contains(1L)); Assert.assertTrue(keys2.contains(2L)); } @SuppressWarnings("unchecked") public void test_object() { Entity e = new Entity(); e.id = 3L; e.name = "hello"; Collection result = null; // age is null result = (Collection)JSONPath.eval(e, "$.keySet()"); Assert.assertEquals(KEY_SET, result); // age not null e.age = 4L; result = (Collection)JSONPath.eval(e, "$.keySet()"); Assert.assertEquals(3, result.size()); Assert.assertTrue(result.containsAll(KEY_SET)); Assert.assertTrue(result.contains("age")); } public void test_nested() { Entity e = new Entity(); e.id = 3L; e.name = "hello"; Object obj = Collections.singletonMap("obj", e); Assert.assertEquals(KEY_SET, JSONPath.eval(obj, "$.obj.keySet()")); Assert.assertEquals(KEY_SET, new JSONPath("$.obj").keySet(obj)); } public void test_unsupported() { Entity e = new Entity(); e.id = 3L; Entity[] array = {e}; Map map = Collections.singletonMap("array", array); Assert.assertEquals(array, JSONPath.eval(map, "$.array")); Assert.assertNull(JSONPath.eval(map, "$.array.keySet()")); Assert.assertNull(JSONPath.keySet(map, "$.array")); Assert.assertNull(new JSONPath("$.array").keySet(map)); } public void test_null() { Assert.assertNull(JSONPath.eval(null, "$.keySet()")); Set keySet = (Set)JSONPath.eval(new HashMap(), "$.keySet()"); Assert.assertEquals(0, keySet.size()); } /** * Demo for wiki */ @SuppressWarnings("unchecked") public void test_demo() { Entity e = new Entity(); e.setId(null); e.setName("hello"); Map map = Collections.singletonMap("e", e); Collection result; // id is null, excluded by keySet result = (Collection)JSONPath.eval(map, "$.e.keySet()"); assertEquals(1, result.size()); Assert.assertTrue(result.contains("name")); e.setId(1L); result = (Collection)JSONPath.eval(map, "$.e.keySet()"); Assert.assertEquals(2, result.size()); Assert.assertTrue(result.contains("id")); // included Assert.assertTrue(result.contains("name")); // Same result Assert.assertEquals(result, JSONPath.keySet(map, "$.e")); Assert.assertEquals(result, new JSONPath("$.e").keySet(map)); } public static class Entity { private Long id; private String name; public Long age; 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_like.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import org.junit.Assert; public class JSONPath_like extends TestCase { public void test_like_not_match() throws Exception { assertNull( JSONPath.read("{\"table\":\"_order_base\"}", "[table LIKE 'order_base%']")); } public void test_like_not_match_1() throws Exception { assertEquals("{\"table\":\"_order_base\"}", JSONPath.read("{\"table\":\"_order_base\"}", "[table LIKE '_order_base%']").toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_list.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_list_field.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_list_multi.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_list_range.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_1.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_2.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_list_size_3.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_map_size.java ================================================ 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()")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_max.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import java.math.BigDecimal; public class JSONPath_max extends TestCase { public void test_max() throws Exception { Object root = JSON.parse("[1,3,9, 5, 2, 4]"); assertEquals(9, JSONPath.eval(root, "$.max()")); } public void test_max_1() throws Exception { Object root = JSON.parse("[1,6,7L,3,8,9.1, 5, 2L, 4]"); assertEquals(new BigDecimal("9.1"), JSONPath.eval(root, "$.max()")); } public void test_max_2() throws Exception { Object root = JSON.parse("[1,6,7L,3,3.1D,8,9.1D, 5, 2L, 4]"); assertEquals(9.1D, JSONPath.eval(root, "$.max()")); } public void test_max_3() throws Exception { Object root = JSON.parse("[1,6,7L,3,3.1F,8,9.1F, 5, 2L, 4]"); assertEquals(9.1F, JSONPath.eval(root, "$.max()")); } public void test_max_4() throws Exception { Object root = JSON.parse("['1', '111', '2']"); assertEquals("2", JSONPath.eval(root, "$.max()")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_min.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import java.math.BigDecimal; public class JSONPath_min extends TestCase { public void test_max() throws Exception { Object root = JSON.parse("[1,3,9, 5, 2, 4]"); assertEquals(1, JSONPath.eval(root, "$.min()")); } public void test_max_1() throws Exception { Object root = JSON.parse("[1,6,7L,3,8,9.1, 5, 2L, 4]"); assertEquals(1, JSONPath.eval(root, "$.min()")); } public void test_max_2() throws Exception { Object root = JSON.parse("[1,6,7L,3,3.1D,8,9.1F, 5, 2L, 4]"); assertEquals(1, JSONPath.eval(root, "$.min()")); } public void test_max_3() throws Exception { Object root = JSON.parse("[1,6,7L,3,3.1F,8,9.1F, 5, 2L, 4]"); assertEquals(1, JSONPath.eval(root, "$.min()")); } public void test_max_4() throws Exception { Object root = JSON.parse("['1', '111', '2']"); assertEquals("1", JSONPath.eval(root, "$.min()")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_none_root.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_object_filter.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_oracle_compatible_test.java ================================================ 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; public class JSONPath_oracle_compatible_test extends TestCase { public void test_reserve() throws Exception { JSONObject object = JSON.parseObject(str); assertEquals("Sayings of the Century", JSONPath.eval(object, "$.store.book[0].title")); assertEquals("Sayings of the Century", JSONPath.eval(object, "$['store']['book'][0]['title']")); } public static final String str = "{\n" + " \"store\": {\n" + " \"book\": [\n" + " {\n" + " \"category\": \"reference\",\n" + "\n" + " \"author\": \"Nigel Rees\",\n" + "\n" + " \"title\": \"Sayings of the Century\",\n" + "\n" + " \"price\": 8.95\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Evelyn Waugh\",\n" + " \"title\": \"Sword of Honour\",\n" + " \"price\": 12.99\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Herman Melville\",\n" + " \"title\": \"Moby Dick\",\n" + " \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.99\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"J. R. R. Tolkien\",\n" + " \"title\": \"The Lord of the Rings\",\n" + " \"isbn\": \"0-395-19395-8\",\n" + " \"price\": 22.99\n" + " }\n" + " ],\n" + " \"bicycle\": {\n" + " \"color\": \"red\",\n" + " \"price\": 19.95\n" + " }\n" + " },\n" + " \"expensive\": 10\n" + "}"; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test1.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test3.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test4.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_paths_test5.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_remove_test.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_reverse_test.java ================================================ package com.alibaba.json.bvt.path; 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_reverse_test extends TestCase { public void test_reserve() throws Exception { JSONObject object = JSON.parseObject("{\"id\":1001,\"name\":\"ljw\",\"age\":50}"); assertEquals("[1001,\"ljw\"]", JSONPath.reserveToArray(object, "id", "name").toString()); assertEquals("[\"ljw\",1001]", JSONPath.reserveToArray(object, "name", "id").toString()); String text = JSON.toJSONString(JSONPath.reserveToArray(object, "name", "*"), SerializerFeature.MapSortField); assertTrue(text.equals("[\"ljw\",[\"ljw\",1001,50]]") || text.equals("[\"ljw\",[\"ljw\",50,1001]]") || text.equals("[\"ljw\",[50,1001,\"ljw\"]]") || text.equals("[\"ljw\",[1001,50,\"ljw\"]]") || text.equals("[\"ljw\",[1001,\"ljw\",50]]") || text.equals("[\"ljw\",[50,\"ljw\",1001]]")); } public void test_reserve2() throws Exception { JSONObject object = JSON.parseObject("{\"id\":1001,\"name\":\"ljw\",\"age\":50}"); assertEquals("{\"id\":1001,\"name\":\"ljw\"}", JSONPath.reserveToObject(object, "id", "name").toString()); assertEquals("{\"name\":\"ljw\",\"id\":1001}", JSONPath.reserveToObject(object, "name", "id").toString()); } public void test_reserve3() throws Exception { JSONObject object = JSON.parseObject("{\"player\":{\"id\":1001,\"name\":\"ljw\",\"age\":50}}"); String text = JSON.toJSONString(JSONPath.reserveToObject(object, "player.id", "player.name"), SerializerFeature.MapSortField); assertEquals("{\"player\":{\"id\":1001,\"name\":\"ljw\"}}", text); text = JSON.toJSONString(JSONPath.reserveToObject(object, "player.name", "player.id", "ab.c"), SerializerFeature.MapSortField); assertEquals("{\"player\":{\"id\":1001,\"name\":\"ljw\"}}", text); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_set.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test2.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test3.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test4.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test5.java ================================================ 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]")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test6.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test7.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class JSONPath_set_test7 extends TestCase { public void test_jsonpath_1() throws Exception { JSONObject aa= new JSONObject(); aa.put("val", "false"); JSONPath path = JSONPath.compile("$.val"); path.set(aa, true); assertEquals(true, aa.getBoolean("val").booleanValue()); path.set(aa, false); assertEquals(false, aa.getBoolean("val").booleanValue()); } public void test_jsonpath_2() throws Exception { VO aa = new VO(); JSONPath path = JSONPath.compile("$.val"); path.set(aa, true); assertEquals(true, aa.val); path.set(aa, false); assertEquals(false, aa.val); path.set(aa, "true"); assertEquals(true, aa.val); path.set(aa, "false"); assertEquals(false, aa.val); } public static class VO { public boolean val; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_size.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPath_toString.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPointTest_0.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/JSONPointTest_1.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/TestSpecial_0.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/TestSpecial_1.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/TestSpecial_2.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/TestSpecial_3.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; public class TestSpecial_3 extends TestCase { public void test_special() throws Exception { String json = "[{\"@type\":\"NAME_CORRECTION\",\"value\":23}]"; JSONArray array = (JSONArray) JSON.parse(json, Feature.DisableSpecialKeyDetect); Object obj = JSONPath.eval(array, "[\\@type='NAME_CORRECTION']"); assertNotNull(obj); } public void test_special_1() throws Exception { String json = "[{\":lang\":\"NAME_CORRECTION\",\"value\":23}]"; JSONArray array = (JSONArray) JSON.parse(json, Feature.DisableSpecialKeyDetect); Object obj = JSONPath.eval(array, "[\\:lang='NAME_CORRECTION']"); assertNotNull(obj); } public void test_special_2() throws Exception { String json = "{\"cpe-item\":{\"@name\":\"cpe:/a:google:chrome:4.0.249.19\",\"cpe-23:cpe23-item\":{\"@name\":\"cpe:2.3:a:google:chrome:4.0.249.19:*:*:*:*:*:*:*\"},\"title\":[{\"#text\":\"グーグル クローム 4.0.249.19\",\"@xml:lang\":\"ja-JP\"},{\"#text\":\"Google Chrome 4.0.249.19\",\"@xml:lang\":\"en-US\"}]}}"; String path = "['cpe-item']['title'][\\@xml\\:lang='en-US']['#text'][0]"; JSONObject object = (JSONObject) JSON.parse(json, Feature.DisableSpecialKeyDetect); Object obj = JSONPath.eval(object, path); assertNotNull(obj); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/TestSpecial_4.java ================================================ package com.alibaba.json.bvt.path; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.parser.Feature; import junit.framework.TestCase; public class TestSpecial_4 extends TestCase { public void test_special() throws Exception { String json = "{\"大小\":123}"; JSONObject object = JSON.parseObject(json); Object obj = JSONPath.eval(object, "$.大小"); assertEquals(123, obj); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/extract/JSONPath_extract_0.java ================================================ package com.alibaba.json.bvt.path.extract; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class JSONPath_extract_0 extends TestCase { public void test_0() throws Exception { String json = "{\"id\":123,\"obj\":{\"id\":123}}"; assertEquals("{\"id\":123}" , JSONPath.extract(json, "$.obj") .toString()); } public void test_1() throws Exception { String json = "{\"f1\":1,\"f2\":2,\"f3\":3,\"f4\":4}"; assertEquals("2" , JSONPath.extract(json, "$.f2") .toString()); } public void test_2() throws Exception { assertEquals("{}" , JSONPath.extract("{}", "$") .toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/extract/JSONPath_extract_1.java ================================================ package com.alibaba.json.bvt.path.extract; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; import java.net.InetSocketAddress; public class JSONPath_extract_1 extends TestCase { public void test_0() throws Exception { String json = "[{\"id\":1001},{\"id\":1002},{\"id\":1003},[1],123,-4,\"a\\\"bc\"]"; assertEquals("{\"id\":1001}" , JSONPath.extract(json, "$.0") .toString()); assertEquals("{\"id\":1002}" , JSONPath.extract(json, "$.1") .toString()); assertEquals("{\"id\":1003}" , JSONPath.extract(json, "$.2") .toString()); assertEquals("[1]" , JSONPath.extract(json, "$.3") .toString()); assertEquals("123" , JSONPath.extract(json, "$.4") .toString()); assertEquals("-4" , JSONPath.extract(json, "$.5") .toString()); assertEquals("a\"bc" , JSONPath.extract(json, "$.6") .toString()); } public void test_1() throws Exception { String json = "[\"a\\\"bc\",123]"; assertEquals("a\"bc" , JSONPath.extract(json, "$.0") .toString()); assertEquals("123" , JSONPath.extract(json, "$.1") .toString()); } public void test_2() throws Exception { String json = "[\"a\\\\bc\",123]"; assertEquals("a\\bc" , JSONPath.extract(json, "$.0") .toString()); assertEquals("123" , JSONPath.extract(json, "$.1") .toString()); } public void test_3() throws Exception { String json = "[\"a\\\"b\\\\c\\\"d\\\"e\",123]"; assertEquals("a\"b\\c\"d\"e" , JSONPath.extract(json, "$.0") .toString()); assertEquals("123" , JSONPath.extract(json, "$.1") .toString()); assertNull(JSONPath.extract(json, "$.2")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/extract/JSONPath_extract_2_book.java ================================================ package com.alibaba.json.bvt.path.extract; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.util.IOUtils; import junit.framework.TestCase; import java.io.InputStream; import java.io.InputStreamReader; public class JSONPath_extract_2_book extends TestCase { public void test_0() throws Exception { assertEquals("[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]" , JSONPath.extract(json, "$.store.book.author") .toString()); } public void test_1() throws Exception { assertEquals("[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]" , JSONPath.extract(json, "$.store.book[*].author") .toString()); } public void test_2() throws Exception { assertNull(JSONPath.extract(json, "$.author")); } public void test_3() throws Exception { assertEquals("[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]" , JSONPath.extract(json, "$..author") .toString()); } public void test_4() throws Exception { assertEquals("[[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":22.99}],{\"color\":\"red\",\"price\":19.95}]" , JSONPath.extract(json, "$.store.*") .toString()); } public void test_5() throws Exception { assertEquals("$.store..price", "[8.95,12.99,8.99,22.99,19.95]" , JSONPath.extract(json, "$.store..price") .toString()); } public void test_6() throws Exception { assertEquals("{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}" , JSONPath.extract(json, "$..book[2]") .toString()); } public void test_7 () throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}]" , JSONPath.extract(json, "$..book[0,1]") .toString()); } public void test_8() throws Exception { assertEquals("{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}" , JSONPath.extract(json, "$..book[-2]") .toString()); } public void test_9() throws Exception { assertEquals("Nigel Rees" , JSONPath.extract(json, "$['store']['book'][0]['author']") .toString()); assertEquals("Evelyn Waugh" , JSONPath.extract(json, "$['store']['book'][1]['author']") .toString()); assertEquals("Herman Melville" , JSONPath.extract(json, "$['store']['book'][2]['author']") .toString()); assertEquals("J. R. R. Tolkien" , JSONPath.extract(json, "$['store']['book'][3]['author']") .toString()); } public void test_10() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}]" , JSONPath.extract(json, "$.store.book[?(@.price < 10)]") .toString()); } public void test_11() throws Exception { assertEquals("10" , JSONPath.extract(json, "$.expensive") .toString()); } public void test_12() throws Exception { assertNull(JSONPath.extract(json, "$.store.book.doesnt_exist")); } public void test_13() throws Exception { assertEquals("J. R. R. Tolkien", JSONPath.extract(json, "$.store.book[3].author")); } public void test_14() throws Exception { assertEquals("[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":22.99}]" , JSONPath.extract(json, "$.store.book").toString()); } public void test_15() throws Exception { assertEquals("{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95}" , JSONPath.extract(json, "$[\"store\"][\"book\"][0]").toString()); } public void test_16() throws Exception { assertNull(JSONPath.extract(json, "$.store.object.inner_object.array[0].inner_array[0].x")); } public void test_17() throws Exception { assertEquals(4, JSONPath.extract(json, "$..book.length()")); } private static String json; static { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/book.json"); InputStreamReader reader = new InputStreamReader(is); json = IOUtils.readAll(reader); IOUtils.close(reader); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/extract/JSONPath_extract_3.java ================================================ package com.alibaba.json.bvt.path.extract; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class JSONPath_extract_3 extends TestCase { public void test_0() throws Exception { assertEquals("male" , JSONPath.extract(json, "$[0]['gender']") .toString()); } public void test_1() throws Exception { assertNull(JSONPath.extract(json, "$[1]['gender']")); } public void test_2() throws Exception { assertEquals("ben" , JSONPath.extract(json, "$[1]['name']").toString()); } private static final String json = "[\n" + " {\n" + " \"name\" : \"john\",\n" + " \"gender\" : \"male\"\n" + " },\n" + " {\n" + " \"name\" : \"ben\"\n" + " }\n" + "]"; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/path/extract/JSONPath_extract_4_multi.java ================================================ package com.alibaba.json.bvt.path.extract; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class JSONPath_extract_4_multi extends TestCase { public void test_0() throws Exception { assertEquals("[\"male\",\"john\"]" , JSONPath.extract(json, "$[0]['gender','name']") .toString()); } public void test_1() throws Exception { assertEquals("[\"john\",\"male\"]" , JSONPath.extract(json, "$[0]['name','gender']") .toString()); } private static final String json = "[\n" + " {\n" + " \"name\" : \"john\",\n" + " \"gender\" : \"male\"\n" + " },\n" + " {\n" + " \"name\" : \"ben\"\n" + " }\n" + "]"; } ================================================ FILE: src/test/java/com/alibaba/json/bvt/proxy/TestProxy.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest10.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest11.java ================================================ 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 + "}"; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest12.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest13.java ================================================ 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"; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest14.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest15.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest16.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest17.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest18.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest19.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest2.java ================================================ 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]); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest20.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest21.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest22.java ================================================ 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")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest23.java ================================================ package com.alibaba.json.bvt.ref; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import junit.framework.TestCase; /** * Created by wenshao on 16/8/23. */ public class RefTest23 extends TestCase { public void test_ref() throws Exception { String json = "{\"$ref\":\"tmall/item\",\"id\":123}"; JSONObject root = JSON.parseObject(json); assertEquals("tmall/item", root.get("$ref")); assertEquals(123, root.get("id")); } public void test_ref_1() throws Exception { String json = "{\"$ref\":123}"; JSONObject root = JSON.parseObject(json); assertEquals(123, root.get("$ref")); } public void test_ref_2() throws Exception { String json = "{\n" + "\t\"bbbb\\\"\":{\n" + "\t\t\"x\":\"x\"\n" + "\t},\n" + "\t\"aaaa\\\"\":{\"$ref\":\"$.bbbb\\\\\\\"\"}\n" + "}"; System.out.println(json); JSONObject root = JSON.parseObject(json); assertSame(root.get("bbbb\\"), root.get("aaaa\\")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest24.java ================================================ package com.alibaba.json.bvt.ref; 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; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * Created by wenshao on 16/8/23. */ public class RefTest24 extends TestCase { public void test_ref() throws Exception { ByteCodeDO codeDO = new ByteCodeDO(); codeDO.id = 1001; Map data = new LinkedHashMap(); Map m1 = new LinkedHashMap(); m1.put("23\"299\\6 $85@47", codeDO); Map m2 = new LinkedHashMap(); m2.put("23299685@47", codeDO); data.put("com.alibaba.extAppConfigs", m1); data.put("com.alibaba.appConfigs", m2); String str = JSON.toJSONString(data); Object o = JSON.parseObject(str, Feature.OrderedField); assertEquals(str, JSON.toJSONString(o, SerializerFeature.WriteMapNullValue)); } public static class ByteCodeDO { public int id; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest3.java ================================================ 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]); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest4.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest5.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest6.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest7.java ================================================ 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(){ } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest8.java ================================================ 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(){ } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest9.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/ref/RefTest_for_huanxige.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/AbstractTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/BooleanArraySerializerTest.java ================================================ 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 BooleanArraySerializerTest extends TestCase { public void test_0() { 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 boolean[] value; public boolean[] getValue() { return value; } public void setValue(boolean[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldSerializerTest.java ================================================ 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.JSONArray; 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; public class BooleanFieldSerializerTest extends TestCase { public void test_0() { Assert.assertEquals("{\"value\":null}", JSON.toJSONString(new Entity(), SerializerFeature.WriteMapNullValue)); Assert.assertEquals("{\"value\":false}", JSON.toJSONString(new Entity(), SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse)); } public void test_codec_no_asm() throws Exception { Entity v = new Entity(); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":null}", text); Entity v1 = parseObjectNoAsm(text, Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(v.getValue(), v1.getValue()); } public void test_codec() throws Exception { Entity v1 = parseObjectNoAsm("{value:1}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(true, v1.getValue()); } public void test_codec_0() throws Exception { Entity v1 = parseObjectNoAsm("{value:0}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(false, v1.getValue()); } public void test_codec_1() throws Exception { Entity v1 = parseObjectNoAsm("{value:'true'}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(true, v1.getValue()); } @SuppressWarnings("unchecked") public static final T parseObjectNoAsm(String input, Type clazz, int featureValues, Feature... features) { if (input == null) { return null; } for (Feature feature : features) { featureValues = Feature.config(featureValues, feature, true); } ParserConfig config = new ParserConfig(); config.setAsmEnable(false); DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues); T value = (T) parser.parseObject(clazz); if (clazz != JSONArray.class) { parser.close(); } return (T) value; } public static class Entity { private Boolean value; public Boolean getValue() { return value; } public void setValue(Boolean value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldSerializerTest_primitive.java ================================================ 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.JSONArray; 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.bvt.serializer.BooleanFieldSerializerTest.Entity; public class BooleanFieldSerializerTest_primitive extends TestCase { public void test_0() { Assert.assertEquals("{\"value\":false}", JSON.toJSONString(new Entity(), SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse)); } public void test_codec_no_asm() throws Exception { Entity v = new Entity(); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":false}", text); Entity v1 = JSON.parseObject(text, Entity.class); Assert.assertEquals(v.getValue(), v1.getValue()); } public void test_codec() throws Exception { Entity v1 = parseObjectNoAsm("{value:1}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(true, v1.getValue()); } public void test_codec_0() throws Exception { Entity v1 = parseObjectNoAsm("{value:0}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(false, v1.getValue()); } public void test_codec_1() throws Exception { Entity v1 = parseObjectNoAsm("{value:'true'}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(true, v1.getValue()); } public void test_codec_2() throws Exception { Entity v1 = parseObjectNoAsm("{value:null}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(false, v1.getValue()); } public void test_codec_3() throws Exception { Entity v1 = parseObjectNoAsm("{value:\"\"}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(false, v1.getValue()); } @SuppressWarnings("unchecked") public static final T parseObjectNoAsm(String input, Type clazz, int featureValues, Feature... features) { if (input == null) { return null; } for (Feature feature : features) { featureValues = Feature.config(featureValues, feature, true); } ParserConfig config = new ParserConfig(); config.setAsmEnable(false); DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues); T value = (T) parser.parseObject(clazz); if (clazz != JSONArray.class) { parser.close(); } return (T) value; } public static class Entity { private boolean value; public boolean getValue() { return value; } public void setValue(boolean value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldTest_array.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/BugTest0.java ================================================ package com.alibaba.json.bvt.serializer; import java.sql.Date; import java.sql.Timestamp; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; public class BugTest0 extends TestCase { public void test_0() throws Exception { Timestamp t = new Timestamp(System.currentTimeMillis()); String text = JSON.toJSONString(t); Timestamp t1 = JSON.parseObject(text, Timestamp.class); Assert.assertEquals(t, t1); } public void test_1() throws Exception { long t1 = System.currentTimeMillis(); String text = JSON.toJSONString(t1); Timestamp t2 = JSON.parseObject(text, Timestamp.class); Assert.assertEquals(t1, t2.getTime()); } public void test_2() throws Exception { Date t = new Date(System.currentTimeMillis()); String text = JSON.toJSONString(t); Date t1 = JSON.parseObject(text, Date.class); Assert.assertEquals(t, t1); } public void test_3() throws Exception { long t1 = System.currentTimeMillis(); String text = JSON.toJSONString(t1); Date t2 = JSON.parseObject(text, Date.class); Assert.assertEquals(t1, t2.getTime()); } public void test_4() throws Exception { A a = new A(); a.setDate(new java.sql.Date(System.currentTimeMillis())); a.setTime(new java.sql.Timestamp(System.currentTimeMillis())); String text = JSON.toJSONString(a); A a1 = JSON.parseObject(text, A.class); Assert.assertEquals(a.getDate(), a1.getDate()); Assert.assertEquals(a.getTime(), a1.getTime()); } public void test_error_0() throws Exception { Exception error = null; try { JSON.parseObject("\"222A\"", Timestamp.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_1() throws Exception { Exception error = null; try { JSON.parseObject("\"222B\"", Date.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_3() throws Exception { Exception error = null; try { JSON.parseObject("true", Timestamp.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_4() throws Exception { Exception error = null; try { JSON.parseObject("true", Date.class); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public static class A { private java.sql.Timestamp time; private java.sql.Date date; public java.sql.Timestamp getTime() { return time; } public void setTime(java.sql.Timestamp time) { this.time = time; } public java.sql.Date getDate() { return date; } public void setDate(java.sql.Date date) { this.date = date; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/BugTest1.java ================================================ 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 org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; public class BugTest1 extends TestCase { public void test_0() throws Exception { AtomicBoolean v = new AtomicBoolean(); Assert.assertEquals("false", JSON.toJSONString(v)); } public void test_1() throws Exception { AtomicBoolean v = new AtomicBoolean(true); Assert.assertEquals("true", JSON.toJSONString(v)); } public void test_2() throws Exception { AtomicInteger v = new AtomicInteger(); Assert.assertEquals("0", JSON.toJSONString(v)); } public void test_3() throws Exception { AtomicLong v = new AtomicLong(); Assert.assertEquals("0", JSON.toJSONString(v)); } public void test_4() throws Exception { AtomicReference v = new AtomicReference(3); Assert.assertEquals("3", JSON.toJSONString(v)); } public void test_5() throws Exception { Assert.assertEquals("\"java.util.concurrent.atomic.AtomicReference\"", JSON.toJSONString(AtomicReference.class)); } public void test_7() throws Exception { Assert.assertEquals("'java.util.concurrent.atomic.AtomicReference'", JSON.toJSONString(AtomicReference.class, SerializerFeature.UseSingleQuotes)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/BugTest2.java ================================================ package com.alibaba.json.bvt.serializer; import junit.framework.TestCase; import net.sf.json.JSONObject; import com.alibaba.fastjson.JSONAware; public class BugTest2 extends TestCase { public void test_0() throws Exception { JSONObject obj = new JSONObject(); obj.put("a", new A()); String text = obj.toString(); System.out.println(text); } public static class A implements JSONAware { private int id; private String name; private JSONObject toJSONObject() { JSONObject json = new JSONObject(); json.put("id", id); json.put("name", name); return json; } 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 toJSONString() { return toJSONObject().toString(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/Bug_for_yegaofei.java ================================================ package com.alibaba.json.bvt.serializer; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.FieldSerializer; import com.alibaba.fastjson.serializer.JavaBeanSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.json.bvtVO.alipay.PlatformDepartmentVO; import junit.framework.TestCase; import java.lang.reflect.Field; public class Bug_for_yegaofei extends TestCase { public void test_0() throws Exception { PlatformDepartmentVO vo = new PlatformDepartmentVO(); vo.setId("xx"); JSON.toJSONString(vo); JavaBeanSerializer serializer = (JavaBeanSerializer) SerializeConfig.globalInstance.getObjectWriter(PlatformDepartmentVO.class); Field field = JavaBeanSerializer.class.getDeclaredField("getters"); field.setAccessible(true); FieldSerializer[] getters = (FieldSerializer[]) field.get(serializer); for (FieldSerializer getter : getters) { assertNotNull(getter); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ByteArrayFieldSerializerTest.java ================================================ 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 ByteArrayFieldSerializerTest extends TestCase { public void test_0() throws Exception { A a1 = new A(); a1.setBytes(new byte[] { 1, 2 }); Assert.assertEquals("{\"bytes\":\"AQI=\"}", JSON.toJSONString(a1)); } public void test_1() throws Exception { A a1 = new A(); Assert.assertEquals("{\"bytes\":null}", JSON.toJSONString(a1, SerializerFeature.WriteMapNullValue)); } public static class A { private byte[] bytes; public byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ByteArraySerializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ByteArrayTest.java ================================================ package com.alibaba.json.bvt.serializer; 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 ByteArrayTest extends TestCase { public void test_bytes() throws Exception { VO vo = new VO(); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty }; String text1 = JSON.toJSONString(vo, mapping, features); Assert.assertEquals("{\"value\":[]}", text1); String text2 = JSON.toJSONString(vo, features); Assert.assertEquals("{\"value\":[]}", text2); } public void test_bytes_1() throws Exception { VO vo = new VO(); vo.setValue(new byte[] {1, 2, 3}); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty }; String text1 = JSON.toJSONString(vo, mapping, features); Assert.assertEquals("{\"value\":\"AQID\"}", text1); String text2 = JSON.toJSONString(vo, features); Assert.assertEquals("{\"value\":\"AQID\"}", text2); } public static class VO { private byte[] value; public byte[] getValue() { return value; } public void setValue(byte[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/CharArraySerializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/CharTest.java ================================================ package com.alibaba.json.bvt.serializer; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class CharTest extends TestCase { public void test_file() throws Exception { char ch = 'a'; String text = JSON.toJSONString(ch); Assert.assertEquals("\"a\"", text); Character c1 = JSON.parseObject(text, Character.class); Character c2 = JSON.parseObject(text, char.class); Assert.assertEquals(ch, c1.charValue()); Assert.assertEquals(ch, c2.charValue()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/CharsetSerializerTest.java ================================================ package com.alibaba.json.bvt.serializer; import java.nio.charset.Charset; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; public class CharsetSerializerTest extends TestCase { public void test_0() { Assert.assertEquals("{\"value\":null}", JSON.toJSONString(new Entity(), SerializerFeature.WriteMapNullValue)); } public static class Entity { private Charset value; public Charset getValue() { return value; } public void setValue(Charset value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/CharsetTest.java ================================================ package com.alibaba.json.bvt.serializer; import java.nio.charset.Charset; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class CharsetTest extends TestCase { public void test_file() throws Exception { Charset c = Charset.defaultCharset(); String text = JSON.toJSONString(c); Assert.assertEquals(JSON.toJSONString(c.toString()), text); Charset c1 = JSON.parseObject(text, Charset.class); Assert.assertEquals(c.toString(), c1.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/CircularReferencesTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ClassFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ClassLoaderTest.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ClobSerializerTest.java ================================================ 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 ClobSerializerTest 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/CollectionSerializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ColorSerializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest5.java ================================================ 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 com.alibaba.fastjson.serializer.SerializeConfig; 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, new SerializeConfig()); 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest6.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest7.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DateFormatSerializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DoubleArraySerializerTest.java ================================================ package com.alibaba.json.bvt.serializer; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.fastjson.JSON; public class DoubleArraySerializerTest extends TestCase { public void test_0() { Assert.assertEquals("[]", JSON.toJSONString(new double[0])); Assert.assertEquals("[null]", JSON.toJSONString(new double[] { Double.NaN })); Assert.assertEquals("[1.0,2.0]", JSON.toJSONString(new double[] { 1, 2 })); Assert.assertEquals("[1.0,2.0,3.0]", JSON.toJSONString(new double[] { 1, 2, 3 })); Assert.assertEquals("[1.0,2.0,3.0,null,null]", JSON.toJSONString(new double[] { 1, 2, 3, Double.NaN, Double.NaN })); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DoubleFormatTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DoubleFormatTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DoubleTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DoubleTest_custom.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DoubleTest_custom2.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest.java ================================================ /* * 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest2.java ================================================ /* * 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest3.java ================================================ /* * 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest4.java ================================================ /* * 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest5.java ================================================ /* * 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/DupSetterTest6.java ================================================ /* * 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/EnumerationSeriliazerTest.java ================================================ 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 { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ErrorGetterTest.java ================================================ package com.alibaba.json.bvt.serializer; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import junit.framework.TestCase; public class ErrorGetterTest extends TestCase { public void test_0() throws Exception { Model m = new Model(); Exception error = null; try { JSON.toJSONString(m); } catch (JSONException ex) { error = ex; } assertNotNull(error); } private static class Model { public int getValue() { throw new UnsupportedOperationException(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ErrorTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ExtendsTest.java ================================================ package com.alibaba.json.bvt.serializer; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class ExtendsTest extends TestCase { public void test_extends() throws Exception { B b = new B(); b.setId(123); b.setName("加爵"); JSONObject json = JSON.parseObject(JSON.toJSONString(b)); Assert.assertEquals(b.getId(), json.get("id")); Assert.assertEquals(b.getName(), json.get("name")); } 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 String getName() { return name; } public void setName(String name) { this.name = name; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/FieldOrderTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/FileTest.java ================================================ package com.alibaba.json.bvt.serializer; import java.io.File; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class FileTest extends TestCase { public void test_file() throws Exception { File file = new File("abc.txt"); String text = JSON.toJSONString(file); Assert.assertEquals(JSON.toJSONString(file.getPath()), text); File file2 = JSON.parseObject(text, File.class); Assert.assertEquals(file, file2); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/FloatArraySerializerTest.java ================================================ 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 FloatArraySerializerTest extends TestCase { public void test_0() { Assert.assertEquals("[]", JSON.toJSONString(new float[0])); Assert.assertEquals("{\"value\":null}", JSON.toJSONString(new Entity(), SerializerFeature.WriteMapNullValue)); Assert.assertEquals("{\"value\":[]}", JSON.toJSONString(new Entity(), SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); Assert.assertEquals("[1.0,2.0]", JSON.toJSONString(new float[] { 1, 2 })); Assert.assertEquals("[1.0,2.0,3.0]", JSON.toJSONString(new float[] { 1, 2, 3 })); Assert.assertEquals("[1.0,2.0,3.0,null,null]", JSON.toJSONString(new float[] { 1, 2, 3, Float.NaN, Float.NaN })); } public static class Entity { private float[] value; public float[] getValue() { return value; } public void setValue(float[] value) { this.value = value; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/FloatFormatTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/FloatFormatTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/FloatTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/FontSerializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/GenericTypeNotMatchTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/GenericTypeNotMatchTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/GenericTypeTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/GenericTypeTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/IgnoreGetMethodTest.java ================================================ 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"); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/IgnoreNonFieldGetterTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/IgnoreNonFieldGetterTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/IgoreGetterTest.java ================================================ package com.alibaba.json.bvt.serializer; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; public class IgoreGetterTest extends TestCase { public void test_for_issue() throws Exception { VO vo = new VO(); assertEquals("{}", JSON.toJSONString(vo)); } public static class VO { public InputStream getInputStream() { throw new UnsupportedOperationException(); } public Reader getReader() { throw new UnsupportedOperationException(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/InetAddressTest.java ================================================ package com.alibaba.json.bvt.serializer; import java.net.InetAddress; import com.alibaba.fastjson.parser.ParserConfig; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class InetAddressTest extends TestCase { public void test_inetAddress() throws Exception { InetAddress address = InetAddress.getLocalHost(); String text = JSON.toJSONString(address); Assert.assertEquals(JSON.toJSONString(address.getHostAddress()), text); InetAddress address2 = JSON.parseObject(text, InetAddress.class); Assert.assertEquals(address, address2); ParserConfig.getGlobalInstance().getDeserializer(InetAddress.class); } public void test_null() throws Exception { Assert.assertEquals(null, JSON.parseObject("null", InetAddress.class)); } public void test_empty() throws Exception { Assert.assertEquals(null, JSON.parseObject("\"\"", InetAddress.class)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/InetSocketAddressTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/IntArrayEncodeTest.java ================================================ 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.SerializeWriter; public class IntArrayEncodeTest extends TestCase { public void test_0_s() throws Exception { SerializeWriter out = new SerializeWriter(1); JSONSerializer serializer = new JSONSerializer(out); serializer.write(new int[] { 0, 1 }); Assert.assertEquals("[0,1]", out.toString()); } public void test_1_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(out); serializer.write(new int[] {}); Assert.assertEquals("[]", out.toString()); } public void test_2_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(out); serializer.write(new int[] { -2147483648 }); Assert.assertEquals("[-2147483648]", out.toString()); } public void test_3_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(out); StringBuilder sb = new StringBuilder(); sb.append('['); int len = 1000; int[] array = new int[len]; for (int i = 0; i < array.length; ++i) { array[i] = i; if (i != 0) { sb.append(','); } sb.append(i); } sb.append(']'); serializer.write(array); Assert.assertEquals(sb.toString(), out.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/IntFieldTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/IntFieldTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/IntegerArrayEncodeTest.java ================================================ 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.SerializeWriter; public class IntegerArrayEncodeTest extends TestCase { public void test_0_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(out); serializer.write(new Integer[] { 0, 1 }); Assert.assertEquals("[0,1]", out.toString()); } public void test_1_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(out); serializer.write(new Integer[] {}); Assert.assertEquals("[]", out.toString()); } public void test_2_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(out); serializer.write(new Integer[] { -2147483648 }); Assert.assertEquals("[-2147483648]", out.toString()); } public void test_3_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(out); StringBuilder sb = new StringBuilder(); sb.append('['); int len = 1000; Integer[] array = new Integer[len]; for (int i = 0; i < array.length; ++i) { array[i] = i; if (i != 0) { sb.append(','); } sb.append(i); } sb.append(']'); serializer.write(array); Assert.assertEquals(sb.toString(), out.toString()); } public void test_4_s() throws Exception { SerializeWriter out = new SerializeWriter(1); JSONSerializer serializer = new JSONSerializer(out); serializer.write(new Integer[] { 1, null, null }); Assert.assertEquals("[1,null,null]", out.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/IntegerArrayFieldSerializerTest.java ================================================ 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 IntegerArrayFieldSerializerTest extends TestCase { public void test_0() throws Exception { A a1 = new A(); a1.setBytes(new int[] { 1, 2 }); Assert.assertEquals("{\"bytes\":[1,2]}", JSON.toJSONString(a1)); } public void test_1() throws Exception { A a1 = new A(); Assert.assertEquals("{\"bytes\":null}", JSON.toJSONString(a1, SerializerFeature.WriteMapNullValue)); } public static class A { private int[] bytes; public int[] getBytes() { return bytes; } public void setBytes(int[] bytes) { this.bytes = bytes; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/IntegerSerializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/InterfaceTest.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest2.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest3.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest4.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest5.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest6.java ================================================ package com.alibaba.json.bvt.serializer; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; public class JSONFieldTest6 extends TestCase { public void test_for_issue1() { NonStringMap nonStringMap = new NonStringMap(); Map map1 = new HashMap(); map1.put( 111,666 ); nonStringMap.setMap1( map1 ); String json = JSON.toJSONString( nonStringMap ); assertEquals( "{\"map1\":{\"111\":666}}", json ); } public void test_for_issue2() { NonStringMap nonStringMap = new NonStringMap(); Map map2 = new HashMap(); map2.put( 222,888 ); nonStringMap.setMap2( map2 ); String json = JSON.toJSONString( nonStringMap ); assertEquals( "{\"map2\":{222:\"888\"}}", json ); } public void test_for_issue3() { NonStringMap nonStringMap = new NonStringMap(); Map map3 = new HashMap(); map3.put( 333,999 ); nonStringMap.setMap3( map3 ); String json = JSON.toJSONString( nonStringMap ); assertEquals( "{\"map3\":{\"333\":\"999\"}}", json ); } public void test_for_issue4() { NonStringMap nonStringMap = new NonStringMap(); Bean person = new Bean(); person.setAge( 23 ); nonStringMap.setPerson( person ); String json = JSON.toJSONString( nonStringMap ); assertEquals( "{\"person\":{\"age\":\"23\"}}", json ); } class NonStringMap { @JSONField( serialzeFeatures = {SerializerFeature.WriteNonStringKeyAsString} ) private Map map1; public Map getMap1() { return map1; } public void setMap1( Map map1 ) { this.map1 = map1; } @JSONField( serialzeFeatures = {SerializerFeature.WriteNonStringValueAsString} ) private Map map2; public Map getMap2() { return map2; } public void setMap2( Map map2 ) { this.map2 = map2; } @JSONField( serialzeFeatures = {SerializerFeature.WriteNonStringKeyAsString, SerializerFeature.WriteNonStringValueAsString} ) private Map map3; public Map getMap3() { return map3; } public void setMap3( Map map3 ) { this.map3 = map3; } @JSONField( serialzeFeatures = {SerializerFeature.WriteNonStringValueAsString} ) private Bean person; public Bean getPerson() { return person; } public void setPerson( Bean person ) { this.person = person; } } class Bean { private int age; public int getAge() { return age; } public void setAge( int age ) { this.age = age; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_0.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_1.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_2.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_3.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_4.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_5.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_6.java ================================================ 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.ArrayList; import java.util.List; public class JSONFieldTest_unwrapped_6 extends TestCase { public void test_jsonField() throws Exception { Health vo = new Health(); List cities = new ArrayList(); cities.add("Beijing"); cities.add("Shanghai"); vo.id = 123; vo.cities = cities; String text = JSON.toJSONString(vo); Assert.assertEquals("{\"cities\":[\"Beijing\",\"Shanghai\"],\"id\":123}", text); Health vo2 = JSON.parseObject(text, Health.class); assertNotNull(vo2.cities); assertEquals("Beijing", vo2.cities.get(0)); assertEquals("Shanghai", vo2.cities.get(1)); } public void test_null() throws Exception { Health vo = new Health(); vo.id = 123; vo.cities = 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(unwrapped = true) public int id; @JSONField(unwrapped = true) public List cities; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest_unwrapped_7.java ================================================ 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.ArrayList; import java.util.List; public class JSONFieldTest_unwrapped_7 extends TestCase { public void test_jsonField() throws Exception { String str = "{\"s\":\"[\\\"123\\\",\\\"xyz\\\"]\"}"; System.out.println(str); A a = JSON.parseObject(str, A.class); System.out.println(a.getS()); } public static class A { private List s; public List getS() { return s; } @JSONField(unwrapped = true) public void setS(List s) { this.s = s; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONObjectOrderTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerDeprecatedTest.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerFeatureTest.java ================================================ package com.alibaba.json.bvt.serializer; import java.io.StringWriter; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.serializer.SerializerFeature; public class JSONSerializerFeatureTest extends TestCase { public void test_0() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); } public void test_0_g() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); } public void test_1() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.config(SerializerFeature.UseSingleQuotes, true); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.write("abc"); Assert.assertEquals("'abc'", serializer.getWriter().toString()); } public void test_1_s() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.config(SerializerFeature.UseSingleQuotes, true); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.write("abc"); Assert.assertEquals("'abc'", serializer.getWriter().toString()); } public void test_2() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); serializer.config(SerializerFeature.UseSingleQuotes, true); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.write(Collections.singletonMap("age", 33)); Assert.assertEquals("{'age':33}", serializer.getWriter().toString()); } public void test_2_s() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); serializer.config(SerializerFeature.UseSingleQuotes, true); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.write(Collections.singletonMap("age", 33)); Assert.assertEquals("{'age':33}", serializer.getWriter().toString()); } public void test_3() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.write(Collections.singletonMap("age", 33)); Assert.assertEquals("{age:33}", serializer.getWriter().toString()); } public void test_3_s() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.write(Collections.singletonMap("age", 33)); Assert.assertEquals("{age:33}", serializer.getWriter().toString()); } public void test_4() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.write(Collections.singletonMap("a\nge", 33)); Assert.assertEquals("{\"a\\nge\":33}", serializer.getWriter().toString()); } public void test_4_s() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.write(Collections.singletonMap("a\nge", 33)); Assert.assertEquals("{\"a\\nge\":33}", serializer.getWriter().toString()); } public void test_5() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.config(SerializerFeature.UseSingleQuotes, true); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.write(Collections.singletonMap("a\nge", 33)); Assert.assertEquals("{'a\\nge':33}", serializer.getWriter().toString()); } public void test_5_s() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.config(SerializerFeature.UseSingleQuotes, true); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.write(Collections.singletonMap("a\nge", 33)); Assert.assertEquals("{'a\\nge':33}", serializer.getWriter().toString()); } public void test_6() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.config(SerializerFeature.UseSingleQuotes, true); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.write(Collections.singletonMap("a'ge", 33)); Assert.assertEquals("{'a\\'ge':33}", serializer.getWriter().toString()); } public void test_6_s() throws Exception { JSONSerializer serializer = new JSONSerializer(new SerializeWriter()); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.config(SerializerFeature.UseSingleQuotes, true); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.write(Collections.singletonMap("a'ge", 33)); Assert.assertEquals("{'a\\'ge':33}", serializer.getWriter().toString()); } public void test_7() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.write(new User(33)); Assert.assertEquals("{age:33}", serializer.getWriter().toString()); } public void test_7_s() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.write(new User(33)); Assert.assertEquals("{age:33}", serializer.getWriter().toString()); } public void test_8() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.config(SerializerFeature.UseSingleQuotes, true); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.write(new User(33)); Assert.assertEquals("{'age':33}", serializer.getWriter().toString()); } public void test_8_s() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.config(SerializerFeature.UseSingleQuotes, true); Assert.assertEquals(true, serializer.isEnabled(SerializerFeature.UseSingleQuotes)); serializer.write(new User(33)); Assert.assertEquals("{'age':33}", serializer.getWriter().toString()); } public void test_9() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.config(SerializerFeature.WriteMapNullValue, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.WriteMapNullValue)); StringWriter out = new StringWriter(); Map map = new LinkedHashMap(); map.put("a", null); map.put("age", 33); map.put("c", null); serializer.write(map); Assert.assertEquals("{age:33}", serializer.getWriter().toString()); } public void test_9_s() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.config(SerializerFeature.QuoteFieldNames, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.QuoteFieldNames)); serializer.config(SerializerFeature.WriteMapNullValue, false); Assert.assertEquals(false, serializer.isEnabled(SerializerFeature.WriteMapNullValue)); SerializeWriter out = new SerializeWriter(); Map map = new LinkedHashMap(); map.put("a", null); map.put("age", 33); map.put("c", null); serializer.write(map); Assert.assertEquals("{age:33}", serializer.getWriter().toString()); } public static class User { private int age; public User(){ } public User(int age){ this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerMapTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest.java ================================================ package com.alibaba.json.bvt.serializer; import java.io.IOException; import java.io.StringWriter; import java.util.AbstractCollection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONAware; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONStreamAware; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.SerializerFeature; public class JSONSerializerTest extends TestCase { public void test_0() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new C()); Assert.assertEquals("[]", serializer.getWriter().toString()); } public void test_0_s() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new C()); Assert.assertEquals("[]", serializer.getWriter().toString()); } public void test_1() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(Collections.singletonList(1)); Assert.assertEquals("[1]", serializer.getWriter().toString()); } public void test_1_s() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(Collections.singletonList(1)); Assert.assertEquals("[1]", serializer.getWriter().toString()); } public void test_2() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(Collections.EMPTY_MAP); Assert.assertEquals("{}", serializer.getWriter().toString()); } public void test_2_s() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(Collections.EMPTY_MAP); Assert.assertEquals("{}", serializer.getWriter().toString()); } public void test_3() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new JSONAware() { public String toJSONString() { return "null"; } }); Assert.assertEquals("null", serializer.getWriter().toString()); } public void test_3_s() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new JSONAware() { public String toJSONString() { return "null"; } }); Assert.assertEquals("null", serializer.getWriter().toString()); } public void test_4() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new JSONStreamAware() { public void writeJSONString(Appendable out) throws IOException { out.append("abc"); } }); Assert.assertEquals("abc", serializer.getWriter().toString()); } public void test_error() throws Exception { JSONException error = null; try { StringWriter out = new StringWriter(); JSONSerializer serializer = new JSONSerializer(); serializer.write(new JSONStreamAware() { public void writeJSONString(Appendable out) throws IOException { throw new IOException(); } }); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_5() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new A(3)); Assert.assertEquals("{\"id\":3}", serializer.getWriter().toString()); } public void test_5_null() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.config(SerializerFeature.WriteMapNullValue, true); serializer.write(new A(null)); Assert.assertEquals("{\"id\":null}", serializer.getWriter().toString()); } public void test_6() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new Date(1293805405498L)); Assert.assertEquals("1293805405498", serializer.getWriter().toString()); } public void test_7() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new B(1293805405498L)); Assert.assertEquals("{\"d\":1293805405498}", serializer.getWriter().toString()); } public void test_8() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new B()); Assert.assertEquals("{}", serializer.getWriter().toString()); } public void test_9() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new D(3L)); Assert.assertEquals("{\"id\":3}", serializer.getWriter().toString()); } public void test_9_null() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.config(SerializerFeature.WriteMapNullValue, true); serializer.write(new D(null)); Assert.assertEquals("{\"id\":null}", serializer.getWriter().toString()); } public void test_10() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(3); Assert.assertEquals("3", serializer.getWriter().toString()); } public void test_11() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(3L); Assert.assertEquals("3", serializer.getWriter().toString()); } public void test_12() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new Object[0]); Assert.assertEquals("[]", serializer.getWriter().toString()); } public void test_13() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new Object[] { 1 }); Assert.assertEquals("[1]", serializer.getWriter().toString()); } public void test_14() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new Object[] { 1, 2, 3, 4 }); Assert.assertEquals("[1,2,3,4]", serializer.getWriter().toString()); } public void test_15() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new Object[] { 1L, 2L, 3L, 4L }); Assert.assertEquals("[1,2,3,4]", serializer.getWriter().toString()); } public void test_16() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new Object[] { "", "", "", "" }); Assert.assertEquals("[\"\",\"\",\"\",\"\"]", serializer.getWriter().toString()); } public void test_17() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new Object[] { null, null, null, null }); Assert.assertEquals("[null,null,null,null]", serializer.getWriter().toString()); } public static class A { private Integer id; public A(Integer id){ super(); this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } public static class B { private Date d; public B(){ } public B(long value){ super(); this.d = new Date(value); } public Date getD() { return d; } public void setD(Date d) { this.d = d; } } public static class D { private Long id; public D(Long id){ super(); this.id = id; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } public static class C extends AbstractCollection { @Override public Iterator iterator() { return Collections.EMPTY_LIST.iterator(); } @Override public int size() { return 0; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest1.java ================================================ package com.alibaba.json.bvt.serializer; import com.alibaba.fastjson.JSON; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.SerializeWriter; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class JSONSerializerTest1 extends TestCase { public void test_0 () throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(out); Assert.assertEquals(0, serializer.getNameFilters().size()); Assert.assertEquals(0, serializer.getNameFilters().size()); Assert.assertEquals(0, serializer.getValueFilters().size()); Assert.assertEquals(0, serializer.getValueFilters().size()); Assert.assertEquals(0, serializer.getPropertyFilters().size()); Assert.assertEquals(0, serializer.getPropertyFilters().size()); serializer.writeWithFormat("123", null); } public void test_1() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(out); Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(2019, Calendar.SEPTEMBER, 5); Date date = calendar.getTime(); String dateFormatPattern = "yyyy/MM/dd"; SimpleDateFormat sdf = new SimpleDateFormat(dateFormatPattern); serializer.writeWithFormat(date, dateFormatPattern); assertEquals("\"" + sdf.format(date) + "\"", serializer.out.toString()); } public void test_2() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(out); Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(2019, Calendar.SEPTEMBER, 5); Date date = calendar.getTime(); String dateFormatPattern = "yyyy.MM.dd"; String temp = JSON.DEFFAULT_DATE_FORMAT; JSON.DEFFAULT_DATE_FORMAT = dateFormatPattern; SimpleDateFormat sdf = new SimpleDateFormat(JSON.DEFFAULT_DATE_FORMAT); //传入null时调用JSON.DEFFAULT_DATE_FORMAT serializer.writeWithFormat(date, null); JSON.DEFFAULT_DATE_FORMAT = temp; assertEquals("\"" + sdf.format(date) + "\"", serializer.out.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest2.java ================================================ package com.alibaba.json.bvt.serializer; import java.io.IOException; import java.io.Writer; 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(); serializer.getMapping().clearSerializers(); int size = JSONSerializerMapTest.size(serializer.getMapping()); serializer.config(SerializerFeature.WriteEnumUsingToString, false); serializer.config(SerializerFeature.WriteEnumUsingName, false); serializer.write(Type.A); 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()); A a = JSON.parseObject(serializer.getWriter().toString(), A.class); Assert.assertEquals(a.getType(), Type.B); } public void test_2() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.write(new C()); Assert.assertEquals("{}", serializer.getWriter().toString()); } public void test_3() throws Exception { JSONSerializer serializer = new JSONSerializer(); serializer.config(SerializerFeature.WriteEnumUsingToString, true); serializer.write(new A(Type.B)); Assert.assertEquals("{\"type\":\"B\"}", serializer.getWriter().toString()); A a = JSON.parseObject(serializer.getWriter().toString(), A.class); Assert.assertEquals(a.getType(), Type.B); } public void test_error() throws Exception { Exception error = null; try { JSONSerializer.write(new 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 { throw new IOException(); } }, (Object) "abc"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public static enum Type { A, B } public static class A { private Type type; public A(){ } public A(Type type){ super(); this.type = type; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } } public static class C { } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONSerializerTest3.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JSONTypeIncludesTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JavaBeanSerializerTest.java ================================================ package com.alibaba.json.bvt.serializer; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.serializer.FieldSerializer; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.JavaBeanSerializer; import com.alibaba.fastjson.serializer.SerializeWriter; public class JavaBeanSerializerTest extends TestCase { public void test_0_s() throws Exception { SerializeWriter out = new SerializeWriter(); A a = new A(); a.getL0().add("A"); a.getL0().add("B"); JavaBeanSerializer serializer = new JavaBeanSerializer(A.class); serializer.write(new JSONSerializer(out), a, null, null, 0); Assert.assertEquals("{\"l0\":[\"A\",\"B\"]}", out.toString()); } public void test_1_s() throws Exception { SerializeWriter out = new SerializeWriter(); B a = new B(); a.getL0().add("A"); a.getL0().add("B"); JavaBeanSerializer serializer = new JavaBeanSerializer(B.class); serializer.write(new JSONSerializer(out), a, null, null, 0); Assert.assertEquals("{\"l0\":[\"A\",\"B\"],\"l1\":[]}", out.toString()); } 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)), null, null, 0); Assert.assertEquals("{\"e\":{\"id\":123}}", out.toString()); } 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), null, null, 0); Assert.assertEquals("{}", out.toString()); } public void test_error_s() throws Exception { JSONException error = null; try { SerializeWriter out = new SerializeWriter(); JavaBeanSerializer serializer = new JavaBeanSerializer(C.class); serializer.write(new JSONSerializer(out), new C(), null, null, 0); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public void test_error_1_s() throws Exception { JSONException error = null; try { SerializeWriter out = new SerializeWriter(); JavaBeanSerializer serializer = new JavaBeanSerializer(D.class); serializer.write(new JSONSerializer(out), new D(), null, null, 0); } catch (JSONException e) { error = e; } Assert.assertNotNull(error); } public static class A { private List l0 = new ArrayList(); public List getL0() { return l0; } public void setL0(List l0) { this.l0 = l0; } public Object get() { return null; } public Object getx() { return null; } public boolean is() { return true; } public boolean isx() { return true; } } public static class B { private Collection l0 = new ArrayList(); private Collection l1 = new ArrayList(); public Collection getL1() { return l1; } public void setL1(Collection l1) { this.l1 = l1; } public Collection getL0() { return l0; } public void setL0(Collection l0) { this.l0 = l0; } public Object get() { return null; } public Object getx() { return null; } public boolean is() { return true; } public boolean isx() { return true; } } public static class C { public List getL0() { throw new RuntimeException(); } public void setL0(List l0) { } } public static class D { public Collection getL0() { throw new RuntimeException(); } } public static class E { private int id; public E(){ } public E(int id){ this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } } public static class F { private E e; public F(){ } public F(E e){ this.e = e; } public E getE() { return e; } public void setE(E e) { this.e = e; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/JavaBeanSerializerTest2.java ================================================ package com.alibaba.json.bvt.serializer; import java.util.Collections; import junit.framework.TestCase; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.JavaBeanSerializer; public class JavaBeanSerializerTest2 extends TestCase { public void test_0() throws Exception { new JavaBeanSerializer(A.class, Collections. emptyMap()); } public static class A { @JSONField(name = "uid") private int id; private String name; @JSONField(deserialize = false) private boolean b1; @JSONField(name = "B2") private boolean b2; private byte[] bytes; public byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } public boolean isB2() { return b2; } public void setB2(boolean b2) { this.b2 = b2; } public boolean isB1() { return b1; } public void setB1(boolean b1) { this.b1 = b1; } public int getId() { return id; } public void setId(int id) { this.id = id; } @JSONField(name = "xname") public String getName() { return name; } public void setName(String name) { this.name = name; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ListFieldTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest2.java ================================================ package com.alibaba.json.bvt.serializer; import java.util.Arrays; import java.util.List; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.ListSerializer; import com.alibaba.fastjson.serializer.SerializeWriter; public class ListSerializerTest2 extends TestCase { public void test_0() throws Exception { SerializeWriter out = new SerializeWriter(); ListSerializer listSerializer = new ListSerializer(); Object[] array = new Object[] { 1, 2, 3L, 4L, 5, 6, "a" }; List list = Arrays.asList(array); 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ListSerializerTest3.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ListTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/LocalTest.java ================================================ package com.alibaba.json.bvt.serializer; import java.util.Locale; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class LocalTest extends TestCase { public void test_timezone() throws Exception { String text = JSON.toJSONString(Locale.CHINA); Assert.assertEquals(JSON.toJSONString(Locale.CHINA.toString()), text); Locale locale = JSON.parseObject(text, Locale.class); Assert.assertEquals(Locale.CHINA, locale); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/LongArraySerializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/MapSerializerTest.java ================================================ package com.alibaba.json.bvt.serializer; import java.util.Collections; 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.JSONObject; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.MapSerializer; import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.serializer.SerializerFeature; public class MapSerializerTest extends TestCase { public void test_empty_1() throws Exception { SerializeWriter out = new SerializeWriter(); MapSerializer mapSerializer = new MapSerializer(); mapSerializer.write(new JSONSerializer(out), Collections.EMPTY_MAP, null, null, 0); Assert.assertEquals("{}", out.toString()); } public void test_singleton_1() throws Exception { SerializeWriter out = new SerializeWriter(); MapSerializer mapSerializer = new MapSerializer(); mapSerializer.write(new JSONSerializer(out), Collections.singletonMap("A", 1), null, null, 0); Assert.assertEquals("{\"A\":1}", out.toString()); } public void test_int2_s() throws Exception { SerializeWriter out = new SerializeWriter(); MapSerializer mapSerializer = new MapSerializer(); Map map = new LinkedHashMap(); map.put("A", 1); map.put("B", 2); mapSerializer.write(new JSONSerializer(out), map, null, null, 0); Assert.assertEquals("{\"A\":1,\"B\":2}", out.toString()); } public void test_long2_s() throws Exception { SerializeWriter out = new SerializeWriter(); MapSerializer mapSerializer = new MapSerializer(); Map map = new LinkedHashMap(); map.put("A", 1L); map.put("B", 2L); mapSerializer.write(new JSONSerializer(out), map, null, null, 0); Assert.assertEquals("{\"A\":1,\"B\":2}", out.toString()); } public void test_string2_s() throws Exception { SerializeWriter out = new SerializeWriter(); MapSerializer mapSerializer = new MapSerializer(); Map map = new LinkedHashMap(); map.put("A", "1"); map.put("B", "2"); mapSerializer.write(new JSONSerializer(out), map, null, null, 0); Assert.assertEquals("{\"A\":\"1\",\"B\":\"2\"}", out.toString()); } public void test_string3_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer serializer = new JSONSerializer(out); serializer.config(SerializerFeature.UseSingleQuotes, true); MapSerializer mapSerializer = new MapSerializer(); Map map = new LinkedHashMap(); map.put("A", "1"); map.put("B", "2"); mapSerializer.write(serializer, map, null, null, 0); Assert.assertEquals("{'A':'1','B':'2'}", out.toString()); } 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), null, null, 0); Assert.assertEquals("{\"A\\nB\":1}", out.toString()); } 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), null, null, 0); Assert.assertEquals("{\"A\\nB\":1}", out.toString()); } 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), null, null, 0); Assert.assertEquals("{\"A\\nB\":{}}", out.toString()); } public void test_4() throws Exception { SerializeWriter out = new SerializeWriter(); Map map = new LinkedHashMap(); map.put("TOP", "value"); map.put("bytes", new byte[] { 1, 2 }); MapSerializer mapSerializer = new MapSerializer(); 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/MapTest.java ================================================ package com.alibaba.json.bvt.serializer; import com.alibaba.fastjson.annotation.JSONField; 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; import java.util.HashMap; import java.util.Map; 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(); } } public void test_onJSONField() { Map map = new HashMap(); map.put("Ariston", null); MapNullValue mapNullValue = new MapNullValue(); mapNullValue.setMap( map ); String json = JSON.toJSONString( mapNullValue ); assertEquals("{\"map\":{\"Ariston\":null}}", json); } class MapNullValue { @JSONField(serialzeFeatures = {SerializerFeature.WriteMapNullValue}) private Map map; public Map getMap() { return map; } public void setMap( Map map ) { this.map = map; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/MaxBufSizeTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/MaxBufSizeTest2.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/MultiFieldIntTest_writer.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/MultiFieldIntTest_writer2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/NoneStringKeyTest.java ================================================ package com.alibaba.json.bvt.serializer; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.parser.Feature; 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)); } public void test_4() throws Exception { SubjectDTO dto = new SubjectDTO(); dto.getResults().put(3, new Result()); String json = JSON.toJSONString(dto); assertEquals("{\"results\":{3:{}}}", json); SubjectDTO dto2 = JSON.parseObject(json, SubjectDTO.class, Feature.NonStringKeyAsString); System.out.println(JSON.toJSONString(dto2.getResults())); } public static class Result { } public static class SubjectDTO { private Map results = new HashMap(); public Map getResults() { return results; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/NotWriteDefaultValueTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/NotWriteDefaultValueTest_NoneASM.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ObjectArraySerializerTest.java ================================================ 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.SerializeWriter; public class ObjectArraySerializerTest extends TestCase { public void test_0() throws Exception { SerializeWriter out = new SerializeWriter(1); JSONSerializer.write(out, new Object[] { "a12", "b34" }); Assert.assertEquals("[\"a12\",\"b34\"]", out.toString()); } public void test_1() throws Exception { SerializeWriter out = new SerializeWriter(1); JSONSerializer.write(out, new Object[] {}); Assert.assertEquals("[]", out.toString()); } public void test_2() throws Exception { SerializeWriter out = new SerializeWriter(1); JSONSerializer.write(out, new Object[] { null, null }); Assert.assertEquals("[null,null]", out.toString()); } public void test_3() throws Exception { Assert.assertEquals("[null,null]", JSON.toJSONString(new Object[] { null, null }, false)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ObjectSerializerTest.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ObjectWriteTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ParserConfigTest.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/PascalNameFilterTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/PascalNameFilterTest_1.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/PatternTest.java ================================================ package com.alibaba.json.bvt.serializer; import java.util.regex.Pattern; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; public class PatternTest extends TestCase { public void test_file() throws Exception { Pattern p = Pattern.compile("a*b"); String text = JSON.toJSONString(p); Assert.assertEquals(JSON.toJSONString(p.pattern()), text); Pattern p1 = JSON.parseObject(text, Pattern.class); Assert.assertEquals(p.pattern(), p1.pattern()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/PointSerializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/PrePropertyFilterTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/PrettyFormatTest.java ================================================ package com.alibaba.json.bvt.serializer; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.SerializerFeature; public class PrettyFormatTest extends TestCase { public void test_0() throws Exception { Assert.assertEquals(0, new JSONSerializer().getIndentCount()); Assert.assertEquals("[\n\t{},\n\t{}\n]", JSON.toJSONString(new Object[] { new Object(), new Object() }, SerializerFeature.PrettyFormat)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/PrettyFormatTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/PrimitiveTest.java ================================================ 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; public class PrimitiveTest extends TestCase { public void test_0() throws Exception { StringWriter out = new StringWriter(); JSONSerializer.write(out, (byte) 1); Assert.assertEquals("1", out.toString()); } public void test_0_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer.write(out, (byte) 1); Assert.assertEquals("1", out.toString()); } public void test_1() throws Exception { StringWriter out = new StringWriter(); JSONSerializer.write(out, (short) 1); Assert.assertEquals("1", out.toString()); } public void test_1_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer.write(out, (short) 1); Assert.assertEquals("1", out.toString()); } public void test_2() throws Exception { StringWriter out = new StringWriter(); JSONSerializer.write(out, true); Assert.assertEquals("true", out.toString()); } public void test_2_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer.write(out, true); Assert.assertEquals("true", out.toString()); } public void test_3() throws Exception { StringWriter out = new StringWriter(); JSONSerializer.write(out, false); Assert.assertEquals("false", out.toString()); } public void test_3_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer.write(out, false); Assert.assertEquals("false", out.toString()); } public void test_4() throws Exception { StringWriter out = new StringWriter(); JSONSerializer.write(out, new boolean[] { true, false }); Assert.assertEquals("[true,false]", out.toString()); } public void test_4_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer.write(out, new boolean[] { true, false }); Assert.assertEquals("[true,false]", out.toString()); } public void test_5() throws Exception { StringWriter out = new StringWriter(); JSONSerializer.write(out, new boolean[] {}); Assert.assertEquals("[]", out.toString()); } public void test_5_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer.write(out, new boolean[] {}); Assert.assertEquals("[]", out.toString()); } public void test_6() throws Exception { StringWriter out = new StringWriter(); JSONSerializer.write(out, new boolean[] { true, false, true }); Assert.assertEquals("[true,false,true]", out.toString()); } public void test_6_s() throws Exception { SerializeWriter out = new SerializeWriter(); JSONSerializer.write(out, new boolean[] { true, false, true }); Assert.assertEquals("[true,false,true]", out.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ProxyTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ProxyTest2.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/RectangleSerializerTest.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/ReferenceDeserializerTest.java ================================================ 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); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerialContextTest.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerialWriterStringEncoderTest2.java ================================================ 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 org.junit.Assert; import com.alibaba.fastjson.serializer.SerializeWriter; 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); Exception error = null; char[] chars = "abc".toCharArray(); try { encode(charsetEncoder, chars, 0, chars.length); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_1() throws Exception { Charset charset = Charset.forName("UTF-8"); CharsetEncoder realEncoder = charset.newEncoder(); CharsetEncoder charsetEncoder = new MockCharsetEncoder(charset, realEncoder); Exception error = null; char[] chars = "abc".toCharArray(); try { 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; protected MockCharsetEncoder(Charset cs, CharsetEncoder raw){ super(cs, raw.averageBytesPerChar(), raw.maxBytesPerChar()); this.raw = raw; } @Override protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) { return raw.encode(in, out, false); } protected CoderResult implFlush(ByteBuffer out) { return CoderResult.malformedForLength(1); } } public static class MockCharsetEncoder2 extends CharsetEncoder { protected MockCharsetEncoder2(Charset cs){ super(cs, 2, 2); } @Override protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) { return CoderResult.OVERFLOW; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerialWriterTest.java ================================================ package com.alibaba.json.bvt.serializer; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.fastjson.serializer.SerializeWriter; public class SerialWriterTest extends TestCase { public void test_0() throws Exception { for (int i = 0; i < 3; ++i) { { String text = "abc"; String charset = "UTF-8"; SerializeWriter writer = new SerializeWriter(); writer.append(text); byte[] bytes = writer.toBytes(charset); Assert.assertArrayEquals(text.getBytes(charset), bytes); } { String text = "efg"; String charset = "UTF-8"; SerializeWriter writer = new SerializeWriter(); writer.append(text); byte[] bytes = writer.toBytes(charset); Assert.assertArrayEquals(text.getBytes(charset), bytes); } } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest.java ================================================ 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)); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest2.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeConfigTest2_private.java ================================================ 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; } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_1.java ================================================ package com.alibaba.json.bvt.serializer; import java.io.ByteArrayOutputStream; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.serializer.SerializerFeature; public class SerializeWriterTest_1 extends TestCase { public void test_0 () throws Exception { SerializeWriter out = new SerializeWriter(SerializerFeature.UseSingleQuotes); out.writeString("abc"); Assert.assertEquals("'abc'", out.toString()); } public void test_1 () throws Exception { SerializeWriter out = new SerializeWriter(SerializerFeature.UseSingleQuotes); out.writeString("abc中文"); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); out.writeTo(byteOut, "UTF-8"); Assert.assertEquals("'abc中文'", new String(byteOut.toByteArray(), "UTF-8")); } public void test_2 () throws Exception { SerializeWriter out = new SerializeWriter(SerializerFeature.UseSingleQuotes); out.writeString("abc"); Assert.assertEquals("'abc'", new String(out.toBytes((String) null), "ISO-8859-1")); } public void test_3 () throws Exception { SerializeWriter out = new SerializeWriter(SerializerFeature.UseSingleQuotes); out.writeString("abc"); Assert.assertEquals("'abc'", new String(out.toBytes("UTF-16"), "UTF-16")); } public void test_5 () throws Exception { SerializeWriter out = new SerializeWriter(1); out.write((String) null); Assert.assertEquals("null", new String(out.toBytes("UTF-16"), "UTF-16")); } public void test_6 () throws Exception { SerializeWriter out = new SerializeWriter(1); out.writeString("中文"); Assert.assertEquals("\"中文\"", new String(out.toBytes("UTF-16"), "UTF-16")); } public void test_null () throws Exception { SerializeWriter out = new SerializeWriter(1); out.writeString((String) null); Assert.assertEquals("null", new String(out.toBytes("UTF-16"), "UTF-16")); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_10.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_11.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_12.java ================================================ 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 { } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_13.java ================================================ 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(); } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_14.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_15.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_16.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_17.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_18.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_19.java ================================================ 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; } } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_2.java ================================================ package com.alibaba.json.bvt.serializer; 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 { SerializeWriter out = new SerializeWriter(1); 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_3.java ================================================ 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()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_4.java ================================================ package com.alibaba.json.bvt.serializer; 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(',', "name", "\t"); Assert.assertEquals(",\"name\":\"\\t\"", out.toString()); out.close(); } public void test_1() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, true); 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 { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, true); 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 { SerializeWriter out = new SerializeWriter(1); 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()); out.close(); } public void test_5() throws Exception { SerializeWriter out = new SerializeWriter(1000); out.config(SerializerFeature.QuoteFieldNames, true); 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_5.java ================================================ package com.alibaba.json.bvt.serializer; import java.math.BigDecimal; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.serializer.SerializeWriter; import com.alibaba.fastjson.serializer.SerializerFeature; public class SerializeWriterTest_5 extends TestCase { public void test_0() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, true); out.writeFieldValue(',', "name", (Enum) null); Assert.assertEquals(",\"name\":null", out.toString()); } public void test_1() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, true); out.writeFieldValue(',', "name", (BigDecimal) null); Assert.assertEquals(",\"name\":null", out.toString()); } public void test_2() 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_3() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, true); out.config(SerializerFeature.UseSingleQuotes, true); out.writeFieldValue(',', "name", (String) null); Assert.assertEquals(",'name':null", out.toString()); } public void test_4() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, true); out.config(SerializerFeature.UseSingleQuotes, true); out.writeFieldValue(',', "name", (String) null); Assert.assertEquals(",'name':null", out.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_6.java ================================================ 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_6 extends TestCase { public void test_0() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, true); out.config(SerializerFeature.UseSingleQuotes, true); out.writeFieldValue(',', "name", (Enum) null); Assert.assertEquals(",'name':null", out.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_7.java ================================================ 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_7 extends TestCase { public void test_0() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, true); out.config(SerializerFeature.UseSingleQuotes, true); out.writeFieldValue(',', "name", (Enum) null); Assert.assertEquals(",'name':null", out.toString()); } public void test_1() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, true); out.config(SerializerFeature.UseSingleQuotes, true); out.writeFieldName("名称"); Assert.assertEquals("'名称':", out.toString()); } public void test_2() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, false); out.writeFieldName("名称"); Assert.assertEquals("名称:", out.toString()); } public void test_3() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, false); out.writeFieldName("a\n\n\n\n"); Assert.assertEquals("\"a\\n\\n\\n\\n\":", out.toString()); } public void test_4() throws Exception { SerializeWriter out = new SerializeWriter(1); out.config(SerializerFeature.QuoteFieldNames, false); out.config(SerializerFeature.UseSingleQuotes, true); out.writeFieldName("a\n\n\n\n"); Assert.assertEquals("'a\\n\\n\\n\\n':", out.toString()); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_8.java ================================================ 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); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_9.java ================================================ 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(); } } ================================================ FILE: src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_BrowserSecure.java ================================================ 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("