com.alibaba.fastjson.serializer.SerializerFeature Java Examples
The following examples show how to use
com.alibaba.fastjson.serializer.SerializerFeature.
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: TestCaseUtil.java From chronus with Apache License 2.0 | 6 votes |
public static String object2JsonString(Object object,Class clazz,String... ignoreField){ Field[] fields = clazz.getDeclaredFields(); String[] fieldName = new String[fields.length-ignoreField.length]; int i = 0; for(Field field:fields) { List<String> ignoreFields = Arrays.asList(ignoreField); if(!ignoreFields.contains(field.getName())) { fieldName[i++] = field.getName(); } } SimplePropertyPreFilter filter = new SimplePropertyPreFilter(clazz, fieldName); return JSON.toJSONString(object,filter, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullListAsEmpty); }
Example #2
Source File: RedisConfig.java From sophia_scaffolding with Apache License 2.0 | 6 votes |
/** * 使用@Bean注入fastJsonHttpMessageConvert,fastJson序列化 */ @Bean public HttpMessageConverters fastJsonHttpMessageConverters(){ // 1、需要先定义一个 convert 转换消息的对象; FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据; FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //2-1 处理中文乱码问题 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastConverter.setSupportedMediaTypes(fastMediaTypes); //3、在convert中添加配置信息. fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); }
Example #3
Source File: MagentoMyCartManager.java From java-magento-client with MIT License | 6 votes |
public boolean transferGuestCartToMyCart(String guestCartId) { if(customerId == -1L) { Account account = client.getMyAccount(); customerId = account.getId(); storeId = account.getStore_id(); } Map<String, Object> request = new HashMap<>(); request.put("customerId", customerId); request.put("storeId", storeId); String json = JSON.toJSONString(request, SerializerFeature.BrowserCompatible); json = putSecure(baseUri() + "/rest/V1/guest-carts/" + guestCartId, json); if(!validate(json)){ return false; } return true; }
Example #4
Source File: RdbSyncService.java From canal with Apache License 2.0 | 6 votes |
/** * 单条 dml 同步 * * @param batchExecutor 批量事务执行器 * @param config 对应配置对象 * @param dml DML */ public void sync(BatchExecutor batchExecutor, MappingConfig config, SingleDml dml) { if (config != null) { try { String type = dml.getType(); if (type != null && type.equalsIgnoreCase("INSERT")) { insert(batchExecutor, config, dml); } else if (type != null && type.equalsIgnoreCase("UPDATE")) { update(batchExecutor, config, dml); } else if (type != null && type.equalsIgnoreCase("DELETE")) { delete(batchExecutor, config, dml); } else if (type != null && type.equalsIgnoreCase("TRUNCATE")) { truncate(batchExecutor, config); } if (logger.isDebugEnabled()) { logger.debug("DML: {}", JSON.toJSONString(dml, SerializerFeature.WriteMapNullValue)); } } catch (SQLException e) { throw new RuntimeException(e); } } }
Example #5
Source File: MagentoClientMyCartUnitTest.java From java-magento-client with MIT License | 6 votes |
@Test public void test_addItemToCart(){ MagentoClient client = new MagentoClient(Mediator.url); client.loginAsClient(Mediator.customerUsername, Mediator.customerPassword); String quoteId = client.myCart().newQuote(); CartItem item = new CartItem(); item.setQty(1); item.setSku("product_dynamic_758"); System.out.println(quoteId); item = client.myCart().addItemToCart(quoteId, item); Cart cart = client.myCart().getCart(); CartTotal cartTotal = client.myCart().getCartTotal(); logger.info("cartItem: \r\n{}", JSON.toJSONString(item, SerializerFeature.PrettyFormat)); logger.info("cart: \r\n{}", JSON.toJSONString(cart, SerializerFeature.PrettyFormat)); logger.info("cartTotal: \r\n{}", JSON.toJSONString(cartTotal, SerializerFeature.PrettyFormat)); }
Example #6
Source File: AlbianRedisCachedAdapter.java From Albianj2 with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void set(String cachedName, String k, Object v, int tto) { // TODO Auto-generated method stub String body = JSON.toJSONString(v, SerializerFeature.WriteClassName); if (isCluster) { jc.set(k, body); jc.expire(k, tto); } else { ShardedJedis sj = null; try { sj = sjp.getResource(); sj.set(k, body); sj.expire(k, tto); } catch (Exception e) { AlbianServiceRouter.getLogger().error( IAlbianLoggerService.AlbianRunningLoggerName, e, "set object:%s is fail.", k); } finally { if (null != sj) sjp.returnResourceObject(sj); } } }
Example #7
Source File: CaconfDbExporter.java From xipki with Apache License 2.0 | 6 votes |
public void export() throws Exception { CaCertstore.Caconf caconf = new CaCertstore.Caconf(); caconf.setVersion(VERSION); System.out.println("exporting CA configuration from database"); exportSigner(caconf); exportRequestor(caconf); exportUser(caconf); exportPublisher(caconf); exportCa(caconf); exportProfile(caconf); exportCaalias(caconf); exportCaHasRequestor(caconf); exportCaHasUser(caconf); exportCaHasPublisher(caconf); exportCaHasProfile(caconf); caconf.validate(); try (OutputStream os = Files.newOutputStream(Paths.get(baseDir, FILENAME_CA_CONFIGURATION))) { JSON.writeJSONString(os, caconf, SerializerFeature.PrettyFormat); } System.out.println(" exported CA configuration from database"); }
Example #8
Source File: RdbSyncService.java From canal-1.1.3 with Apache License 2.0 | 6 votes |
/** * 单条 dml 同步 * * @param batchExecutor 批量事务执行器 * @param config 对应配置对象 * @param dml DML */ public void sync(BatchExecutor batchExecutor, MappingConfig config, SingleDml dml) { if (config != null) { try { String type = dml.getType(); if (type != null && type.equalsIgnoreCase("INSERT")) { insert(batchExecutor, config, dml); } else if (type != null && type.equalsIgnoreCase("UPDATE")) { update(batchExecutor, config, dml); } else if (type != null && type.equalsIgnoreCase("DELETE")) { delete(batchExecutor, config, dml); } else if (type != null && type.equalsIgnoreCase("TRUNCATE")) { truncate(batchExecutor, config); } if (logger.isDebugEnabled()) { logger.debug("DML: {}", JSON.toJSONString(dml, SerializerFeature.WriteMapNullValue)); } } catch (SQLException e) { throw new RuntimeException(e); } } }
Example #9
Source File: HttpUtil.java From s2g-zuul with MIT License | 6 votes |
public static <T> T postData(CloseableHttpClient httpClient,String url, Object par, Map<String, String> header, Class<T> clazz) throws ClientProtocolException, IOException { HttpPost method = new HttpPost(url); method.setHeader("Content-type", "application/json; charset=utf-8"); method.setHeader("Accept", "application/json"); if (header != null) { for (String key : header.keySet()) { method.setHeader(key, header.get(key)); } } if (par != null) { String parameters = JSON.toJSONString(par, SerializerFeature.DisableCircularReferenceDetect); HttpEntity entity = new StringEntity(parameters, Charset.forName("UTF-8")); method.setEntity(entity); } CloseableHttpResponse response = httpClient.execute(method); String body = EntityUtils.toString(response.getEntity()); return JSON.parseObject(body, clazz); }
Example #10
Source File: WebMvcConfig.java From littleca with Apache License 2.0 | 6 votes |
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { //1.需要定义一个convert转换消息的对象; FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //2.添加fastJson的配置信息,比如:是否要格式化返回的json数据; FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //3处理中文乱码问题 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON); fastJsonConfig.setCharset(Charset.forName("UTF-8")); //4.在convert中添加配置信息. fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); //5.将convert添加到converters当中. converters.add(1,fastJsonHttpMessageConverter); }
Example #11
Source File: AuditEventServiceImpl.java From spring-websocket-android-client-demo with MIT License | 6 votes |
@Override public void sendWarning(String category, String name, String description) { AuditEvent auditEvent = new AuditEvent(); auditEvent.setCategory(category); auditEvent.setDescription(description); auditEvent.setName(name); auditEvent.setTime(new Date()); auditEvent.setCount(counter++); auditEvent.setLevel("Warning"); enqueue(auditEvent); histogram.put(category, histogram.getOrDefault(category, 0L) + 1); lastEvent = auditEvent; brokerMessagingTemplate.convertAndSend("/topics/event", JSON.toJSONString(auditEvent, SerializerFeature.BrowserCompatible)); }
Example #12
Source File: RedisConfig.java From sophia_scaffolding with Apache License 2.0 | 6 votes |
/** * 使用@Bean注入fastJsonHttpMessageConvert,fastJson序列化 */ @Bean public HttpMessageConverters fastJsonHttpMessageConverters(){ // 1、需要先定义一个 convert 转换消息的对象; FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据; FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //2-1 处理中文乱码问题 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastConverter.setSupportedMediaTypes(fastMediaTypes); //3、在convert中添加配置信息. fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); }
Example #13
Source File: ArchivedRequestsTest.java From java-unified-sdk with Apache License 2.0 | 6 votes |
public void testOperationSerialize() { List<BaseOperation> ops = new ArrayList<>(); SetOperation setOp = new SetOperation("age", 3); ops.add(setOp); AddOperation addOp = new AddOperation("course", "Computer Science"); ops.add(addOp); BitAndOperation bitAndOp = new BitAndOperation("score", 0x002); ops.add(bitAndOp); String opString = JSON.toJSONString(ops, ObjectValueFilter.instance, /*SerializerFeature.WriteClassName, */SerializerFeature.QuoteFieldNames, SerializerFeature.DisableCircularReferenceDetect); System.out.println(opString); List<BaseOperation> parsedOps = JSON.parseObject(opString, new TypeReference<List<BaseOperation>>() {}, IgnoreNotMatch); assertEquals(ops.size(), parsedOps.size()); }
Example #14
Source File: AlbianMonitorLoggerService.java From Albianj2 with BSD 3-Clause "New" or "Revised" License | 6 votes |
public void addMonitorLog(String sessionId,AlbianMonitorData data) { String json = JSON.toJSONString(data, SerializerFeature.SkipTransientField, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.DisableCircularReferenceDetect); try { mlog.info(json); }catch (Exception e){ throw new RuntimeException(e); } }
Example #15
Source File: MagentoCategoryManager.java From java-magento-client with MIT License | 6 votes |
public long addCategory(Category category) { Map<String, Object> cat = new HashMap<>(); cat.put("id", category.getId()); cat.put("parent_id", category.getParent_id()); cat.put("name", category.getName()); cat.put("is_active", category.is_active()); cat.put("position", category.getPosition()); cat.put("level", category.getLevel()); cat.put("children", "string"); cat.put("include_in_menu", true); cat.put("available_sort_by", new ArrayList<>()); cat.put("extension_attributes", new ArrayList<>()); cat.put("custom_attributes", new ArrayList<>()); Map<String, Object> req = new HashMap<>(); req.put("category", cat); String url = baseUri() + "/" + relativePath4Categories; String body = JSON.toJSONString(req, SerializerFeature.BrowserCompatible); String json = postSecure(url, body); if(!validate(json)){ return -1; } return Long.parseLong(json); }
Example #16
Source File: TermExpressionParserTest.java From hsweb-framework with Apache License 2.0 | 6 votes |
@Test public void testNest() { String expression = "name = 测试 and (age > 10 or age <= 20) and test like test2 and (age gt age2 or age btw age3,age4 or (age > 10 or age <= 20))"; System.out.println(expression); List<Term> terms = TermExpressionParser.parse(expression); System.out.println(JSON.toJSONString(terms, SerializerFeature.PrettyFormat)); Assert.assertNotNull(terms); Assert.assertEquals(terms.size(), 4); Assert.assertEquals(terms.get(1).getTerms().size(),2); Assert.assertEquals(terms.get(0).getColumn(), "name"); Assert.assertEquals(terms.get(0).getValue(), "测试"); Assert.assertEquals(terms.get(1).getTerms().get(0).getColumn(), "age"); Assert.assertEquals(terms.get(1).getTerms().get(0).getTermType(), "gt"); Assert.assertEquals(terms.get(1).getTerms().get(0).getValue(), "10"); Assert.assertEquals(terms.get(1).getTerms().get(1).getColumn(), "age"); Assert.assertEquals(terms.get(1).getTerms().get(1).getTermType(), "lte"); Assert.assertEquals(terms.get(1).getTerms().get(1).getValue(), "20"); Assert.assertEquals(terms.get(1).getTerms().get(1).getType(), Term.Type.or); Assert.assertEquals(terms.get(2).getColumn(), "test"); Assert.assertEquals(terms.get(2).getValue(), "test2"); Assert.assertEquals(terms.get(2).getTermType(), "like"); }
Example #17
Source File: JdbcAdapter.java From nano-framework with Apache License 2.0 | 6 votes |
public Result executeQuery(final String sql, final List<Object> values, final Connection conn) throws SQLException { Assert.notNull(conn); final long start = System.currentTimeMillis(); Result result = null; ResultSet rs = null; PreparedStatement pstmt = null; try { pstmt = getPreparedStmt(conn, sql, values); pstmt.setQueryTimeout(60); rs = pstmt.executeQuery(); rs.setFetchSize(rs.getRow()); result = ResultSupport.toResult(rs); } finally { close(rs, pstmt); if (LOGGER.isDebugEnabled()) { LOGGER.debug("[ Execute Query SQL ]: {} [cost {}ms ]", sql, System.currentTimeMillis() - start); LOGGER.debug("[ Execute Parameter ]: {}", JSON.toJSONString(values, SerializerFeature.WriteDateUseDateFormat)); } } return result; }
Example #18
Source File: JournalkeeperClusterInternalService.java From joyqueue with Apache License 2.0 | 6 votes |
@Override public String getCluster() { try { Map<String, Object> result = Maps.newHashMap(); ClusterConfiguration clusterConfiguration = sqlClient.getAdminClient().getClusterConfiguration().get(); for (URI voter : clusterConfiguration.getVoters()) { if (voter.getHost().equals(IpUtil.getLocalIp())) { ServerStatus serverStatus = sqlClient.getAdminClient().getServerStatus(voter).get(); result.put("status", serverStatus); } } result.put("cluster", clusterConfiguration); return JSON.toJSONString(result, SerializerFeature.DisableCircularReferenceDetect); } catch (Exception e) { throw new NsrException(e); } }
Example #19
Source File: JSONFileRegionDataOutput.java From addrparser with Apache License 2.0 | 6 votes |
@Override public void init() throws IOException { if (initialized) { return; } synchronized (this) { if (initialized) { return; } if (this.filename == null) { this.writer = new JSONWriter(_writer); } else { this.writer = new JSONWriter(new FileWriter(filename)); } this.writer.config(SerializerFeature.WriteEnumUsingName, false); this.writer.config(SerializerFeature.SortField, false); this.writer.startArray(); this.initialized = true; } }
Example #20
Source File: XPackBaseDemo.java From elasticsearch-full with Apache License 2.0 | 5 votes |
@Test public void testRestClientConnection() throws Exception { String method = "GET"; String endpoint = "/_analyze"; Map<String, String> params = new HashMap<>(); params.put("analyzer","standard"); params.put("text","中华人民共和国"); Response response = restClient.performRequest(method,endpoint,params); System.out.println(JSON.toJSONString(JSONObject.parse(EntityUtils.toString(response.getEntity())),SerializerFeature.PrettyFormat)); }
Example #21
Source File: FastJsonConfiguration.java From flower with Apache License 2.0 | 5 votes |
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures( SerializerFeature.DisableCircularReferenceDetect, // SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.PrettyFormat); fastJsonConfig.setCharset(Charset.forName("UTF-8")); fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); converter.setFastJsonConfig(fastJsonConfig); converters.add(0, converter); }
Example #22
Source File: FastJsonRedisSerializer.java From ywh-frame with GNU General Public License v3.0 | 5 votes |
@Override public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte[0]; } return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); }
Example #23
Source File: VoItf.java From DataLink with Apache License 2.0 | 5 votes |
/** * * Description: 将消息体转换为json串 * Created on 2016-7-29 下午3:24:09 * @author 孔增([email protected]) * @return */ public String toJsonString(Object content) { String json = null; if(retainNullValue) { json = JSONObject.toJSONString(content, SerializerFeature.WriteMapNullValue); }else { json = JSONObject.toJSONString(content); } return json; }
Example #24
Source File: FastJsonRedisSerializer.java From SpringBootLearn with Apache License 2.0 | 5 votes |
@Override public byte[] serialize(T t) throws SerializationException { if (null == t) { return new byte[0]; } return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); }
Example #25
Source File: HttpsUtils.java From singleton with Eclipse Public License 2.0 | 5 votes |
public static String doPostWithJson(String url, Object jsonObj) throws Exception { String jsontext = JSON.toJSONString(jsonObj, SerializerFeature.WriteSlashAsSpecial); logger.debug("request url = {}, content = {}",url,jsontext); HttpPost post = new HttpPost(url); HttpEntity requestEntity = new StringEntity(jsontext, ContentType.APPLICATION_JSON); post.setEntity(requestEntity); return execute(post); }
Example #26
Source File: MagentoClientProductMediaUnitTest.java From java-magento-client with MIT License | 5 votes |
@Test public void test_get_product_media() { String productSku = "B202-SKU"; MagentoClient client = new MagentoClient(Mediator.url); client.loginAsAdmin(Mediator.adminUsername, Mediator.adminPassword); long entryId = 1L; logger.info("media: \r\n{}", JSON.toJSONString(client.media().getProductMedia(productSku, entryId), SerializerFeature.PrettyFormat)); }
Example #27
Source File: GetAllMetadataResponseCodec.java From joyqueue with Apache License 2.0 | 5 votes |
public static byte[] toJson(Object value) { try { String json = JSON.toJSONString(value, SerializerFeature.DisableCircularReferenceDetect); return ZipUtil.compress(json); } catch (Exception e) { throw new RuntimeException(e); } }
Example #28
Source File: MagentoClientProductMediaUnitTest.java From java-magento-client with MIT License | 5 votes |
@Test public void test_get_product_media_url() { String productSku = "B202-SKU"; MagentoClient client = new MagentoClient(Mediator.url); client.loginAsAdmin(Mediator.adminUsername, Mediator.adminPassword); long entryId = 1L; logger.info("media absoluate url: \r\n{}", JSON.toJSONString(client.media().getProductMediaAbsoluteUrl(productSku, entryId), SerializerFeature.PrettyFormat)); logger.info("media relative url: \r\n{}", JSON.toJSONString(client.media().getProductMediaRelativeUrl(productSku, entryId), SerializerFeature.PrettyFormat)); }
Example #29
Source File: RedisConfig.java From eladmin with Apache License 2.0 | 5 votes |
@Override public byte[] serialize(T t) { if (t == null) { return new byte[0]; } return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(StandardCharsets.UTF_8); }
Example #30
Source File: AuthorizeTests.java From hsweb-framework with Apache License 2.0 | 5 votes |
/** * 测试数据权限控制s */ @Test public void testGetDataAccessHandler() { DefaultAuthorizingHandler handler = new DefaultAuthorizingHandler(); DefaultDataAccessController controller = new DefaultDataAccessController(); handler.setDataAccessController(controller); AuthorizeDefinition definition = parser.parse(queryById.getTarget().getClass(), queryById.getMethod()); //响应结果 Object response = queryById.getInvokeResult(); System.out.println(JSON.toJSONString(response, SerializerFeature.PrettyFormat)); AuthorizingContext authorizingContext = new AuthorizingContext(); authorizingContext.setAuthentication(authentication); authorizingContext.setDefinition(definition); authorizingContext.setParamContext(queryById); handler.handleDataAccess(authorizingContext); System.out.println(JSON.toJSONString(response, SerializerFeature.PrettyFormat)); Assert.assertTrue(response instanceof ResponseMessage); Assert.assertTrue(((User) ((ResponseMessage) response).getResult()).getPassword() == null); Assert.assertTrue(((User) ((ResponseMessage) response).getResult()).getSalt() == null); }