如何将对象序列化为查询字符串格式? [英] How do I serialize an object into query-string format?

查看:31
本文介绍了如何将对象序列化为查询字符串格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将对象序列化为查询字符串格式?我似乎无法在谷歌上找到答案.谢谢.

How do I serialize an object into query-string format? I can't seem to find an answer on google. Thanks.

这里以我将序列化的对象为例.

Here is the object I will serialize as an example.

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 键/值字符串.

I'm 99% sure there's no built-in utility method for this. It's not a very common task, since a web server doesn't typically respond with a URLEncoded key/value string.

你如何看待混合反射和 LINQ?这有效:

How do you feel about mixing reflection and LINQ? This works:

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-deep 对象的 QueryString 表示的方法,您可以这样做:

To write a method that returns the QueryString representation of any 1-deep object, you could do this:

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);

你也可以让它成为一个扩展方法而无需太多额外的工作

You could also make it an extension method without much additional work

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();

这篇关于如何将对象序列化为查询字符串格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