com.alibaba.fastjson.serializer.SerializeConfig Java Examples
The following examples show how to use
com.alibaba.fastjson.serializer.SerializeConfig.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FastJsonUnitTest.java From tutorials with MIT License | 6 votes |
@Test public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() { NameFilter formatName = new NameFilter() { public String process(Object object, String name, Object value) { return name.toLowerCase() .replace(" ", "_"); } }; SerializeConfig.getGlobalInstance() .addFilter(Person.class, formatName); String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd"); assertEquals(jsonOutput, "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]"); // resetting custom serializer SerializeConfig.getGlobalInstance() .put(Person.class, null); }
Example #2
Source File: SentinelRecorder.java From Sentinel with Apache License 2.0 | 6 votes |
/** * register fastjson serializer deserializer class info */ public void init() { SerializeConfig.getGlobalInstance().getObjectWriter(NodeVo.class); SerializeConfig.getGlobalInstance().getObjectWriter(FlowRule.class); SerializeConfig.getGlobalInstance().getObjectWriter(SystemRule.class); SerializeConfig.getGlobalInstance().getObjectWriter(DegradeRule.class); SerializeConfig.getGlobalInstance().getObjectWriter(AuthorityRule.class); SerializeConfig.getGlobalInstance().getObjectWriter(ParamFlowRule.class); ParserConfig.getGlobalInstance().getDeserializer(NodeVo.class); ParserConfig.getGlobalInstance().getDeserializer(FlowRule.class); ParserConfig.getGlobalInstance().getDeserializer(SystemRule.class); ParserConfig.getGlobalInstance().getDeserializer(DegradeRule.class); ParserConfig.getGlobalInstance().getDeserializer(AuthorityRule.class); ParserConfig.getGlobalInstance().getDeserializer(ParamFlowRule.class); }
Example #3
Source File: FastJson.java From actframework with Apache License 2.0 | 6 votes |
private void handleForSerializer(final ObjectSerializer serializer, Class targetType) { ClassNode node = repo.node(targetType.getName()); if (null == node) { warn("Unknown target type: " + targetType.getName()); return; } final SerializeConfig config = SerializeConfig.getGlobalInstance(); node.visitSubTree(new Lang.Visitor<ClassNode>() { @Override public void visit(ClassNode classNode) throws Lang.Break { Class type = app.classForName(classNode.name()); config.put(type, serializer); } }); config.put(targetType, serializer); }
Example #4
Source File: DefaultWebMvcConfigurerAdapter.java From dk-foundation with GNU Lesser General Public License v2.1 | 6 votes |
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; fastJsonConfig.setSerializerFeatures(SerializerFeature.BrowserCompatible, SerializerFeature.BrowserSecure, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect); /** * 解决Long转json精度丢失的问题 */ SerializeConfig serializeConfig = SerializeConfig.globalInstance; serializeConfig.put(BigInteger.class, ToStringSerializer.instance); serializeConfig.put(Long.class, ToStringSerializer.instance); serializeConfig.put(Long.TYPE, ToStringSerializer.instance); fastJsonConfig.setSerializeConfig(serializeConfig); fastConvert.setFastJsonConfig(fastJsonConfig); converters.add(fastConvert); }
Example #5
Source File: Endpoint.java From actframework with Apache License 2.0 | 6 votes |
private String generateSampleJson(BeanSpec spec, Map<String, Class> typeParamLookup, boolean isReturn) { Class<?> type = spec.rawType(); if (Result.class.isAssignableFrom(type) || void.class == type) { return null; } returnSampleObject = generateSampleData(spec, typeParamLookup, new HashSet<Type>(), new ArrayList<String>(), isReturn); if (null == returnSampleObject) { return null; } if (returnSampleObject instanceof Map && ((Map) returnSampleObject).isEmpty()) { return null; } if (!type.isArray() && $.isSimpleType(type) && (String.class != type || !isValidJson(S.string(returnSampleObject)))) { returnSampleObject = C.Map("result", returnSampleObject); } SerializeFilter[] filters = new SerializeFilter[null == fastJsonPropertyPreFilter ? 0 : 1]; if (null != fastJsonPropertyPreFilter) { filters[0] = fastJsonPropertyPreFilter; } SerializerFeature[] features = new SerializerFeature[] { SerializerFeature.PrettyFormat }; return JSON.toJSONString(returnSampleObject, SerializeConfig.globalInstance, filters, features); }
Example #6
Source File: AVOSCloud.java From java-unified-sdk with Apache License 2.0 | 5 votes |
public static void initialize(String appId, String appKey) { ObjectTypeAdapter adapter = new ObjectTypeAdapter(); ParserConfig.getGlobalInstance().putDeserializer(AVObject.class, adapter); ParserConfig.getGlobalInstance().putDeserializer(AVUser.class, adapter); ParserConfig.getGlobalInstance().putDeserializer(AVFile.class, adapter); ParserConfig.getGlobalInstance().putDeserializer(AVStatus.class, adapter); ParserConfig.getGlobalInstance().putDeserializer(AVInstallation.class, adapter); SerializeConfig.getGlobalInstance().put(AVObject.class, adapter); SerializeConfig.getGlobalInstance().put(AVUser.class, adapter); SerializeConfig.getGlobalInstance().put(AVFile.class, adapter); SerializeConfig.getGlobalInstance().put(AVStatus.class, adapter); SerializeConfig.getGlobalInstance().put(AVInstallation.class, adapter); BaseOperationAdapter opAdapter = new BaseOperationAdapter(); ParserConfig.getGlobalInstance().putDeserializer(BaseOperation.class, opAdapter); SerializeConfig.getGlobalInstance().put(BaseOperation.class, opAdapter); AVObject.registerSubclass(AVStatus.class); AVObject.registerSubclass(AVUser.class); AVObject.registerSubclass(AVFile.class); AVObject.registerSubclass(AVInstallation.class); applicationId = appId; applicationKey = appKey; PaasClient.initializeGlobalClient(); }
Example #7
Source File: JsonSerialization.java From joyrpc with Apache License 2.0 | 5 votes |
/** * 创建序列化配置 * * @return */ protected SerializeConfig createSerializeConfig() { //不采用全局配置,防止用户修改,造成消费者处理错误 SerializeConfig config = new SerializeConfig(); config.put(MonthDay.class, MonthDaySerialization.INSTANCE); config.put(YearMonth.class, YearMonthSerialization.INSTANCE); config.put(Year.class, YearSerialization.INSTANCE); config.put(ZoneOffset.class, ZoneOffsetSerialization.INSTANCE); config.put(ZoneId.class, ZoneIdSerialization.INSTANCE); config.put(ZoneId.systemDefault().getClass(), ZoneIdSerialization.INSTANCE); config.put(Invocation.class, InvocationCodec.INSTANCE); config.put(ResponsePayload.class, ResponsePayloadCodec.INSTANCE); config.put(BackupShard.class, BackupShardSerializer.INSTANCE); return config; }
Example #8
Source File: AbstractRepository.java From yue-library with Apache License 2.0 | 5 votes |
/** * 插入数据-实体 * * @param paramIPO 参数IPO(POJO-IPO对象) * @param databaseFieldNamingStrategyEnum 数据库字段命名策略 * @return 返回主键值 */ public Long insert(Object paramIPO, FieldNamingStrategyEnum databaseFieldNamingStrategyEnum) { PropertyNamingStrategy propertyNamingStrategy = databaseFieldNamingStrategyEnum.getPropertyNamingStrategy(); SerializeConfig serializeConfig = new SerializeConfig(); serializeConfig.setPropertyNamingStrategy(propertyNamingStrategy); JSONObject paramJson = (JSONObject) JSONObject.toJSON(paramIPO, serializeConfig); return insert(paramJson); }
Example #9
Source File: DefaultFastjsonConfig.java From flash-waimai with MIT License | 5 votes |
/** * fastjson的配置 */ public FastJsonConfig fastjsonConfig() { FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures( SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteEnumUsingToString, SerializerFeature.DisableCircularReferenceDetect ); fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); ValueFilter valueFilter = new ValueFilter() { @Override public Object process(Object o, String s, Object o1) { if (null == o1) { o1 = ""; } return o1; } }; fastJsonConfig.setCharset(Charset.forName("utf-8")); fastJsonConfig.setSerializeFilters(valueFilter); //解决Long转json精度丢失的问题 SerializeConfig serializeConfig = SerializeConfig.globalInstance; serializeConfig.put(BigInteger.class, ToStringSerializer.instance); serializeConfig.put(Long.class, ToStringSerializer.instance); serializeConfig.put(Long.TYPE, ToStringSerializer.instance); fastJsonConfig.setSerializeConfig(serializeConfig); return fastJsonConfig; }
Example #10
Source File: FastJsonConfig.java From metrics with Apache License 2.0 | 5 votes |
public FastJsonConfig(SerializeConfig serializeConfig, SerializerFeature[] serializerFeatures, Map<Class<?>, SerializeFilter> serializeFilters, ParserConfig parserConfig, Feature[] features) { this.serializeConfig = serializeConfig; this.parserConfig = parserConfig; this.serializerFeatures = serializerFeatures; this.features = features; this.serializeFilters = serializeFilters; }
Example #11
Source File: GHIssue297.java From actframework with Apache License 2.0 | 5 votes |
@BeforeClass public static void prepareFastJson() { FastJsonObjectIdCodec objectIdCodec = new FastJsonObjectIdCodec(); SerializeConfig serializeConfig = SerializeConfig.getGlobalInstance(); serializeConfig.put(ObjectId.class, objectIdCodec); }
Example #12
Source File: JsonDataCodec.java From spring-boot-protocol with Apache License 2.0 | 5 votes |
@Override public byte[] encodeResponseData(Object data,RpcMethod rpcMethod) { if(data == null){ return EMPTY; } try (SerializeWriter out = new SerializeWriter(null, JSON.DEFAULT_GENERATE_FEATURE, SERIALIZER_FEATURES)) { JSONSerializer serializer = new JSONSerializer(out, SerializeConfig.globalInstance); serializer.write(data); return out.toBytes(CHARSET_UTF8); } }
Example #13
Source File: FastJsonConfig.java From fastjson-jaxrs-json-provider with Apache License 2.0 | 5 votes |
public FastJsonConfig(SerializeConfig serializeConfig, SerializerFeature[] serializerFeatures, Map<Class<?>, SerializeFilter> serializeFilters, ParserConfig parserConfig, Feature[] features) { this.serializeConfig = serializeConfig; this.parserConfig = parserConfig; this.serializerFeatures = serializerFeatures; this.features = features; this.serializeFilters = serializeFilters; }
Example #14
Source File: FastJsonHttpMessageConverter.java From mcg-helper with Apache License 2.0 | 5 votes |
protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { HttpHeaders headers = outputMessage.getHeaders(); String text = null; this.writeBefore(obj); if (!(obj instanceof JsonpResult)) { text = JSON.toJSONString(obj, // SerializeConfig.globalInstance, // filters, // dateFormat, // JSON.DEFAULT_GENERATE_FEATURE, // features); } else { JsonpResult jsonp = (JsonpResult) obj; text = new StringBuilder(jsonp.getJsonpFunction()) .append('(') .append(JSON.toJSONString( jsonp.getValue(), // SerializeConfig.globalInstance, filters, dateFormat, JSON.DEFAULT_GENERATE_FEATURE, features)) .append(");").toString(); } this.writeAfter(text); byte[] bytes = text.getBytes(charset); headers.setContentLength(bytes.length); OutputStream out = outputMessage.getBody(); out.write(bytes); out.flush(); }
Example #15
Source File: Transformer.java From java-unified-sdk with Apache License 2.0 | 5 votes |
public static <T extends AVObject> void registerClass(Class<T> clazz) { AVClassName avClassName = clazz.getAnnotation(AVClassName.class); if (avClassName == null) { throw new IllegalArgumentException("The class is not annotated by @AVClassName"); } String className = avClassName.value(); checkClassName(className); subClassesMAP.put(className, clazz); subClassesReverseMAP.put(clazz, className); // register object serializer/deserializer. ParserConfig.getGlobalInstance().putDeserializer(clazz, new ObjectTypeAdapter()); SerializeConfig.getGlobalInstance().put(clazz, new ObjectTypeAdapter()); }
Example #16
Source File: DefaultFastjsonConfig.java From MeetingFilm with Apache License 2.0 | 5 votes |
/** * fastjson的配置 */ public FastJsonConfig fastjsonConfig() { FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures( SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteEnumUsingToString ); fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); ValueFilter valueFilter = new ValueFilter() { public Object process(Object o, String s, Object o1) { if (null == o1) { o1 = ""; } return o1; } }; fastJsonConfig.setCharset(Charset.forName("utf-8")); fastJsonConfig.setSerializeFilters(valueFilter); //解决Long转json精度丢失的问题 SerializeConfig serializeConfig = SerializeConfig.globalInstance; serializeConfig.put(BigInteger.class, ToStringSerializer.instance); serializeConfig.put(Long.class, ToStringSerializer.instance); serializeConfig.put(Long.TYPE, ToStringSerializer.instance); fastJsonConfig.setSerializeConfig(serializeConfig); return fastJsonConfig; }
Example #17
Source File: FastJsonKvCodecTest.java From actframework with Apache License 2.0 | 5 votes |
@BeforeClass public static void prepare() { SerializeConfig config = SerializeConfig.getGlobalInstance(); config.put(KV.class, FastJsonKvCodec.INSTANCE); config.put(KVStore.class, FastJsonKvCodec.INSTANCE); ParserConfig parserConfig = ParserConfig.getGlobalInstance(); parserConfig.putDeserializer(KV.class, FastJsonKvCodec.INSTANCE); parserConfig.putDeserializer(KVStore.class, FastJsonKvCodec.INSTANCE); JSON.DEFAULT_PARSER_FEATURE = Feature.config(JSON.DEFAULT_PARSER_FEATURE, Feature.UseBigDecimal, false); }
Example #18
Source File: JbootSwaggerController.java From jboot with Apache License 2.0 | 5 votes |
/** * 渲染json * 参考:http://petstore.swagger.io/ 及json信息 http://petstore.swagger.io/v2/swagger.json */ @EnableCORS public void json() { Swagger swagger = JbootSwaggerManager.me().getSwagger(); if (swagger == null) { renderText("swagger config error."); return; } // 适配swaggerUI, 解决页面"Unknown Type : ref"问题。 SerializeConfig serializeConfig = new SerializeConfig(); serializeConfig.put(RefProperty.class, new RefPropertySerializer()); renderJson(JSON.toJSONString(swagger, serializeConfig)); }
Example #19
Source File: ApiManager.java From actframework with Apache License 2.0 | 5 votes |
public void load(App app) { LOGGER.info("start compiling API book"); if (app.isProd()) { try { deserialize(); } catch (Exception e) { warn(e, "Error deserialize api-book"); } if (!endpoints.isEmpty()) { return; } } loadActAppDocs(); Router router = app.router(); AppConfig config = app.config(); Set<Class> controllerClasses = new HashSet<>(); ApiDocCompileContext ctx = new ApiDocCompileContext(); ctx.saveCurrent(); SerializeConfig fjConfig = SerializeConfig.globalInstance; Class<?> stringSObjectType = SObject.of("").getClass(); fjConfig.put(stringSObjectType, new FastJsonSObjectSerializer()); try { load(router, null, config, controllerClasses, ctx); for (NamedPort port : app.config().namedPorts()) { router = app.router(port); load(router, port, config, controllerClasses, ctx); } if (Act.isDev()) { exploreDescriptions(controllerClasses); } buildModuleLookup(); serialize(); } finally { ctx.destroy(); } LOGGER.info("API book compiled"); }
Example #20
Source File: JSONPath_t.java From coming with MIT License | 5 votes |
public JSONPath(String path, SerializeConfig serializeConfig, ParserConfig parserConfig){ if (path == null || path.length() == 0) { throw new JSONPathException("json-path can not be null or empty"); } this.path = path; this.serializeConfig = serializeConfig; this.parserConfig = parserConfig; }
Example #21
Source File: Retrofit2ConverterFactory.java From uavstack with Apache License 2.0 | 5 votes |
public RequestBody convert(T value) throws IOException { byte[] content = JSON.toJSONBytes(value , serializeConfig == null ? SerializeConfig.globalInstance : serializeConfig , serializerFeatures == null ? SerializerFeature.EMPTY : serializerFeatures ); return RequestBody.create(MEDIA_TYPE, content); }
Example #22
Source File: FastJsonConfig.java From uavstack with Apache License 2.0 | 5 votes |
/** * init param. */ public FastJsonConfig() { this.charset = Charset.forName("UTF-8"); this.serializeConfig = SerializeConfig.getGlobalInstance(); this.parserConfig = new ParserConfig(); this.serializerFeatures = new SerializerFeature[] { SerializerFeature.BrowserSecure }; this.serializeFilters = new SerializeFilter[0]; this.features = new Feature[0]; }
Example #23
Source File: JSONPath_s.java From coming with MIT License | 5 votes |
public JSONPath(String path, SerializeConfig serializeConfig, ParserConfig parserConfig){ if (path == null || path.length() == 0) { throw new JSONPathException("json-path can not be null or empty"); } this.path = path; this.serializeConfig = serializeConfig; this.parserConfig = parserConfig; }
Example #24
Source File: JSONPath.java From uavstack with Apache License 2.0 | 5 votes |
public JSONPath(String path, SerializeConfig serializeConfig, ParserConfig parserConfig){ if (path == null || path.length() == 0) { throw new JSONPathException("json-path can not be null or empty"); } this.path = path; this.serializeConfig = serializeConfig; this.parserConfig = parserConfig; }
Example #25
Source File: FastJsonExample.java From pragmatic-java-engineer with GNU General Public License v3.0 | 5 votes |
public static void main(String[] args) { User user = new User(); user.setName("testUser"); user.setGender("M"); user.setNickName("nickTest"); SerializeConfig config = new SerializeConfig(); config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase; String str = JSON.toJSONString(user, config); System.out.println(str); user = JSON.parseObject(str, User.class); JSONObject jo = JSON.parseObject("{\"name\":\"test\"}"); String name = jo.getString("name"); String nick = jo.getString("nickName"); System.out.println(nick); JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "test"); String jsonStr = "{\"name\":\"testName\",\"interests\":[\"music\",\"basketball\"]," + "\"notes\":[{\"title\":\"note1\",\"contentLength\":200},{\"title\":\"note2\",\"contentLength\":100}]}"; JSONObject jsonObject1 = JSON.parseObject(jsonStr); System.out.println(JSONPath.eval(jsonObject1, "$.interests.size()")); System.out.println(JSONPath.eval(jsonObject1, "$.interests[0]")); System.out.println(JSONPath.eval(jsonObject1, "$.notes[contentLength > 100].title")); System.out.println(JSONPath.eval(jsonObject1, "$.notes['title']")); }
Example #26
Source File: FastJsonRedisSerializer.java From jeesupport with MIT License | 5 votes |
@Override public byte[] serialize ( T _data ) throws SerializationException { if ( null == _data ) { return new byte[ 0 ]; } String json_data = JSON.toJSONString( _data, SerializeConfig.globalInstance, filters, null, features, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteClassName, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty ); return json_data.getBytes(DEFAULT_CHARSET); }
Example #27
Source File: MetricRegistryMetrics.java From watcher with Apache License 2.0 | 5 votes |
public MetricRegistryMetrics() { this.metricRegistry = MetricsHolder.metricRegistry(); SerializeConfig.getGlobalInstance().put(Counter.class, CounterSerializer.INSTANCE); SerializeConfig.getGlobalInstance().put(Gauge.class, GaugeSerializer.INSTANCE); SerializeConfig.getGlobalInstance().put(Histogram.class, HistogramSerializer.INSTANCE); SerializeConfig.getGlobalInstance().put(Meter.class, MeterSerializer.INSTANCE); SerializeConfig.getGlobalInstance().put(Timer.class, TimerSerializer.INSTANCE); }
Example #28
Source File: AjaxAuthenticationFilter.java From java-platform with Apache License 2.0 | 5 votes |
protected void writeObject(ServletRequest request, ServletResponse response, Object result) throws IOException { String characterEncoding = ((HttpServletRequest) request).getCharacterEncoding(); Charset charset = Strings.isNullOrEmpty(characterEncoding) ? DEFAULT_CHARSET : Charset.forName(characterEncoding); OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), charset); SerializeWriter writer = new SerializeWriter(out); JSONSerializer serializer = new JSONSerializer(writer, SpringContext.getBean(SerializeConfig.class)); serializer.config(SerializerFeature.DisableCircularReferenceDetect, true); serializer.write(result); writer.flush(); out.close(); }
Example #29
Source File: FastJsonConfig.java From fastjson-jaxrs-json-provider with Apache License 2.0 | 4 votes |
public FastJsonConfig(ParserConfig parserConfig, Feature[] features) { this(new SerializeConfig(), null, null, parserConfig, features); }
Example #30
Source File: FastJsonConverterFactory.java From retrofit-converter-fastjson with Apache License 2.0 | 4 votes |
public SerializeConfig getSerializeConfig() { return serializeConfig; }