• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# JsonSerializer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: ReadJson

 // Token: 0x06000685 RID: 1669
 // RVA: 0x0003758C File Offset: 0x0003578C
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     if (reader.TokenType == JsonToken.Null)
     {
         if (!ReflectionUtils.IsNullable(objectType))
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Cannot convert null value to {0}.", CultureInfo.InvariantCulture, objectType));
         }
         return null;
     }
     else
     {
         if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token or value when parsing date. Token: {0}, Value: {1}", CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
         }
         reader.Read();
         if (reader.TokenType != JsonToken.Integer)
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token parsing date. Expected Integer, got {0}.", CultureInfo.InvariantCulture, reader.TokenType));
         }
         long javaScriptTicks = (long)reader.Value;
         DateTime dateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(javaScriptTicks);
         reader.Read();
         if (reader.TokenType != JsonToken.EndConstructor)
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token parsing date. Expected EndConstructor, got {0}.", CultureInfo.InvariantCulture, reader.TokenType));
         }
         return dateTime;
     }
 }
开发者ID:newchild,项目名称:Project-DayZero,代码行数:33,代码来源:JavaScriptDateTimeConverter.cs


示例17: 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)
          resolvedEnumName = StringUtils.ToCamelCase(resolvedEnumName);

        writer.WriteValue(resolvedEnumName);
      }
    }
开发者ID:rejemy,项目名称:serverville-client-unity,代码行数:36,代码来源:StringEnumConverter.cs


示例18: 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)
        {
            DataTable table = (DataTable)value;
            DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;

            writer.WriteStartArray();

            foreach (DataRow row in table.Rows)
            {
                writer.WriteStartObject();
                foreach (DataColumn column in row.Table.Columns)
                {
                    object columnValue = row[column];

                    if (serializer.NullValueHandling == NullValueHandling.Ignore && (columnValue == null || columnValue == DBNull.Value))
                    {
                        continue;
                    }

                    writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(column.ColumnName) : column.ColumnName);
                    serializer.Serialize(writer, columnValue);
                }
                writer.WriteEndObject();
            }

            writer.WriteEndArray();
        }
开发者ID:rlugojr,项目名称:Newtonsoft.Json,代码行数:33,代码来源:DataTableConverter.cs


示例19: 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)
    {
      IEntityKeyMember entityKeyMember = DynamicWrapper.CreateWrapper<IEntityKeyMember>(value);
      Type keyType = (entityKeyMember.Value != null) ? entityKeyMember.Value.GetType() : null;

      writer.WriteStartObject();
      writer.WritePropertyName("Key");
      writer.WriteValue(entityKeyMember.Key);
      writer.WritePropertyName("Type");
      writer.WriteValue((keyType != null) ? keyType.FullName : null);

      writer.WritePropertyName("Value");

      if (keyType != null)
      {
        string valueJson;
        if (JsonSerializerInternalWriter.TryConvertToString(entityKeyMember.Value, keyType, out valueJson))
          writer.WriteValue(valueJson);
        else
          writer.WriteValue(entityKeyMember.Value);
      }
      else
      {
        writer.WriteNull();
      }

      writer.WriteEndObject();
    }
开发者ID:Gert-Cominotto,项目名称:MvvmCross,代码行数:34,代码来源:EntityKeyMemberConverter.cs


示例20: ReadJson

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            reader.Read();

            Debug.Assert(reader.TokenType == JsonToken.PropertyName);
            Debug.Assert((string)reader.Value == "coordinates");

            if (objectType == typeof(Coordinate))
            {
                return ReadJsonCoordinate(reader);
            }

            if (typeof(IEnumerable<Coordinate>).IsAssignableFrom(objectType))
            {
                return ReadJsonCoordinates(reader);
            }

            if (typeof(List<Coordinate[]>).IsAssignableFrom(objectType))
            {
                return ReadJsonCoordinatesEnumerable(reader);
            }
            if (typeof(List<List<Coordinate[]>>).IsAssignableFrom(objectType))
            {
                return ReadJsonCoordinatesEnumerable2(reader);
            }

            throw new Exception();
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:28,代码来源:CoordinateConverters.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# JsonSerializerSettings类代码示例发布时间:2022-05-24
下一篇:
C# JsonSchemaType类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap