我需要将包含数组的对象模型序列化为查询字符串,我有以下代码:
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" }
};
当序列化模型时,查询字符串的转换如下:
&#34;排序依据=名&安培; OrderByDesc =真安培; PERSONNAME =约翰&安培;语言=法语&安培;语言=英语&安培;语言=西班牙语&#34;
正如您所看到的那样,这是不可取的,因为该属性&#34;语言&#34;在查询字符串中为集合中的每个值重复。有谁知道如何设法获取查询字符串,如:
&#34;排序依据=名&安培; OrderByDesc =真安培; PERSONNAME =约翰&安培;语言=法语,英语,西班牙语&#34;
答案 0 :(得分:2)
将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());
}
答案 1 :(得分:1)
检查属性值是否为数组,并且由于数组实现IEnumerable,您可以创建一个通用函数,如下所示:
public string ConvertToQueryString(object obj)
{
var properties = from p in obj.GetType().GetProperties()
where p.GetValue(obj, null) != null
select p.Name + "=" + (
p.GetValue(obj, null).GetType().IsArray ?
string.Join(",", ((IEnumerable)p.GetValue(obj, null)).Cast<object>().Select(x => x.ToString()).ToArray()) :
p.GetValue(obj, null).ToString()
);
return string.Join("&", properties.ToArray());
}