我正在尝试将以下JSON属性转换为对象。字符串数组是一种混合类型:它的元素可以是字符串或字符串数组。 (虽然字符串数组只出现在偶尔的记录中。)
我将booster
属性设为List<String>
,这很好,但是最后有几个数组的行导致解析失败。我有什么想法可以处理这种情况?
"booster": [
"land",
"marketing",
"common",
"common",
"common",
"common",
"common",
"common",
"common",
"common",
"common",
"common",
"uncommon",
"uncommon",
"uncommon",
[
"rare",
"mythic rare"
]
]
using(var db = new MTGFlexContext()){
JObject AllData = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(path));
List<String> SetCodes = db.Sets.Select(x => x.Code).ToList();
foreach (var set in AllData)
{
try
{
Set convert = JsonConvert.DeserializeObject<Set>(set.Value.ToString()) as Set;
if (!SetCodes.Contains(set.Key))
{
convert.Name = set.Key;
foreach (var c in convert.Cards)
{
db.Cards.Add(c);
db.SaveChanges();
}
db.Sets.Add(convert);
db.SaveChanges();
}
}
}
}
完整的json是40mb http://mtgjson.com/
答案 0 :(得分:1)
您可以booster
成为List<dynamic>
。它会正确地反序列化,对于那些不是字符串的索引,你可以将它们转换为JArray并获取值。
class MyObject {
List<dynamic> booster { get; set; }
}
var result = JsonConvert.Deserialize<MyObject>(json);
string value = result.booster[0];
var jArray = result.booster[15] as JArray;
var strings = jArray.Values<string>();
foreach(var item in strings)
Console.WriteLine(item);
更新:也许编写自定义json转换器可以做你想要的。此代码可能容易出错,并且没有很多错误处理或检查。它只是演示并说明了如何做到这一点:
public class CustomConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException(); // since we don't need to write a serialize a class, i didn't implement it
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jObject = JObject.Load(reader); // load the json string into a JObject
foreach (KeyValuePair<string, JToken> jToken in jObject) // loop through the key-value-pairs
{
if(jToken.Key == "booster") // we have a fixed structure, so just wait for booster property
{
// we take any entry in booster which is an array and select it (in this example: ['myth', 'mythic rare'])
var tokens = from entry in jToken.Value
where entry.Type == JTokenType.Array
select entry;
// let's loop through the array/arrays
foreach (var entry in tokens.ToList())
{
if (entry.Type == JTokenType.Array)
{
// now we take every string of ['myth', 'mythic rare'] and put it into newItems
var newItems = entry.Values<string>().Select(e => new JValue(e));
// add 'myth' and 'mythic rare' after ['myth', 'mythic rare']
// now the json looks like:
// {
// ...
// ['myth', 'mythic rare'],
// 'myth',
// 'mythic rare'
// }
foreach (var newItem in newItems)
entry.AddAfterSelf(newItem);
// remove ['myth', 'mythic rare']
entry.Remove();
}
}
}
}
// return the new target object, which now lets us convert it into List<string>
return new MyObject
{
booster = jObject["booster"].Values<string>().ToList()
};
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(MyObject);
}
}
希望它有所帮助...