【问题标题】:Filtering Properties from Dto before outputting as Json在输出为 Json 之前从 Dto 过滤属性
【发布时间】:2011-09-08 00:05:30
【问题描述】:

我有一个用于公开报价数据的 REST API。有时 API 可以采用特定的参数来为其提供数据。

一般用法:http://blah.com/quotes?symbol=MSFT

具体用法:http://blah.com/quotes?symbol=MSFT&params=[Symbol,Sector,Industry]

DTO:

public class QuoteDto 
{
    public string CompanyName { get; private set; }
    public string Symbol { get; private set; }
    public string Exchange { get; private set; }
    public string Sector { get; private set; }
    public string Industry { get; private set; }
    . . . 
}

在一般使用过程中,我只是将我的 DTO 序列化为 Json。但是当我收到特定请求时,如何在序列化之前从我的 dto 中过滤掉不需要的参数??

是否有任何第三方库可以做到这一点?我可以使用反射,但那是靠不住的方式。 我正在使用 ASP.NET MVC 和 C#

【问题讨论】:

    标签: json model-view-controller serialization


    【解决方案1】:

    混合使用两种技术 - 首先是编写自己的json结果。

    Control serializer in JsonResult aka Json function in ASP.Net MVC?

    http://brianreiter.org/2011/01/03/custom-jsonresult-class-for-asp-net-mvc-to-avoid-maxjsonlength-exceeded-exception/

    其次,不要使用 for ex。 javascriptserializer,您将反过来使用 JSON.Net 手动进行序列化。这样您就可以根据您的规则排除您想要的任何属性。他们网站上的一段代码显示其序列化非常简单 http://james.newtonking.com/projects/json/help/ReadingWritingJSON.html

    StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); 使用 (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("驱动器"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD 读/写"); jsonWriter.WriteComment("(破)"); jsonWriter.WriteValue("500 GB 硬盘"); jsonWriter.WriteValue("200g硬盘"); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); }

    【讨论】:

      【解决方案2】:

      我经常使用 NHibernate,但这比我在 JSON 中发送所有内容所需的要多。

      虽然 hacky,但我喜欢使用 Dictionary<string, object>,然后添加我想要发送的成员。

      return Json(someDict);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-19
        • 2012-06-20
        • 1970-01-01
        • 2017-05-05
        • 1970-01-01
        • 2013-09-16
        • 1970-01-01
        • 2022-01-15
        相关资源
        最近更新 更多