简体   繁体   English

对象数据类型的Json序列化

[英]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. 我有一个像上面的类,我正在从上面的Class对象创建Json字符串。 Property "BidAutoObject " is of type "object". 属性“ BidAutoObject”的类型为“对象”。 The object may be "CxDays" or "AMPM". 该对象可以是“ CxDays”或“ AMPM”。 It is setting dynamically. 它是动态设置的。 I am using newtonsoft.JsonConvert.SerializeObject to serialize the C# object to Json string. 我正在使用newtonsoft.JsonConvert.SerializeObject将C#对象序列化为Json字符串。 The outpout of Json serialization is like Json序列化的结果就像

"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 "? 因此,我无法从上述json字符串中识别出“ BidAutoObject类型是“ CxDays”还是“ AMPM”。如何在序列化过程中添加类型信息。是否需要向“ 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 (ie Base) does not match the instance type (ie 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. 代替Json字符串中的“ BidAutoObject”:我需要json字符串中的类对象名称,例如“ CxDays”或“ AMPM”。我们有一个使用“ Jsonserializer setting”的选项。当我们设置TypeNameHandling = TypeNameHandling.Auto时-这只会为声明的类型(即Base)与实例类型(即Derived)不匹配的实例添加一个$ type属性,但是它显示了该类的完整名称空间。 Json字符串而不是全名空间。

I guess what you are looking for is the TypeNameHandling in the JsonSerializerSettings which you need to add for de- and serialization. 我猜您正在寻找的是JsonSerializerSettingsTypeNameHandling ,您需要添加该TypeNameHandling以便进行反序列化和序列化。 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. 只需将其设置为TypeNameHandling.Auto即可为类型与声明的类型不相等的实例添加type属性到json。

If you simply don't want the assembly name and namespace name to appear in the JSON for some reason (why?), you can create your own custom subclass of DefaultSerializationBinder and then set it in JsonSerializerSettings.Binder : 如果您只是出于某种原因不希望程序集名称和名称空间名称出现在JSON中(为什么?),则可以创建自己的DefaultSerializationBinder的自定义子类,然后在JsonSerializerSettings.Binder进行设置:

public class DefaultAssemblyBinder : DefaultSerializationBinder
{
    public string DefaultAssemblyName { get; private set; }
    public string DefaultNamespaceName { get; private set; }

    public DefaultAssemblyBinder(string defaultAssemblyName, string defaultNamespaceName)
    {
        this.DefaultAssemblyName = defaultAssemblyName;
        this.DefaultNamespaceName = defaultNamespaceName;
    }

    public override Type BindToType(string assemblyName, string typeName)
    {
        if (!string.IsNullOrEmpty(DefaultAssemblyName))
        {
            if (string.IsNullOrEmpty(assemblyName))
                assemblyName = DefaultAssemblyName;
        }
        if (!string.IsNullOrEmpty(DefaultNamespaceName))
        {
            if (typeName != null && !typeName.Contains("."))
                typeName = DefaultNamespaceName + "." + typeName;
        }
        return base.BindToType(assemblyName, typeName);
    }

    public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
    {
        base.BindToName(serializedType, out assemblyName, out typeName);
        if (!string.IsNullOrEmpty(DefaultAssemblyName) && assemblyName != null)
            if (assemblyName == DefaultAssemblyName)
                assemblyName = null;
        if (!string.IsNullOrEmpty(DefaultNamespaceName) && typeName != null)
        {
            int index = typeName.LastIndexOf('.');
            if (index < 0)
                throw new JsonSerializationException(string.Format("Type {0} does not exist in any namespace, but a default namespace {1} has been set", serializedType.FullName, DefaultNamespaceName));
            if (index == DefaultNamespaceName.Length && string.Compare(DefaultNamespaceName, 0, typeName, 0, index, StringComparison.Ordinal) == 0)
                typeName = typeName.Substring(index + 1);
        }
    }
}

And then, later: 然后,稍后:

        var test = new MyClass { IsApplied = true, BidAutoObject = new CxDays { IsMon = false, IsSun = true, IsTue = false } };

        var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, Binder = new DefaultAssemblyBinder(typeof(MyClass).Assembly.FullName, typeof(MyClass).Namespace) };
        var json = JsonConvert.SerializeObject(test, Formatting.Indented, settings);
        Console.WriteLine(json);

Creates the following JSON: 创建以下JSON:

 { "BidAutoObject": { "$type": "CxDays", "IsSun": true, "IsMon": false, "IsTue": false }, "IsApplied": true } 

Prototype fiddle . 原型摆弄

For another custom binder example, see Custom SerializationBinder from the documentation. 有关另一个定制活页夹示例,请参阅文档中的“ Custom SerializationBinder ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在C#json对象序列化和数据协定中包装原始类型 - Wrap primitive type in C# json object serialization and data contract Web Api 2 - 自定义数据类型JSON序列化 - Web Api 2 - custom data type JSON serialization 带有Stream类型成员的对象上的JSON.NET序列化? - JSON.NET Serialization on an object with a member of type Stream? Newtonsoft.JSON序列化产生一个带有对象类型的唯一字符串 - Newtonsoft.JSON serialization results in a sole string with the object's type 具有多态子对象的Json.Net序列化 - Json.Net Serialization of Type with Polymorphic Child Object JSON对象序列化和反序列化 - JSON object serialization and deserialization Json.NET自定义带有数据注释的枚举类型序列化 - Json.NET custom serialization of a enum type with data annotation 将C#对象序列化为json - Serialization C# object to json “无法将&#39;System.Net.Http.Formatting.JsonContractResolver&#39;类型的对象强制转换为&#39;Newtonsoft.Json.Serialization.DefaultContractResolver&#39;。” - “Unable to cast object of type 'System.Net.Http.Formatting.JsonContractResolver' to type 'Newtonsoft.Json.Serialization.DefaultContractResolver'.” 无法将类型为“Newtonsoft.Json.Linq.JObject”的对象强制转换为“System.Runtime.Serialization.ISafeSerializationData” - Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'System.Runtime.Serialization.ISafeSerializationData'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM