@Test public void main() throws IOException { File a = FileUtils.getFile("D:/a.txt"); String str = FileUtils.readFileToString(a,"utf-8"); JSONObject json = JSON.parseObject(str); JSONArray arry = JSONArray.parseArray(json.get("delegates").toString()); for(int i = 0;i<arry.size();i++){ JSONObject obj= (JSONObject) arry.get(i); String username = obj.getString("username"); String productivity = obj.getString("productivity"); String producedblocks = obj.getString("producedblocks"); String balance = obj.getString("balance"); String approval = obj.getString("approval"); System.out.println(username +"||" + productivity +"||" + producedblocks + "||" + balance + "||" + approval); } }
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); } }
@Test public void map2ObjectTest() { Map<String, String> result = mockRefundResult(); String json = JSON.toJSONString(result); System.out.println("json:" + json); AlipayRefundResult refund = JSON.parseObject(json, AlipayRefundResult.class); System.out.println("refund:" + refund); String value = StringUtil.toJoinForSign(refund, Constants.UTF_8, false); System.out.println("value:" + value); String text = JSON.toJSONString(refund); System.out.println("text:" + text); System.out.println("map:" + JSON.parseObject(text, Map.class)); System.out.println("refund2:"+StringUtil.toJoinForSign(JSON.parseObject(text, Map.class),Constants.UTF_8,false)); }
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()); }
public static void main(String[] args) { PropertyConfigurator.configure("conf/log4j.properties"); Method[] methods = HelloImpl.class.getDeclaredMethods(); for (Method method : methods) { System.out.println(method.getName()); Class<?>[] param = method.getParameterTypes(); System.out.println(JSON.toJSONString(param)); try { Method m2 = RMethodUtils.searchMethod(HelloImpl.class, method.getName(), param); if (m2 == null) { System.out.println("null"); } else { System.out.println(method.getName()); } } catch (NoSuchMethodException e) { e.printStackTrace(); } } }
public String indices() { String uri = "/_cat/indices?v"; String result = base(uri, HttpUtil.METHOD_GET, null); if(!StringUtil.isEmpty(result)){ String[] data = result.split("\n"); if(data!=null&&data.length>1){ List<JSONObject> list = new ArrayList<JSONObject>(); String[] header = data[0].split("(\\s+)"); for(int i=1;i<data.length;i++){ String[] values = data[i].split("(\\s+)"); JSONObject json = new JSONObject(); for(int j=0;j<values.length;j++){ json.put(header[j], values[j]); } list.add(json); } if(list!=null&&list.size()==1){ return list.get(0).toJSONString(); }else{ return JSON.toJSONString(list); } } } return result; }
@Override public RpcAcsRequest build() { com.aliyuncs.cloudphoto.model.v20170711.MergeFacesRequest request = new com.aliyuncs.cloudphoto.model.v20170711.MergeFacesRequest(); request.setProtocol(ProtocolType.HTTPS); //指定访问协议 request.setAcceptFormat(FormatType.JSON); //指定api返回格式 request.setMethod(MethodType.POST); //指定请求方法 request.setRegionId(REGION_CN);//指定要访问的Region,仅对当前请求生效,不改变client的默认设置。 request.setTargetFaceId(targetId); request.setFaceIds(faceIds); if (!stsToken.isEmpty()) request.setSecurityToken(stsToken); else if (!libraryId.isEmpty()) request.setLibraryId(libraryId); request.setStoreName(storeName); request.setActionName("MergeFaces"); return request; }
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)); }
@Override protected void onPostExecute(String result) { super.onPostExecute(result); if (!TextUtils.isEmpty(result)) { String jsonString = JSON.parseObject(result).getString(Constant.SUC_MSG); if (jsonString != null) { mDataList = JSON.parseArray(jsonString, FavorPrivateInfo.class); mRecyclerViewAdapter = new RecyclerViewAdapter(getActivity(), mDataList); mPullLoadMoreRecyclerView.setAdapter(mRecyclerViewAdapter); mRecyclerViewAdapter.notifyDataSetChanged(); mPullLoadMoreRecyclerView.setPullLoadMoreCompleted(); } else { //Toast.makeText(QianXunApplication.getInstance(), JSON.parseObject(result).getString(Constant.FAIL_MSG), Toast.LENGTH_LONG).show(); mPullLoadMoreRecyclerView.setPullLoadMoreCompleted(); return; } } }
@GET @Path("/executeSql") public Response executeSql(Map<String, Object> map) { try { DbusDataSource ds = new DbusDataSource(); ds.setDsType(map.get("dsType").toString()); ds.setMasterURL(map.get("URL").toString()); ds.setDbusUser(map.get("user").toString()); ds.setDbusPassword(map.get("password").toString()); TableFetcher fetcher = TableFetcher.getFetcher(ds); List<Map<String,Object>> list = fetcher.fetchTableColumn(map); return Response.ok().entity(list).build(); } catch (Exception e) { logger.error("Error encountered while search data table with parameter:{}", JSON.toJSONString(map), e); return Response.status(200).entity(new Result(-1, e.getMessage())).build(); } }
/** * Send DanMu. * * @param color color of DanMu * @param fontSize font size of DanMu * @param mode DanMu mode * @param message DanMu content * @return server response entity */ public DanMuResponseEntity send(String color, String fontSize, String mode, String message) throws IOException, IllegalArgumentException { resolveRoomData(); CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://live.bilibili.com/msg/send"); httpPost.setHeader("Cookie", cookies); httpPost.setEntity( new UrlEncodedFormEntity( Arrays.asList( new BasicNameValuePair("color", color), new BasicNameValuePair("fontsize", fontSize), new BasicNameValuePair("mode", mode), new BasicNameValuePair("msg", message), new BasicNameValuePair("random", random.toString()), new BasicNameValuePair("roomid", roomId.toString()) ), StandardCharsets.UTF_8 ) ); DanMuResponseEntity danMuResponseEntity = JSON.parseObject(EntityUtils.toString(closeableHttpClient.execute(httpPost).getEntity()), DanMuResponseEntity.class); closeableHttpClient.close(); return danMuResponseEntity; }
void testOKHttpGetListForce() { dlg.show(); ArrayList<RequestParameter> params = new ArrayList<RequestParameter>(); RequestParameter rp1 = new RequestParameter("cityId", "1"); params.add(rp1); RequestParameter rp2 = new RequestParameter("showdate", "20161101"); params.add(rp2); RemoteService.getInstance().invoke("getMovieList", params, new AbstractRequectCallback() { @Override public void onSuccess(String content) { dlg.dismiss(); MovieList entity = JSON.parseObject(content, MovieList.class); tvMovie.setText(entity.movieList.get(0).movieName); } }, true); }
@Override public List<PowerVO> getPowerVOByUserId(int userId) { Power powerDTO = powerMapper.selectByUserId(userId); List<PowerVO> listDTO = powerTypeService.listPowerVO(); if(powerDTO!=null){ List<Integer> powerListDTO = JSON.parseArray(powerDTO.getPower(), Integer.class); for(PowerVO p1: listDTO){ for(int p2: powerListDTO){ if(p1.getId()==p2){ p1.setPermit(1); if(p1.getMaxLv()!=0){ FormManager formManagerDTO = formManagerService.getFormManagerByApprover(userId); List<Integer> lvListDTO = JSON.parseArray(formManagerDTO.getApproverForm(), Integer.class); int formTypeDTO = powerTypeService.getPowerTypeByPowerId(p2).getFormType(); try { p1.setPermit(lvListDTO.get(formTypeDTO - 1)); }catch (Exception e){ e.printStackTrace(); } } } } } } return listDTO; }
private void processStringMessage(String msg) { logger.info("get Message {}", msg); /** * 处理GMsession */ JSONObject json = JSON.parseObject(msg); ActorRef actorRef = null; String COMMAND_ID = json.getString("id"); if (gmSession.containsKey(COMMAND_ID)) { actorRef = gmSession.get(COMMAND_ID); } else { gmSession.put(COMMAND_ID, actorRef); } CacheManager component = ContextResolver.getComponent(CacheManager.class); ActorRef localPath = component.getActorGlobalPath(ClusterDistributedPub.IDENTIFY); localPath.tell("ssss", ActorRef.noSender()); actorRef.tell(msg, getSender()); }
@RequestMapping("test5") public @ResponseBody String test5(@RequestBody FastJsonEnumTestVO vo) { return JSON.toJSONString(vo); }
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void deser(Blackhole bh) { for (int i = 0; i < 1000; i++) { bh.consume(JSON.parseObject(testJSON, TestObject.class)); } }
public void test_error_1() throws Exception { String text = "[123:\"wenshao\"]"; Exception error = null; try { JSON.parseObject(text, VO.class, Feature.SupportArrayToBean); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); }
public void test_for_au() throws Exception { Locale.setDefault(new Locale("en", "AU")); VO vo = JSON.parseObject("{\"date\":\"06/05/2016 09:03:16\"}", VO.class); Assert.assertEquals(2016, vo.date.getYear()); Assert.assertEquals(5, vo.date.getMonthValue()); Assert.assertEquals(6, vo.date.getDayOfMonth()); }
public void test_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_model_max() throws Exception { Model model = new Model(); model.value = false; String text = JSON.toJSONString(model); Assert.assertEquals("{\"value\":false}", text); }
public void test_error_3() throws Exception { Exception error = null; try { JSON.parseObject("[null", Model.class, Feature.SupportArrayToBean); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); }
@RequestMapping(value = "/pay/query") public String queryPayOrder(@RequestParam String jsonParam) { _log.info("selectPayOrder << {}", jsonParam); JSONObject retObj = new JSONObject(); retObj.put("code", "0000"); if(StringUtils.isBlank(jsonParam)) { retObj.put("code", "0001"); // 参数错误 retObj.put("msg", "缺少参数"); return retObj.toJSONString(); } JSONObject paramObj = JSON.parseObject(new String(MyBase64.decode(jsonParam))); String mchId = paramObj.getString("mchId"); String payOrderId = paramObj.getString("payOrderId"); String mchOrderNo = paramObj.getString("mchOrderNo"); PayOrder payOrder; if(StringUtils.isNotBlank(payOrderId)) { payOrder = payOrderService.selectPayOrderByMchIdAndPayOrderId(mchId, payOrderId); }else { payOrder = payOrderService.selectPayOrderByMchIdAndMchOrderNo(mchId, mchOrderNo); } if(payOrder == null) { retObj.put("code", "0002"); retObj.put("msg", "支付订单不存在"); return retObj.toJSONString(); } // boolean executeNotify = paramObj.getBooleanValue("executeNotify"); // 如果选择回调且支付状态为支付成功,则回调业务系统 if(executeNotify && payOrder.getStatus() == PayConstant.PAY_STATUS_SUCCESS) { this.doNotify(payOrder); } retObj.put("result", JSON.toJSON(payOrder)); _log.info("selectPayOrder >> {}", retObj); return retObj.toJSONString(); }
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()); }
@Override public ArrayList<MultipleItemEntity> convert() { final JSONArray array = JSON.parseObject(getJsonData()).getJSONArray("data"); final int size = array.size(); for (int i = 0; i < size; i++) { final JSONObject data = array.getJSONObject(i); final int id = data.getInteger("id"); final String name = data.getString("name"); final String phone = data.getString("phone"); final String address = data.getString("address"); final boolean isDefault = data.getBoolean("default"); final MultipleItemEntity entity = MultipleItemEntity.builder() .setItemType(AddressItemType.ITEM_ADDRESS) .setField(MultipleFields.ID, id) .setField(MultipleFields.NAME, name) .setField(MultipleFields.TAG, isDefault) .setField(AddressItemFields.PHONE, phone) .setField(AddressItemFields.ADDRESS, address) .build(); ENTITIES.add(entity); } return ENTITIES; }
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_bug()throws Exception { MyObject myObject = new MyObject(); List<String> listObj = new LinkedList<String>(); Set<String> setObj = new HashSet<String>(); Map<String, String> mapObj = new HashMap<String, String>(); 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 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 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_enum() throws Exception { Model model = new Model(); model.t1 = Type.A; model.t2 = null; String text = JSON.toJSONString(model, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"t1\":\"A\",\"t2\":null}", text); }
/** * @param taskId * @return */ @Override public boolean triggerCdnSyncAction(String taskId) { String lockName = lockService.getLockName(LockConstants.CDN_TRIGGER_LOCK, taskId); if (lockService.isAccessWindow(lockName, 120 * 1000) && lockService.tryLock(lockName)) { try { Task task = taskService.get(taskId); synchronized (task) { if (task.isFrozen()) { if (task.isWait()) { ResultInfo resultInfo = peerRegistryService.registryCdnNode(task); if (!resultInfo.successCode()) { logger.error("do trigger cdn fail for task:{}", JSON.toJSONString(task)); return false; } } taskService.updateCdnStatus(taskId, CdnStatus.RUNNING); new Thread(this.new Trigger(task)).start(); logger.info("do trigger cdn start for taskId:{},httpLen:{}", taskId, task.getHttpFileLen()); } } } finally { lockService.unlock(lockName); } } return true; }
public int callAddElement(String instanceId, String ref,String dom,String index, String callback){ if (WXEnvironment.isApkDebugable()) { mLodBuilder.append("[WXBridgeManager] callNative::callAddElement >>>> instanceId:").append(instanceId) .append(", ref:").append(ref).append(", dom:").append(dom).append(", callback:").append(callback); WXLogUtils.d(mLodBuilder.substring(0)); mLodBuilder.setLength(0); } if(mDestroyedInstanceId!=null && mDestroyedInstanceId.contains(instanceId)){ return IWXBridge.DESTROY_INSTANCE; } if (WXSDKManager.getInstance().getSDKInstance(instanceId) != null) { long start = System.currentTimeMillis(); JSONObject domObject = JSON.parseObject(dom); if (WXSDKManager.getInstance().getSDKInstance(instanceId) != null) { WXSDKManager.getInstance().getSDKInstance(instanceId).jsonParseTime(System.currentTimeMillis() - start); } WXDomModule domModule = getDomModule(instanceId); domModule.postAction(Actions.getAddElement(domObject, ref,Integer.parseInt(index)),false); } if (UNDEFINED.equals(callback) || NON_CALLBACK.equals(callback)) { return IWXBridge.INSTANCE_RENDERING_ERROR; } // get next tick getNextTick(instanceId, callback); return IWXBridge.INSTANCE_RENDERING; }
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 static void testAutoTypeDeny(String rootPath) throws Exception { ParserConfig config = new ParserConfig(); final String fileSeparator = System.getProperty("file.separator"); final String evilClassPath = rootPath + fileSeparator + "WEB-INF" + fileSeparator + "classes" + fileSeparator + "person" + fileSeparator + "Test.class"; String evilCode = readClass(evilClassPath); final String nastyClass = "com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl"; String text1 = "{\"@type\":\"" + nastyClass + "\",\"_bytecodes\":[\"" + evilCode + "\"],'_name':'a.b','_tfactory':{ },\"_outputProperties\":{ }," + "\"_name\":\"a\",\"_version\":\"1.0\",\"allowedProtocols\":\"all\"}\n"; System.out.println(text1); Object obj = JSON.parseObject(text1, Object.class, config, Feature.SupportNonPublicField); }
private JSONArray uncompact(JSONArray arr) { val uncompacted = new JSONArray(arr.size()); for (Object item : arr) { Object obj = item instanceof JSON ? uncompact((JSON) item) : item; uncompacted.add(obj); } return uncompacted; }
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 void test_error_value_notmatch() throws Exception { String text = "[true,\"wenshao\"]"; Exception error = null; try { JSON.parseObject(text, VO.class, Feature.SupportArrayToBean); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); }
public final void set(final String key, final Serializable value, final int seconds) { JedisTemplate.run(key, new Executor<String>() { public String execute(ShardedJedis jedis) { return jedis.setex(key, seconds, JSON.toJSONString(value)); } }, seconds, seconds); }
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_0() throws Exception { A a = new A(); a.setId(123); a.setName("wenshao"); VO vo = new VO(); vo.setA(a); String text = JSON.toJSONString(vo, SerializerFeature.BeanToArray); Assert.assertEquals("[[123,\"wenshao\"]]", text); VO vo2 = JSON.parseObject(text, VO.class, Feature.SupportArrayToBean); Assert.assertEquals(vo.getA().getId(), vo2.getA().getId()); Assert.assertEquals(vo.getA().getName(), vo2.getA().getName()); }
public void test() throws Exception { Exception error = null; try { JSON.parseObject("{\"date\":\"2012040125000a\"}", VO.class); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); }