Sunday 15 May 2011

c# - What is the use of the StreamingContext parameter in Json.NET Serialization Callbacks? -



c# - What is the use of the StreamingContext parameter in Json.NET Serialization Callbacks? -

i'm trying understand streamingcontext parameter supposed contain in json.net serialization callbacks, first thought allow me access current json tree beingness read, doesn't seem that, tried may arrangements of json objects, none of them streamingcontext parameter.

here illustration shows have beingness doing please right me if i'm wrong:

using system; using system.runtime.serialization; using newtonsoft.json; namespace testes { public class programme { [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(); } } }

good question. i've wondered myself, you've inspired me find out.

searching through json.net source code, appears streamingcontext not used much serializer @ all, instead simply passed through serializer settings other places might need it. guess added back upwards .net iserializable interface, contract requires implementors provide constructor accepts streamingcontext. json.net provides empty streamingcontext default, allows set explicitly in settings if need to. can see little alter main method:

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(); }

output:

ondeserializing: foo ondeserialized: foo

in short, streamingcontext parameter not going useful in cases (since empty default). not provide access json tree beingness serialized or deserialized.

c# json json.net deserialization

No comments:

Post a Comment