Java Code Examples for com.alibaba.fastjson.JSON

The following are top voted examples for showing how to use com.alibaba.fastjson.JSON. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: asch-java   File: AccountServiceTest.java   Source Code and License 8 votes vote down vote up
@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);
    }
}
 
Example 2
Project: TakinRPC   File: HelloImpl.java   Source Code and License 7 votes vote down vote up
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();
        }
    }
}
 
Example 3
Project: GitHub   File: LongFieldTest_3.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 4
Project: pay4j   File: Map2ObjectTest.java   Source Code and License 6 votes vote down vote up
@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));

}
 
Example 5
Project: GitHub   File: BooleanDeserializerTest.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 6
Project: css-elasticsearch   File: ElasticsearchHttpFactory.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 7
Project: aliyun-cloudphotos-android-demo   File: MergeFacesRequest.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 8
Project: GitHub   File: Issue1492.java   Source Code and License 6 votes vote down vote up
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));

}
 
Example 9
Project: QianXun   File: ContentFragment.java   Source Code and License 6 votes vote down vote up
@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;
        }
    }
}
 
Example 10
Project: DBus   File: DataTableResource.java   Source Code and License 6 votes vote down vote up
@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();
    }
}
 
Example 11
Project: bilibili-live-api   File: LiveDanMuSender.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 12
Project: AndroidNetwork   File: MainActivity.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 13
Project: sztw   File: PowerServiceImpl.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 14
Project: CodeBroker   File: WorldActor.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 15
Project: GitHub   File: FastJsonControllerTest.java   Source Code and License 5 votes vote down vote up
@RequestMapping("test5")
public
@ResponseBody
String test5(@RequestBody FastJsonEnumTestVO vo) {

    return JSON.toJSONString(vo);
}
 
Example 16
Project: java-benchmark   File: DeserFastjson.java   Source Code and License 5 votes vote down vote up
@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));
    }
}
 
Example 17
Project: GitHub   File: WriteAsArray_long_public.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 18
Project: GitHub   File: LocalDateTimeTest5.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 19
Project: GitHub   File: NumberFieldTest.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 20
Project: GitHub   File: BooleanFieldTest.java   Source Code and License 5 votes vote down vote up
public void test_model_max() throws Exception {
    Model model = new Model();
    model.value = false;
    
    String text = JSON.toJSONString(model);
    Assert.assertEquals("{\"value\":false}", text);
}
 
Example 21
Project: GitHub   File: WriteAsArray_string.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 22
Project: pay-xxpay-master   File: PayOrderServiceController.java   Source Code and License 5 votes vote down vote up
@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();
}
 
Example 23
Project: GitHub   File: CharsetFieldTest.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 24
Project: FastEc   File: AddressDataConverter.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 25
Project: GitHub   File: StackTraceElementTest.java   Source Code and License 5 votes vote down vote up
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());
    }
}
 
Example 26
Project: GitHub   File: Bug_for_Johnny.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 27
Project: GitHub   File: IgnoreNonFieldGetterTest.java   Source Code and License 5 votes vote down vote up
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);
    
}
 
