我想返回一个单一的json对象,其中包含该对象内的所有不同字段。下面的代码生成此json,该json返回值的三个条目,除了最后两个字段外,其余值相同。
.thumbnail img {
max-height: 300px;
}
这是我的代码,该代码执行网络请求以获取此数据
{
"value": [
{
"name": "russ",
"id": "12345",
"grade": 5,
"TestID": "12332",
"testResult": "Pass"
},
{
"name": "russ",
"id": "12345",
"grade": 5,
"TestID": "15474",
"testResult": "Pass"
},
{
"name": "russ",
"id": "12345",
"gradeLevel": 5,
"TestID": "75783",
"testResult": "Fail"
}
]
}
我想将其合并为:
var result = Helper.DoRequest(requestUrl, null, httpMethod, "");
var jObj = JObject.Parse(result.Last().Value.ToString());
JArray valueList = JArray.Parse(jObj["value"].ToString());
答案 0 :(得分:2)
此代码可能是一个开始。它将json反序列化为类,并按名称,ID和等级将结果分组(我假设第三个结果中的“ gradelevel”键是一个错字),然后将其作为Json输出,并将测试结果作为数组输出(您的所需的输出不是有效的Json,因为它包含重复的键名):
void Main()
{
var json = json_from_api;
var results = JsonConvert.DeserializeObject<RootObject>(json);
var groupedResults = results.value.GroupBy(r => new { r.id, r.name, r.grade });
var finalResults = groupedResults.Select(g => new
{
g.Key.id,
g.Key.name,
g.Key.grade,
test_results = g.ToList().Select(v => new
{
v.TestID,
v.testResult
}
)});
var output = new {
value = finalResults
};
Console.WriteLine(JsonConvert.SerializeObject(output, Newtonsoft.Json.Formatting.Indented));
}
public class Value
{
public string name { get; set; }
public string id { get; set; }
public int grade { get; set; }
public string TestID { get; set; }
public string testResult { get; set; }
}
public class RootObject
{
public List<Value> value { get; set; }
}
输出:
{
"value": [
{
"id": "12345",
"name": "russ",
"grade": 5,
"test_results": [
{
"TestID": "12332",
"testResult": "Pass"
},
{
"TestID": "15474",
"testResult": "Pass"
},
{
"TestID": "75783",
"testResult": "Fail"
}
]
}
]
}