我有以下C#代码,使用Newtonsoft.Json v6.0.6:
void Main() {
var data=new AllData();
var cst=new CustomerData();
cst.CustomerName="Customer1";
cst.Add(1, new UserData() {UserName="User1", UserPhone="123456789"});
cst.Add(2, new UserData() {UserName="User2", UserPhone="987654321"});
data.Add(1, cst);
string json = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
public class UserData {
public string UserName;
public string UserPhone;
}
public class CustomerData:Dictionary<int,UserData> {
public string CustomerName;
}
public class AllData:Dictionary<int,CustomerData> {}
所以从这段代码我希望看到这个输出:
{
"1": {
"CustomerName": "Customer1",
"1": {
"UserName": "User1",
"UserPhone": "123456789"
},
"2": {
"UserName": "User2",
"UserPhone": "987654321"
}
}
}
但相反,我看到了:
{
"1": {
"1": {
"UserName": "User1",
"UserPhone": "123456789"
},
"2": {
"UserName": "User2",
"UserPhone": "987654321"
}
}
}
即。我的CustomerName属性被忽略。
我玩过Newtonsoft.Json.MemberSerialization和Newtonsoft.Json.JsonProperty属性没有成功,所以我想知道现在在哪里看。一个完整的自定义序列化实现似乎有点矫枉过正,有一个简单的方法来解决这个问题吗?
答案 0 :(得分:2)
您可以使用JSON.Net提供的JsonExtensionDataAttribute将父对象中不存在的任何属性放入集合属性。
以下是another SO post的示例。
JSON:
{
"X" : "value",
"key1": "value1",
"key2": "value2"
}
C#数据对象:
public class Test
{
public string X { get; set; }
[JsonExtensionData]
public Dictionary<string, object> Y { get; set; }
}
Key1和Key2将最终出现在Dictionary中,因为它们不存在于“Test”类中,而X将最终出现在X属性中。
它不完美,似乎你必须有一个Dictionary字典,但它仍然可能是一个更好的选择使用自定义序列化器?
这是使用一级数据类的example on DotNetFiddle。
对于数据:
public class UserData
{
public string UserName;
public string UserPhone;
}
public class CustomerData
{
public string CustomerName;
[JsonExtensionData]
public Dictionary<string, object> Users;
}
var data = new CustomerData()
{
CustomerName = "Foo",
Users = new Dictionary<string, object>()
{
{ "1", new UserData() { UserName = "Fireman", UserPhone = "0118 999 881 999 119 725 ... 3" } },
{ "2", new UserData() { UserName = "Jenny", UserPhone = "867-5309" } }
}
};
它生成JSON:
{
"customerName": "Foo",
"1": {
"userName": "Fireman",
"userPhone": "0118 999 881 999 119 725 ... 3"
},
"2": {
"userName": "Jenny",
"userPhone": "867-5309"
}
}