简体   繁体   中英

Using Newtonsoft.Json to iterate through multiple records

I'm looking for an answer in either C# or VB.net.

I'm getting a string like this:

{"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"}}

So, just two records. I just need to pull "name", "watts" and "rpm" from each. I don't need to store the entire record in an array or list as I'll just dispose of row anyway.

How can I do this?

You can use Newtonsoft.Json to do this, just find it in on Nuget.

You COULD use it like this, though it's a little dirty...

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");
        }
    }
}

I tested it with your json string in the TextFile1, and it works well. You'd be better off making a custom type for it to deserialise into.

The key parts are the JsonConvert.DeserializeObject(json) which converts the json string into CLR objects, namely a JObject . Then there's the .Value<JObject>("1") bit, which is just using the newtonsoft api.

ps I notice you've got a json.net tag on there, their website pretty much says it: https://www.newtonsoft.com/json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM