为了绑定到网格,我必须将JSON字符串反序列化为C#类。我用C#实现了相应的类。但在特定实例中,这将失败,因为JSON属性将是一个数组或一个对象。请检查字符串的一部分。
我已经创建了ItemList类,它有3个属性IL1、Name和另一个对象类“Item”。但是,您可以看到,当属性“name”是Rubber时,我应该将Item class列表作为属性而不是Item对象。当它是橡胶时,它返回2个项目的数组。
"ItemList": [
{
"@IL1": "Yes",
"@Name": "Pencil"
"Item": {
"@ItemType": "Pencil",
"@Item2": "1A7716744F7048ACA2549BE93F0A2BF1",
"aimLink": {
"@id": "1A7716744F7048ACA2549BE93F0A2BF1",
"@DisplayText": "P00001"
}
}
},
{
"@IL1": "Yes",
"@Name": "Pen",
"Item": {
"@ItemType": "Pen",
"@Item2": "AE067F7EDB6147C09AED243C1F7FAD25",
"aimLink": {
"@id": "AE067F7EDB6147C09AED243C1F7FAD25",
"@DisplayText": "5100010654120001
}
}
},
{
"@IL1": "Yes",
"@Name": "Rubber",
"Item": [
{
"@ItemType": "Rubber",
"@ItemGID": "622025629037499394DF092DA16BAB7F",
"aimLink": {
"@id": "622025629037499394DF092DA16BAB7F",
"@DisplayText": "12345678-1234-123456-7116#01"
}
},
{
"@ItemType": "Rubber",
"@ItemGID": "F336F65F8E014E80B84A2312F829493C"
"aimLink": {
"@id": "F336F65F8E014E80B84A2312F829493C",
"@DisplayText": "12345678-1234-123456-7116#14"
}
}
]
}
],
我怎样才能有效地将它解析成一个C#类,以及实现这一目标的最简单的方法呢?
谢谢,Divya
您可以通过自定义JSONConverter
来解决此问题,您可以使用下面的方法将单个值转换为数组,然后使用JSONConverter
属性标记Item
属性
public class SingleValueArrayConverter<T> : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object retVal = new Object();
if (reader.TokenType == JsonToken.StartObject)
{
T instance = (T)serializer.Deserialize(reader, typeof(T));
retVal = new List<T>() { instance };
}
else if (reader.TokenType == JsonToken.StartArray)
{
retVal = serializer.Deserialize(reader, objectType);
}
return retVal;
}
public override bool CanConvert(Type objectType)
{
return false;
}
}
假设这是ItemList
类
public class ItemList
{
public string @IL1 { get; set; }
public string @Name { get; set; }
[JsonConverter(typeof(SingleValueArrayConverter<Item>))]
public List<Item> Item { get; set; }
}
public class Item
{
public string @ItemType { get; set; }
public string @Item2 { get; set; }
public AimLink aimLink { get; set; }
}
public class AimLink
{
public string @id { get; set; }
public string @DisplayText { get; set; }
}
您可以自定义JSONConverter
(例如ItemConverter
)并使用[JSONConverter(typeof(ItemConverter))]
属性标记Item
属性