public static void RegisterApis(HttpConfiguration config) { var serializerSettings = new JsonSerializerSettings(); serializerSettings.Converters.Add(new IsoDateTimeConverter()); config.Formatters[0] = new JsonNetFormatter(serializerSettings); config.Formatters.Add(new ProtoBufFormatter()); config.Formatters.Add(new ContactPngFormatter()); config.Formatters.Add(new VCardFormatter()); config.Formatters.Add(new ContactCalendarFormatter()); config.MessageHandlers.Add(new UriFormatExtensionHandler(new UriExtensionMappings())); //var loggingRepo = config.ServiceResolver.GetService(typeof(ILoggingRepository)) as ILoggingRepository; //config.MessageHandlers.Add(new LoggingHandler(loggingRepo)); config.MessageHandlers.Add(new NotAcceptableHandler()); ConfigureResolver(config); config.Routes.MapHttpRoute( "Default", "{controller}/{id}/{ext}", new { id = RouteParameter.Optional, ext = RouteParameter.Optional }); }
public Reddit() { JsonSerializerSettings = new JsonSerializerSettings(); JsonSerializerSettings.CheckAdditionalContent = false; JsonSerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore; _webAgent = new WebAgent(); }
// ReSharper disable once InconsistentNaming public async void Controller_Can_POST_a_new_Registerd_User() { using (var client = new HttpClient()) { // Arrange client.BaseAddress = new Uri(UrlBase); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Manually set "content-type" header to reflect serialized data format. var settings = new JsonSerializerSettings(); var ser = JsonSerializer.Create(settings); var j = JObject.FromObject(_registration, ser); HttpContent content = new StringContent(j.ToString()); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); // Act // PostAsJsonAsync(), per MS recommendation, however results in problem of RegisterAsync() accepting payload: content type? // Serialized registration data is now associated with HttpContent element explicitly, with format then set. var response = await client.PostAsync(client.BaseAddress + "/RegisterAsync", content); //var response = await client.PostAsJsonAsync(client.BaseAddress + "/RegisterAsync", _registration); // error // Assert Assert.IsTrue(response.StatusCode == HttpStatusCode.Created); Assert.IsTrue(response.IsSuccessStatusCode); } }
public JsonNetFormatter(JsonSerializerSettings jsonSerializerSettings) { _jsonSerializerSettings = jsonSerializerSettings ?? new JsonSerializerSettings(); SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); Encoding = new UTF8Encoding(false, true); }
public static new void Install(HttpConfiguration config, IAppBuilder app) { config.SuppressHostPrincipal(); app.UseCors(CorsOptions.AllowAll); app.MapSignalR(); var jSettings = new JsonSerializerSettings(); jSettings.Formatting = Formatting.Indented; jSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.Remove(config.Formatters.XmlFormatter); config.Formatters.JsonFormatter.SerializerSettings = jSettings; config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
public JsonInputFormatter() { _supportedMediaTypes = new List<string> { "application/json", "text/json" }; _supportedEncodings = new List<Encoding> { new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true) }; _jsonSerializerSettings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore, // Limit the object graph we'll consume to a fixed depth. This prevents stackoverflow exceptions // from deserialization errors that might occur from deeply nested objects. MaxDepth = DefaultMaxDepth, // Do not change this setting // Setting this to None prevents Json.NET from loading malicious, unsafe, or security-sensitive types TypeNameHandling = TypeNameHandling.None }; }
static JsonFormatter() { SerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; }
public TesterController(IInstanceService instanceService) { this.instanceService = instanceService; jsonSerializerSettings = new JsonSerializerSettings(); jsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore; }
public SchemaRegistry( JsonSerializerSettings jsonSerializerSettings, IDictionary<Type, Func<Schema>> customSchemaMappings, IEnumerable<ISchemaFilter> schemaFilters, IEnumerable<IModelFilter> modelFilters, Func<Type, string> schemaIdSelector, bool ignoreObsoleteProperties, bool describeAllEnumsAsStrings, bool describeStringEnumsInCamelCase, AutoRestEnumSupportType? autoRestEnumSupport) { _jsonSerializerSettings = jsonSerializerSettings; _customSchemaMappings = customSchemaMappings; _schemaFilters = schemaFilters; _modelFilters = modelFilters; _schemaIdSelector = schemaIdSelector; _ignoreObsoleteProperties = ignoreObsoleteProperties; _describeAllEnumsAsStrings = describeAllEnumsAsStrings; _describeStringEnumsInCamelCase = describeStringEnumsInCamelCase; _autoRestEnumSupport = autoRestEnumSupport; _contractResolver = jsonSerializerSettings.ContractResolver ?? new DefaultContractResolver(); _referencedTypes = new Dictionary<Type, SchemaInfo>(); Definitions = new Dictionary<string, Schema>(); }
static MobileServiceSerializerTests() { var settings = new JsonSerializerSettings(); settings.DateFormatHandling = DateFormatHandling.IsoDateFormat; settings.DateFormatString = "yyyy-MM-dd'T'HH:mm:ss.fff'Z'"; MinDateTimeSerializedToJson = JsonConvert.SerializeObject(default(DateTime).ToUniversalTime(), settings); }
public async Task<LoginResult> Login(string username, string password) { var json = ""; if (string.IsNullOrEmpty (username) || string.IsNullOrEmpty (password)) { return new LoginResult { Successful = false }; } using (var client = new HttpClient ()) { using (var message = new HttpRequestMessage (HttpMethod.Post, BaseUrl + "/account/login")) { var userPass = string.Format("{0}:{1}", username, password); var encoded = Convert.ToBase64String(new System.Text.ASCIIEncoding().GetBytes(userPass)); message.Headers.Add("Authorization", String.Format("Basic {0}", encoded)); var result = await client.SendAsync(message); json = await result.Content.ReadAsStringAsync(); } } var settings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore, NullValueHandling = NullValueHandling.Ignore }; var loginCredentials = JsonConvert.DeserializeObject<LoginResult>(json, settings); return loginCredentials; }
public override string ToString() { JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Formatting = Formatting.Indented; settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); return JsonConvert.SerializeObject(this, settings); }
/// <summary> /// Called before an action method executes. /// </summary> /// <param name="filterContext">The filter context.</param> public override void OnActionExecuting(ActionExecutingContext filterContext) { // Continue normally if the model is valid. if (filterContext == null || filterContext.Controller.ViewData.ModelState.IsValid) { return; } var serializationSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; // Serialize Model State for passing back to AJAX call var serializedModelState = JsonConvert.SerializeObject( filterContext.Controller.ViewData.ModelState, serializationSettings); var result = new ContentResult { Content = serializedModelState, ContentType = "application/json" }; filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; filterContext.Result = result; }
public override string ToString() { var settings = new JsonSerializerSettings(); settings.DefaultValueHandling = DefaultValueHandling.Ignore; settings.NullValueHandling = NullValueHandling.Ignore; return this.ToJson(settings: settings); }
public static new void Install(HttpConfiguration config, IAppBuilder app) { config.SuppressHostPrincipal(); SecurityApi.Services.Contracts.IIdentityService identityService = UnityConfiguration.GetContainer().Resolve<SecurityApi.Services.Contracts.IIdentityService>(); app.UseOAuthAuthorizationServer(new OAuthOptions(identityService)); app.UseJwtBearerAuthentication(new SecurityApi.Auth.JwtOptions()); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); app.UseCors(CorsOptions.AllowAll); app.MapSignalR(); var jSettings = new JsonSerializerSettings(); jSettings.Formatting = Formatting.Indented; jSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.Remove(config.Formatters.XmlFormatter); config.Formatters.JsonFormatter.SerializerSettings = jSettings; config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
/// <summary> /// El código es el mismo de ASP.NET MVC 3, cambie el método que escribe en el response /// http://aspnet.codeplex.com/SourceControl/changeset/view/63930#266491 /// </summary> /// <param name = "context"></param> public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException( "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."); } var response = context.HttpContext.Response; if (!String.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { var settings = new JsonSerializerSettings(); settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; settings.Converters.Add(new IsoDateTimeConverter()); response.Write(JsonConvert.SerializeObject(this.Data, Formatting.None, settings)); } }
public static void LogFailedMessage(object messageObj) { if (LogConfig.IsLoggingEnabled) { try { //log.SessionId = ApplicationContext.GetSessionId(); var dataProvider = new LoggingDataProvider(); var settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects, }; var log = new Log() { Name = "FailedMessageItem", ServiceName = messageObj.GetType().Name, Request = JsonConvert.SerializeObject(messageObj, settings), }; if (LogConfig.IsLogAsyncEnabled) { Task.Factory.StartNew(() => dataProvider.SaveLog(log)); } else { dataProvider.SaveLog(log); } } catch (Exception ex) { File.AppendAllText("Logs.txt", "LogMessage method failed" + ex.ToString()); } } }
public static string ToJson( this object val ) { var settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; return JsonConvert.SerializeObject( val, Formatting.Indented, settings ); }
public string Serialize(object obj) { var settings = new JsonSerializerSettings(); settings.ContractResolver = new LowercaseContractResolver(); return JsonConvert.SerializeObject(obj, settings); }
public JsonNetResult() { Settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Error }; }
// GET api/Bill public object GetBillData(string url) { JsonResult jsonResult = new JsonResult(); try { using (var client = new WebClient()) { var jsonData = client.DownloadString(url); var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; object model; using (GlimpseTimeline.Capture("====> Get bills from Json URL AngularJS")) { model = CacheHandler.Get(homeAngularJSCacheKey, () => { return JsonConvert.DeserializeObject<BillModel>(jsonData, jsonSerializerSettings); }); } jsonResult = new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception(ex.Message)); } return jsonResult.Data; }
public static GlobalSettings Load() { GlobalSettings settings; var configFile = Path.Combine(Directory.GetCurrentDirectory(), "Config", "config.json"); if (File.Exists(configFile)) { //if the file exists, load the settings var input = File.ReadAllText(configFile); var jsonSettings = new JsonSerializerSettings(); jsonSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); jsonSettings.ObjectCreationHandling = ObjectCreationHandling.Replace; jsonSettings.DefaultValueHandling = DefaultValueHandling.Populate; settings = JsonConvert.DeserializeObject<GlobalSettings>(input, jsonSettings); } else { settings = new GlobalSettings(); } var firstRun = !File.Exists(configFile); settings.Save(configFile); if (firstRun || settings.Port == 0 ) { Log.Error($"Invalid configuration detected. \nPlease edit {configFile} and try again"); return null; } return settings; }
public void Blah2() { var foo = new Foo { Name = "Andrew", Friends = { new Friend{Name = "Matt"}, new SubFriend { Name = "Nick", Age = 28 }, } }; var settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All, ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; var serializeObject = JsonConvert.SerializeObject(foo, Formatting.Indented, settings); var bytes = Encoding.UTF8.GetBytes(serializeObject); var result = JsonConvert.DeserializeObject<Foo>(Encoding.UTF8.GetString(bytes), new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects }); Assert.That(result.Friends.Count, Is.EqualTo(2)); var nick = result.Friends.Single(x => x.Name == "Nick"); Assert.That(nick, Is.TypeOf<SubFriend>()); var matt = result.Friends.Single(x => x.Name == "Matt"); Assert.That(matt, Is.TypeOf<Friend>()); }
public MetaController() { JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings(); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings; _serializer = new SerializeLibra.JsonSerializer(); }
public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."); var response = context.HttpContext.Response; response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; if (Data == null) return; var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; response.Write(JsonConvert.SerializeObject(Data, Formatting.Indented, jsonSerializerSettings)); }
public void SaveProject(IProject project, string location) { this.project = project; CreateDirectoryStructure(project.ResourceTree, location); settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented, }; var rootFile = new JsonRootProject(); rootFile.Version = SpecificVersion; ExportSprites(location); ExportScripts(location); // Export icon var icoFileName = Path.Combine(location, "app.ico"); File.WriteAllBytes(icoFileName, project.Settings.IconData); // Write project file var rootFileName = Path.Combine(location, "project.json"); File.WriteAllText(rootFileName, JsonConvert.SerializeObject(rootFile, settings)); }
public static string JsonCamelCase(this object obj) { var formatter = new JsonSerializerSettings(); formatter.ContractResolver = new CamelCasePropertyNamesContractResolver(); return JsonConvert.SerializeObject(obj, formatter); }
public void CanSerializeAndDeserializeAScope() { var s1 = new Scope { Name = "email", Required = true, Type = ScopeType.Identity, Emphasize = true, DisplayName = "email foo", Description = "desc foo", Claims = new List<ScopeClaim> { new ScopeClaim{Name = "email", Description = "email"} } }; var s2 = new Scope { Name = "read", Required = true, Type = ScopeType.Resource, Emphasize = true, DisplayName = "foo", Description = "desc", }; var converter = new ScopeConverter(new InMemoryScopeStore(new Scope[] { s1, s2 })); var settings = new JsonSerializerSettings(); settings.Converters.Add(converter); var json = JsonConvert.SerializeObject(s1, settings); var result = JsonConvert.DeserializeObject<Scope>(json, settings); Assert.Same(s1, result); }
public virtual ActionResult Read([DataSourceRequest]DataSourceRequest request) { var data = this.GetData(); var serializationSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; var json = JsonConvert.SerializeObject(data.ToDataSourceResult(request), Formatting.None, serializationSettings); return this.Content(json, "application/json"); }
public override string ToString() { Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings(); //日期类型默认格式化处理 setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; //setting.DateFormatString = "yyyy-MM-dd"; setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; //空值处理 setting.NullValueHandling = NullValueHandling.Ignore; string str = JsonConvert.SerializeObject(this, setting); return(str); }
public ContentResult JsonContent(object data, Encoding encoding, JsonRequestBehavior behavior = JsonRequestBehavior.DenyGet) { Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings(); settings.ContractResolver = new DefaultContractResolver(); //设置属性输出默认值; if (Request.HttpMethod == HttpMethod.Get.Method) { if (behavior != JsonRequestBehavior.AllowGet) { return(Content("不支持的方法", "text/plain", encoding)); } } return(Content(JsonConvert.SerializeObject(data, settings), "application/json", encoding)); }
private void CustomizeJsonFormatting() { var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter; var settings = new Newtonsoft.Json.JsonSerializerSettings() { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat }; jsonFormatter.SerializerSettings = settings; jsonFormatter.SerializerSettings.Converters = new List <JsonConverter>() { new StringEnumConverter() }; }
public string ToJSON(object oo) { Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings(); var iso = new IsoDateTimeConverter(); iso.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; setting.Converters = new List <JsonConverter> { new StringEnumConverter(), iso }; setting.Formatting = Formatting.Indented; // setting.en return(JsonConvert.SerializeObject(oo, setting)); }
private JsonSerializer Serializer() { var Settings = new Newtonsoft.Json.JsonSerializerSettings() { Formatting = Formatting.Indented, Converters = new List <JsonConverter>() { new VersionConverter(), new StringEnumConverter(), } }; var S = Newtonsoft.Json.JsonSerializer.Create(Settings); return(S); }
public static void SaveJson <T>(T source, string path, IContractResolver contractResolver, JsonConverter converter) { var settings = new Newtonsoft.Json.JsonSerializerSettings(); if (contractResolver != null) { settings.ContractResolver = contractResolver; } if (converter != null) { settings.Converters.Add(converter); } settings.Converters.Add(new StringEnumConverter()); SaveJson(JsonConvert.SerializeObject(source, Newtonsoft.Json.Formatting.Indented, settings), path); }
public static void RegisterFormatters(MediaTypeFormatterCollection formatters) { var json = new JsonMediaTypeFormatter(); JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings() { Formatting = Formatting.Indented, DateTimeZoneHandling = DateTimeZoneHandling.Utc, }; jSettings.Converters.Add(new CustomDateTimeConvertor()); json.SerializerSettings = jSettings; formatters.Insert(0, json); // Remove XML formatter because Opera 12 replaces headers from */* to text/html formatters.Remove(formatters.XmlFormatter); }
static JT808CoreDotnettyExtensions() { JsonConvert.DefaultSettings = new Func <JsonSerializerSettings>(() => { Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings(); //日期类型默认格式化处理 settings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; settings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; //空值处理 settings.NullValueHandling = NullValueHandling.Ignore; settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; settings.Converters.Add(new JsonIPAddressConverter()); settings.Converters.Add(new JsonIPEndPointConverter()); return(settings); }); }
public JsonResult Add(string roleJson) { if (ModelState.IsValid) { var s = new Newtonsoft.Json.JsonSerializerSettings(); s.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore; s.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; Model.RoleInfo role = Newtonsoft.Json.JsonConvert.DeserializeObject <Model.RoleInfo>(roleJson, s); _iPrivilegesService.AddPlatformRole(role); } else { return(Json(new { success = true, msg = "验证失败" })); } return(Json(new { success = true })); }
public ActionResult Edit(long id) { var shopId = CurrentSellerManager.ShopId; SetPrivileges(); var model = _iPrivilegesService.GetSellerRole(id, shopId); RoleInfoModel result = new RoleInfoModel() { ID = model.Id, RoleName = model.RoleName }; var s = new Newtonsoft.Json.JsonSerializerSettings(); s.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; ViewBag.RolePrivilegeInfo = Newtonsoft.Json.JsonConvert.SerializeObject(model.RolePrivilegeInfo.Select(item => new { Privilege = item.Privilege }), s); return(View(result)); }
static JsonHelper() { DefaultSetting = new JsonSerializerSettings() { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat, NullValueHandling = NullValueHandling.Ignore, }; DefaultSetting.Converters.Add(new StringEnumConverter()); //全局序列化设置 Newtonsoft.Json.JsonConvert.DefaultSettings = new Func <JsonSerializerSettings>(() => { var setting = JsonHelper.DefaultSetting; return(setting); }); }
private string ConvertToProperJSON(Object value) { DefaultContractResolver contractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() }; var settings = new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = contractResolver, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented, }; return(JsonConvert.SerializeObject(value, settings)); }
public void PackageSerializationTest() { // arrange var settings = new Newtonsoft.Json.JsonSerializerSettings(); settings.Converters.Add(new StorageConverter()); // act var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(Package); var deserialized = Newtonsoft.Json.JsonConvert.DeserializeObject <DownloadPackage>(serialized, settings); // assert PackagesAreEqual(Package, deserialized); Package.Clear(); }
protected void Application_Start(object sender, EventArgs e) { GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AutoMapperConfiguration.Configure(); //fix bug serialize for web API GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize; GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings(); jSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings; }
SpotCharter IEventSourceCommandRepository <SpotCharter, SpotCharterId> .Get(SpotCharterId id) { var settings = new Newtonsoft.Json.JsonSerializerSettings() { ContractResolver = new JsonNet.PrivateSettersContractResolvers.PrivateSetterContractResolver() }; if (!this.repository.ContainsKey(id)) { return(null); } var eventStream = this.repository[id]; return(new SpotCharter(eventStream.Select(json => JsonConvert.DeserializeObject(json.JsonString, json.Type, settings) as IEvent <SpotCharterId>).ToArray())); }
/// <summary> /// 输到前端网页使用时要注册 camelCase/longToStr 参数 /// </summary> /// <param name="data"></param> /// <param name="camelCase"> 名称 驼峰结构输出</param> /// <param name="longToStr">long转成字串(javascript 超过15长度会有精度问题)</param> /// <returns></returns> public static string SerializeObject(object data, bool camelCase = false, bool longToStr = false) { var setting = new Newtonsoft.Json.JsonSerializerSettings(); if (longToStr) { setting.Converters.Add(new HexLongConverter()); } if (camelCase) { setting.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); } setting.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; return(JsonConvert.SerializeObject(data, setting)); }
public static string ToJson(this object obj) { Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings(); JsonConvert.DefaultSettings = new Func <JsonSerializerSettings>(() => { //日期类型默认格式化处理 setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; //空值处理 setting.NullValueHandling = NullValueHandling.Ignore; //setting.FloatParseHandling = FloatParseHandling.Decimal; return(setting); }); return(JsonConvert.SerializeObject(obj, Formatting.None, setting));//Formatting.Indented缩进排版 }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var setting = new Newtonsoft.Json.JsonSerializerSettings(); JsonConvert.DefaultSettings = new Func <JsonSerializerSettings>(() => { // 日期类型默认格式化处理 setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; return(setting); }); }
public SpeckleApiClient(string baseUrl, bool isPersistent = false) : base() { _settings = new System.Lazy <Newtonsoft.Json.JsonSerializerSettings>(() => { var settings = new Newtonsoft.Json.JsonSerializerSettings(); UpdateJsonSerializerSettings(settings); return(settings); }); UseGzip = true; BaseUrl = baseUrl; IsPersistent = isPersistent; SetReadyTimer(); }
public async Task <IList <Country> > GetAll() { var key = "all_country"; try { if (!Barrel.Current.IsExpired(key)) { return(Barrel.Current.Get <List <Country> >(key)); } var response = await Constants.BASE_URL .AppendPathSegment(@"/countries") .SetQueryParam("sort", new[] { "country" }) .WithTimeout(30) .GetAsync(); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); var setting = new Newtonsoft.Json.JsonSerializerSettings(); JsonConvert.DefaultSettings = new Func <JsonSerializerSettings>(() => { setting.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; setting.FloatParseHandling = FloatParseHandling.Decimal; return(setting); }); var all = JsonConvert.DeserializeObject <List <Country> >(content); if (all != null) { Barrel.Current.Add(key: key, data: all, expireIn: TimeSpan.FromHours(1)); } return(all); } } catch (Exception ex) { return(null); } return(null); }
public override void RegisterBuilder(ConfigurationContext context) { var apiConfig = AppConfig.Options.ApiGetWay; if (apiConfig != null) { ApiGateWay.AppConfig.AuthenticationServiceKey = apiConfig.AuthenticationServiceKey; ApiGateWay.AppConfig.AuthorizationServiceKey = apiConfig.AuthorizationServiceKey; ApiGateWay.AppConfig.AuthorizationRoutePath = apiConfig.AuthorizationRoutePath; ApiGateWay.AppConfig.AuthenticationRoutePath = apiConfig.AuthenticationRoutePath; ApiGateWay.AppConfig.TokenEndpointPath = apiConfig.TokenEndpointPath; ApiGateWay.AppConfig.IsUsingTerminal = apiConfig.IsUsingTerminal; ApiGateWay.AppConfig.Terminals = apiConfig.Terminals; ApiGateWay.AppConfig.JwtSecret = apiConfig.JwtSecret; ApiGateWay.AppConfig.DefaultExpired = apiConfig.DefaultExpired; } context.Services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; if (AppConfig.Options.IsCamelCaseResolver) { JsonConvert.DefaultSettings = new Func <JsonSerializerSettings>(() => { JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings(); setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; setting.ContractResolver = new CamelCasePropertyNamesContractResolver(); return(setting); }); options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } else { JsonConvert.DefaultSettings = new Func <JsonSerializerSettings>(() => { JsonSerializerSettings setting = new JsonSerializerSettings(); setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; setting.ContractResolver = new DefaultContractResolver(); return(setting); }); options.SerializerSettings.ContractResolver = new DefaultContractResolver(); } }); context.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); context.Services.AddSingleton <IIPChecker, IPAddressChecker>(); context.Services.AddFilters(typeof(AuthorizationFilterAttribute)); context.Services.AddFilters(typeof(ActionFilterAttribute)); context.Services.AddFilters(typeof(IPFilterAttribute)); }
/// <summary> /// Configura el tipo de respuesta como JSON /// </summary> /// <param name="config"></param> public static void configureJSONResponse(HttpConfiguration config) { config.Formatters.Add(new JsonMediaTypeFormatter()); //Sets default JSON response format JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings() { Formatting = WebConfigurationManager.AppSettings["entorno"] == "Desarrollo" ? Formatting.Indented : Formatting.None, DateFormatString = "dd-MM-yyyy HH:mm:ss", //Evitamos referencias cíclicas al serializar a JSON PreserveReferencesHandling = PreserveReferencesHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; config.Formatters.JsonFormatter.SerializerSettings = jSettings; }
private void SetSerialisationSettings() { _settings = new System.Lazy <Newtonsoft.Json.JsonSerializerSettings>(() => { var settings = new Newtonsoft.Json.JsonSerializerSettings() { ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver() { NamingStrategy = new Newtonsoft.Json.Serialization.CamelCaseNamingStrategy() }, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore }; UpdateJsonSerializerSettings(settings); return(settings); }); }
public bool TrySerializeObjectToString(Object value, out string serValue) { Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings(); const Formatting formatting = Newtonsoft.Json.Formatting.None; try { serValue = JsonConvert.SerializeObject(value, formatting, getSettings()); return(true); } catch (Exception) { serValue = null; return(false); } }
public static void Register(HttpConfiguration httpConfiguration) { // Web API configuration and services // Web API routes httpConfiguration.MapHttpAttributeRoutes(); httpConfiguration.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); httpConfiguration.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger()); httpConfiguration.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger()); httpConfiguration.Services.Replace(typeof(IExceptionHandler), new ApiExceptionHandler()); //httpConfiguration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = // new CamelCasePropertyNamesContractResolver(); // WebApi formatters var formatters = httpConfiguration.Formatters; formatters.Remove(formatters.XmlFormatter); // Set json formatters var jsonFormatter = formatters.JsonFormatter; var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings() { Formatting = Formatting.Indented, // Nice for debugging I think, looks pretty ReferenceLoopHandling = ReferenceLoopHandling.Ignore, // Fix JSON.NET self referencing hell ContractResolver = new CamelCasePropertyNamesContractResolver(), // automatic camelCasing Culture = new CultureInfo("fr-BE") }; // add a custom date formatter to override Datetime format settings //jsonSettings.Converters.Add(new MyDateFormatConverter()); // Finally set new settings to global config jsonFormatter.SerializerSettings = jsonSettings; //httpConfiguration.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; //httpConfiguration.Formatters.JsonFormatter.SerializerSettings.Culture = new CultureInfo("fr-FR"); //httpConfiguration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyDateFormatConverter()); }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context is null"); } if (context.RequestContext.HttpContext.Request.HttpMethod == HttpMethod.Get.Method && this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) { throw new NotSupportedException("不支持get请求"); } HttpResponseBase httpResponseBase = context.RequestContext.HttpContext.Response; if (string.IsNullOrEmpty(this.ContentType)) { httpResponseBase.ContentType = "application/json"; } else { httpResponseBase.ContentType = this.ContentType; } if (ContentEncoding == null) { httpResponseBase.ContentEncoding = Encoding.UTF8; } else { httpResponseBase.ContentEncoding = this.ContentEncoding; } if (string.IsNullOrEmpty(this.DateFormatString)) { this.DateFormatString = "yyyy-MM-dd"; } if (Data != null) { Newtonsoft.Json.JsonSerializerSettings serializerSettings = new Newtonsoft.Json.JsonSerializerSettings(); serializerSettings.DateFormatString = this.DateFormatString; serializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; serializerSettings.ContractResolver = new DefaultContractResolver(); httpResponseBase.Write(JsonConvert.SerializeObject(new { code = this.Code, msg = this.Msg, data = this.Data }, serializerSettings)); } }
/// <summary> Initialization function for this storage provider. </summary> /// <see cref="IProvider#Init"/> public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config) { Name = name; serviceId = providerRuntime.ServiceId.ToString(); if (!config.Properties.ContainsKey(CONNECTION_STRING) || string.IsNullOrWhiteSpace(config.Properties[CONNECTION_STRING])) { throw new ArgumentException("Specify a value for:", CONNECTION_STRING); } var connectionString = config.Properties[CONNECTION_STRING]; sqlconnBuilder = new SqlConnectionStringBuilder(connectionString); //a validation of the connection would be wise to perform here //await new SqlConnection(sqlconnBuilder.ConnectionString).OpenAsync(); //initialize to use the default of JSON storage (this is to provide backwards compatiblity with previous version useJsonOrBinaryFormat = StorageFormatEnum.Binary; if (config.Properties.ContainsKey(USE_JSON_FORMAT_PROPERTY)) { if ("true".Equals(config.Properties[USE_JSON_FORMAT_PROPERTY], StringComparison.OrdinalIgnoreCase)) { useJsonOrBinaryFormat = StorageFormatEnum.Json; } if ("both".Equals(config.Properties[USE_JSON_FORMAT_PROPERTY], StringComparison.OrdinalIgnoreCase)) { useJsonOrBinaryFormat = StorageFormatEnum.Both; } } jsonSettings = new Newtonsoft.Json.JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All, PreserveReferencesHandling = PreserveReferencesHandling.Objects, DateFormatHandling = DateFormatHandling.IsoDateFormat, DefaultValueHandling = DefaultValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor }; Log = providerRuntime.GetLogger("StorageProvider.SimpleSQLServerStorage." + serviceId); }
public LndSwaggerClient(LndRestSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } _LndSettings = settings; _Authentication = settings.CreateLndAuthentication(); BaseUrl = settings.Uri.AbsoluteUri.TrimEnd('/'); _httpClient = CreateHttpClient(settings); _settings = new System.Lazy <Newtonsoft.Json.JsonSerializerSettings>(() => { var json = new Newtonsoft.Json.JsonSerializerSettings(); UpdateJsonSerializerSettings(json); return(json); }); }
protected void Application_Start() { //Override the default json serializer settings var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter; var jSettings = new Newtonsoft.Json.JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Include }; jsonFormatter.SerializerSettings = jSettings; AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
/// <summary> Initialization function for this storage provider. </summary> /// <see cref="IProvider#Init"/> public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config) { serviceId = providerRuntime.ServiceId.ToString(); Log = providerRuntime.GetLogger("StorageProvider.SimpleSQLServerStorage." + serviceId); try { Name = name; this.jsonSettings = SerializationManager.UpdateSerializerSettings(SerializationManager.GetDefaultJsonSerializerSettings(), config); if (!config.Properties.ContainsKey(CONNECTION_STRING) || string.IsNullOrWhiteSpace(config.Properties[CONNECTION_STRING])) { throw new BadProviderConfigException($"Specify a value for: {CONNECTION_STRING}"); } var connectionString = config.Properties[CONNECTION_STRING]; sqlconnBuilder = new SqlConnectionStringBuilder(connectionString); //a validation of the connection would be wise to perform here var sqlCon = new SqlConnection(sqlconnBuilder.ConnectionString); await sqlCon.OpenAsync(); sqlCon.Close(); //initialize to use the default of JSON storage (this is to provide backwards compatiblity with previous version useJsonOrBinaryFormat = StorageFormatEnum.Binary; if (config.Properties.ContainsKey(USE_JSON_FORMAT_PROPERTY)) { if ("true".Equals(config.Properties[USE_JSON_FORMAT_PROPERTY], StringComparison.OrdinalIgnoreCase)) { useJsonOrBinaryFormat = StorageFormatEnum.Json; } if ("both".Equals(config.Properties[USE_JSON_FORMAT_PROPERTY], StringComparison.OrdinalIgnoreCase)) { useJsonOrBinaryFormat = StorageFormatEnum.Both; } } } catch (Exception ex) { Log.Error((int)SimpleSQLServerProviderErrorCodes.SimpleSQLServerProvider_InitProvider, ex.ToString(), ex); throw; } }
/// <summary> /// default constructor /// </summary> public CustomJsonConverter(JsonSerializerSettings settings) { if (settings == null) throw new ArgumentNullException("settings"); JsonSerializerSettings = settings; }