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
655 views
in Technique[技术] by (71.8m points)

c# - Json serialization for Object Data Type

public class MyClass
{ 
    public object BidAutoObject { get; set; }
    public bool IsApplied { get; set; }
}

I have a class like above and I am creating the Json string from the above Class object. Property "BidAutoObject " is of type "object". The object may be "CxDays" or "AMPM". It is setting dynamically. I am using newtonsoft.JsonConvert.SerializeObject to serialize the C# object to Json string. The outpout of Json serialization is like

"BidAutoObject": {
    "IsSun": true,
    "IsMon": false,
    "IsTue": true,
    "IsWed": true,
    "IsThu": false,
    "IsFri": true,
    "IsSat": true
}

So I couldn't identify whether "BidAutoObject type is "CxDays" or "AMPM" from the above json string. how can I add the type information during the serialization process. Do I need to add any attribute to "BidAutoObject "?

public class CxDays
{
    public bool IsSun { get; set; }
    public bool IsMon { get; set; }
    public bool IsTue { get; set; }
}

public class AMPM
{
   public bool AM { get; set; }
   public bool PM { get; set; }
   public bool MIX { get; set; }
}

Instead of ""BidAutoObject": in the Json string, I need the class object name such as "CxDays" or "AMPM" in the json string. We have one option using "Jsonserializer setting" .When we set TypeNameHandling = TypeNameHandling.Auto - this will add a $type property ONLY for instances where the declared type (i.e. Base) does not match the instance type (i.e. Derived). But it showing the full namespace of that class.Now I want to show only the class name in the Json string instead of full name space.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I guess what you are looking for is the TypeNameHandling in the JsonSerializerSettings which you need to add for de- and serialization. Just set it to TypeNameHandling.Auto which will add a type property to the json for instances which have a type not equal to the declared type.


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

...