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

C#如何提取JSON文本中JArray里概率最高的tagName值

C# 提取JSON中概率最高的tagName实现方案

你可以使用.NET生态下两种主流JSON处理库完成需求,以下是两种常用实现方案:

方案1:定义实体类反序列化(推荐,类型安全,适合正式项目使用)

首先根据JSON结构定义对应C#实体类:

/// 预测项实体类
public class Prediction
{
    public double probability { get; set; }
    public string tagId { get; set; }
    public string tagName { get; set; }
}

/// JSON根节点实体类
public class CustomHttpResponse
{
    public string id { get; set; }
    public string project { get; set; }
    public string iteration { get; set; }
    public DateTime created { get; set; }
    public List<Prediction> predictions { get; set; }
}

基于.NET内置System.Text.Json实现(.NET Core 3.0+/.NET 5+ 无需额外安装依赖)

using System.Linq;
using System.Text.Json;

// 替换为你从HttpResponse获取的JSON字符串
string jsonContent = "你的JSON字符串";

// 反序列化JSON到实体对象
CustomHttpResponse response = JsonSerializer.Deserialize<CustomHttpResponse>(jsonContent);

// 用LINQ筛选概率最大的项对应的tagName
string highestProbTagName = response.predictions
    .OrderByDescending(p => p.probability)
    .First()
    .tagName;

基于Newtonsoft.Json(Json.NET)实现(兼容全版本.NET,需先安装NuGet包Newtonsoft.Json)

using System.Linq;
using Newtonsoft.Json;

string jsonContent = "你的JSON字符串";
CustomHttpResponse response = JsonConvert.DeserializeObject<CustomHttpResponse>(jsonContent);

string highestProbTagName = response.predictions
    .OrderByDescending(p => p.probability)
    .First()
    .tagName;

方案2:动态解析(无需定义实体类,适合临时快速开发使用)

基于System.Text.Json实现

using System.Linq;
using System.Text.Json;

string jsonContent = "你的JSON字符串";
JsonDocument jsonDoc = JsonDocument.Parse(jsonContent);
JsonElement predictionArray = jsonDoc.RootElement.GetProperty("predictions");

string highestProbTagName = predictionArray.EnumerateArray()
    .OrderByDescending(item => item.GetProperty("probability").GetDouble())
    .First()
    .GetProperty("tagName")
    .GetString();

基于Newtonsoft.Json实现

using System.Linq;
using Newtonsoft.Json.Linq;

string jsonContent = "你的JSON字符串";
JObject rootObj = JObject.Parse(jsonContent);
JArray predictionArray = (JArray)rootObj["predictions"];

string highestProbTagName = predictionArray
    .OrderByDescending(item => (double)item["probability"])
    .First()["tagName"]
    .ToString();

小提示:如果业务场景中predictions数组可能为空,可以将代码中的First()替换为FirstOrDefault(),补充空值判断逻辑避免运行时异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:06:01