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

如何在C#中解析JSON中的指定命名对象(value数组)

如何直接反序列化JSON响应中的"value"数组?

API端点返回的JSON响应如下:

{
  "value": [
    {
      "id": 1,
      "name": "Brushcreek"
    },
    {
      "id": 2,
      "name": "Formula"
    }
  ],
  "statusCode": 200,
  "contentType": null
}

当前使用的代码(手动截取字符串来反序列化):

HttpResponseMessage response = await client.GetAsync("http://localhost:5000/api/Project/GetAll").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
    string content = await response.Content.ReadAsStringAsync();
    //these three lines make sure to send a json array of the project objects to the deserializer
    int startInd = content.IndexOf('[');
    int endInd = content.IndexOf(']');
    string valueThing = content.Substring(startInd, (endInd - startInd)+1);
    Projects = JsonSerializer.Deserialize<IEnumerable<DataAccess.Models.ProjectModel>>(valueThing, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true}).ToList();
}

想要不通过字符串截取,直接将JSON中的"value"数组传入反序列化器,避免格式不匹配的报错。


方法1:创建响应模型类(推荐)

定义一个和整个响应结构匹配的类,反序列化整个对象后直接取value属性,这是最规范的做法:

// 定义响应模型
public class ApiResponse
{
    public IEnumerable<DataAccess.Models.ProjectModel> Value { get; set; }
    public int StatusCode { get; set; }
    public string ContentType { get; set; }
}

// 修改请求解析代码
HttpResponseMessage response = await client.GetAsync("http://localhost:5000/api/Project/GetAll").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
    var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse>(new JsonSerializerOptions 
    { 
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase 
    });
    Projects = apiResponse.Value?.ToList() ?? new List<DataAccess.Models.ProjectModel>();
}

注:ReadFromJsonAsync是.NET Core 3.0+提供的简化方法,也可以先读字符串再用JsonSerializer.Deserialize<ApiResponse>完成反序列化

方法2:使用JsonDocument直接定位节点

如果不想额外创建模型类,可以用JsonDocument来解析JSON并提取value数组:

HttpResponseMessage response = await client.GetAsync("http://localhost:5000/api/Project/GetAll").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
    string content = await response.Content.ReadAsStringAsync();
    using var doc = JsonDocument.Parse(content);
    var valueElement = doc.RootElement.GetProperty("value");
    Projects = valueElement.Deserialize<IEnumerable<DataAccess.Models.ProjectModel>>(new JsonSerializerOptions 
    { 
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase 
    }).ToList();
}

方法3:使用Newtonsoft.Json(Json.NET)

如果项目中使用的是Newtonsoft.Json,可以用JObject来提取数组:

// 确保已安装Newtonsoft.Json包
HttpResponseMessage response = await client.GetAsync("http://localhost:5000/api/Project/GetAll").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
    string content = await response.Content.ReadAsStringAsync();
    var jObject = JObject.Parse(content);
    var valueArray = jObject["value"];
    Projects = valueArray.ToObject<List<DataAccess.Models.ProjectModel>>();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:45:47