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


C# Json.JsonSerializer类代码示例

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


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

示例1: ReadJson

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken value = null;
            var response = new FindConnectedObjectsResponse();
            // status
            var json = JObject.ReadFrom(reader) as JObject;
            json.TryGetValue("status", out value);
            response.Status = serializer.Deserialize<Status>(value.CreateReader());
            if (response.Status.IsSuccessful == false)
                return response;
            json.Remove("status");

            // paging info
            // Extract paging info
            json.TryGetValue("paginginfo", out value);
            response.PagingInfo = serializer.Deserialize<PagingInfo>(value.CreateReader());
            json.Remove("paginginfo");

            // extract parent label
            json.TryGetValue("parent", out value);
            var parentLabel = value.ToString();

            // Extract graph node.
            json.TryGetValue("nodes", out value);
            if (value.Type != JTokenType.Null)
            {
                var nodes = value.Values<JObject>();
                ParseNodes(response, parentLabel, nodes, serializer);
            }
            else
                response.Nodes = new List<GraphNode>();
            return response;
        }
开发者ID:ytokas,项目名称:appacitive-dotnet-sdk,代码行数:33,代码来源:FindConnectedObjectsResponseConverter.cs

示例2: WriteJson

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var representation = value as Representation;
            if (representation != null)
                representation.RepopulateHyperMedia();

            var list = (IRepresentationList)value;

            writer.WriteStartObject();
            writer.WritePropertyName("_links");
            serializer.Serialize(writer, list.Links);

            writer.WritePropertyName("_embedded");
            writer.WriteStartObject();
            writer.WritePropertyName(list.Rel);
            writer.WriteStartArray();
            foreach (Representation halResource in list)
            {
                serializer.Serialize(writer, halResource);
            }

            writer.WriteEndArray();
            writer.WriteEndObject();

            var listType = list.GetType();
            var propertyInfos = typeof(RepresentationList<>).GetProperties().Select(p => p.Name);
            foreach (var property in listType.GetProperties().Where(p => !propertyInfos.Contains(p.Name)))
            {
                writer.WritePropertyName(property.Name.ToLower());
                serializer.Serialize(writer, property.GetValue(value, null));
            }

            writer.WriteEndObject();
        }
开发者ID:JoryUK,项目名称:WebApi.Hal,代码行数:34,代码来源:ResourceListConverter.cs

示例3: GetTypeFromJObject

		private IElasticCoreType GetTypeFromJObject(JObject po, JsonSerializer serializer)
		{
			JToken typeToken;
			serializer.TypeNameHandling = TypeNameHandling.None;
			if (po.TryGetValue("type", out typeToken))
			{
				var type = typeToken.Value<string>().ToLowerInvariant();
				switch (type)
				{
					case "string":
						return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping;
					case "float":
					case "double":
					case "byte":
					case "short":
					case "integer":
					case "long":
						return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping;
					case "date":
						return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping;
					case "boolean":
						return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping;
					case "binary":
						return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping;
				}
			}
			return null;
		}
开发者ID:BiYiTuan,项目名称:elasticsearch-net,代码行数:28,代码来源:ElasticCoreTypeConverter.cs

