public JsonSerializer(JsonConverter[] converters) { _Converters = converters; _Serializer = new Newtonsoft.Json.JsonSerializer(); _Deserializer = new Newtonsoft.Json.JsonSerializer(); _Serializer.NullValueHandling = NullValueHandling.Include; _Deserializer.NullValueHandling = NullValueHandling.Include; if (_Converters != null) { foreach (var converter in _Converters) { _Serializer.Converters.Add(converter); _Deserializer.Converters.Add(converter); } } // Only give out strict ISO-8601 _Serializer.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "o" }); _Serializer.Converters.Add(new UriConverter()); // Parse just about anything for input _Deserializer.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AdjustToUniversal }); // custom handling ip address keys :( _Deserializer.Converters.Add(new DictionaryIPAddressKeyConverter()); }
public static void AddConverter(JsonConverter converter) { if (!Instance.Converters.Contains(converter)) { Instance.Converters.Add(converter); } }
public ExactContractJsonConverterAttribute(Type jsonConverter) { if (typeof(JsonConverter).IsAssignableFrom(jsonConverter)) { Converter = jsonConverter.CreateInstance<JsonConverter>(); } }
public DataController(JsonConverter[] converters, ISummarizer repository, ISitesRepository sitesRepository, IErrorController errorController, IUsersRepository userRepository) : base(errorController) { m_Converters = converters; m_TimeSeriesRepository = repository; m_SiteRepository = sitesRepository; m_userRepository = userRepository; }
public static void RegisterJsonConverter(JsonConverter converter) { if (_registeredJsonConverters == null) { _registeredJsonConverters = new List<JsonConverter>(); } _registeredJsonConverters.Add(converter); }
public static void TestSuccess <TDeserialized>( string input, TDeserialized expected, System.Text.Json.Serialization.JsonConverter systemTextJsonSerializer, Newtonsoft.Json.JsonConverter newtonsoftJsonConverter) { TestSuccess <TDeserialized>(input, expected, expected, systemTextJsonSerializer, newtonsoftJsonConverter); }
public TimeSpanConverter() { this.readConverter = new IsoDateTimeConverter { DateTimeStyles = System.Globalization.DateTimeStyles.AssumeLocal }; this.writeConverter = new IsoDateTimeConverter { DateTimeFormat = "HH:mm", DateTimeStyles = System.Globalization.DateTimeStyles.AssumeLocal }; }
public JsonSerialisationSettings() { Converters = new JsonConverter[] { new StringEnumConverter(), }; ContractResolver = new CamelCasePropertyNamesContractResolver(); }
public BillingService(IHttpClient client, JsonConverter[] converters, string endpoint) { Check.Argument.IsNotNull(client, nameof(client)); Check.Argument.IsNotNull(converters, nameof(converters)); Check.Argument.IsNotNullOrWhiteSpace(endpoint, nameof(endpoint)); this.client = client; this.converters = converters; this.endpoint = endpoint; }
public MemberMapping(string mappingName, MemberInfo member, bool ignored, bool readable, bool writable, JsonConverter memberConverter, object defaultValue) { _mappingName = mappingName; _member = member; _ignored = ignored; _readable = readable; _writable = writable; _memberConverter = memberConverter; _defaultValue = defaultValue; }
/// <summary> /// 反序列化对象; /// </summary> /// <param name="json"></param> /// <returns></returns> public static object Deserialize(string json) { if (string.IsNullOrEmpty(json)) { throw new ArgumentException("JSON string can not be null or empty", "json"); } var converters = new Newtonsoft.Json.JsonConverter[] { new JsonKeyValuePairConverter(), new JExtConverter() }; var v = JsonConvert.DeserializeObject <object>(json, converters); return(v); }
public static string ToJson4Collection(dynamic obj) { var jsonconverters = new JsonConverter[] { new RawPointConverter() }; return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = jsonconverters, Formatting = Formatting.None }); }
public static void TestSuccess <TDeserialized>( string input, TDeserialized systemTextJsonExpected, TDeserialized newtonsoftJsonExpected, System.Text.Json.Serialization.JsonConverter systemTextJsonSerializer, Newtonsoft.Json.JsonConverter newtonsoftJsonConverter) { var deserialized = DeserializeSystemTextJson <TDeserialized>(input, systemTextJsonSerializer); Console.WriteLine("Checking System.Text.Json deserialized value"); Assert.AreEqual(systemTextJsonExpected, deserialized); var deserializedNewtonsoft = DeserializeNewtonsoftJson <TDeserialized>(input, newtonsoftJsonConverter); Console.WriteLine("Checking Newtonsoft.Json deserialized value"); Assert.AreEqual(newtonsoftJsonExpected, deserializedNewtonsoft); }
/// <summary> /// Initializes default serializer settings. There is no need to call this manually /// as it is already initialized in the static constructor. /// </summary> public static void InitializeDefault() { Converters = new JsonConverter[] { DateTimeConverter = new ReqlDateTimeConverter(), BinaryConverter = new ReqlBinaryConverter(), GroupingConverter = new ReqlGroupingConverter(), PocoExprConverter = new PocoExprConverter(), }; var settings = new JsonSerializerSettings() { Converters = Converters }; Serializer = JsonSerializer.CreateDefault(settings); }
public async Task Find_JsonBillWithoutCallCharges_ShouldReturnBillWithNullCallChargesAndNotNullSkyStore() { // Arrange var client = new Mock<IHttpClient>(); client.Setup(x => x.GetString(It.IsAny<string>())).Returns(Task.FromResult(SampleData.BillWithoutCallCharges())); var converters = new JsonConverter[] { new MoneyJsonConverter(), new SkyStoreMovieJsonConverter(), new TelephoneNumberJsonConverter() }; var service = new BillingService(client.Object, converters, "http://some-end-point"); var accountNumber = new CustomerAccountNumber("1234567890"); // Act var bill = await service.Find(accountNumber); // Assert Assert.IsNotNull(bill); Assert.IsNull(bill.CallCharges); Assert.IsNotNull(bill.SkyStore); }
/// <summary>Converts the description object to JSON.</summary> /// <returns>The JSON string.</returns> public string ToJson(JsonConverter converter = null) { var settings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.None, Formatting = Formatting.Indented }; if (converter != null) { settings.Converters.Add(converter); } GenerateOperationIds(); JsonSchemaReferenceUtilities.UpdateSchemaReferencePaths(this); JsonSchemaReferenceUtilities.UpdateSchemaReferences(this); var data = JsonConvert.SerializeObject(this, settings); return JsonSchemaReferenceUtilities.ConvertPropertyReferences(data); }
/// <summary> /// Gets a JsonSerializer without specified converter. /// </summary> /// <param name="serializer">JsonSerializer</param> /// <param name="converterToExclude">Converter to exclude from serializer.</param> /// <returns></returns> public static JsonSerializer WithoutConverter(this JsonSerializer serializer, JsonConverter converterToExclude) { if (serializer == null) { throw new ArgumentNullException("serializer"); } JsonSerializer newSerializer = new JsonSerializer(); var properties = typeof(JsonSerializer).GetTypeInfo().DeclaredProperties; foreach (var property in properties.Where(p => p.SetMethod != null && !p.SetMethod.IsPrivate)) { property.SetValue(newSerializer, property.GetValue(serializer, null), null); } foreach (var converter in serializer.Converters) { if (converter != converterToExclude) { newSerializer.Converters.Add(converter); } } return newSerializer; }
private object CreateObject(JsonReader reader, Type objectType, object existingValue, JsonConverter memberConverter) { _level++; object value; JsonConverter converter; if (memberConverter != null) { return memberConverter.ReadJson(reader, objectType); } else if (objectType != null && HasClassConverter(objectType, out converter)) { return converter.ReadJson(reader, objectType); } else if (objectType != null && HasMatchingConverter(objectType, out converter)) { return converter.ReadJson(reader, objectType); } else if (objectType == typeof(JsonRaw)) { return JsonRaw.Create(reader); } else { switch (reader.TokenType) { // populate a typed object or generic dictionary/array // depending upon whether an objectType was supplied case JsonToken.StartObject: if (objectType == null) { value = CreateJToken(reader); } else if (CollectionUtils.IsDictionaryType(objectType)) { if (existingValue == null) value = CreateAndPopulateDictionary(reader, objectType); else value = PopulateDictionary(CollectionUtils.CreateDictionaryWrapper(existingValue), reader); } else { if (existingValue == null) value = CreateAndPopulateObject(reader, objectType); else value = PopulateObject(existingValue, reader, objectType); } break; case JsonToken.StartArray: if (objectType != null) { if (existingValue == null) value = CreateAndPopulateList(reader, objectType); else value = PopulateList(CollectionUtils.CreateCollectionWrapper(existingValue), ReflectionUtils.GetCollectionItemType(objectType), reader); } else { value = CreateJToken(reader); } break; case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Date: value = EnsureType(reader.Value, objectType); break; case JsonToken.StartConstructor: case JsonToken.EndConstructor: string constructorName = reader.Value.ToString(); value = constructorName; break; case JsonToken.Null: case JsonToken.Undefined: if (objectType == typeof(DBNull)) value = DBNull.Value; else value = null; break; default: throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType); } } _level--; return value; }
internal static bool HasMatchingConverter(IList<JsonConverter> converters, Type objectType, out JsonConverter matchingConverter) { if (objectType == null) throw new ArgumentNullException("objectType"); if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter converter = converters[i]; if (converter.CanConvert(objectType)) { matchingConverter = converter; return true; } } } matchingConverter = null; return false; }
private MultiGetResponse DeserializeMultiGetResponse(IApiCallDetails response, Stream stream, JsonConverter converter) => this.ConnectionSettings.StatefulSerializer(converter).Deserialize<MultiGetResponse>(stream);
public LocalJsonNetSerializer(IConnectionSettingsValues settings, Action<JsonSerializerSettings, IConnectionSettingsValues> s, JsonConverter converter) : base(settings, converter) { this.OverwriteDefaultSerializers(s); }
public IElasticsearchSerializer CreateStateful(IConnectionSettingsValues settings, JsonConverter converter) => new LocalJsonNetSerializer(settings, this._settingsOverride, converter);
private void SerializeValue(JsonWriter writer, object value, JsonConverter memberConverter) { JsonConverter converter; if (value == null) { writer.WriteNull(); } else if (memberConverter != null) { memberConverter.WriteJson(writer, value); } else if (HasClassConverter(value.GetType(), out converter)) { converter.WriteJson(writer, value); } else if (HasMatchingConverter(value.GetType(), out converter)) { converter.WriteJson(writer, value); } else if (JsonConvert.IsJsonPrimitive(value)) { writer.WriteValue(value); } else if (value is IList) { SerializeList(writer, (IList)value); } else if (value is IDictionary) { SerializeDictionary(writer, (IDictionary)value); } else if (value is ICollection) { SerializeCollection(writer, (ICollection)value); } else if (value is IEnumerable) { SerializeEnumerable(writer, (IEnumerable)value); } else if (value is JsonRaw) { writer.WriteRawValue(((JsonRaw)value).Content); } else { SerializeObject(writer, value); } }
/// <summary> /// Строит строку запроса URL /// </summary> /// <param name="requestException"></param> /// <param name="responseText"></param> /// <param name="converters"></param> /// <returns></returns> public static AjaxResponse CreResponseObject(EBioException requestException, String responseText, JsonConverter[] converters) { AjaxResponse response; if (requestException == null) { try { response = AjaxResponse.Decode(responseText, converters); response.ResponseText = responseText; } catch (Exception e) { response = new AjaxResponse { Ex = new EBioException("Ошибка при восстановлении объекта Response. Сообщение: " + e.Message + "\nResponseText: " + responseText, e), ResponseText = responseText, Success = false }; } } else { response = new AjaxResponse { Ex = requestException, ResponseText = responseText, //request = pRequest, Success = false }; } return response; }
private bool HasMatchingConverter(Type type, out JsonConverter matchingConverter) { if (_converters != null) { for (int i = 0; i < _converters.Count; i++) { JsonConverter converter = _converters[i]; if (converter.CanConvert(type)) { matchingConverter = converter; return true; } } } matchingConverter = null; return false; }
private object CreateObject(JsonReader reader, Type objectType, object existingValue, JsonConverter memberConverter) { _level++; object value; JsonConverter converter; if (memberConverter != null) { return(memberConverter.ReadJson(reader, objectType)); } else if (objectType != null && HasClassConverter(objectType, out converter)) { return(converter.ReadJson(reader, objectType)); } else if (objectType != null && HasMatchingConverter(objectType, out converter)) { return(converter.ReadJson(reader, objectType)); } else if (objectType == typeof(JsonRaw)) { return(JsonRaw.Create(reader)); } else { switch (reader.TokenType) { // populate a typed object or generic dictionary/array // depending upon whether an objectType was supplied case JsonToken.StartObject: if (objectType == null) { value = CreateJToken(reader); } else if (CollectionUtils.IsDictionaryType(objectType)) { if (existingValue == null) { value = CreateAndPopulateDictionary(reader, objectType); } else { value = PopulateDictionary(CollectionUtils.CreateDictionaryWrapper(existingValue), reader); } } else { if (existingValue == null) { value = CreateAndPopulateObject(reader, objectType); } else { value = PopulateObject(existingValue, reader, objectType); } } break; case JsonToken.StartArray: if (objectType != null) { if (existingValue == null) { value = CreateAndPopulateList(reader, objectType); } else { value = PopulateList(CollectionUtils.CreateCollectionWrapper(existingValue), ReflectionUtils.GetCollectionItemType(objectType), reader); } } else { value = CreateJToken(reader); } break; case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Date: value = EnsureType(reader.Value, objectType); break; case JsonToken.StartConstructor: case JsonToken.EndConstructor: string constructorName = reader.Value.ToString(); value = constructorName; break; case JsonToken.Null: case JsonToken.Undefined: if (objectType == typeof(DBNull)) { value = DBNull.Value; } else { value = null; } break; default: throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType); } } _level--; return(value); }
public virtual String Encode(JsonConverter[] converters) { return jsonUtl.encode(this, converters); }
internal static bool HasMatchingConverter(IList <JsonConverter> converters, Type objectType, out JsonConverter matchingConverter) { if (objectType == null) { throw new ArgumentNullException("objectType"); } if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter converter = converters[i]; if (converter.CanConvert(objectType)) { matchingConverter = converter; return(true); } } } matchingConverter = null; return(false); }
private bool HasClassConverter(Type objectType, out JsonConverter converter) { if (objectType == null) throw new ArgumentNullException("objectType"); converter = JsonTypeReflector.GetConverter(objectType, objectType); return (converter != null); }
private bool HasMatchingConverter(Type type, out JsonConverter matchingConverter) { return HasMatchingConverter(_converters, type, out matchingConverter); }
private bool HasMatchingConverter(Type type, out JsonConverter matchingConverter) { return(HasMatchingConverter(_converters, type, out matchingConverter)); }
public string GetJsonOutput(object contents, JsonConverter converter) { JsonResponse resp = new JsonResponse(contents is Exception, contents); string output = JavaScriptConvert.SerializeObject(resp, converter); return output; }
public void Batch(string[] args) { var parserResults = Parser.Default.ParseArguments<Options>(args); if (parserResults.Tag == ParserResultType.NotParsed) { Console.WriteLine( new HelpText { AddDashesToOption = true } .AddPreOptionsLine("MongoExtract") .AddPreOptionsLine("") .AddOptions(parserResults).ToString()); return; } var options = (parserResults as Parsed<Options>).Value; var idAccessors = options.IdPaths.Select(idPath => BuildIdAccesor(idPath)).ToList(); var hasOutputDirectory = !string.IsNullOrWhiteSpace(options.OutputDirectory); try { if (hasOutputDirectory && !Directory.Exists(options.OutputDirectory)) { Directory.CreateDirectory(options.OutputDirectory); } var mongoClient = new MongoClient(); var database = mongoClient.GetDatabase(options.Database); var collection = database.GetCollection<BsonDocument>(options.Collection); var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; var jsonConverters = new JsonConverter[] { new FloatConverter() { Precission = options.Precission } }; Console.WriteLine("Exporting collection {0}.{1}\n", options.Database, options.Collection); var documents = collection.Find(_ => true).ToListAsync().GetAwaiter().GetResult(); foreach (var document in documents) { var jsonString = document.ToJson(jsonWriterSettings); var json = JToken.Parse(jsonString); var ids = idAccessors.Select(ida => ida(json)).ToArray(); if (options.StripId) { var nodeToRemove = json.Children().OfType<JProperty>().Where(p => p.Name.Equals("_id")).FirstOrDefault(); if (nodeToRemove != null) { nodeToRemove.Remove(); } } jsonString = json.ToString(Formatting.None, jsonConverters); if (hasOutputDirectory) { var fileName = string.Format(options.IdFormat, ids); var outputPath = Path.Combine(options.OutputDirectory, fileName) + ".json"; File.WriteAllText(outputPath, jsonString); Console.WriteLine(" Exported {0}", fileName); } else { Console.WriteLine(jsonString); } } } catch (Exception e) { Console.Error.WriteLine("Failed to export collection \"{0}\" from database \"{1}\":\n\n{2}\n\n", options.Collection, options.Database, e); } Console.WriteLine(); }
public static AjaxResponse Decode(String pJsonString, JsonConverter[] converters) { return jsonUtl.Decode(pJsonString, null, converters) as AjaxResponse; }
/// <summary> /// Handles nulls as default values. /// </summary> /// <param name="inner"></param> public NullHandlingConverter(JsonConverter inner = null) { this.inner = inner; }
private MultiGetResponse DeserializeMultiGetResponse(IElasticsearchResponse response, Stream stream, JsonConverter converter) { return this.Serializer.DeserializeInternal<MultiGetResponse>(stream, converter); }
/// <summary> /// Register a custom converter. The converter specifies the type of object /// that is supports, as well as serialize and deserialize implementations. /// Once registered, ExoWeb becomes able to serialize and/or deserialize objects /// of the supported type. Also, the converter is automatically aware of other /// converters that have been registered for derived types and defers to them. /// </summary> /// <param name="converter"></param> public static void RegisterConverter(Newtonsoft.Json.JsonConverter converter, Type type) { serializer.Converters.Add(converter); serializableTypes.Add(type); }