本质上我需要这个:
"/xxx/dynamicFileName1": {
"lines": {
"total": 8,
"covered": 4,
"skipped": 0,
"pct": 50
},
"functions": {
"total": 1,
"covered": 0,
"skipped": 0,
"pct": 0
},
"statements": {
"total": 8,
"covered": 4,
"skipped": 0,
"pct": 50
},
"branches": {
"total": 2,
"covered": 0,
"skipped": 0,
"pct": 0
}
},
"/xxx/dynamicFileName2": {
"lines": {
"total": 13,
"covered": 4,
"skipped": 0,
"pct": 30.77
},
"functions": {
"total": 1,
"covered": 0,
"skipped": 0,
"pct": 0
},
"statements": {
"total": 13,
"covered": 4,
"skipped": 0,
"pct": 30.77
},
"branches": {
"total": 12,
"covered": 0,
"skipped": 0,
"pct": 0
}
}
变成这样:(动态文件名键向下移动,用作键值对中的值(
{
"results": [{
"Name": "/xxx/dynamicFileName1",
"lines": {
"total": 3321,
"covered": 853,
"skipped": 0,
"pct": 25.69
},
"statements": {
"total": 3327,
"covered": 853,
"skipped": 0,
"pct": 25.64
},
"functions": {
"total": 724,
"covered": 36,
"skipped": 0,
"pct": 4.97
},
"branches": {
"total": 1984,
"covered": 42,
"skipped": 0,
"pct": 2.12
}
},
{
"Name": "/xxx/dynamicFileName2",
"lines": {
"total": 3321,
"covered": 853,
"skipped": 0,
"pct": 25.69
},
"statements": {
"total": 3327,
"covered": 853,
"skipped": 0,
"pct": 25.64
},
"functions": {
"total": 724,
"covered": 36,
"skipped": 0,
"pct": 4.97
},
"branches": {
"total": 1984,
"covered": 42,
"skipped": 0,
"pct": 2.12
}
}
]}
我正在尝试将上面的JSON反序列化为类。想知道以前是否有人处理过这样的问题?我一直在读NewtonSoft的文档,但我什么都没能拼凑出来。如有任何帮助,我们将不胜感激。
第二个JSON对应的类结构如下:
public class RootObject
{
public List<Result> Results { get; set; }
}
public class Result
{
public string Name { get; set; }
public Statistics Lines { get; set; }
public Statistics Statements { get; set; }
public Statistics Functions { get; set; }
public Statistics Branches { get; set; }
}
public class Statistics
{
public int Total { get; set; }
public int Covered { get; set; }
public int Skipped { get; set; }
public float Pct { get; set; }
}
以下是将第一个JSON反序列化到此类结构所需的代码。它将JSON加载到JObject
中,将每个动态键移动到其相应子对象的Name
属性中,将子对象收集到列表中,最后将列表放置到新的RootObject
实例中。
var root = new RootObject
{
Results = JObject.Parse(json)
.Properties()
.Select(jp =>
{
JObject item = (JObject)jp.Value;
item.AddFirst(new JProperty("Name", jp.Name));
return item.ToObject<Result>();
})
.ToList()
};
以下是一个工作演示:https://dotnetfiddle.net/30xova