【发布时间】: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