Example 28
Project: GitHub   File: Bug_127_for_qiuyan81.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 29
Project: GitHub   File: EnumFieldsTest.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 30
Project: Dragonfly   File: CdnManagerImpl.java   Source Code and License 5 votes vote down vote up
/**
 * @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;
}
 
Example 31
Project: ucar-weex-core   File: WXBridgeManager.java   Source Code and License 5 votes vote down vote up
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;

  }
 
Example 32
Project: ucar-weex-core   File: WXJsonUtils.java   Source Code and License 5 votes vote down vote up
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 "{}";
  }
}
 
Example 33
Project: openrasp-testcases   File: Poc.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 34
Project: westjson   File: WestJsonUncompacter.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 35
Project: GitHub   File: FinalTest.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 36
Project: GitHub   File: WriteAsArray_int_public.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 37
Project: iBase4J   File: JedisHelper.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 38
Project: GitHub   File: InetSocketAddressFieldTest.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 39
Project: GitHub   File: WriteAsArray_Object.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 40
Project: GitHub   File: DateParseTest13.java   Source Code and License 5 votes vote down vote up
public void test() throws Exception {
    Exception error = null;
    try {
        JSON.parseObject("{\"date\":\"2012040125000a\"}", VO.class);
    } catch (Exception ex) {
        error = ex;
    }
    Assert.assertNotNull(error);
}
 
Example 41
Project: GitHub   File: SerializeWriterTest_BrowserSecure_6_name_script.java   Source Code and License 5 votes vote down vote up
public void test_0() throws Exception {
        JSONObject object = new JSONObject();
        object.put("<script>alert(1);</script>", "value");
        String text = JSON.toJSONString(object, SerializerFeature.BrowserSecure);
//        assertEquals("{\"value\":\"&lt;script&gt;alert(1);&lt;\\/script&gt;\"}", text);
        assertEquals("{\"\\u003Cscript\\u003Ealert\\u00281\\u0029;\\u003C/script\\u003E\":\"value\"}", text);
        JSONObject object1 = JSON.parseObject(text);
        assertEquals(object.get("<script>alert(1);</script>"), object1.get("<script>alert(1);</script>"));
    }
 
Example 42
Project: LibraSock   File: JsonUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 返回map类型的对像
 * 
 * @param jsonString
 * @param clazz1
 * @param clazz2
 * @return
 */
public static <K, V> Map<K, V> JsonToObjectMap(String jsonString, Class<K> clazz1, Class<V> clazz2) {
	if (StringUtils.isNull(jsonString)) {
		LibraLog.info("jsonString=" + jsonString + " 不是json对象");
		return new HashMap<K, V>();
	}
	Map<K, V> result = null;
	try {
		result = JSON.parseObject(jsonString, new TypeReference<Map<K, V>>() {
		});
	} catch (Exception e) {
		e.printStackTrace();
	}
	return result;
}
 
Example 43
Project: GitHub   File: Bug_for_issue_447.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 44
Project: shop-manager   File: AuthAspect.java   Source Code and License 5 votes vote down vote up
private String getInputParamInfo(String className, String methodName, Object[] args) {
	String inputArgJson = "";
	try {
		inputArgJson = (args.length <= 0 ? "" : JSON.toJSONString(args));
	} catch (Exception e) {
		inputArgJson = "!!json解析error!!";
		log.warn("入参json解析error", e);
	}
	// 打印类名,方法名,传入参数
	return className + "." + methodName + ",入参:" + inputArgJson;
}
 
Example 45
Project: GitHub   File: Issue1547.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 46
Project: wx-idk   File: ThirdpartyAccessToken.java   Source Code and License 5 votes vote down vote up
/**
  * 获取微信Token
  * @return Token数据键值对
  */
 public Map<String, Object> getWxToken() {
     Jedis jedis = null;
     try{
         jedis = RedisConnectionFactory.getJedisInstance();
         String jsonString = jedis.get("token:" + this.appId);
         if(jsonString == null){
             return getNewWxToken();
         }else{
             Map<String, Object> tokenMap = JSON.parseObject(jsonString, new TypeReference<Map<String, Object>>(){});
             long nowTime = System.currentTimeMillis();
             if(nowTime < (Long.parseLong(tokenMap.get("time").toString())-5000)){
                 return tokenMap;
             }else{
                 return getNewWxToken();
             }
         }
     }catch (Exception e) {
         e.printStackTrace();
         logger.error("从Redis中取AccessToken时:" + e.toString());
         return null;
     }finally{
if(jedis != null){
	jedis.close();
}
     }
 }
 
Example 47
Project: easyweb   File: OfficeController.java   Source Code and License 5 votes vote down vote up
@ResponseBody
@PostMapping("/delete")
@ApiOperation(value = "机构管理-删除接口")
public BaseResult delete(String ids){
    BaseResult result=new BaseResult(BaseResultCode.SUCCESS,"删除成功");
    List<String> idList= JSON.parseArray(ids,String.class);
    int count= service.deleteByIds(idList);
    _log.info("删除了:"+count+"数据");
    return result;
}
 
