Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

c# - Json.net serialize only certain properties

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...