Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I customize Json.NET to serialize private members and NOT serialize public readonly properties (without using attributes).

I've had a stab around at creating a custom IContractResolver but am a bit lost.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
670 views
Welcome To Ask or Share your Answers For Others

1 Answer

For a partial answer, messing with DefaultContractResolver.DefaultMembersSearchFlags can get it to include private things:

Newtonsoft.Json.JsonSerializerSettings jss = new Newtonsoft.Json.JsonSerializerSettings();

if (includePrivateMembers)
{
    Newtonsoft.Json.Serialization.DefaultContractResolver dcr = new Newtonsoft.Json.Serialization.DefaultContractResolver();
    dcr.DefaultMembersSearchFlags |= System.Reflection.BindingFlags.NonPublic;
    jss.ContractResolver = dcr;
}

return Newtonsoft.Json.JsonConvert.SerializeObject(o, jss);

Seems to work on a lot of objects, though with some this seems to generate a CLR exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...