Filtering Properties from Dto before outputting as Json
I have a REST API for exposing quote data. Sometimes API can take specific parameters to provide data for.
General usage: http://blah.com/quotes?symbol=MSFT
specific usage: http://blah.com/quotes?symbol=MSFT¶ms=[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; pri开发者_开发百科vate set; }
public string Industry { get; private set; }
. . .
}
during general usage i simply serialize my DTO into Json. But when i get specific request how can i filter out unwanted params from my dto before i serialize ??
is there any third party lib to do this? I can use reflection but thats way to wonky. I am using ASP.NET MVC and C#
Use a mix of two techniques - the first is to write your own json result.
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/
Secondly, instead of using for ex. javascriptserializer, you would in turn use JSON.Net to manually do the serialization. This way you could exclude whatever properties you want based on your rules. A block of code from their site shows its quite simple to serialize http://james.newtonking.com/projects/json/help/ReadingWritingJSON.html
StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (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("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); }
I use NHibernate quite a bit, but it's more than I need to send down everything in the JSON.
While hacky, I like to use a Dictionary<string, object>
and then just add the members I want to send down.
return Json(someDict);
精彩评论