将具有对象类型键和List类型值的Dictionary序列化为Json

时间:2018-01-03 10:50:51

标签: c# json dictionary serialization json.net

我想将以下词典类型转换为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。 我怎样才能使它发挥作用?

1 个答案:

答案 0 :(得分:0)

您拥有的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; }
    }

}