public class Person{ string Firstname; string Lastname; public Person(string fn,string ln) { Firstname = fn; Lastname = ln; }}public class Team{ string Teamname; Person Teamleader; List<Person> TeamMembers; public Team(string name,Person lead,List<Person> members) { Teamname = name; Teamleader = lead; TeamMembers = members; }}public class Response{ int ResponseCode; string ResponseMessage; object ResponsePayload; public Response(int code,string message,object payload) { ResponseCode = code; ResponseMessage = message; ResponsePayload = payload; }}
(1)
这是带有Get方法的Person控制器:
public class PersonController : APIController{ public Response Get() { Person tom = new Person("Tom","Cruise"); Response response = new Response(1,"It works!",tom); return response; }}
(2)
这是使用Get方法的Team控制器:
public class TeamController : APIController{ public Response Get() { Person tom = new Person("Tom","Cruise"); Person cindy = new Person("Cindy","Cullen"); Person jason = new Person("Jason","LIEn"); Team awesome = new Team("Awesome",jason,new List<Person>(){tom,cindy}); Response response = new Response(1,awesome); return response; }}
我想要的是在用户呼叫之后
http://www.app123.com/api/person
我收到这样的JsON结果:
{ "ResponseCode":1,"ResponseMessage":"It works!","ResponsePayload": { "Firstname":"Tom","Lastname":"Cruise" } }
并打电话
http://www.app123.com/api/team
我收到这样的JsON结果:
{ "ResponseCode":1,"ResponsePayload": { "Teamleader": { "Firstname":"Jason","Lastname":"LIEn" } "TeamMember": [ { "Firstname":"Tom","Lastname":"Cruise" },{ "Firstname":"Cindy","Lastname":"Cullen" } ] } }
但它们从不为我工作,你知道如何使用ASP.NET MVC 4生成如上所述的JsON结果吗?
解决方法 首先,确保您使用的是JsON格式化程序,例如将以下代码添加到Application_Startvar Json = config.Formatters.JsonFormatter;Json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
其次,只需返回自定义对象,JsON格式化程序将完成其余工作,您将在客户端获得不错的JsON数据.
[httpGet]public httpResponseMessage GetPeopleList(){ var people = // create a List of person here... return Request.CreateResponse(httpStatusCode.OK,people);}总结
以上是内存溢出为你收集整理的MVC 4 Web API – 自定义对象的JSON序列化全部内容,希望文章能够帮你解决MVC 4 Web API – 自定义对象的JSON序列化所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)