【问题标题】:Implementing C# code that generates a string from an object field and field values实现从对象字段和字段值生成字符串的 C# 代码
【发布时间】:2021-06-06 14:42:20
【问题描述】:

我有一个用 Javascript 编写的代码,我想将它转换为 C#。代码所做的是获取一个 javascript 对象,然后使用对象中的键值对创建一个字符串。你会如何在 C# 中做类似的事情。

这里是javascript代码

     const userSession = {
            application_id: 1111,
            auth_key: "abc123456,
            nonce: a456654,
            timestamp: 1254564,
            user: { 
                    login : "johnwick",
                    password: 123434543
            } 
        }



 signParams(userSession) {
        if (typeof userSession != 'object') {
            throw Error('not an object');
        }

        let signature = Object.keys(userSession)
            .map(elem => {
                if (typeof userSession[elem] === 'object') {
                    return Object.keys(userSession[elem])
                        .map(elem1 => {
                            return elem + '[' + elem1 + ']=' + userSession[elem][elem1];
                        })
                        .sort()
                        .join('&')
                }
                else {
                    return elem + '=' + userSession[elem]
                }
            })
            .sort()
            .join('&')



        return this.hmacSha1(signature);
    }

signParams(userSession)

字符串应该是这样的 "application_id=3610&auth_key=aDRceQyTXSYEdJU&nonce=a456654&timestamp=${timestamp}&user[login]=johnwick&user[password]=123434543"

这是我使用 c# 对象在 c# 中初始化对象的方法,因为 c# 中没有类似于 Javascript 对象的对象

public class UserSession
    {
        public int ApplicationId { get; set; }
        public string AuthKey { get; set; }
        public double Nonce { get; set; }
        public double Timestamp { get; set; }
        public string Signature { get; set; }
        public dynamic User { get; set; }
    }


public async Task<Session> GenerateSessionParams(User user)
        {
            string filename = "config.json";
            using FileStream openStream = File.OpenRead(filename);
            Config config = await JsonSerializer.DeserializeAsync<Config>(openStream);

          Session session = new Session();

            session.ApplicationId = config.cred.appId; 
            session.AuthKey = config.cred.authKey;
            session.Nonce = this.RandomNonce();
            session.Timestamp = this.GetTimeStamp();

            if (user.Login != default && user.Password != default)
            {
                session.User = new { Login = user.Login, Password = user.Password };
            }
            else if (user.Email != default && user.Password != default)
            {
                session.User = new { Email = user.Email, Password = user.Password };
            }



            return session;
        }

【问题讨论】:

  • 为什么不能使用 Newtonsoft 来处理 JSON?
  • 我是 c# 生态系统的新手,所以对它了解不多。我猜你的意思是在 C# 中使用 Newtonsoft 将 javascript 对象转换为 JSON,而不是创建 C# 类?

标签: javascript c# .net object


【解决方案1】:

我认为您要做的是将对象转换为查询字符串。

我不认为 c# 有任何内置函数可以做到这一点,你需要编写自己的函数来做到这一点。

尝试使用反射在运行时获取属性名称及其值,并将它们连接成查询字符串格式的字符串。

这是一篇关于如何做到这一点的文章。

Serialize object into a query string with Reflection

我已从文章中获取代码 sn-p 并根据您的需要更改了一些内容。

 static string ConvertToQueryString(UserSession session)
        {
            var properties = session.GetType().GetProperties()
                        .Where(x => x.CanRead)
                        .Where(x => x.GetValue(session,null) != null)
                        .ToDictionary(x=>x.Name, x=>x.GetValue(session,null));
            
            var propertyNames = properties
            .Where(x => !(x.Value is string) && x.Value is IEnumerable)
            .Select(x => x.Key)
            .ToList();

             foreach (var key in propertyNames)
        {
            var valueType = properties[key].GetType();
            var valueElemType = valueType.IsGenericType
                                    ? valueType.GetGenericArguments()[0]
                                    : valueType.GetElementType();
            if (valueElemType.IsPrimitive || valueElemType == typeof (string))
            {
                var enumerable = properties[key] as IEnumerable;
                properties[key] = string.Join("&", enumerable.Cast<object>());
            }
        }
             return string.Join("&", properties
            .Select(x => string.Concat(
                Uri.EscapeDataString(x.Key), "=",
                Uri.EscapeDataString(x.Value.ToString()))));
        }
    }

注意:和文章一样,如果你想链接这个函数,最好创建一个扩展方法。

阅读更多关于扩展函数的信息:Extension Methods (C# Programming Guide)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 2021-06-11
    • 2016-12-19
    • 2021-10-06
    • 1970-01-01
    • 2019-04-08
    • 2013-07-26
    相关资源
    最近更新 更多