当前位置: 首页>>代码示例>>C#>>正文


C# JsonSerializer类代码示例

本文整理汇总了C#中JsonSerializer的典型用法代码示例。如果您正苦于以下问题:C# JsonSerializer类的具体用法?C# JsonSerializer怎么用?C# JsonSerializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


JsonSerializer类属于命名空间,在下文中一共展示了JsonSerializer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ReadJson

        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DataTable dt = existingValue as DataTable;

            if (dt == null)
            {
                // handle typed datasets
                dt = (objectType == typeof(DataTable))
                    ? new DataTable()
                    : (DataTable)Activator.CreateInstance(objectType);
            }

            if (reader.TokenType == JsonToken.PropertyName)
            {
                dt.TableName = (string)reader.Value;

                CheckedRead(reader);
            }

            if (reader.TokenType != JsonToken.StartArray)
                throw JsonSerializationException.Create(reader, "Unexpected JSON token when reading DataTable. Expected StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));

            CheckedRead(reader);

            while (reader.TokenType != JsonToken.EndArray)
            {
                CreateRow(reader, dt);

                CheckedRead(reader);
            }

            return dt;
        }
开发者ID:jrwren,项目名称:yahoofinance,代码行数:41,代码来源:DataTableConverter.cs

示例2: ReadJson

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            NameContainer nameContainer = new NameContainer();
            nameContainer.Value = (string)reader.Value;

            return nameContainer;
        }
开发者ID:JamesNK,项目名称:Newtonsoft.Json,代码行数:7,代码来源:NameContainerConverter.cs

示例3: ReadJson

        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DataTable dt = existingValue as DataTable;

            if (dt == null)
            {
                // handle typed datasets
                dt = (objectType == typeof(DataTable))
                    ? new DataTable()
                    : (DataTable)Activator.CreateInstance(objectType);
            }

            if (reader.TokenType == JsonToken.PropertyName)
            {
                dt.TableName = (string)reader.Value;

                reader.Read();
            }

            if (reader.TokenType == JsonToken.StartArray)
                reader.Read();

            while (reader.TokenType != JsonToken.EndArray)
            {
                CreateRow(reader, dt);

                reader.Read();
            }

            return dt;
        }
开发者ID:rucksemail2,项目名称:Newtonsoft.Json,代码行数:39,代码来源:DataTableConverter.cs

示例4: WriteJson

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WritePropertyName("coordinates");

            List<List<Coordinate[]>> coordinatesss = value as List<List<Coordinate[]>>;
            if (coordinatesss != null)
            {
                WriteJsonCoordinatesEnumerable2(writer, coordinatesss, serializer);
                return;
            }

            List<Coordinate[]> coordinatess = value as List<Coordinate[]>;
            if (coordinatess != null)
            {
                WriteJsonCoordinatesEnumerable(writer, coordinatess, serializer);
                return;
            }

            IEnumerable<Coordinate> coordinates = value as IEnumerable<Coordinate>;
            if (coordinates != null)
            {
                WriteJsonCoordinates(writer, coordinates, serializer);
                return;
            }

            Coordinate coordinate = value as Coordinate;
            if (coordinate != null)
            {
                WriteJsonCoordinate(writer, coordinate, serializer);
                return;
            }
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:32,代码来源:CoordinateConverters.cs

示例5: ReadJson

 /// <summary>
 /// Reads the JSON representation of the object.
 /// </summary>
 /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
 /// <param name="objectType">Type of the object.</param>
 /// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
 /// <param name="serializer">The calling serializer.</param>
 /// <returns>The object value.</returns>
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     if (reader.TokenType == JsonToken.Null)
     {
         return null;
     }
     else
     {
         if (reader.TokenType == JsonToken.String)
         {
             try
             {
                 Version v = new Version((string)reader.Value);
                 return v;
             }
             catch (Exception ex)
             {
                 throw JsonSerializationException.Create(reader, "Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex);
             }
         }
         else
         {
             throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
         }
     }
 }
开发者ID:extesla,项目名称:OpenGamingLibrary,代码行数:34,代码来源:VersionConverter.cs

示例6: WriteJson

        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            Enum e = (Enum)value;

            string enumName = e.ToString("G");

            if (char.IsNumber(enumName[0]) || enumName[0] == '-')
            {
                // enum value has no name so write number
                writer.WriteValue(value);
            }
            else
            {
                Type enumType = e.GetType();

                string finalName = EnumUtils.ToEnumName(enumType, enumName, CamelCaseText);

                writer.WriteValue(finalName);
            }
        }
开发者ID:b-bot-110,项目名称:Newtonsoft.Json,代码行数:32,代码来源:StringEnumConverter.cs

示例7: WriteJson

    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      if (value == null)
      {
        writer.WriteNull();
        return;
      }

      Enum e = (Enum)value;

      string enumName = e.ToString("G");

      if (char.IsNumber(enumName[0]) || enumName[0] == '-')
      {
        writer.WriteValue(value);
      }
      else
      {
        BidirectionalDictionary<string, string> map = GetEnumNameMap(e.GetType());

        string resolvedEnumName;
        map.TryGetByFirst(enumName, out resolvedEnumName);
        resolvedEnumName = resolvedEnumName ?? enumName;

        if (CamelCaseText)
        {
          string[] names = resolvedEnumName.Split(',').Select(item => StringUtils.ToCamelCase(item.Trim())).ToArray();
          resolvedEnumName = string.Join(", ", names);
        }

        writer.WriteValue(resolvedEnumName);
      }
    }