Example 48
Project: GitHub   File: WriteAsArray_double_public.java   Source Code and License 5 votes vote down vote up
public void test_0 () throws Exception {
    VO vo = new VO();
    vo.setId(123D);
    vo.setName("wenshao");
    
    String text = JSON.toJSONString(vo, SerializerFeature.BeanToArray);
    Assert.assertEquals("[123.0,\"wenshao\"]", text);
    
    VO vo2 = JSON.parseObject(text, VO.class, Feature.SupportArrayToBean);
    Assert.assertTrue(vo.id == vo2.id);
    Assert.assertEquals(vo.name, vo2.name);
}
 
Example 49
Project: GitHub   File: JSONLexerTest_13.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 50
Project: MusicuuApi   File: WyMusic.java   Source Code and License 5 votes vote down vote up
private static String GetLostPlayUrl(String id, String quality) {
    String albumId = GetLostAlbumId(id);
    try {
        String s = NetUtil.GetHtmlContent("http://music.163.com/api/album/" + albumId, true);
        NeteaseLostSong neteaseLostSong = JSON.parseObject(s, NeteaseLostSong.class);
        List<NeteaseLostSong.AlbumBeanX.SongsBean> songs = neteaseLostSong.getAlbum().getSongs();
        int size = songs.size();
        for (NeteaseLostSong.AlbumBeanX.SongsBean songsBean : songs) {
            if (songsBean.getId() == Integer.parseInt(id)) {
                switch (quality) {
                    case "320000":
                        String dfsId;
                        if (songsBean.getHMusic() == null) {
                            if (songsBean.getMMusic() == null) {
                                return songsBean.getMp3Url();
                            }
                            dfsId = String.valueOf(songsBean.getMMusic().getDfsId());
                        } else {
                            dfsId = String.valueOf(songsBean.getHMusic().getDfsId());
                        }
                        return GetUrlBySid(dfsId);
                    case "192000":
                        if (songsBean.getMMusic() == null) {
                            return songsBean.getMp3Url();
                        } else {
                            dfsId = String.valueOf(songsBean.getMMusic().getDfsId());
                            return GetUrlBySid(dfsId);
                        }
                    default:
                        return songsBean.getMp3Url();
                }
            }
        }
        return "";
    } catch (Exception e) {
        return "";
    }
}
 
