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

使用Newtonsoft.Json遍历JSON记录提取指定字段(C#/VB.NET)

用Newtonsoft.Json按需提取JSON中的指定字段(C# & VB.NET)

嘿,你的需求很清晰——不用把整条泵记录都序列化到数组/列表里,只揪出name、watts和rpm这三个字段对吧?用Newtonsoft.Json的JObject动态解析就完美解决,不用定义多余的实体类,直接按需取值就行!


C# 实现示例

首先确保你已经通过NuGet安装了Newtonsoft.Json包,然后可以这么写:

using Newtonsoft.Json.Linq;
using System;

class Program
{
    static void Main()
    {
        string json = @"{""1"":{""pump"":1,""name"":""Pump 1"",""type"":""VS"",""time"":""2:10 PM"",""run"":10,""mode"":0,""drivestate"":0,""watts"":1656,""rpm"":2850,""gpm"":0,""ppc"":0,""err"":0,""timer"":1,""duration"":""durationnotset"",""currentrunning"":{""mode"":""off"",""value"":0,""remainingduration"":-1},""externalProgram"":{""1"":-1,""2"":-1,""3"":-1,""4"":-1},""remotecontrol"":1,""power"":1,""friendlyName"":""Pump 1""},""2"":{""pump"":2,""name"":""Pump 2"",""type"":""None"",""time"":""timenotset"",""run"":""runnotset"",""mode"":""modenotset"",""drivestate"":""drivestatenotset"",""watts"":""wattsnotset"",""rpm"":""rpmnotset"",""gpm"":""gpmnotset"",""ppc"":""ppcnotset"",""err"":""errnotset"",""timer"":""timernotset"",""duration"":""durationnotset"",""currentrunning"":{""mode"":""off"",""value"":0,""remainingduration"":-1},""externalProgram"":{""1"":-1,""2"":-1,""3"":-1,""4"":-1},""remotecontrol"":""remotecontrolnotset"",""power"":""powernotset"",""friendlyName"":""Pump 2""}}";

        // 解析JSON为JObject
        JObject pumpData = JObject.Parse(json);

        // 遍历每个泵的记录(键是"1"、"2")
        foreach (var pumpProperty in pumpData.Properties())
        {
            JToken pumpRecord = pumpProperty.Value;
            
            // 提取指定字段,注意处理不同类型(比如第二个泵的watts/rpm是字符串)
            string name = pumpRecord["name"]?.ToString() ?? "N/A";
            string watts = pumpRecord["watts"]?.ToString() ?? "N/A";
            string rpm = pumpRecord["rpm"]?.ToString() ?? "N/A";

            // 输出或者按需使用这些值
            Console.WriteLine($"泵 {pumpProperty.Name}:");
            Console.WriteLine($"  名称: {name}");
            Console.WriteLine($"  功率(W): {watts}");
            Console.WriteLine($"  转速(RPM): {rpm}\n");
        }
    }
}

说明:

  • 用JObject.Parse把JSON字符串转成动态的JObject,不用定义实体类
  • 遍历Properties()拿到每个泵的记录(键是"1"、"2")
  • 用[]直接访问字段,?.ToString()处理字段可能不存在的情况,?? "N/A"给默认值
  • 因为第二个泵的watts和rpm是字符串(比如"wattsnotset"),所以统一转成字符串处理最稳妥,如果你需要数字类型,可以加int.TryParse之类的判断转换

VB.NET 实现示例

同样先确保安装了Newtonsoft.Json包,代码如下:

Imports Newtonsoft.Json.Linq

Module Module1
    Sub Main()
        Dim json As String = "{""1"":{""pump"":1,""name"":""Pump 1"",""type"":""VS"",""time"":""2:10 PM"",""run"":10,""mode"":0,""drivestate"":0,""watts"":1656,""rpm"":2850,""gpm"":0,""ppc"":0,""err"":0,""timer"":1,""duration"":""durationnotset"",""currentrunning"":{""mode"":""off"",""value"":0,""remainingduration"":-1},""externalProgram"":{""1"":-1,""2"":-1,""3"":-1,""4"":-1},""remotecontrol"":1,""power"":1,""friendlyName"":""Pump 1""},""2"":{""pump"":2,""name"":""Pump 2"",""type"":""None"",""time"":""timenotset"",""run"":""runnotset"",""mode"":""modenotset"",""drivestate"":""drivestatenotset"",""watts"":""wattsnotset"",""rpm"":""rpmnotset"",""gpm"":""gpmnotset"",""ppc"":""ppcnotset"",""err"":""errnotset"",""timer"":""timernotset"",""duration"":""durationnotset"",""currentrunning"":{""mode"":""off"",""value"":0,""remainingduration"":-1},""externalProgram"":{""1"":-1,""2"":-1,""3"":-1,""4"":-1},""remotecontrol"":""remotecontrolnotset"",""power"":""powernotset"",""friendlyName"":""Pump 2""}}"

        ' 解析JSON为JObject
        Dim pumpData As JObject = JObject.Parse(json)

        ' 遍历每个泵的记录
        For Each pumpProperty In pumpData.Properties()
            Dim pumpRecord As JToken = pumpProperty.Value

            ' 提取字段,处理空值和类型差异
            Dim name As String = If(pumpRecord("name")?.ToString(), "N/A")
            Dim watts As String = If(pumpRecord("watts")?.ToString(), "N/A")
            Dim rpm As String = If(pumpRecord("rpm")?.ToString(), "N/A")

            ' 输出结果
            Console.WriteLine($"泵 {pumpProperty.Name}:")
            Console.WriteLine($"  名称: {name}")
            Console.WriteLine($"  功率(W): {watts}")
            Console.WriteLine($"  转速(RPM): {rpm}" & vbCrLf)
        Next
    End Sub
End Module

说明:

  • VB.NET里用If()运算符处理空值,和C#的??作用一致
  • 逻辑和C#完全匹配,只是语法适配了VB.NET的风格

这样就不用把整条记录存到数组或列表里,直接提取你需要的三个字段,用多少取多少,非常高效!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:07:15