我正在寻找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"}}
所以,只有两个记录。我只需要从每个中提取“名称”,“瓦特”和“转速”。我不需要将整个记录存储在数组或列表中,因为我只是处理行。
我该怎么做?
答案 0 :(得分:0)
您可以使用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字符串测试它,它运行良好。你最好为它做一个自定义类型反序列化。
关键部分是JsonConvert.DeserializeObject(json)
,它将json字符串转换为CLR对象,即JObject
。然后是.Value<JObject>("1")
位,它只是使用了newtonsoft api。
P.S。我注意到你有一个json.net标签,他们的网站几乎说:https://www.newtonsoft.com/json