Example 51
Project: pds   File: RRExceptionHandler.java   Source Code and License 5 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest request,
		HttpServletResponse response, Object handler, Exception ex) {
	R r = new R();
	try {
		response.setContentType("application/json;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		
		if (ex instanceof RRException) {
			r.put("code", ((RRException) ex).getCode());
			r.put("msg", ((RRException) ex).getMessage());
		}else if(ex instanceof DuplicateKeyException){
			r = R.error("数据库中已存在该记录");
		}else if(ex instanceof AuthorizationException){
			r = R.error("没有权限,请联系管理员授权");
		}else{
			r = R.error();
		}
		
		//记录异常日志
		logger.error(ex.getMessage(), ex);
		
		String json = JSON.toJSONString(r);
		response.getWriter().print(json);
	} catch (Exception e) {
		logger.error("RRExceptionHandler 异常处理失败", e);
	}
	return new ModelAndView();
}
 
Example 52
Project: GitHub   File: Bug_7.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 53
Project: wakeup-qcloud-sdk   File: DefaultQCloudClient.java   Source Code and License 5 votes vote down vote up
@Override
public String getUserSig(String identifier, long expire)throws QCloudException {
	try {
		 	Security.addProvider(new BouncyCastleProvider());
	        Reader reader = new CharArrayReader(imConfig.getPrivateKey().toCharArray());
	        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
	        PEMParser parser = new PEMParser(reader);
	        Object obj = parser.readObject();
	        parser.close();
	    	PrivateKey privKeyStruct = converter.getPrivateKey((PrivateKeyInfo) obj);
			
			String jsonString = "{" 
			+ "\"TLS.account_type\":\"" + 0 +"\","
			+"\"TLS.identifier\":\"" + identifier +"\","
			+"\"TLS.appid_at_3rd\":\"" + 0 +"\","
		    +"\"TLS.sdk_appid\":\"" + imConfig.getSdkAppId() +"\","
			+"\"TLS.expire_after\":\"" + expire +"\","
	        +"\"TLS.version\": \"201512300000\""
			+"}";
			
			String time = String.valueOf(System.currentTimeMillis()/1000);
			String SerialString = 
				"TLS.appid_at_3rd:" + 0 + "\n" +
				"TLS.account_type:" + 0 + "\n" +
				"TLS.identifier:" + identifier + "\n" + 
				"TLS.sdk_appid:" + imConfig.getSdkAppId() + "\n" + 
				"TLS.time:" + time + "\n" +
				"TLS.expire_after:" + expire +"\n";
			
			//Create Signature by SerialString
			Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
			signature.initSign(privKeyStruct);
			signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
			byte[] signatureBytes = signature.sign();
			
			String sigTLS = Base64.encodeBase64String(signatureBytes);
			
			//Add TlsSig to jsonString
		    JSONObject jsonObject= JSON.parseObject(jsonString);
		    jsonObject.put("TLS.sig", (Object)sigTLS);
		    jsonObject.put("TLS.time", (Object)time);
		    jsonString = jsonObject.toString();
		    
		    //compression
		    Deflater compresser = new Deflater();
		    compresser.setInput(jsonString.getBytes(Charset.forName("UTF-8")));

		    compresser.finish();
		    byte [] compressBytes = new byte [512];
		    int compressBytesLength = compresser.deflate(compressBytes);
		    compresser.end();
		    return new String(Base64Url.base64EncodeUrl(Arrays.copyOfRange(compressBytes,0,compressBytesLength)));
	}catch (Exception e) {
		throw new  QCloudException(e);
	}
}
 
Example 54
Project: dshell   File: CompilingFunction.java   Source Code and License 5 votes vote down vote up
@Override
public String run(Context context) throws Exception {
    final String functionCodes = context.getString("function");
    final String fileName = context.getString("fileName");
    final String dependencies = context.getString("dependencies");

    try {
        // save code to disk
        Files.write(workspace.resolve(fileName), functionCodes.getBytes("UTF-8"), StandardOpenOption.CREATE);
        // compile
        final CompilationResult compilationResult = javaFileCompiler.compile(
                workspace.resolve(fileName).toString(),
                StringUtils.isNotBlank(dependencies)
                ? Arrays.asList(dependencies.split(","))
                : Collections.emptyList()
        );
        if (compilationResult.isSuccess()) {

            // archive codes to a zip file
            final Path zipFilePath = compilationResult.getPath().resolve("artifact.zip");
            ZipFileUtil.zipDir(compilationResult.getPath(), zipFilePath);
            final String artifactPath = artifactStore.save(zipFilePath).get().toString();
            log.info("compiling succeeded: " + artifactPath);

            updateHttpContextIfPossible(context, 200);
            return JSON.toJSONString(new CompilingFunctionResult(true, artifactPath, null));
        } else {
            updateHttpContextIfPossible(context, 500);
            final List<String> errors = CollectionUtils.isEmpty(compilationResult.getCompilerBarks())
                                        ? Arrays.asList(compilationResult.getMessage())
                                        : compilationResult.getCompilerBarks();
            return JSON.toJSONString(new CompilingFunctionResult(false, null, errors));
        }
    } catch (Exception ex) {
        log.error("compiling function failed: " + ex.getMessage(), ex);
        updateHttpContextIfPossible(context, 500);
        return JSON.toJSONString(new CompilingFunctionResult(false, null, Arrays.asList(ex.getMessage())));
    }
}
 
Example 55
Project: FastAndroid   File: FastJsonResponseBodyConverter.java   Source Code and License 5 votes vote down vote up
@Override
public T convert(ResponseBody value) throws IOException {
    try {
        return JSON.parseObject(value.string(), mType, config, featureValues, features != null ? features : EMPTY_SERIALIZER_FEATURES);
    } finally {
        value.close();
    }
}
 
Example 56
Project: iBase4J-Common   File: BaseController.java   Source Code and License 5 votes vote down vote up
/** 设置响应代码 */
protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code, Object data) {
    Map<String, Object> map = InstanceUtil.newLinkedHashMap();
    map.putAll(modelMap);
    modelMap.clear();
    for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
        String key = iterator.next();
        if (!key.startsWith("org.springframework.validation.BindingResult") && !key.equals("void")) {
            modelMap.put(key, map.get(key));
        }
    }
    if (data != null) {
        if (data instanceof Page) {
            Page<?> page = (Page<?>)data;
            modelMap.put("rows", page.getRecords());
            modelMap.put("current", page.getCurrent());
            modelMap.put("size", page.getSize());
            modelMap.put("pages", page.getPages());
            modelMap.put("total", page.getTotal());
        } else if (data instanceof List<?>) {
            modelMap.put("rows", data);
            modelMap.put("total", ((List<?>)data).size());
        } else {
            modelMap.put("data", data);
        }
    }
    modelMap.put("code", code.value().toString());
    modelMap.put("msg", code.msg());
    modelMap.put("timestamp", System.currentTimeMillis());
    logger.info("RESPONSE : " + JSON.toJSONString(modelMap));
    return ResponseEntity.ok(modelMap);
}
 
