我有以下对象:
{
"pickups": {
"7": [
5,
8
],
"10": [
6,
7,
9
],
"15": [
1
],
"20": [
0,
2
],
"25": [
3,
4
]
}
}
我想将每个拾音器元素删除到以下对象中:
public class Pickups {
public Pickup[] pickups;
}
public class Pickup {
public int Group; // This could be the 7, 10, 15, 20, 25, etc.
public int[] Values; // If this was the "7" grouping, it would contain 5, 8.
}
您可以从数据中看到,这样做有点棘手。我一直在尝试使用jsonConverter使用一些自定义代码转换对象,但它是一场噩梦,我无法正确处理。我想知道是否有人会知道将这种类型的对象转换为我需要的正确格式的最佳方法?
虽然转换器将是一个不错的选择
var root = JsonConvert.DeserializeObject<RootObject>(json);
var pickups = new Pickups {
pickups = root.pickups.Select(kvp =>
new Pickup {
Group = int.Parse(kvp.Key),
Values = kvp.Value
}
).ToArray()
};
其中
public class RootObject {
public IDictionary<string, int[]> pickups { get; set; }
}
这就是son2csharp.com所说的,它会出现错误,因为您无法用启动号码定义名称。
public class Pickups
{
public List<int> __invalid_name__7 { get; set; }
public List<int> __invalid_name__10 { get; set; }
public List<int> __invalid_name__15 { get; set; }
public List<int> __invalid_name__20 { get; set; }
public List<int> __invalid_name__25 { get; set; }
}
public class RootObject
{
public Pickups pickups { get; set; }
}
但我认为
[DataMember(Name = "Name")]
应该工作导致其在JSON格式方面的错误。
如果它是您使用jobight.parse(...)的可行选择等等):
var jsonPickups = JObject.Parse(json);
var myPickups = new Pickups
{
pickups = jsonPickups.First.First.Select(x =>
{
JProperty xProp = x as JProperty;
return new Pickup
{
Group = int.Parse(xProp.Name),
Values = (xProp.Value as JArray).Select(y => int.Parse(y.ToString())).ToArray()
};
}).ToArray()
};