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

Does Json.net have any way to specify only the properties you want to be serialized? or alternatively serialize certain properties based on binding flags like Declared Only?

Right now I am using JObject.FromObject(MainObj.SubObj); to get all properties of SubObj which is an instance of a class that obeys the ISubObject interface:

public interface ISubObject
{

}

public class ParentSubObject : ISubObject
{
    public string A { get; set; }
}


public class SubObjectWithOnlyDeclared : ParentSubObject
{
    [JsonInclude] // This is fake, but what I am wishing existed
    public string B { get; set; }

    [JsonInclude] // This is fake, but what I am wishing existed
    public string C { get; set; }
}

public class NormalSubObject: ParentSubObject
{
    public string B { get; set; }
}

If MainObj.SubObj was a NormalSubObject it would serailize both A and B but if it was SubObjectWithOnlyDeclared it would serailize only B and C and ignore the parent property

See Question&Answers more detail:os

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

1 Answer

Rather then having to use [JsonIgnore] on every attribtue you don't want to serialise as suggested in another answer.

If you just want to specify properties to serialise, you can do this, using [JsonObject(MemberSerialization.OptIn)] and [JsonProperty] attributes, like so:

using Newtonsoft.Json;
...
[JsonObject(MemberSerialization.OptIn)]
public class Class1
{
    [JsonProperty]
    public string Property1 { set; get; }
    public string Property2 { set; get; }
}

Here only Property1 would be serialised.


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