public void test_map() throws Exception { Map<Object, Object> map = new LinkedHashMap<Object, Object>(); 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_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 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(); } }
/** 异常处理 */ @ExceptionHandler(Exception.class) public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception { logger.error(Constants.Exception_Head, ex); OperationResult result=new OperationResult(); if (ex instanceof AbstractException) { ((AbstractException) ex).handler(result); } /*else if (ex instanceof IllegalArgumentException) { new IllegalParameterException(ex.getMessage()).handler(modelMap); } else if (ex instanceof UnauthorizedException) { modelMap.put("httpCode", HttpCode.FORBIDDEN.value()); modelMap.put("msg", StringUtils.defaultIfBlank(ex.getMessage(), HttpCode.FORBIDDEN.msg())); } */else { result.setCode(HttpCode.INTERNAL_SERVER_ERROR.value()); String msg = StringUtils.defaultIfBlank(ex.getMessage(), HttpCode.INTERNAL_SERVER_ERROR.msg()); result.setMessage(msg.length() > 100 ? "系统走神了,请稍候再试." : msg); } response.setContentType("application/json;charset=UTF-8"); logger.info(JSON.toJSONString(result)); byte[] bytes = JSON.toJSONBytes(result, SerializerFeature.DisableCircularReferenceDetect); response.getOutputStream().write(bytes); }
/** * 修改自定义消息转换器 * @param converters 消息转换器列表 */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { //调用父类的配置 super.configureMessageConverters(converters); //创建fastJson消息转换器 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //处理中文乱码问题 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastConverter.setSupportedMediaTypes(fastMediaTypes); //创建配置类 FastJsonConfig fastJsonConfig = new FastJsonConfig(); //修改配置返回内容的过滤 fastJsonConfig.setSerializerFeatures( SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty ); fastConverter.setFastJsonConfig(fastJsonConfig); //将fastjson添加到视图消息转换器列表内 converters.add(fastConverter); }
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_point() throws Exception { JSONSerializer serializer = new JSONSerializer(); Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Point.class).getClass()); Point point = new Point(3, 4); String text = JSON.toJSONString(point, SerializerFeature.WriteClassName); System.out.println(text); Object obj = JSON.parse(text); Point point2 = (Point) obj; Assert.assertEquals(point, point2); Point point3 = (Point) JSON.parseObject(text, Point.class); Assert.assertEquals(point, point3); }
public void test_writer() throws Exception { StringWriter out = new StringWriter(); JSONWriter writer = new JSONWriter(out); writer.config(SerializerFeature.UseSingleQuotes, true); writer.startObject(); writer.startObject(); writer.endObject(); writer.startObject(); writer.endObject(); writer.endObject(); writer.close(); Assert.assertEquals("{{}:{}}", out.toString()); }
public CartItem addItemToCart(String quoteId, CartItem item) { Map<String, Map<String, Object>> request = new HashMap<>(); Map<String, Object> cartItem = new HashMap<>(); cartItem.put("qty", item.getQty()); cartItem.put("sku", item.getSku()); cartItem.put("quote_id", quoteId); request.put("cartItem", cartItem); String json = JSON.toJSONString(request, SerializerFeature.BrowserCompatible); json = postSecure(baseUri() + "/" + relativePath + "/" + cartId + "/items", json); if(!validate(json)){ return null; } CartItem saved = JSON.parseObject(json, CartItem.class); return saved; }
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 void test_bug() throws Exception { Map<Object, Object> params = new HashMap<Object, Object>(); params.put("msg", "<img class=\"em\" src=\"http://ab.com/12/33.jpg\" />"); params.put("uid", "22034343"); String s001 = JSON.toJSONString(params, SerializerFeature.BrowserCompatible); System.out.println(s001); Map<Object, Object> params2 = (Map<Object, Object>) 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); }
public void test_0() throws Exception { VO vo = new VO(); vo.setId(123); vo.setName("wenshao"); vo.getValues().add(new A()); String text = JSON.toJSONString(vo, SerializerFeature.BeanToArray); Assert.assertEquals("[123,\"wenshao\",[[0]]]", text); VO vo2 = JSON.parseObject(text, VO.class, Feature.SupportArrayToBean); Assert.assertEquals(vo.getId(), vo2.getId()); Assert.assertEquals(vo.getName(), vo2.getName()); Assert.assertEquals(vo.getValues().size(), vo2.getValues().size()); Assert.assertEquals(vo.getValues().get(0).getClass(), vo2.getValues().get(0).getClass()); Assert.assertEquals(vo.getValues().get(0).getValue(), vo2.getValues().get(0).getValue()); }
public void test_set() throws Exception { Map<Integer, Object> map = new LinkedHashMap<Integer, Object>(); 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()); }
@RequestMapping(value="/delAndAdd",method=RequestMethod.GET) @ResponseBody // @ResponseBody /*public String delAndAddUser(@RequestParam("name")String name,@RequestParam("sex")String sex, @RequestParam("age")int age,@RequestParam("phone")String phone)*/ public String delAndAddUser(String name,String sex, int age,String phone,String password){ String result = null; ResponseBean responseBean = null; try { User newUser = new User(name,sex,age,phone,password); userService.deleteAndAdd(newUser); // responseBean = new ResponseBean(200,true,"用户删除并添加成功",null); responseBean = new ResponseBean(200,true,"用户删除并添加成功","none"); result = JSON.toJSONString(responseBean, SerializerFeature.WriteMapNullValue); return result; }catch(Exception e) { e.printStackTrace(); responseBean = new ResponseBean(200,true,"删除失败!","原因不明!"); result = JSON.toJSONString(responseBean, SerializerFeature.WriteMapNullValue); return result; } }
public void test_11() throws Exception { SerializeWriter out = new SerializeWriter(); out.config(SerializerFeature.QuoteFieldNames, true); out.config(SerializerFeature.UseSingleQuotes, true); out.writeFieldName("123\na\nb\nc\nd\"'e"); Assert.assertEquals("'123\\na\\nb\\nc\\nd\"\\'e':", out.toString()); }
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); }
public void test_writeSlashAsSpecial() throws Exception { int features = JSON.DEFAULT_GENERATE_FEATURE; features = SerializerFeature.config(features, SerializerFeature.WriteSlashAsSpecial, true); features = SerializerFeature.config(features, SerializerFeature.WriteTabAsSpecial, true); features = SerializerFeature.config(features, SerializerFeature.DisableCircularReferenceDetect, true); features = SerializerFeature.config(features, SerializerFeature.SortField, false); Assert.assertEquals("\"\\/\"", JSON.toJSONString("/", features)); }
public void test_null() throws Exception { Map<String, String> map = new HashMap<String, String>(); 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")); }
public static String createSuccessResponse(Integer httpCode, String message, Object result, SerializerFeature serializerFeature, SerializeFilter filter, HttpServletResponse response){ PrintWriter printWriter = null; String jsonString = ""; try { response.setCharacterEncoding(RESPONSE_CHARACTERENCODING); response.setContentType(RESPONSE_CONTENTTYPE); response.setStatus(httpCode); printWriter = response.getWriter(); SerializeConfig config = new SerializeConfig(); config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); Map<String, Object> map = new HashMap<String, Object>(); if(null != result){ map.put("res_code", httpCode); map.put("message", message); map.put("data",result); if(null!=filter){ jsonString = JSONObject.toJSONString(map,filter,serializerFeature); }else{ // jsonString = JSONObject.toJSONString(map,config,serializerFeature); jsonString = JSONObject.toJSONStringWithDateFormat(map,"yyyy-MM-dd"); } printWriter.write(jsonString); } printWriter.flush(); } catch (Exception e) { log.error("createResponse failed", e); } finally { if(null!=printWriter)printWriter.close(); } return jsonString; }
public void test_for_SpitFire() { Generic<Payload> q = new Generic<Payload>(); q.setHeader("Sdfdf"); q.setPayload(new Payload()); String text = JSON.toJSONString(q, SerializerFeature.WriteClassName); System.out.println(text); JSON.parseObject(text, Generic.class); }
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); }
public void test_for_issue() throws Exception { ParserConfig config = new ParserConfig(); config.setAutoTypeSupport(true); Map<Long, Bean> map = new HashMap<Long, Bean>(); map.put(null, new Bean()); Map<Long, Bean> rmap = (Map<Long, Bean>) JSON.parse(JSON.toJSONString(map, SerializerFeature.WriteClassName), config); System.out.println(rmap); }
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_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()); }
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_writer() throws Exception { StringWriter out = new StringWriter(); JSONWriter writer = new JSONWriter(out); writer.config(SerializerFeature.UseSingleQuotes, true); writer.writeObject(Collections.emptyMap()); writer.close(); Assert.assertEquals("{}", out.toString()); }
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<Person>(); // 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_0() throws Exception { VO vo = new VO(); vo.id = 100; String text = JSON.toJSONString(vo, SerializerFeature.WriteNonStringValueAsString); Assert.assertEquals("{\"id\":\"100\"}", text); }
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()); } }
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)); }
@SuppressWarnings("unchecked") public void test_self() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); 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<String, Object> entity2 = (Map<String, Object>) JSON.parse(text); Assert.assertEquals(map.getClass(), entity2.getClass()); Assert.assertSame(entity2, entity2.get("self")); }
public static final void writeJSONStringTo(Object object, Writer writer, SerializerFeature... features) { SerializeWriter out = new SerializeWriter(writer); try { JSONSerializer serializer = new JSONSerializer(out); for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) { serializer.config(feature, true); } serializer.write(object); } finally { out.close(); } }
public @NonNull static String fromObjectToJSONString(Object obj, boolean WriteNonStringKeyAsString){ try { if(WriteNonStringKeyAsString) { return JSON.toJSONString(obj, SerializerFeature.WriteNonStringKeyAsString); }else { return JSON.toJSONString(obj); } }catch(Exception e){ if(WXEnvironment.isApkDebugable()){ throw new WXRuntimeException("fromObjectToJSONString parse error!"); } WXLogUtils.e("fromObjectToJSONString error:", e); return "{}"; } }
public void test_0() throws Exception { VO vo = new VO(); vo.setId(123); vo.setName("wenshao"); String text = JSON.toJSONString(vo, SerializerFeature.BeanToArray); Assert.assertEquals("[123,\"wenshao\"]", text); VO vo2 = JSON.parseObject(text, VO.class, Feature.SupportArrayToBean); Assert.assertEquals(vo.getId(), vo2.getId()); Assert.assertEquals(vo.getName(), vo2.getName()); }
public void test_0() throws Exception { Model model = new Model(); model.name = "a\\bc"; String text = JSON.toJSONString(model, SerializerFeature.BeanToArray); Assert.assertEquals("[\"a\\\\bc\"]", text); JSONReader reader = new JSONReader(new StringReader(text)); reader.config(Feature.SupportArrayToBean, true); Model model2 = reader.readObject(Model.class); Assert.assertEquals(model.name, model2.name); reader.close(); }
public void test_0() throws Exception { List<Object> message = new ArrayList<Object>(); 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 int getSerializeFeatures(Class<?> clazz) { JSONType annotation = clazz.getAnnotation(JSONType.class); if (annotation == null) { return 0; } return SerializerFeature.of(annotation.serialzeFeatures()); }
public void test_0 () throws Exception { VO vo = new VO(); vo.setId(123); vo.setName("wenshao"); String text = JSON.toJSONString(vo, SerializerFeature.BeanToArray); Assert.assertEquals("[123,\"wenshao\"]", text); JSONReader reader = new JSONReader(new StringReader(text), Feature.SupportArrayToBean); VO vo2 = reader.readObject(VO.class); Assert.assertEquals(vo.getId(), vo2.getId()); Assert.assertEquals(vo.getName(), vo2.getName()); reader.close(); }
public void test_0 () throws Exception { VO vo = new VO(); vo.setId('x'); vo.setName("wenshao"); String text = JSON.toJSONString(vo, SerializerFeature.BeanToArray); Assert.assertEquals("[\"x\",\"wenshao\"]", text); }
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 }