Example 57
Project: java-nio-test   File: ByteBufferEncoder.java   Source Code and License 5 votes vote down vote up
private static JSONObject parseJsonObject(byte[] entryContent) {
    try {
        return JSON.parseObject(new String(entryContent, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        LOG.error("Error parsing json", e);
        return new JSONObject();
    }
}
 
Example 58
Project: pay-xxpay-master   File: AlipayConfig.java   Source Code and License 5 votes vote down vote up
/**
 * 初始化支付宝配置
 * @param configParam
 * @return
 */
public AlipayConfig init(String configParam) {
    Assert.notNull(configParam, "init alipay config error");
    JSONObject paramObj = JSON.parseObject(configParam);
    this.setApp_id(paramObj.getString("appid"));
    this.setRsa_private_key(paramObj.getString("private_key"));
    this.setAlipay_public_key(paramObj.getString("alipay_public_key"));
    this.setIsSandbox(paramObj.getShortValue("isSandbox"));
    if(this.getIsSandbox() == 1) this.setUrl("https://openapi.alipaydev.com/gateway.do");
    return this;
}
 
Example 59
Project: minsx-java-example   File: RepositoryProxyFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
    Object result = null;
    System.out.println("[method name] = "+method.getName());
    System.out.println("[parameter] = "+ JSON.toJSONString(args));

    System.out.println("[before]");
    //result = methodProxy.invokeSuper(obj, args);
    System.out.println("[after]");
    //new User(1,"goodsave","Ss123456","[email protected]")
    return result;
}
 
Example 60
Project: iBase4J-Common   File: AlipayUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 退款
 * @param outTradeNo 订单支付时传入的商户订单号,不能和 trade_no同时为空。
 * @param tradeNo 支付宝交易号,和商户订单号不能同时为空
 * @param outRequestNo 标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传。
 * @param refundAmount 退款金额
 * @param refundReason 退款原因
 * @return 支付参数
 */
public static RefundResult refund(String outTradeNo, String tradeNo, String outRequestNo, BigDecimal refundAmount,
    String refundReason) {
    // 实例化客户端
    AlipayClient alipayClient = AliPayConfig.build().getAlipayClient();
    // 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay
    AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
    // SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
    AlipayTradeRefundModel model = new AlipayTradeRefundModel();
    model.setOutTradeNo(outTradeNo);
    model.setTradeNo(tradeNo);
    model.setRefundAmount(refundAmount.toString());
    model.setRefundReason(refundReason);
    model.setOutRequestNo(outRequestNo);
    request.setBizModel(model);
    try {
        // 这里和普通的接口调用不同,使用的是sdkExecute
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        logger.info(response.getBody());
        if (!response.isSuccess()) {
            throw new RuntimeException(response.getSubMsg());
        }
        Map<?, ?> body = JSON.parseObject(response.getBody(), Map.class);
        Map<?, ?> result = JSON.parseObject(body.get("alipay_trade_refund_response").toString());
        return new RefundResult((String)result.get("trade_no"), outTradeNo, refundAmount.toString(),
            DateUtil.stringToDate((String)result.get("gmt_refund_pay")),
            "Y".equals(result.get("fund_change")) ? "1" : "2");
    } catch (AlipayApiException e) {
        throw new RuntimeException(e);
    }
}