在 C# 中枚举 JSON 属性 DalSoft.RestClient and/or Json.net

enumerate JSON properties in C# DalSoft.RestClient and/or Json.net

举一个简单的例子,试图让它在控制台应用程序中工作。 我正在使用来自 nuget 的 Json.Net and DalSoft.RestClient 包。我没有嫁给其中任何一个我只是想完成工作。对替代方案持开放态度。

http://jsonplaceholder.typicode.com/usersreturns有效JSON。

我想列举一下事先不知道的属性。以下似乎可行,但失败并出现 System.AggregateException - RuntimeBinderException:无法对空引用执行运行时绑定 我觉得我错过了一些简单的事情。

using System;
using System.Threading.Tasks;
using DalSoft.RestClient;
using Newtonsoft.Json.Linq;

namespace ImTired
{
    class Program
    {
        static void Main(string[] args)
        {
            DoThingsAsync().Wait();
            Console.ReadLine();
        }

        private static async Task<object> DoThingsAsync()
        {
            dynamic client = new RestClient("http://jsonplaceholder.typicode.com");
            var user = await client.Users.Get();
            var foo = user[0].name; // grab the first item (Works to this point)

            //JProperty item = new JProperty(user);
            var item = user[0];

            foreach (JProperty property in item.Properties()) //(fails here I've missed a cast or conversion)
            {
                Console.WriteLine(property.Name + " - " + property.Value);
            }

            Console.WriteLine("Call Complete: " + foo);

            return null;
        }
    }
}


跟进编辑:为所有潜伏者添加了这个。 我需要 将程序集添加到 GAC 以使其可用于 scripting tool。这是为了您的强名称信息。

我知道可能有另一种更好的方法来引用非 GAC 程序集。我只是没有时间弄清楚。也许我会在这里形成一个有意义的问题。

有趣的结果:

试试这个(我用的是 RestSharp):

 using System;
 using System.Threading.Tasks;
 using Newtonsoft.Json.Linq;
 using RestSharp;

 namespace ImNotSoTired
 {
    class Program
    {
         static void Main(string[] args)
         {
             DoThingsAsync().Wait();
             Console.ReadLine();
         }

         private static async Task<object> DoThingsAsync()
         {
             RestClient client = new RestClient("http://jsonplaceholder.typicode.com");
             var response = client.Execute(new RestRequest("users"));

             JArray users = JArray.Parse(response.Content);
             var user = (JObject)users[0];

             foreach (JProperty property in user.Properties())
             {
                 Console.WriteLine(property.Name + " - " + property.Value);
             }

             return null;
         }
     }
}

DalSoft Rest Client 不公开 JsObject/JsArray。它将 JSON 包装在 RestClientResponseObject 中并公开为带有 ToString method.To 的字符串获取所有 JSON 属性,我们需要将字符串显式解析为 JObject/JArray.

var item =JObject.Parse(user[0].ToString());
OR  
var users = JArray.Parse(user.ToString());
var item = users[0]; 

DalSoft.RestClient return 可以是动态对象,也可以将其转换为 class。文档中有这方面的示例,让我知道是否缺少任何内容。

也可以在 gitter 频道上提问。

下面是您的代码。如果您需要 return 属性 名称,那么您必须先转换为静态类型,然后正常使用反射。

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DalSoft.RestClient;

namespace ImTired
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                DoThingsAsync().ConfigureAwait(false);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            Console.ReadLine();
        }

        private static async Task<object> DoThingsAsync()
        {
            dynamic client = new RestClient("http://jsonplaceholder.typicode.com");
            List<User> users = await client.Users.Get();
            var foo = users[0].name; // grab the first item (Works to this point)

            var user = users[0]; 
            foreach (var propertyInfo in user.GetType().GetProperties())
            {
                Console.WriteLine(propertyInfo.Name + " - " + propertyInfo.GetValue(user));
            }

            return null;
        }        
    }

    public class User
    {
        public int id { get; set; }
        public string name { get; set; }
        public string username { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
        public string website { get; set; }
    }
}