Converts an object to and from JSON.
コード例 #1
0
ファイル: JsonSerializer.cs プロジェクト: frontporch/LiteQ
        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());
        }
コード例 #2
0
 public static void AddConverter(JsonConverter converter)
 {
     if (!Instance.Converters.Contains(converter))
     {
         Instance.Converters.Add(converter);
     }
 }
コード例 #3
0
		public ExactContractJsonConverterAttribute(Type jsonConverter)
		{
			if (typeof(JsonConverter).IsAssignableFrom(jsonConverter))
			{
				Converter = jsonConverter.CreateInstance<JsonConverter>();
			}
		}
コード例 #4
0
ファイル: DataController.cs プロジェクト: izevaka/stacktagz
 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;
 }
コード例 #5
0
 public static void RegisterJsonConverter(JsonConverter converter)
 {
     if (_registeredJsonConverters == null)
     {
         _registeredJsonConverters = new List<JsonConverter>();
     }
     _registeredJsonConverters.Add(converter);
 }
コード例 #6
0
ファイル: Helpers.cs プロジェクト: jeremyVignelles/ooak
 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);
 }
コード例 #7
0
 public TimeSpanConverter()
 {
     this.readConverter = new IsoDateTimeConverter {
         DateTimeStyles = System.Globalization.DateTimeStyles.AssumeLocal
     };
     this.writeConverter = new IsoDateTimeConverter {
         DateTimeFormat = "HH:mm", DateTimeStyles = System.Globalization.DateTimeStyles.AssumeLocal
     };
 }
コード例 #8
0
        public JsonSerialisationSettings()
        {
            Converters = new JsonConverter[]
            {
                new StringEnumConverter(),
            };

            ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
コード例 #9
0
ファイル: BillingService.cs プロジェクト: jasatwal/skybill
        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;
        }
コード例 #10
0
ファイル: MemberMapping.cs プロジェクト: robgreen/nom
 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;
 }
コード例 #11
0
ファイル: JsonParser.cs プロジェクト: zanjs/Wawaji
        /// <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);
        }
コード例 #12
0
 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
     });
 }
コード例 #13
0
ファイル: Helpers.cs プロジェクト: jeremyVignelles/ooak
        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);
        }
コード例 #14
0
        /// <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);
        }
コード例 #15
0
        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);
        }
コード例 #16
0
        /// <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);
        }
コード例 #17
0
 /// <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;
 }
コード例 #18
0
ファイル: JsonSerializer.cs プロジェクト: jabbo/Jabbo
        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;
        }
コード例 #19
0
ファイル: JsonSerializer.cs プロジェクト: jabbo/Jabbo
        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;
        }
コード例 #20
0
		private MultiGetResponse DeserializeMultiGetResponse(IApiCallDetails response, Stream stream, JsonConverter converter) =>
			this.ConnectionSettings.StatefulSerializer(converter).Deserialize<MultiGetResponse>(stream);
コード例 #21
0
			public LocalJsonNetSerializer(IConnectionSettingsValues settings, Action<JsonSerializerSettings, IConnectionSettingsValues> s, JsonConverter converter)
				: base(settings, converter)
			{
				this.OverwriteDefaultSerializers(s);
			}
コード例 #22
0
			public IElasticsearchSerializer CreateStateful(IConnectionSettingsValues settings, JsonConverter converter) =>
				new LocalJsonNetSerializer(settings, this._settingsOverride, converter);
コード例 #23
0
ファイル: JsonSerializer.cs プロジェクト: jabbo/Jabbo
        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);
              }
        }
コード例 #24
0
ファイル: ajaxUTL.cs プロジェクト: tormoz70/Bio.Framework.8
 /// <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;
 }
コード例 #25
0
ファイル: JsonSerializer.cs プロジェクト: mrkurt/mubble-old
        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;
        }
コード例 #26
0
 public TimeSpanConverter()
 {
     this.readConverter = new IsoDateTimeConverter { DateTimeStyles = System.Globalization.DateTimeStyles.AssumeLocal };
     this.writeConverter = new IsoDateTimeConverter { DateTimeFormat = "HH:mm", DateTimeStyles = System.Globalization.DateTimeStyles.AssumeLocal };
 }
コード例 #27
0
        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);
        }
コード例 #28
0
 public virtual String Encode(JsonConverter[] converters) {
   return jsonUtl.encode(this, converters);
 }
コード例 #29
0
        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);
        }
コード例 #30
0
ファイル: JsonSerializer.cs プロジェクト: jabbo/Jabbo
        private bool HasClassConverter(Type objectType, out JsonConverter converter)
        {
            if (objectType == null)
            throw new ArgumentNullException("objectType");

              converter = JsonTypeReflector.GetConverter(objectType, objectType);
              return (converter != null);
        }
コード例 #31
0
ファイル: JsonSerializer.cs プロジェクト: jabbo/Jabbo
 private bool HasMatchingConverter(Type type, out JsonConverter matchingConverter)
 {
     return HasMatchingConverter(_converters, type, out matchingConverter);
 }
コード例 #32
0
 private bool HasMatchingConverter(Type type, out JsonConverter matchingConverter)
 {
     return(HasMatchingConverter(_converters, type, out matchingConverter));
 }
コード例 #33
0
ファイル: Base.cs プロジェクト: mrkurt/mubble-old
 public string GetJsonOutput(object contents, JsonConverter converter)
 {
     JsonResponse resp = new JsonResponse(contents is Exception, contents);
     string output = JavaScriptConvert.SerializeObject(resp, converter);
     return output;
 }
コード例 #34
0
ファイル: Program.cs プロジェクト: rpowers3/TheBlackMarket
        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();
        }
コード例 #35
0
 public static AjaxResponse Decode(String pJsonString, JsonConverter[] converters) {
   return jsonUtl.Decode(pJsonString, null, converters) as AjaxResponse;
 }
コード例 #36
0
 /// <summary>
 /// Handles nulls as default values.
 /// </summary>
 /// <param name="inner"></param>
 public NullHandlingConverter(JsonConverter inner = null)
 {
     this.inner = inner;
 }
コード例 #37
0
		private MultiGetResponse DeserializeMultiGetResponse(IElasticsearchResponse response, Stream stream, JsonConverter converter)
		{
			return this.Serializer.DeserializeInternal<MultiGetResponse>(stream, converter);
		}
コード例 #38
0
 /// <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);
 }