linq 在c#控制台应用程序中从Web反序列化c#中的json

mwg9r5ms  于 2022-12-06  发布在  C#
关注(0)|答案(1)|浏览(151)

基本上,我试图使我为对象创建的类能够读取单个项,以便我可以使用它们。
这是我想读的Json的副本

//    "roles": [
            //      {
            //        "name": "All Modules",
            //          "oid": "G|2",
            //          "uuid": "06be0407-53f9-4a0a-9b97-e771631e8d83",
            //          "study": true,
            //          "site": false,
            //          "href": "coming soon"
            //      }

下面是我使用的类

namespace SomeNamespace
{
    public class Roles
    {
        [JsonProperty("name")]
        public string name { get; set; }

        
    }

    public class RolesJson
    {
        [JsonProperty("roles")]
        public Roles roles { get; set; }
    }
}

下面是我的RequestExample.cs

var outputString = $"{await response.Content.ReadAsStringAsync()}";

            //Console.WriteLine(outputString);
            
            JObject stuff = JObject.Parse(outputString);
            Console.WriteLine(stuff);
            //The Response body is the following:
            //{
            //    "roles": [
            //      {
            //        "name": "All Modules",
            //          "oid": "G|2",
            //          "uuid": "06be0407-53f9-4a0a-9b97-e771631e8d83",
            //          "study": true,
            //          "site": false,
            //          "href": "coming soon"
            //      }
            //            ]
            //}
            foreach (JObject jo in stuff["roles"])
            {
                foreach (var item in jo)
                {
                    Console.WriteLine(item);

                }
                // Console.WriteLine(jo.ToString());
                //prints this
                //{
                //    "name": "All Modules",
                //    "oid": "G|2",
                //    "uuid": "06be0407-53f9-4a0a-9b97-e771631e8d83",
                //    "study": true,
                //    "site": false,
                //    "href": "coming soon"
                //}
            }
3pmvbmvn

3pmvbmvn1#

您可以使用此网站https://app.quicktype.io/创建类

public partial class Data
    {
        [JsonProperty("roles")]
        public List<Role> Roles { get; set; }
    }

    public partial class Role
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("oid")]
        public string Oid { get; set; }

        [JsonProperty("uuid")]
        public Guid Uuid { get; set; }

        [JsonProperty("study")]
        public bool Study { get; set; }

        [JsonProperty("site")]
        public bool Site { get; set; }

        [JsonProperty("href")]
        public string Href { get; set; }
    }

和反序列化数据

List<Role> roles=JsonConvert.DeserializeObject<Data>(json).Roles;

     Role role = roles[0];

     string name = role.Name;

相关问题