在C#中獲取JSON對(duì)象中指定屬性的值,可以使用Newtonsoft.JSON庫(kù)的JObject類
using Newtonsoft.Json.Linq;
using System;
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-690688.html
public class Program
{
? ? public static void Main(string[] args)
? ? {
? ? ? ? string json = @"{
? ? ? ? ? ? 'Name': 'John',
? ? ? ? ? ? 'age': 30,
? ? ? ? ? ? 'City': 'New York'
? ? ? ? }";
?
? ? ? ? // 解析JSON對(duì)象
? ? ? ? JObject jsonObject = JObject.Parse(json);
?
? ? ? ? // 獲取指定屬性的值
? ? ? ? string name = (string)jsonObject["Name"];
? ? ? ? int age = (int)jsonObject["Age"];
? ? ? ? string city = (string)jsonObject["City"];
?
? ? ? ? // 打印屬性值
? ? ? ? Console.WriteLine("Name: " + name);
? ? ? ? Console.WriteLine("Age: " + age);
? ? ? ? Console.WriteLine("City: " + city);
? ? }
}
在上面的示例中,我們首先使用JObject.Parse()方法將JSON字符串解析為JObject對(duì)象。
?
然后,我們可以使用索引器([])來(lái)獲取指定屬性的值。
?
需要注意,我們需要將屬性值轉(zhuǎn)換為適當(dāng)?shù)念愋停鐚ge屬性轉(zhuǎn)換為int類型。
?
最后,我們可以打印屬性的值文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-690688.html
?
到了這里,關(guān)于C# 獲取Json對(duì)象中指定屬性的值的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!