C# 获取Json对象中指定属性的值

在C#中获取JSON对象中指定属性的值,可以使用Newtonsoft.JSON库的JObject类

using Newtonsoft.Json.Linq;

using System;

public class Program

{

public static void Main(string[] args)

{

string json = @"{

'Name': 'John',

'age': 30,

'City': 'New York'

}";

// 解析JSON对象

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对象。

然后,我们可以使用索引器([])来获取指定属性的值。

需要注意,我们需要将属性值转换为适当的类型,例如将Age属性转换为int类型。

最后,我们可以打印属性的值

相关推荐
阿蒙Amon10 小时前
C#每日面试题-Array和ArrayList的区别
java·开发语言·c#
i橡皮擦12 小时前
TheIsle恐龙岛读取游戏基址做插件(C#语言)
开发语言·游戏·c#·恐龙岛·theisle
用户219916797039118 小时前
C# 14 中的新增功能
c#
垂葛酒肝汤19 小时前
放置挂机游戏的离线和在线收益unity实现
游戏·unity·c#
爱说实话21 小时前
C# 20260112
开发语言·c#
无风听海21 小时前
C#中实现类的值相等时需要保留null==null为true的语义
开发语言·c#
云草桑21 小时前
海外运单核心泡货计费术语:不计泡、计全泡、比例分泡
c#·asp.net·net·计泡·海运
精神小伙就是猛1 天前
C# Task/ThreadPool async/await对比Golang GMP
开发语言·golang·c#