开发者ID:GotenXiao,项目名称:blink1,代码行数:39,代码来源:StringEnumConverter.cs

示例8: ReadJson

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			// NOTE: THIS DOESN'T SUPPORT READING OF DynamicJsonObject !!!

			var o = RavenJToken.Load(reader);
			return (o.Type == JTokenType.Null || o.Type == JTokenType.Undefined) ? null : o;
		}
开发者ID:WimVergouwe,项目名称:ravendb,代码行数:7,代码来源:JsonToJsonConverter.cs

示例9: testJsonDeserializingAnalyticServiceStatus

        public void testJsonDeserializingAnalyticServiceStatus()
        {
            String source =
                    "{" +
                        "\"service_status\":\"online\"," +
                        "\"api_version\":\"2.0\"," +
                        "\"service_version\":\"1.0.2.63\"," +
                        "\"supported_encoding\":\"UTF-8\"," +
                        "\"supported_compression\":\"gzip\"," +
                        "\"supported_languages\":[" +
                                "\"English\"," +
                                "\"French\"" +
                        "]" +
                    "}";

            ISerializer serializer = new JsonSerializer();
            Status status = serializer.Deserialize<Status>(source);
            Assert.AreEqual("online", status.Service);
            Assert.AreEqual("2.0", status.ApiVersion);
            Assert.AreEqual("1.0.2.63", status.ServiceVersion);
            Assert.AreEqual("UTF-8", status.SupportedEncoding);
            Assert.AreEqual("gzip", status.SupportedCompression);
            Assert.AreEqual(2, status.SupportedLanguages.Count);
            Assert.AreEqual("English", status.SupportedLanguages[0]);
            Assert.AreEqual("French", status.SupportedLanguages[1]);
        }
开发者ID:Serotonin7,项目名称:semantria-sdk,代码行数:26,代码来源:SerializerTest.cs

示例10: ReadJson

            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                User user = new User();
                user.UserName = (string)reader.Value;

                return user;
            }
开发者ID:GorelH,项目名称:ravendb,代码行数:7,代码来源:JsonConverterAttributeClass.cs

示例11: WriteJson

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if(value == null)
            {
                writer.WriteNull();
                return;
            }

            if ((value as UniquenessType?).HasValue)
                writer.WriteValue(enumToStrings[typeof(UniquenessType?)](value));

            else if ((value as TraversalStrategy?).HasValue)
                writer.WriteValue(enumToStrings[typeof(TraversalStrategy?)](value));

            else if ((value as TraversalOrder?).HasValue)
                writer.WriteValue(enumToStrings[typeof(TraversalOrder?)](value));

            else if ((value as TraversalItemOrder?).HasValue)
                writer.WriteValue(enumToStrings[typeof(TraversalItemOrder?)](value));

            else if ((value as EdgeDirection?).HasValue)
                writer.WriteValue(enumToStrings[typeof(EdgeDirection?)](value));

            else
                throw new InvalidOperationException($"cant find binding to serialize type {value.GetType()}, this is client bug");
        }
开发者ID:GOArango,项目名称:arangoclient.net,代码行数:26,代码来源:EnumValueConverter.cs

示例12: WriteJson

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var converter = GetConverter(value.GetType());
            var text = converter.ConvertToInvariantString(value);

            writer.WriteValue(text);
        }
开发者ID:JamesNK,项目名称:Newtonsoft.Json,代码行数:7,代码来源:TypeConverterJsonConverter.cs

示例13: JsonSerializerProxy

        public JsonSerializerProxy(JsonSerializerWriter serializerWriter)
        {
            ValidationUtils.ArgumentNotNull(serializerWriter, "serializerWriter");

              _serializerWriter = serializerWriter;
              _serializer = serializerWriter._serializer;
        }
开发者ID:BGCX262,项目名称:zulu-omoto-pos-client-svn-to-git,代码行数:7,代码来源:JsonSerializerProxy.cs

示例14: WriteJson

    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
      //long ticks;

      /*if (value is DateTime) {
        DateTime dateTime = (DateTime)value;
        DateTime utcDateTime = dateTime.ToUniversalTime();
        ticks = JsonConvert.ConvertDateTimeToJavaScriptTicks(utcDateTime);
      } else if (value is DateTimeOffset) {
        DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
        DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime();
        ticks = JsonConvert.ConvertDateTimeToJavaScriptTicks(utcDateTimeOffset.UtcDateTime);
      } else {
        throw new Exception("Expected date object value.");
      }*/

      //writer.WriteStartConstructor("Date");
      //writer.WriteValue(ticks);
      //writer.WriteEndConstructor();
      if (value is DateTime) {
        DateTime dateTime = (DateTime)value;
        DateTime vLocValue = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
        writer.WriteValue(vLocValue);
      } else {
        throw new Exception("Expected date object value.");
      }
    }
开发者ID:tormoz70,项目名称:Bio.Framework.8,代码行数:32,代码来源:LocDateTimeConverter.cs

示例15: MapReduceIndex

 public MapReduceIndex(Directory directory, int id, IndexDefinition indexDefinition,
                       AbstractViewGenerator viewGenerator, WorkContext context)
     : base(directory, id, indexDefinition, viewGenerator, context)
 {
     jsonSerializer = JsonExtensions.CreateDefaultJsonSerializer();
     jsonSerializer.Converters = MapReduceConverters;
 }
开发者ID:VPashkov,项目名称:ravendb,代码行数:7,代码来源:MapReduceIndex.cs


注:本文中的JsonSerializer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。