json.net解析混合的字符串和数组 [英] json.net parsing mixed string and array
问题描述
我正在尝试将以下JSON属性转换为对象.字符串数组是一种混合类型:它的元素可以是字符串或字符串数组. (尽管字符串数组仅出现在偶尔的记录中.)
I am trying to convert the below JSON property into an object. The string array is kind of a mixed type: its elements may be strings or string arrays. (Although the string arrays only show up in the occasional record.)
我将booster
属性设置为List<String>
,这很好,但是最后有数组的几行会导致解析失败.有什么想法可以解决这种情况吗?
I made the booster
property a List<String>
, which is fine, but the few rows that have the array at the end cause parsing to fail. Any ideas how I could handle this situation?
"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/
The full json is 40mb http://mtgjson.com/
推荐答案
您可以将booster
设置为List<dynamic>
.它将正确地反序列化,对于那些不是字符串的索引,可以将其转换为JArray并获取值.
You could make booster
a List<dynamic>
. It would deserialize correctly and for those indices that are not strings you could cast as JArray and get the values.
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转换器可以完成您想要的事情.此代码可能容易出错,并且没有太多错误处理或检查.它只是演示并说明了如何实现:
UPDATE: Maybe writing a custom json converter can do what you want. This code may be error prone and there's not a lot of error handling or checking. It just demonstrates and illustrates how you can do it:
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);
}
}
希望有帮助...
这篇关于json.net解析混合的字符串和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!