如何用C#从Custom Vision Prediction API返回的JSON中仅输出Predictions数组
没问题!作为C#和JSON新手,直接提取特定部分确实会有点懵,我给你两种简单的方案,都是常用的JSON处理方式,你可以选适合自己的:
方案1:使用.NET内置的System.Text.Json(无需额外安装包)
这个是.NET Core 3.0+、.NET 5及以后版本自带的,不用装额外NuGet包,非常方便。
修改后的完整代码如下:
byte[] byteData = GetImageAsByteArray(imageFilePath); using (var content = new ByteArrayContent(byteData)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); var response = await client.PostAsync(url, content); // 获取接口返回的完整JSON字符串 string fullJson = await response.Content.ReadAsStringAsync(); // 解析JSON并提取Predictions数组 using (JsonDocument doc = JsonDocument.Parse(fullJson)) { JsonElement root = doc.RootElement; // 直接定位到Predictions属性 JsonElement predictions = root.GetProperty("Predictions"); // 将数组转为字符串输出 Console.WriteLine(predictions.ToString()); } }
这段代码的逻辑很简单:先把完整JSON解析成可操作的JsonDocument,再通过属性名直接定位到你需要的Predictions数组,最后转成字符串打印。
方案2:使用Newtonsoft.Json(Json.NET,更灵活)
如果你的项目是.NET Framework,或者更习惯用这个老牌JSON库,可以先在NuGet包管理器里搜索安装Newtonsoft.Json,然后用下面的代码:
byte[] byteData = GetImageAsByteArray(imageFilePath); using (var content = new ByteArrayContent(byteData)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); var response = await client.PostAsync(url, content); string fullJson = await response.Content.ReadAsStringAsync(); // 解析JSON对象 JObject jsonObj = JObject.Parse(fullJson); // 提取Predictions数组 JArray predictions = (JArray)jsonObj["Predictions"]; // 输出数组的JSON字符串 Console.WriteLine(predictions.ToString()); }
这个方法的语法更简洁直观,通过索引器就能直接拿到目标数组,适合快速开发。
进阶:把Predictions转成C#对象列表(方便后续处理)
如果之后你需要操作每个预测结果的属性(比如遍历标签和概率),可以先定义一个对应结构的类:
public class Prediction { public string TagId { get; set; } public string TagName { get; set; } public double Probability { get; set; } }
然后用System.Text.Json反序列化:
List<Prediction> predictionList = JsonSerializer.Deserialize<List<Prediction>>(root.GetProperty("Predictions"));
或者用Newtonsoft.Json:
List<Prediction> predictionList = jsonObj["Predictions"].ToObject<List<Prediction>>();
之后就可以直接操作对象了,比如遍历打印:
foreach (var pred in predictionList) { Console.WriteLine($"标签:{pred.TagName},概率:{pred.Probability}"); }
内容的提问来源于stack exchange,提问作者Eloise Lines
相关产品推荐
相关产品推荐

