【发布时间】:2014-11-25 16:18:11
【问题描述】:
我必须阅读一个 JSON 文档,它有一个可以包含不同类型的字段。 例如,可以是长整数或整数数组。我知道我需要使用自定义反序列化器,但不确定如何。 在下面的示例中,xx 字段有时是长整数,否则是整数数组。 任何有关如何处理此问题的帮助表示赞赏。
static void JsonTest() {
const string json = @"
{
'Code': 'XYZ',
'Response': {
'Type' : 'S',
'Docs': [
{
'id' : 'test1',
'xx' : 1
},
{
'id' : 'test2',
'xx' : [1, 2, 4, 8]
},
]
}
}";
A a;
try {
a = JsonConvert.DeserializeObject<A>(json);
}
catch( Exception ex ) {
Console.Error.WriteLine(ex.Message);
}
}
public class A {
public string Code;
public TResponse Response;
}
public class TResponse {
public string Type;
public List<Doc> Docs;
}
public class Doc {
public string id;
public int[] xx;
}
我的实现基于以下建议(将数组从 int 更改为 long):
[JsonConverter(typeof(DocConverter))]
public class Doc {
public string id;
public long[] xx;
}
public class DocConverter : JsonConverter {
public override bool CanWrite { get { return false; } }
public override bool CanConvert( Type objectType ) {
return typeof(Doc).IsAssignableFrom(objectType);
}
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer ) {
JObject item = JObject.Load(reader);
Doc doc = new Doc();
doc.id = item["id"].ToObject<string>();
if( item["xx"].Type == JTokenType.Long )
doc.xx = new [] { item["xx"].ToObject<long>() };
else
doc.xx = item["xx"].ToObject<long[]>();
return doc;
}
public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer ) {
throw new NotImplementedException();
}
}
【问题讨论】:
-
将值分配给一个字符串并执行一个长的 TryParse,如果失败尝试将其转换为一个数组。
-
你不能这样做,你会得到一个数组分隔符的异常 [.
标签: c# json deserialization