加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何将一个对象序列化为查询字符串格式?

发布时间:2020-12-15 19:42:06 所属栏目:asp.Net 来源:网络整理
导读:如何将对象序列化为查询字符串格式?我似乎找不到在谷歌的答案。谢谢。 这里是我将序列化的对象作为一个例子。 public class EditListItemActionModel{ public int? Id { get; set; } public int State { get; set; } public string Prefix { get; set; } pu
如何将对象序列化为查询字符串格式?我似乎找不到在谷歌的答案。谢谢。

这里是我将序列化的对象作为一个例子。

public class EditListItemActionModel
{
    public int? Id { get; set; }
    public int State { get; set; }
    public string Prefix { get; set; }
    public string Index { get; set; }
    public int? ParentID { get; set; }
}

解决方法

我99%肯定没有内置的实用程序方法。这不是一个很常见的任务,因为Web服务器通常不会使用URLEncoded键/值字符串进行响应。

你如何混合反射和LINQ?这工作:

var foo = new EditListItemActionModel() {
  Id = 1,State = 26,Prefix = "f",Index = "oo",ParentID = null
};

var properties = from p in foo.GetType().GetProperties()
                 where p.GetValue(foo,null) != null
                 select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(foo,null).ToString());

// queryString will be set to "Id=1&State=26&Prefix=f&Index=oo"                  
string queryString = String.Join("&",properties.ToArray());

更新:

要编写一个返回任何1深度对象的QueryString表示形式的方法,您可以这样做:

public string GetQueryString(object obj) {
  var properties = from p in obj.GetType().GetProperties()
                   where p.GetValue(obj,null) != null
                   select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj,null).ToString());

  return String.Join("&",properties.ToArray());
}

// Usage:
string queryString = GetQueryString(foo);

你也可以使它成为一个扩展方法,没有太多的额外工作

public static class ExtensionMethods {
  public static string GetQueryString(this object obj) {
    var properties = from p in obj.GetType().GetProperties()
                     where p.GetValue(obj,null) != null
                     select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj,null).ToString());

    return String.Join("&",properties.ToArray());
  }
}

// Usage:
string queryString = foo.GetQueryString();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读