在 Json.Net 中序列化类名

cig*_*man 0 c# serialization json.net

我有以下 C# 代码:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

public class Program
{
    private static readonly JsonSerializerSettings prettyJson = new JsonSerializerSettings()
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver(),
        Formatting = Formatting.Indented
    };
    public class dialup {
        public Dictionary<string,uint> speeds;
        public string phonenumber;
    }
    public class Ethernet {
        public string speed;
    }
    public class ipv4 {
        public bool somecapability;
    }

    public class SiteData {
        public string SiteName;

        [JsonExtensionData]
        public Dictionary<string, object> ConnectionTypes;
    }
    public static void Main() 
    {   
        var data = new SiteData()
        {
            SiteName = "Foo",
            ConnectionTypes = new Dictionary<string, object>() 
            {
                { "1",  new dialup() { speeds=new Dictionary<string,uint>() {{"1",9600},{"2",115200}}, phonenumber = "0118 999 881 999 119 725 ... 3" } },
                { "2",  new Ethernet() { speed = "1000" } },
                {"3", new ipv4() { somecapability=true}}
            }
        };
        var json = JsonConvert.SerializeObject(data, prettyJson);   
        Console.WriteLine(json);
    }
}
Run Code Online (Sandbox Code Playgroud)

这将产生以下 JSON:

{
  "siteName": "Foo",
  "1": {
    "speeds": {
      "1": 9600,
      "2": 115200
    },
    "phonenumber": "0118 999 881 999 119 725 ... 3"
  },
  "2": {
    "speed": "1000"
  },
  "3": {
    "somecapability": true
  }
}
Run Code Online (Sandbox Code Playgroud)

我在 JSON 中需要的是:

{
  "siteName": "Foo",
  "1": {
    "dialup":{
    "speeds": {
      "1": 9600,
      "2": 115200
    },
    "phonenumber": "0118 999 881 999 119 725 ... 3"
    }
  },
  "2": {
    "Ethernet":{
    "speed": "1000"
    }
  },
  "3": {
    "ipv4":{
    "somecapability": true
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我如何使用 Json.NET 做到这一点?Json.NET 反序列化这很好,但我一直在寻找如何让它以相同的方式序列化它的日子。

Bri*_*ers 5

为此,您需要将ConnectionTypes字典中的每个值都包装在另一个字典中。您可以创建一个辅助方法来简化此操作:

private static Dictionary<string, object> WrapInDictionary(object value) 
{
    return new Dictionary<string, object>()
    {
        { value.GetType().Name, value }
    };
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样初始化你的数据:

var data = new SiteData()
{
    SiteName = "Foo",
    ConnectionTypes = new Dictionary<string, object>() 
    {
        { "1", WrapInDictionary( new dialup() { Speeds = new Dictionary<string, uint>() { {"1", 9600}, {"2", 115200} }, PhoneNumber = "0118 999 881 999 119 725 ... 3" } ) },
        { "2", WrapInDictionary( new Ethernet() { Speed = "1000" } ) },
        { "3", WrapInDictionary( new ipv4() { SomeCapability=true } ) }
    }
};
Run Code Online (Sandbox Code Playgroud)

小提琴:https : //dotnetfiddle.net/gGXlDo