json.net解析混合字符串和数组



我正在尝试将下面的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为40mbhttp://mtgjson.com/

您可以将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);
    }
}

希望它能帮助。。。

相关内容

  • 没有找到相关文章

最新更新