C#从反序列化的json对象中获取值

标签 c# json

我目前正在使用以下代码使用 Newtonsoft.Json nuget 数据包反序列化 json 字符串:

var data = (JObject)JsonConvert.DeserializeObject(json);

现在我收到了以下格式的对象:

{{  "meta": {    "rap": 2098,    "count": 5  },  "data": [    {      "name": "Gold Tetramino of Mastery",      "rap": 735,      "uaid": "16601901",      "link": "https://www.roblox.com/Gold-Tetramino-of-Mastery-item?id=5786047",      "img": "https://t4.rbxcdn.com/081337d7ea86e6a406512aaa83bbcdeb",      "serial": "---",      "count": 1    },    {      "name": "Silver Tetramino of Accomplishment",      "rap": 385,      "uaid": "16601900",      "link": "https://www.roblox.com/Silver-Tetramino-of-Accomplishment-item?id=5786026",      "img": "https://t1.rbxcdn.com/60da69cd76f8dad979326f63f4a5b657",      "serial": "---",      "count": 1    },    {      "name": "Subzero Ski Specs",      "rap": 370,      "uaid": "155175547",      "link": "https://www.roblox.com/Subzero-Ski-Specs-item?id=19644587",      "img": "https://t4.rbxcdn.com/8ead2b0418ef418c7650d34103d39b6d",      "serial": "---",      "count": 1    },    {      "name": "Rusty Tetramino of Competence",      "rap": 319,      "uaid": "16601899",      "link": "https://www.roblox.com/Rusty-Tetramino-of-Competence-item?id=5785985",      "img": "https://t2.rbxcdn.com/968ad11ee2f4ee0861ae511c419148c8",      "serial": "---",      "count": 1    },    {      "name": "Bluesteel Egg of Genius",      "rap": 289,      "uaid": "16601902",      "link": "https://www.roblox.com/Bluesteel-Egg-of-Genius-item?id=1533893",      "img": "https://t7.rbxcdn.com/48bf59fe531dd1ff155e455367e52e73",      "serial": "---",      "count": 1    }  ]}}

现在我试图从中获取以下值:

"rap": 2098,

我只需要 2098 并且我一直在尝试以下代码:

string rap = data["rap"].Value<string>();

但遗憾的是,这行不通。有谁知道如何获得值(value)?

最佳答案

尝试:

var result = data["meta"]["rap"].Value<int>();

var result = data.SelectToken("meta.rap").ToString();

或者如果你不想传递整个路径,你可以像这样搜索属性:

var result = data.Descendants()
                 .OfType<JProperty>()
                 .FirstOrDefault(x => x.Name == "rap")
                 ?.Value;

关于C#从反序列化的json对象中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41752928/

相关文章:

c# - 如何在 Rx 中交替缓冲和流动实时数据流

c# - 如何在 C# 中实现点在凸多边形算法中的有效测试?

javascript - JSON获取表单数据的请求

ruby-on-rails - rails 3 : Escape characters (\) appearing in part of JSON string

c++ - Casablanca C++ REST SDK 中 web::json::value::parse 和 web::json::value::string 的区别

php - 更好的想法如何从数据库中获取大量 MySql 数据

c# - C#判断字符串是否为数字

C# WPF 按钮点击

c# - 在嵌套类中使用配置设置

javascript - ajax表单提交不起作用