gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:50:10 25 4
gpt4 key购买 nike

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

       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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com