c# – 在Json.NET序列化回调中使用StreamingContext参数?
发布时间:2020-12-15 06:34:58 所属栏目:百科 来源:网络整理
导读:我想了解在Json.NET序列化回调中应该包含什么StreamingContext参数,首先我以为你会允许我访问正在读取的当前json树,但是似乎并没有这样做可以安排 JSON对象,但是没有一个可以从StreamingContext参数中获取任何内容. 这是一个例子,显示我正在做什么请纠正我,
我想了解在Json.NET序列化回调中应该包含什么StreamingContext参数,首先我以为你会允许我访问正在读取的当前json树,但是似乎并没有这样做可以安排
JSON对象,但是没有一个可以从StreamingContext参数中获取任何内容.
这是一个例子,显示我正在做什么请纠正我,如果我错了: using System; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Testes { public class Program { [JsonObject(MemberSerialization.OptIn)] public class Person { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("age")] public int Age { get; set; } [OnDeserialized] internal void OnDeserializedMethod(StreamingContext context) { Console.WriteLine(String.Format("OnDeserialized: {0}",context.Context)); } [OnDeserializing] internal void OnDeserializingMethod(StreamingContext context) { Console.WriteLine(String.Format("OnDeserializing: {0}",context.Context)); } } public static void Main(string[] args) { var lucy = JsonConvert.DeserializeObject<Person>("{ 'id': 1,'name': 'Lucy','age': 22 }"); Console.ReadKey(); } } } 解决方法
好问题.我经常想知道这一点,所以你启发了我找出来.
通过Json.Net source code搜索,似乎StreamingContext根本不是真的被串行器使用,而是从串行器设置传递到可能需要的其他地方.我的猜测是被添加到支持.NET public static void Main(string[] args) { JsonSerializerSettings settings = new JsonSerializerSettings { Context = new StreamingContext(StreamingContextStates.Other,"foo") }; var json = @"{ ""id"": 1,""name"": ""Lucy"",""age"": 22 }"; var lucy = JsonConvert.DeserializeObject<Person>(json,settings); Console.ReadKey(); } 输出: OnDeserializing: foo OnDeserialized: foo 简而言之,StreamingContext参数在大多数情况下不会非常有用(因为默认情况下为空).它绝对不提供对被序列化或反序列化的JSON树的访问. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |