我正在寻找C#或VB.net的答案。
我得到了一个这样的字符串:
{"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即可。
我该怎么做呢?
发布于 2018-05-30 07:09:24
你可以使用Newtonsoft.Json来做这件事,只需在Nuget上找到它即可。
你可以像这样使用它,尽管它有点脏...
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
https://stackoverflow.com/questions/50594063
复制相似问题