c# - 如何将数组序列化为查询字符串?

标签 c# serialization query-string

我需要将包含数组的对象模型序列化为查询字符串,我有以下代码:

       public static string ToQueryString(this object query)
    {
        var result = new List<string>();
        var properties = query.GetType().GetProperties().Where(p => p.GetValue(query, null) != null && p.GetValue(query, null).ToString() != "0");

        foreach (var p in properties)
        {
            var value = p.GetValue(query, null);
            var collection = value as ICollection;
            if (collection != null)
            {
                result.AddRange(from object o in collection select string.Format("{0}={1}", p.Name, HttpUtility.UrlEncode(o.ToString())));
            }
            else
            {
                result.Add($"{p.Name}={HttpUtility.UrlEncode(value.ToString())}");
            }
        }

        return string.Join("&", result.ToArray());
    }

和以下示例模型:

        var model = new exampleModel()
        {
            OrderBy = "name",
            OrderByDesc = true,
            PersonName= "John",
            Languages = new string[] { "French", "English", "Spanish" }
        };

当模型被序列化时,查询字符串会像这样转换:

"OrderBy=name&OrderByDesc=true&PersonName=John&Languages=French&Languages=English&Languages=Spanish"

如您所见,这是不可取的,因为集合中每个值的查询字符串中都会重复属性“Languages”。有谁知道我如何设法获取查询字符串,例如:

"OrderBy=name&OrderByDesc=true&PersonName=John&Languages=法语、英语、西类牙语"

最佳答案

将您对 ICollection 的处理更改为您想要的格式:

  public static string ToQueryString(this object query)
{
    var result = new List<string>();
    var properties = query.GetType().GetProperties().Where(p => p.GetValue(query, null) != null && p.GetValue(query, null).ToString() != "0");

    foreach (var p in properties)
    {
        var value = p.GetValue(query, null);
        var collection = value as ICollection;
        if (collection != null)
        {
            result.Add(p.Name+"="+string.Join(",", collection.Select(o => HttpUtility.UrlEncode(o.ToString())).ToArray());
        }
        else
        {
            result.Add($"{p.Name}={HttpUtility.UrlEncode(value.ToString())}");
        }
    }

    return string.Join("&", result.ToArray());
}

关于c# - 如何将数组序列化为查询字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47799562/

相关文章:

c# - 限制中间抽象类的继承

c# - 使 protobuf-net 将子类序列化为基类?

C++ vector 矩阵的 Boost 序列化

asp.net - 在 asp.net 4 中通过登录控件传递查询字符串?

php - parse_str 随机向键添加分号

c# - 我是否应该始终检查某些东西的返回值是否为空

c# - 系统.InvalidOperationException : < xmlns ='' > was not expected

c# - C# PayPal REST API Winforms 应用程序中的授权代码在哪里?

php - 在 PHP/MySQL 中存储大量表单数据的最佳方式?

javascript - 查询字符串参数