简体   繁体   English

如何使用Newtonsoft解析JSON?

[英]How to parse JSON with Newtonsoft?

I created an ASP.NET Application, where I have to parse a csv file with a json structure. 我创建了一个ASP.NET应用程序,必须在其中解析具有json结构的csv文件。 The csv file itself is structured like: csv文件本身的结构如下:

{"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. 我将jsonCsvData作为字符串获取,并尝试对其进行解析。 Then I want to save some of the elements of this json object into a db. 然后,我想将此json对象的某些元素保存到数据库中。

        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. 现在的问题是,变量first是一个空字符串。 The result should be (like in the json structure example above) "abc". 结果应为(如上述json结构示例中的)“ 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). 我不知道是否有帮助,但这是我的解决方案(在Json末尾删除“中的一个”)。

I use the "Jobject" to parse Json as I want. 我可以根据需要使用“ Jobject”解析Json。 Import this two reference. 导入这两个参考。

using Newtonsoft.Json.Linq;
using Newtonsoft;

Then you have to create your JObject : 然后,您必须创建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 : 然后,要检索特定数据,只需像使用带有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 : 如果您的“实例” json对象中有一个表,则可以像下面这样从列表中检索所有数据:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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