c# - 我如何从 JSON 字符串中获取值

标签 c# .net json

我正在尝试从下面的 JSON 中获取 "response" 对象的值。 我有一个问题,因为我不知道如何从 JSON 获取数据。我是这方面的新手。

{
    "error": false,
    "response": {
        "id": 6818,
        "name": "Krashnz",
        "avatar": "https:\/\/static.truckersmp.com\/avatarsN\/6818.1538179228.png",
        "smallAvatar": "https:\/\/static.truckersmp.com\/avatarsN\/small\/6818.1538179228.png",
        "joinDate": "2014-11-14 01:33:03",
        "steamID64": 76561198046080290,
        "steamID": "76561198046080290",
        "groupName": "Developer",
        "groupID": 2,
        "banned": false,
        "bannedUntil": null,
        "displayBans": false,
        "permissions": {
            "isGameAdmin": true,
            "showDetailedOnWebMaps": false
        },
        "vtc": {
            "id": 1,
            "name": "TruckersMP Developers",
            "tag": "TMP-DEV",
            "inVTC": true,
            "memberID": 1579
        }
    }
}

我该怎么做?我在 C# 工作

最佳答案

您可以使用类似 json2csharp 的工具将 json 转换为 C# 类。然后使用 Newtonsoft.Json nuget 包将 json 反序列化到您的类中。

创建以下类。然后你可以像这样反序列化:

var json = // your json string
var root = JsonConvert.DeserializeObject<RootObject>(json);
var response = root.Response;


// classes below
public class Permissions
{
    public bool isGameAdmin { get; set; }
    public bool showDetailedOnWebMaps { get; set; }
}

public class Vtc
{
    public int id { get; set; }
    public string name { get; set; }
    public string tag { get; set; }
    public bool inVTC { get; set; }
    public int memberID { get; set; }
}

public class Response
{
    public int id { get; set; }
    public string name { get; set; }
    public string avatar { get; set; }
    public string smallAvatar { get; set; }
    public string joinDate { get; set; }
    public long steamID64 { get; set; }
    public string steamID { get; set; }
    public string groupName { get; set; }
    public int groupID { get; set; }
    public bool banned { get; set; }
    public object bannedUntil { get; set; }
    public bool displayBans { get; set; }
    public Permissions permissions { get; set; }
    public Vtc vtc { get; set; }
}

public class RootObject
{
    public bool error { get; set; }
    public Response response { get; set; }
}

关于c# - 我如何从 JSON 字符串中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58236945/

相关文章:

java - SQL Server Java 兼容 GUID/UUID(Big Endian 唯一标识符)

php - json_encode,json.parse 丢弃一个 '+' 字符?

ios - 接收自定义通知 iOS swift 2.0

json - 嵌套 JSON 的 JOLT 转换?

c# - 在 devenv 和 msbuild 中使用 CruiseControl.net 时输出二进制文件的任何差异

c# - 同时维护和部署应用程序的两个版本

c# - 如何从 XML 文档注释创建网站?

C# 文件处理 - 创建文件并打开

.net - FitNesse App.Config

c# - SqlDatareader GetValue 根据系统日期格式返回日期值