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

如何从HttpClient返回的JSON响应中提取Item1与Item2的值?

提取JSON响应中的Item1和Item2值

下面提供几种.NET环境下常用的提取方案:

方案一:使用内置的System.Text.Json(推荐,无需额外NuGet包)

方法1:自定义实体类映射

先定义与JSON结构匹配的类,再通过反序列化提取值:

// 定义对应JSON结构的实体类
public class ResponseModel
{
    public string Item1 { get; set; }
    public string Item2 { get; set; } // 若需要将Item2转为数字,可改为int类型
}

// 执行反序列化并取值
using System.Text.Json;

// 注意:原代码中"responce"拼写应为"response"
string response = await httpClient.GetStringAsync(Home.BaseAddr + "LastID?pass=" + Password);
var model = JsonSerializer.Deserialize<ResponseModel>(response);

string item1Value = model.Item1; // 结果:"aaa"
string item2Value = model.Item2; // 结果:"123",若改为int类型则为123

方法2:使用匿名类型反序列化

如果不想定义实体类,可直接用匿名类型匹配结构:

using System.Text.Json;

string response = await httpClient.GetStringAsync(Home.BaseAddr + "LastID?pass=" + Password);
var template = new { Item1 = "", Item2 = "" };
var result = JsonSerializer.Deserialize(response, template.GetType());

string item1Value = result.Item1;
string item2Value = result.Item2;

方案二:使用Newtonsoft.Json(Json.NET,需安装NuGet包Newtonsoft.Json)

方法1:JObject直接解析

无需定义类,直接解析JSON节点:

using Newtonsoft.Json.Linq;

string response = await httpClient.GetStringAsync(Home.BaseAddr + "LastID?pass=" + Password);
JObject jsonObj = JObject.Parse(response);

string item1Value = jsonObj["Item1"].ToString(); // "aaa"
string item2Value = jsonObj["Item2"].ToString(); // "123"
// 转为数字:int item2Num = (int)jsonObj["Item2"];

方法2:实体类反序列化

逻辑与System.Text.Json类似,使用JsonConvert完成反序列化:

public class ResponseModel
{
    public string Item1 { get; set; }
    public string Item2 { get; set; }
}

using Newtonsoft.Json;

string response = await httpClient.GetStringAsync(Home.BaseAddr + "LastID?pass=" + Password);
var model = JsonConvert.DeserializeObject<ResponseModel>(response);

string item1Value = model.Item1;
string item2Value = model.Item2;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 20:42:03