/// <summary> /// 发送语音短信 /// </summary> /// <param name="param"></param> /// <returns></returns> public SmsResponseDto <SendSmsResponseDto> SendVoiceSms(SendVoiceSmsParam param) { new SendVoiceSmsParamValidator().Validate(param).Check(HttpStatus.Err.Name); CommonRequest request = base.GetRequest("dyvmsapi.aliyuncs.com", "SingleCallByTts", "2017-05-25", "cn-hangzhou"); request.AddQueryParameters("CalledNumber", param.Phone); request.AddQueryParameters("CalledShowNumber", param.CalledShowNumber); request.AddQueryParameters("TtsCode", param.TemplateCode); request.AddQueryParameters("PlayTimes", param.PlatTimes.ToString()); //播放次数 request.AddQueryParameters("Volume", param.Volume.ToString()); //播放音量 Dictionary <string, string> data = new Dictionary <string, string>(); param.Content.ForEach(item => { data.Add(item.Key, item.Value); }); request.AddQueryParameters("TtsParam", _jsonProvider.Serializer(data)); try { CommonResponse response = GetClient().GetCommonResponse(request); if (response != null) { var res = _jsonProvider .Deserialize <SendVoiceSmsResponseDto>( response.Data); if (res != null) { SmsCode smsCode = SmsCodeMap.Where(x => x.Key == res.Code).Select(x => x.Value) .FirstOrDefault(); if (smsCode != default(SmsCode)) { return(new SmsResponseDto <SendSmsResponseDto>() { Code = smsCode, Msg = smsCode == SmsCode.Ok ? "success" : "lose", Extend = new SendSmsResponseDto(param.Phone, new SendSmsExtend() { BizId = smsCode == SmsCode.Ok ? _jsonProvider .Deserialize <SendVoiceSmsSuccessResponseDto>( response.Data).CallId : "", RequestId = res.RequestId, Msg = res.Message }) }); } } } } catch (ServerException e) { } return(new SmsResponseDto <SendSmsResponseDto>() { Code = SmsCode.Unknown, Msg = "发送异常" }); }
/// <summary> /// 根据标签筛选空间获取空间名列表 /// </summary> /// <param name="request"></param> /// <returns></returns> public BucketItemResultDto GetBucketList(GetBucketParam request) { UrlParameter urlParameter = new UrlParameter(); request.TagFilters.ForEach(tag => { urlParameter.Add(tag.Key, tag.Value); }); string url = $"http://rs.qbox.me/buckets?tagCondition={Base64.UrlSafeBase64Encode(urlParameter.GetQueryResult())}"; _httpClient.Headers = new Dictionary <string, string>() { { "Authorization", $"{_storageProvider.GetManageToken(new GetManageTokenParam(url))}" } }; try { var response = _httpClient.GetString(url); return(GetResponse(response, () => { var bucketList = _jsonProvider.Deserialize <List <string> >(response); Expression <Func <string, bool> > condition = x => true; if (!string.IsNullOrEmpty(request.Prefix)) { condition = condition.And(x => x.StartsWith(request.Prefix)); } var list = bucketList.Where(condition.Compile()).ToList(); if (!string.IsNullOrEmpty(request.Marker)) { var index = list.ToList().IndexOf(request.Marker); if (index != -1) { list = list.Skip(index + 1).ToList(); } } if (request.PageSize != -1) { var isTruncated = list.Take(request.PageSize).Count() != list.Count; return new BucketItemResultDto( list.Take(request.PageSize).Select(x => new BucketItemResultDto.BucketItemDto(null, x)) .ToList(), request.Prefix, isTruncated, request.Marker, isTruncated ? list.Take(request.PageSize).LastOrDefault() : ""); } return new BucketItemResultDto( list.Select(x => new BucketItemResultDto.BucketItemDto(null, x)).ToList(), request.Prefix, false, request.Marker, ""); }, resultResponse => new BucketItemResultDto(request.Prefix, request.Marker, $"{resultResponse.Error}|{resultResponse.ErrorCode}"))); } catch (Exception ex) { this._logger?.LogError(ex.ExtractAllStackTrace()); return(new BucketItemResultDto(request.Prefix, request.Marker, $"lose {ex.Message}")); } }
/// <summary> /// 得到结果 /// </summary> /// <param name="response">响应信息</param> /// <param name="successAction">成功响应</param> /// <param name="errAction">失败响应</param> /// <typeparam name="T"></typeparam> protected void GetResult <T>(string response, Action <T> successAction, Action <ErrDto> errAction) where T : class, new() { if (response.Contains("error_response")) { errAction(_jsonProvider.Deserialize <ErrDto>(response)); } successAction(_jsonProvider.Deserialize <T>(response)); }
/// <summary> /// Get请求 得到响应字符串 /// </summary> /// <param name="url">请求地址</param> /// <returns></returns> public T GetJson <T>(string url) { var res = Get(url).Content; if (string.IsNullOrEmpty(res)) { return(default(T)); } return((T)_jsonProvider.Deserialize(res, typeof(T))); }
/// <summary> /// Get请求 得到响应字符串 /// </summary> /// <param name="url">请求地址</param> /// <returns></returns> public T GetJson <T>(string url) where T : class, new() { var res = GetString(url); if (string.IsNullOrEmpty(res)) { return(default(T)); } return((T)_jsonProvider.Deserialize(res, typeof(T))); }
static void Test(IJsonProvider provider, object obj) { string json = ""; object newObj = null; CodeTimer.TimeLine(provider.GetType().Name + " - Serialize", 10 * 10000, i => json = provider.Serialize(obj)); CodeTimer.TimeLine(provider.GetType().Name + " - Deserialize", 10 * 10000, i => newObj = provider.Deserialize(json, obj.GetType())); }
/// <summary> /// 将JSON反序列化成对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <returns></returns> private T ConvertObj <T>(string value) where T : class, new() { if (string.IsNullOrWhiteSpace(value)) { return(default(T)); } Type t = typeof(T); if (string.Equals(t.Name, "string", StringComparison.OrdinalIgnoreCase)) { return((T)Convert.ChangeType(value, typeof(T))); } return(_jsonProvider.Deserialize <T>(value)); }
public virtual void Deserialize_Should_ReturnGenericInstanceByUtf8BytesPassedIn() { // Arrange var utf8JsonBytes = Encoding.UTF8.GetBytes("{\"RedPanda\":\"Hello World!\",\"Happy\":true,\"Year\":2020,\"Enum\":0,\"BDto\":{\"Service\":\"RedPanda\"}}"); var expectedResult = new ADto { RedPanda = "Hello World!", Happy = true, Year = 2020, Enum = TestEnum.RedPanda, BDto = new BDto { Service = "RedPanda" } }; // Assert var actualResult = jsonProvider.Deserialize <ADto>(utf8JsonBytes); // Act actualResult.Should().BeEquivalentTo(expectedResult); }
/// <summary> /// 得到响应信息 /// </summary> /// <param name="response">响应信息</param> /// <returns></returns> private ContentInfoDto GetResponse(string response) { if (string.IsNullOrEmpty(response)) { return(new ContentInfoDto() { Success = false, Msg = "lose" }); } var data = _jsonProvider.Deserialize <dynamic>(response); if (data == null || data["errno"] != 0) { return(new ContentInfoDto() { Success = false, Msg = "lose" }); } ContentInfoDto contentInfo = new ContentInfoDto() { Msg = data["data"]["conclusion"], Success = true, Data = new List <ContentInfoDto.DataDto>() }; if (data["data"]["conclusionType"] == 1) { contentInfo.Data.Add(new ContentInfoDto.DataDto() { Msg = "合规", Rating = ContentRatingEnum.Normal, SubRating = SubContentRatingEnum.Normal }); } else if (data["data"]["conclusionType"] == 2) { List <ImageResponse> responseList = _jsonProvider.Deserialize <List <ImageResponse> >(data["data"]); foreach (var item in responseList) { if (item.Star != null) { contentInfo.Data.Add(new ContentInfoDto.DataDto() { Msg = item.Msg, Probability = item.Probability, Rating = GetRating(item.Type), Star = item.Star.Select(x => new ContentInfoDto.PersonDto() { Name = x.Name, Probability = x.Probability }).ToList() }); } } } return(null); }
public IList <TransactionData> GetCurrentHoldings() { var contents = _ioWrapper.Read(_appSettingProvider.Get(Constants.HoldingsJsonFilePath)); return(_jsonProvider.Deserialize <IList <TransactionData> >(contents)); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task Invoke(HttpContext context) { try { await _next(context); } catch (System.Exception ex) { if (ExceptionAction != null) { var isStop = ExceptionAction.Invoke(context, ex); if (isStop) { return; } } var statusCode = context.Response.StatusCode; string msg; if (ex is BusinessException) { var data = _jsonProvider.Deserialize <dynamic>(ex.Message); statusCode = data.code; msg = data.content; } else if (ex is AuthException) { statusCode = 401; msg = ex.Message; } else { msg = "未知错误"; } await HandleExceptionAsync(context, statusCode, msg); } finally { var statusCode = context.Response.StatusCode; var msg = ""; if (statusCode == 401) { msg = "未授权"; } else if (statusCode == 404) { msg = "未找到服务"; } else if (statusCode == 502) { msg = "请求错误"; } else if (statusCode == 500) { msg = "未知错误"; } if (!string.IsNullOrWhiteSpace(msg) && statusCode != 401) { await HandleExceptionAsync(context, statusCode, msg); } } }