C# 获取Newtonsoft.Json的JObject多层节点内容

json形如

{

  "object":{

  "name":"cwr"

  },

  "others":"123"

}

 

要获取name的值,则需要构造两个JObject来获取,如下:

JObject json = JObject.Parse(jsonresult);

string name = ((JObject)json["object"])["name"].ToString();

 

json形如

{

  "object":{

  "name": [

       {

         "firstname" : "cwr",

         "lastname" : "cwr"

        }

      ]

  },

  "others":"123"

}

获取firstname的值如下:

JObject json = JObject.Parse(jsonresult);

string firstname = ((JObject)((JObject)json["object"])["name"][0])[firstname].ToString();

 

昨天调试程序一直报"未将对象引用到实例",报错代码是 fpmccontent.Text = json["words_result"]["InvoiceType"].ToString() ?? "";

我一直以为是json["words_result"]["InvoiceType"].ToString()为null,但实际上是json["words_result"]["InvoiceType"]为null,是调用ToString()方法的时候报错了,对自己无语。

转载于:https://www.cnblogs.com/cwr-toki/p/10092089.html

你可能感兴趣的:(C# 获取Newtonsoft.Json的JObject多层节点内容)