首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Newtonsoft.Json遍历多个记录

使用Newtonsoft.Json遍历多个记录
EN

Stack Overflow用户
提问于 2018-05-30 06:50:33
回答 1查看 251关注 0票数 0

我正在寻找C#或VB.net的答案。

我得到了一个这样的字符串:

代码语言:javascript
复制
{"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"}}

所以,只有两条记录。我只需要从其中提取"name“、"watts”和"rpm“。我不需要将整个记录存储在数组或列表中,因为我只需要处理row即可。

我该怎么做呢?

EN

回答 1

Stack Overflow用户

发布于 2018-05-30 07:09:24

你可以使用Newtonsoft.Json来做这件事,只需在Nuget上找到它即可。

你可以像这样使用它,尽管它有点脏...

代码语言:javascript
复制
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = File.ReadAllText("TextFile1.txt");
            JObject jsonObject= (JsonConvert.DeserializeObject(json) as JObject);
            string name = jsonObject.Value<JObject>("1").Value<string>("name");
        }
    }
}

我在TextFile1中使用您的json字符串对其进行了测试,它工作得很好。您最好为其创建一个自定义类型,以便将其反序列化。

关键部分是将json字符串转换为CLR对象的JsonConvert.DeserializeObject(json),即JObject。然后是.Value<JObject>("1")位,它只使用newtonsoft api。

附注:我注意到他们的网站上有一个json.net标签,上面写着:https://www.newtonsoft.com/json

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50594063

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档