【问题标题】:Serialize a Dictionary with an object type key and a List type value into Json将具有对象类型键和列表类型值的字典序列化为 Json
【发布时间】:2018-01-03 10:50:50
【问题描述】:

我想将以下 Dictionary 类型转换为 Json:

public class Repsonse
{
    public Dictionary<Employee, List<Car>> Dictionary { get; set; }

    public class Employee
    {
        public string Name { get; set; }
        public string Id { get; set; }
        public decimal Seniority { get; set; }        
    }

    public class Car
    {
        public string OwnerId { get; set; }
        public string Model { get; set; }
        public string RegistrationPlate { get; set; }
    }
}

我希望它被序列化为以下Json

{
  "Dictionary": [
    {
      "Name": "John Doe",
      "Seniority": "2",
      "OwnerId": "1111"
      "Cars": [
          {
            "OwnerId": "1111"
            "Model": "Chevrolet Spark",
            "RegistrationPlate": "LTO1234"
          },
          {
            "OwnerId": "1111"
            "Model": "Chevrolet Malibu",
            "RegistrationPlate": "LTO5678"
          }
        ]
    },
    {
      "Name": "Jane Doe",
      "Seniority": "10",
      "OwnerId": "9999"
      "Cars": [
          {
            "OwnerId": "9999"
            "Model": "Mercedes Benz",
            "RegistrationPlate": "ABC1234"
          },
          {
            "OwnerId": "9999"
            "Model": "Mercedes Maybach",
            "RegistrationPlate": "ABC5678"
          }
        ]
    }
  ]
}

我正在使用 NewtonSoft Json 进行序列化,read 我需要使用 TypeConverter 来启用这种序列化,但它对我不起作用。

这是TypeConverter 的实现:

public class Employee : TypeConverter
{
    public string Name { get; set; }
    public string Id { get; set; }
    public decimal Seniority { get; set; }

    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string))
        {
            return true;
        }
        return base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
        {
            return ((Employee)value).Name + "," + ((Employee)value).Id + "," + ((Employee)value).Seniority;
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

您可以查看完整的示例代码here。 我怎样才能让它发挥作用?

【问题讨论】:

  • “不起作用”到底是怎么回事?出了什么问题?
  • 关键属性没有序列化。只是它的类型名称。您可以在链接的小提琴中看到它。
  • 预期的 json 将很难从该字典中获取,更合适的是字典序列化,正如您在代码示例中所暗示的那样,例如 "Smith, John": { cars }, "Anderson, Mr.": { cars }。如果你想要那个 JSON,你最好让 Cars 成为 Employee 的属性

标签: c# json dictionary serialization json.net


【解决方案1】:

您拥有的 json 输出格式是用于列表而不是用于字典。如果你想使用字典可能你可以按照下面的一个

JSON 响应

{
 "Dictionary": {
  "John Doe": {
   "Name": "John Doe",
   "Id": "1111",
   "Seniority": 2,
   "Cars": [
     {
       "OwnerId": "1111",
       "Model": "Chevrolet Spark",
       "RegistrationPlate": "LTO1234"
     },
     {
       "OwnerId": "1111",
       "Model": "Chevrolet Malibu",
       "RegistrationPlate": "LTO5678"
     }
   ]
 },
 "Jane Doe": {
   "Name": "Jane Doe",
   "Id": "9999",
   "Seniority": 10,
   "Cars": [
     {
       "OwnerId": "9999",
       "Model": "Mercedes Benz",
       "RegistrationPlate": "ABC1234"
     },
     {
       "OwnerId": "9999",
       "Model": "Mercedes Maybach",
       "RegistrationPlate": "ABC5678"
     }
   ]
  }
 }
}

代码将是

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        Response res = new Response { Dictionary = new Dictionary<string, Employee>() };

        Employee firstEmployee = new Employee { Name = "John Doe", Id = "1111", Seniority = 2 };
        Employee secondEmployee = new Employee { Name = "Jane Doe", Id = "9999", Seniority = 10 };
        firstEmployee.Cars.Add(new Car { OwnerId = "1111", Model = "Chevrolet Spark", RegistrationPlate = "LTO1234" });
        firstEmployee.Cars.Add(new Car { OwnerId = "1111", Model = "Chevrolet Malibu", RegistrationPlate = "LTO5678" });

        secondEmployee.Cars.Add(new Car { OwnerId = "9999", Model = "Mercedes Benz", RegistrationPlate = "ABC1234" });
        secondEmployee.Cars.Add(new Car { OwnerId = "9999", Model = "Mercedes Maybach", RegistrationPlate = "ABC5678" });

        res.Dictionary.Add(firstEmployee.Name, firstEmployee);
        res.Dictionary.Add(secondEmployee.Name, secondEmployee);

        var result = JsonConvert.SerializeObject(res);
        Console.WriteLine(result);

    }
}

public class Response
{
    public Dictionary<string, Employee> Dictionary { get; set; }

    public class Employee : TypeConverter
    {
        public Employee(string name, decimal seniority, string id, List<Car> cars)
        {
            Name = name;
            Seniority = seniority;
            Id = id;
            Cars = cars;
            Cars = new List<Car>();
        }
        public Employee()
        {
            Cars = new List<Car>();
        }

        public string Name { get; set; }
        public string Id { get; set; }
        public decimal Seniority { get; set; }
        public List<Car> Cars { get; set; }

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return ((Employee)value).Name + "," + ((Employee)value).Id + "," + ((Employee)value).Seniority;
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }

    public class Car
    {
        public string OwnerId { get; set; }
        public string Model { get; set; }
        public string RegistrationPlate { get; set; }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2017-12-19
    相关资源
    最近更新 更多