相关疑难解决方法(0)

json.net - 如何在根对象上添加属性$ type ONLY

我想修改我的json.NET序列化程序,只将$ type属性添加到实现给定接口但不对任何属性或嵌套对象的对象.

使用TypeNameHandling.Auto(默认)

{
  "PropertyA": 123,
  "PropertyB": "foo",
  "PropertyC": [1, 2, 3, 4]
}
Run Code Online (Sandbox Code Playgroud)

使用TypeNameHandling.All

{
  "$type": "JsonNetTypeNameHandling.TestEvent, jsonNetTypeNameHandling",
  "PropertyA": 123,
  "PropertyB": "foo",
  "PropertyC": {
    "$type": "System.Collections.Generic.List`1[[System.Int32, mscorlib]], mscorlib",
    "$values": [1, 2, 3, 4 ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我想要的是

{
  "$type": "JsonNetTypeNameHandling.TestEvent, jsonNetTypeNameHandling",
  "PropertyA": 123,
  "PropertyB": "foo",
  "PropertyC": [1, 2, 3, 4]
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用自定义的ContractResolver,但我没有让它工作:

class Program
{
    static void Main(string[] args)
    {
        var serializerSettings = new JsonSerializerSettings()
        {
            TypeNameHandling = TypeNameHandling.Auto,
            TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,
            NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
            ContractResolver = new EnableTypeNameHandlingAllOnlyForEvents(), …
Run Code Online (Sandbox Code Playgroud)

json.net

9
推荐指数
1
解决办法
2316
查看次数

NewtonSoft SerializeObject 忽略 TypeNameHandling

按照官方文档

string jsonTypeNameAll = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
});

Console.WriteLine(jsonTypeNameAll);
// {
//   "$type": "Newtonsoft.Json.Samples.Stockholder, Newtonsoft.Json.Tests",
//   "FullName": "Steve Stockholder",
//   "Businesses": {
//     "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Samples.Business, Newtonsoft.Json.Tests]], mscorlib",
//     "$values": [
//       {
//         "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",
//         "Stars": 4,
//         "Name": "Hudson Hotel"
//       }
//     ]
//   }
// }
Run Code Online (Sandbox Code Playgroud)

我已经复制粘贴了这段代码。

    public static string Convert<T>(T cacheObject)
    {
        return JsonConvert.SerializeObject(cacheObject, Formatting.Indented, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All
        });
    }
Run Code Online (Sandbox Code Playgroud)

但是,如果我用 调用它Convert(DateTime.Now),我会得到一个序列化的 …

c# json.net

1
推荐指数
1
解决办法
1793
查看次数

标签 统计

json.net ×2

c# ×1