示例4: WriteJson

        /// <summary>
        ///     Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="T:Newtonsoft.Json.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)
        {
            var coordinateElements = value as List<LineString>;
            if (coordinateElements != null && coordinateElements.Count > 0)
            {
                if (coordinateElements[0].Coordinates[0] != null)
                {
                    writer.WriteStartArray();

                    foreach (var subPolygon in coordinateElements)
                    {
                        LineStringConverter.WriteJson(writer, subPolygon.Coordinates, serializer);
                    }

                    writer.WriteEndArray();
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            else
            {
                serializer.Serialize(writer, value);
            }
        }
开发者ID:llambanna,项目名称:GeoJSON.Net,代码行数:32,代码来源:PolygonConverter.cs

示例5: ReadJsonWithInnerObjectTest

        public void ReadJsonWithInnerObjectTest()
        {
            const string json = "{\"properties\":{\"test1\":\"value1\",\"test2\": { \"innertest1\":\"innervalue1\" }}}";
            AttributesTableConverter target = new AttributesTableConverter();
            using (JsonTextReader reader = new JsonTextReader(new StringReader(json)))
            {
                JsonSerializer serializer = new JsonSerializer();

                // read start object token and prepare the next token
                reader.Read();
                reader.Read();
                AttributesTable result =
                    (AttributesTable)
                    target.ReadJson(reader, typeof(AttributesTable), new AttributesTable(), serializer);
                Assert.IsFalse(reader.Read()); // read the end of object and ensure there are no more tokens available
                Assert.IsNotNull(result);
                Assert.AreEqual(2, result.Count);
                Assert.AreEqual("value1", result["test1"]);
                Assert.IsNotNull(result["test2"]);
                Assert.IsInstanceOf<IAttributesTable>(result["test2"]);
                IAttributesTable inner = (IAttributesTable)result["test2"];
                Assert.AreEqual(1, inner.Count);
                Assert.AreEqual("innervalue1", inner["innertest1"]);
            }
        }
开发者ID:ste10k41,项目名称:nettopologysuite,代码行数:25,代码来源:AttributesTableConverterTest.cs

示例6: ReadJson

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var relations = new Relations();
            
            var jToken = JToken.ReadFrom(reader);
            foreach (JProperty jProperty in jToken.Where(_ => _.GetType() == typeof(JProperty)).Cast<JProperty>())
            {
                if (jProperty.Value.GetType() == typeof (JArray))
                {
                    var links = serializer.Deserialize<Link[]>(jProperty.Value.CreateReader());
                    foreach (var link in links)
                    {
                        relations.Add(link);
                        link.Rel = jProperty.Name;
                    }
                }
                else
                {
                    var link = serializer.Deserialize<Link>(jProperty.Value.CreateReader());
                    link.Rel = jProperty.Name;
                    relations.Add(link);
                }
            }

            return relations;
        }
开发者ID:olohmann,项目名称:Lohmann.HALight,代码行数:26,代码来源:RelationsConverter.cs

示例7: ReadJson

        //TODO: This method can be removed if we used DateTimeOffsets instead
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                object o = base.ReadJson(reader, objectType, existingValue, serializer);

                //This is required because DateTime is really bad at parsing RFC1123 dates in C#.  Basically it parses the value but 
                //doesn't attach a DateTimeKind to it (even though RFC1123 specification says that the "Kind" should be UTC.  This results
                //in a DateTime WITHOUT a DateTimeKind specifier, which is bad bad bad.  We do the below in order to force the DateTimeKind
                //of the resulting DateTime to be DateTimeKind.Utc since that is what the RFC1123 specification implies.
                //See: http://stackoverflow.com/questions/1201378/how-does-datetime-touniversaltime-work
                //See: http://stackoverflow.com/questions/16442484/datetime-unspecified-kind
                DateTime? time = o as DateTime?;

                if (time.HasValue && time.Value.Kind == DateTimeKind.Unspecified)
                {
                    time = DateTime.SpecifyKind(time.Value, DateTimeKind.Utc);
                }

                return time;
            }
            catch (FormatException ex)
            {
                throw new JsonException("Unable to deserialize a Date.", ex);
            }
        }
开发者ID:Ranjana1996,项目名称:autorest,代码行数:27,代码来源:DateTimeRfc1123JsonConverter.cs

示例8: ReadJson

 /// <summary>
 ///     Reads the JSON representation of the object.
 /// </summary>
 /// <param name="reader">The <see cref="T:Newtonsoft.Json.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) {
     var result = new ItemOrders();
     serializer.Converters.Add(new EmdRowCollectionJsonConverter<ItemOrders.ItemOrderEntry>());
     result.Orders = serializer.Deserialize<EmdRowCollection<ItemOrders.ItemOrderEntry>>(reader);
     return result;
 }
开发者ID:dinomight,项目名称:evelib,代码行数:15,代码来源:EmdItemOrdersJsonConverter.cs

示例9: ReadJson

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var reference = SupportedTypes[objectType].Invoke();
            serializer.Populate(reader, reference);

            return reference;
        }
开发者ID:skipme,项目名称:simple-mongodb,代码行数:7,代码来源:SimoReferenceJsonConverter.cs

示例10: 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">Serializer</param>
        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, JsonSerializer serializer)
        {
            string text;

            if (value is DateTime || value is DateTime?)
            {
                DateTime dateTime = value is DateTime ? (DateTime)value : (value as DateTime?).Value;

                if ((dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                  || (dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
                {
                    dateTime = dateTime.ToUniversalTime();
                }

                text = dateTime.ToString(ISODateTimeJsonConverter.DateTimeFormat, CultureInfo.InvariantCulture);
            }
            else
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;

                if ((dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                  || (dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
                    dateTimeOffset = dateTimeOffset.ToUniversalTime();

                text = dateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture);
            }

            writer.WriteValue(text);
        }
开发者ID:hh22333,项目名称:Ext.NET.Community,代码行数:35,代码来源:ISODateTimeJsonConverter.cs

示例11: Copy

        public override void Copy(ODataObject source, JsonSerializer serializer)
        {
            if(source == null || serializer == null) return;
            base.Copy(source, serializer);

            var typedSource = source as Metadata;
            if(typedSource != null)
            {
                Name = typedSource.Name;
                Value = typedSource.Value;
                IsPublic = typedSource.IsPublic;
            }
            else
            {
                JToken token;
                if(source.TryGetProperty("Name", out token) && token.Type != JTokenType.Null)
                {
                    Name = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
                }
                if(source.TryGetProperty("Value", out token) && token.Type != JTokenType.Null)
                {
                    Value = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
                }
                if(source.TryGetProperty("IsPublic", out token) && token.Type != JTokenType.Null)
                {
                    IsPublic = (bool?)serializer.Deserialize(token.CreateReader(), typeof(bool?));
                }
            }
        }
开发者ID:BobDankert,项目名称:ShareFile-NET,代码行数:29,代码来源:Metadata.cs

示例12: 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">Serializer</param>
        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is DateTime || value is DateTime?)
            {
                DateTime date = value is DateTime ? (DateTime)value : (value as DateTime?).Value;

                if (date != DateTime.MinValue)
                {
                    writer.WriteValue(date.ToString(this.RenderMilliseconds ? DateTimeFormatMs : DateTimeFormat, CultureInfo.InvariantCulture));
                }
                else
                {
                    writer.WriteRawValue("null");
                }

                return;
            }
            else
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;

                if (dateTimeOffset != DateTimeOffset.MinValue)
                {
                    writer.WriteValue(dateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture));
                }
                else
                {
                    writer.WriteRawValue("null");
                }
            }

            writer.WriteRawValue("null");
        }
开发者ID:emayk,项目名称:Ext.NET.Pro,代码行数:39,代码来源:JSONDateTimeJsonConverter.cs

示例13: Json

 public static string Json(Message message)
 {
     JsonSerializer js = new JsonSerializer();
     StringWriter str=new StringWriter();
     js.Serialize(str, message);
     return str.ToString();
 }
开发者ID:qixin6618,项目名称:IM,代码行数:7,代码来源:MessageHelper.cs

示例14: ReadJson

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var tokenArray = JToken.ReadFrom(reader);

            var children = new List<IChartOfAccountChild>();

            foreach (var token in tokenArray)
            {
                string type = token["type"].Value<string>();

                if (type == AccountGroup.typeName)
                {
                    var accountGroup = JsonConvert.DeserializeObject<AccountGroup>(token.ToString());
                    children.Add(accountGroup);
                }

                if (type == AccountIntervalGroup.typeName)
                {
                    var accountIntervalGroup = JsonConvert.DeserializeObject<AccountIntervalGroup>(token.ToString());
                    children.Add(accountIntervalGroup);
                }
            }

            return children;
        }
开发者ID:foretagsplatsen,项目名称:Foretagsplatsen-DotNet-API,代码行数:25,代码来源:ChartOfAccountChildJsonConverter.cs

示例15: ReadJson

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            List<ResolvedAction> resolvedActions = new List<ResolvedAction>();

            JArray actionsArray = JArray.Load(reader);
            foreach (JObject jobject in actionsArray)
            {
                ResolvedAction resolvedAction = new ResolvedAction();
                serializer.Populate(jobject.CreateReader(), resolvedAction);
                resolvedAction.BeaconAction = new BeaconAction();
                serializer.Populate(jobject.CreateReader(), resolvedAction.BeaconAction);
                if (jobject["content"] != null)
                {
                    serializer.Populate(jobject["content"]?.CreateReader(), resolvedAction.BeaconAction);
                    resolvedAction.BeaconAction.PayloadString = jobject["content"]["payload"]?.ToString();
                    // create json object for fallback
                    if(!string.IsNullOrEmpty(resolvedAction.BeaconAction.PayloadString))
                    {
                        resolvedAction.BeaconAction.Payload = JsonObject.Parse(resolvedAction.BeaconAction.PayloadString);
                    }
                }
                resolvedActions.Add(resolvedAction);
            }

            return resolvedActions;
        }
开发者ID:sensorberg-dev,项目名称:windows10-sdk,代码行数:26,代码来源:ResolvedActionConverter.cs


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