【发布时间】:2020-10-05 05:15:22
【问题描述】:
我有下面的 json,我需要在 C# 中反序列化 -
{
"clientSettings":[
{
"clientId":12345,
"entries":[
{
"key":"abc",
"value":false
},
{
"key":"def",
"value":false
},
{
"key":"ghi",
"value":false
}
]
},
{
"clientId":9876,
"entries":[
{
"key":"lkmn",
"value":false
}
]
}
],
"productSettings":[
{
"productId":11,
"entries":[
{
"key":"jkl",
"value":true
},
{
"key":"mno",
"value":true
}
]
},
{
"productId":12,
"entries":[
{
"key":"jkl",
"value":true
},
{
"key":"mno",
"value":true
}
]
}
],
"customerSettings":[
{
"key":"enableData",
"value":false
},
{
"key":"minPriceValue",
"value":"10.28"
},
{
"key":"presentData",
"value":"AEGIS"
}
],
"thothTest":{
"9876":[
"K"
],
"5431":[
"A",
"L"
],
"5123":[
"L"
]
},
"osirisTest":{
"7678":[
"K"
]
}
}
以下是我创建的用于将 json 反序列化到的类 -
public class ProcessHolder : Holder
{
public IDictionary<int, ISet<string>> OsirisTest { get; set; }
public IDictionary<int, ISet<string>> ThothTest { get; set; }
}
public class Holder
{
public IList<Mapping> CustomerSettings { get; set; }
public IList<ClientSettingsMapping> ClientSettings { get; set; }
public IList<ProductSettingsMapping> ProductSettings { get; set; }
}
public class Mapping
{
public string Key { get; set; }
public object Value { get; set; }
}
public class ProductSettingsMapping : Mapping
{
public int ProductId { get; set; }
}
public class ClientSettingsMapping : Mapping
{
public int ClientId { get; set; }
}
- 我想将所有
customerSettings值加载到CustomerSettings类的CustomerSettings对象中。 - 同样,我想将所有
clientSettings值加载到Holder类的ClientSettings对象中。 - 类似地,所有
productSettings值都放入Holder类的ProductSettings对象中。 - 类似地将
thothTest值转换为ThothTest和osirisTest值转换为OsirisTest对象。
我正在尝试使用下面的代码,但在反序列化上面的 json 之后,我无法看到 Key 和 Value 变量被填充到 Mapping 类对象中。
private static readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
};
public static void Main(string[] args)
{
var jsonContent = File.ReadAllText("/beta/Downloads/test.json");
var config = JsonConvert.DeserializeObject<ProcessHolder>(jsonContent, serializerSettings);
if (config == null)
{
Console.WriteLine("Some Parsing Issue");
}
// using config object here
}
我在这里做错了什么?我只需要将我的 json 反序列化为上述类,然后将 ProcessHolder 对象返回给我,以便我以后使用。
【问题讨论】:
-
请注意:您当前依赖 JSON 转换器,假设您的 JSON 中的骆驼大小写名称和代码中的帕斯卡大小写名称相同(例如“clientId”==“ClientId ”)。相反,您应该考虑使用
JsonProperty手动指定名称
标签: c# json json.net deserialization