You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#处理Web API返回JSON:提取最高概率的tagName及probability方法

解决方案:在C#中提取JSON响应中概率最高的条目

不需要使用第三方库,.NET框架自带的System.Text.Json(适用于.NET Core/.NET 5+)或System.Runtime.Serialization.Json(适用于.NET Framework)就能完成JSON反序列化和数据处理。以下是具体实现步骤:

1. 定义与JSON结构对应的实体类

创建匹配返回JSON结构的类,将JSON字符串反序列化为强类型对象,方便后续操作:

// 根响应类
public class PredictionResponse
{
    public List<PredictionItem> Predictions { get; set; }
}

// 单个预测条目类
public class PredictionItem
{
    // 用JsonPropertyName确保和JSON字段名匹配
    [System.Text.Json.Serialization.JsonPropertyName("probability")]
    public double Probability { get; set; }
    
    [System.Text.Json.Serialization.JsonPropertyName("tagName")]
    public string TagName { get; set; }
    
    // 其他不需要的字段可省略,反序列化时自动忽略
}

2. 修改API调用方法,处理JSON响应

更新MakeRequest方法,完成JSON反序列化并筛选概率最高的条目:

using System;
using System.Net.Http.Headers;
using System.Net.Http;
using System.IO;
using System.Linq;
using System.Text.Json;

namespace Rest_API_Test
{
    static class Program
    {
        // .NET 5+支持async Main,替代同步Main
        static async Task Main(string[] args)
        {   
            string imageFilePath = @"C:\Users\wissarut.s\Desktop\Test Capture\Left.png";
            await MakeRequest(imageFilePath);
            Console.ReadLine();
        }

        // 将async void改为async Task,避免异步操作潜在问题
        public static async Task MakeRequest(string imageFilePath)
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Prediction-key", "****");
            var uri = "*******************";

            byte[] byteData = File.ReadAllBytes(imageFilePath); // 简化图片读取逻辑

            using (var content = new ByteArrayContent(byteData))
            {
                // 注意:发送图片数据时,ContentType应设为对应图片类型,比如"image/png",而非"application/json"
                content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                var response = await client.PostAsync(uri, content);
                response.EnsureSuccessStatusCode(); // 确保请求成功

                // 读取并反序列化JSON响应
                var jsonString = await response.Content.ReadAsStringAsync();
                var predictionResponse = JsonSerializer.Deserialize<PredictionResponse>(jsonString);

                // 筛选概率最高的条目
                if (predictionResponse?.Predictions != null && predictionResponse.Predictions.Any())
                {
                    // .NET 6+可用MaxBy直接获取概率最高项
                    var highestProbItem = predictionResponse.Predictions.MaxBy(item => item.Probability);
                    
                    // .NET 5及以下版本用以下代码替代
                    // var highestProbItem = predictionResponse.Predictions.OrderByDescending(item => item.Probability).First();

                    // 输出目标字段
                    Console.WriteLine($"概率最高的标签: {highestProbItem.TagName},概率值: {highestProbItem.Probability:F4}");
                }
                else
                {
                    Console.WriteLine("未获取到有效预测数据");
                }
                Console.WriteLine("From Left Side Camera");
            }
        }
    }

    // 实体类放在命名空间内
    public class PredictionResponse
    {
        public List<PredictionItem> Predictions { get; set; }
    }

    public class PredictionItem
    {
        [System.Text.Json.Serialization.JsonPropertyName("probability")]
        public double Probability { get; set; }
        
        [System.Text.Json.Serialization.JsonPropertyName("tagName")]
        public string TagName { get; set; }
    }
}

关键说明

  • 反序列化:使用System.Text.Json.JsonSerializer将JSON转为强类型对象,比手动解析更简洁可靠。
  • 筛选逻辑:
    • .NET 6+版本用MaxBy直接获取目标元素,代码更精简。
    • 低版本.NET可通过OrderByDescending+First实现相同效果。
  • 代码优化:
    • 替换async void为async Task,避免异步操作未捕获异常。
    • 用File.ReadAllBytes简化图片读取,无需手动处理流对象。
    • 添加response.EnsureSuccessStatusCode(),确保API请求失败时抛出异常提示。

内容的提问来源于stack exchange,提问作者Wissarut Saiyud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 12:36:14