MVC 4 Web API – 自定义对象的JSON序列化

前端之家收集整理的这篇文章主要介绍了MVC 4 Web API – 自定义对象的JSON序列化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有几个对象如下:
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_Start
var 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);
}
原文链接:https://www.f2er.com/html/226603.html

猜你在找的HTML相关文章