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

       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 =法语&Languages = English&Languages =西班牙语”

如您所见,这是不理想的,因为在查询字符串中为集合中的每个值重复了属性“ 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());
}

09-17 08:11