简体   繁体   中英

How to parse JSON with Newtonsoft?

I created an ASP.NET Application, where I have to parse a csv file with a json structure. The csv file itself is structured like:

{"Instance":"abc","Date":"2019-06-03T00:00:02.056Z","Identification":"someFunction","Type":"DurationInMs","Value":"5","iserror":"False""}

I get the jsonCsvData as a string and tried to parse it. Then I want to save some of the elements of this json object into a db.

        public IActionResult ReadJsonCsvData(string jsonCsvData)
        {
            Console.WriteLine("ReadJsonCsvData");

            ChartData chartData = new ChartData();

            var lines = jsonCsvData.Split("\n");

            foreach (var line in lines)
            {
                var values = JObject.Parse(line);

                var first = string.Concat(values["Instance"]); //Output for first: ""
            }
        }

The problem now is, that the variable first is an empty string. The result should be (like in the json structure example above) "abc".

Thank you in advance!

I don't know if it will help but here is my solution (remove one of " at the end of your Json).

I use the "Jobject" to parse Json as I want. Import this two reference.

using Newtonsoft.Json.Linq;
using Newtonsoft;

Then you have to create your JObject :

JObject o = JObject.Parse(myJsonString);

Then to retrieve specifics data, you just have to search in your object just like you do with a dictionary with key :

instanceFromJson = o["Instance"].ToString;
dateFromJson = o["Date"].ToString;

If you have a table in your "instance" json object you can retrieve all data from this list just like that :

foreach (var item in o["Instance"]["tabFromInstanceObject"])
{
    MyList.Add(item);
}

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