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

如何在C#中解析包含多层嵌套模型的JSON数据

解析指定JSON载荷的C#方法实现思路

首先修正原始JSON中的语法错误:workouts数组内的对象存在无效行Datastructure 2,需删除该行才能正常解析,修正后的JSON如下:

{
  "meals": [
    {
      "id": 279205,
      "isDeleted": false,
      "image": "https://d15rxdoyo1waj2.cloudfront.net/production/image?b=snaq-app-production&i=meals/279204/image.jpg&w=1200&q=90",
      "mealName": "Smoked salmon ala Mamma",
      "mealTime": "2023-09-08T14:17:52Z",
      "ingredients": [
        { "name": "Carrot" },
        { "name": "Lemon" },
        { "name": "Arugula" },
        { "name": "Salmon Grilled" }
      ],
      "nutrition": {
        "carbohydrates": { "unit": "g", "value": 8 },
        "fatTotal": { "unit": "g", "value": 22 },
        "protein": { "unit": "g", "value": 34 },
        "dietryFibers": { "unit": "g", "value": 4 },
        "energy": { "unit": "kcal", "value": 365 }
      },
      "weight": { "unit": "g", "value": 302 }
    }
  ],
  "insulinDelivery": [
    {
      "id": 123456,
      "isDeleted": false,
      "injectionTime": "2023-09-09T13:12:12Z",
      "insulinType": "SHORT",
      "unit": "units",
      "value": 5.0
    }
  ],
  "workouts": [
    {
      "id": 10223,
      "isDeleted": false,
      "startDate": "2023-09-10T10:52:23Z",
      "endDate": "2023-09-10T11:35:45Z",
      "intensity": "EASY",
      "workoutName": "Baseball"
    }
  ],
  "steps": [
    {
      "startDate": "2023-09-18T14:00:00Z",
      "endDate": "2023-09-18T15:00:00Z",
      "stepCount": "1500"
    }
  ]
}

一、定义对应的数据模型类

根据JSON结构创建匹配的C#实体类,确保属性映射关系正确:

// 根数据类
public class HealthData
{
    public List<Meal> Meals { get; set; }
    public List<InsulinDelivery> InsulinDelivery { get; set; }
    public List<Workout> Workouts { get; set; }
    public List<Step> Steps { get; set; }
}

// 餐食实体
public class Meal
{
    public int Id { get; set; }
    public bool IsDeleted { get; set; }
    public string Image { get; set; }
    public string MealName { get; set; }
    public DateTime MealTime { get; set; }
    public List<Ingredient> Ingredients { get; set; }
    public Nutrition Nutrition { get; set; }
    public Weight Weight { get; set; }
}

// 食材实体
public class Ingredient
{
    public string Name { get; set; }
}

// 通用营养项(碳水、脂肪等结构一致)
public class NutritionItem
{
    public string Unit { get; set; }
    public int Value { get; set; }
}

// 营养汇总实体
public class Nutrition
{
    public NutritionItem Carbohydrates { get; set; }
    public NutritionItem FatTotal { get; set; }
    public NutritionItem Protein { get; set; }
    public NutritionItem DietryFibers { get; set; }
    public NutritionItem Energy { get; set; }
}

// 重量实体
public class Weight
{
    public string Unit { get; set; }
    public int Value { get; set; }
}

// 胰岛素注射记录实体
public class InsulinDelivery
{
    public int Id { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime InjectionTime { get; set; }
    public string InsulinType { get; set; }
    public string Unit { get; set; }
    public double Value { get; set; }
}

// 运动记录实体
public class Workout
{
    public int Id { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public string Intensity { get; set; }
    public string WorkoutName { get; set; }
}

// 步数记录实体
public class Step
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public int StepCount { get; set; }
}

二、编写解析方法

方案1:使用.NET内置System.Text.Json

无需额外安装依赖,直接使用框架自带工具:

using System.Text.Json;

public static HealthData ParseHealthData(string jsonString)
{
    try
    {
        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true, // 忽略属性名大小写匹配
            WriteIndented = true
        };
        return JsonSerializer.Deserialize<HealthData>(jsonString, options);
    }
    catch (JsonException ex)
    {
        Console.WriteLine($"解析失败:{ex.Message}");
        return null;
    }
}

方案2:使用Newtonsoft.Json(Json.NET)

若习惯使用Json.NET,需先通过NuGet安装Newtonsoft.Json包:

using Newtonsoft.Json;

public static HealthData ParseHealthDataWithNewtonsoft(string jsonString)
{
    try
    {
        return JsonConvert.DeserializeObject<HealthData>(jsonString);
    }
    catch (JsonException ex)
    {
        Console.WriteLine($"解析失败:{ex.Message}");
        return null;
    }
}

三、使用示例

// 读取JSON文件内容
string jsonContent = File.ReadAllText("health_data.json");
var healthData = ParseHealthData(jsonContent);

// 访问解析后的数据
if (healthData != null && healthData.Meals.Any())
{
    var firstMeal = healthData.Meals.First();
    Console.WriteLine($"餐食名称:{firstMeal.MealName}");
    Console.WriteLine($"总热量:{firstMeal.Nutrition.Energy.Value}{firstMeal.Nutrition.Energy.Unit}");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:24:54