web api 吐出 json 範例

 

 以下例出基本的 web api 吐出 json 範例


一、範例一

using Newtonsoft.Json.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebApplication1.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class personalTestController : ApiController
    {
        [HttpPost]
        public object CreateEvent()
        {
            JArray newJa = new JArray();
            JObject tmpJo01 = new JObject();
            tmpJo01.Add(new JProperty("code_stat", "Y"));
            newJa.Add(tmpJo01);

            return new
            {
                Result = "F",
                Message = "Message",
                TotalRec = "100",
                Data = newJa
            };
        }
    }
}


二、範例二

using Newtonsoft.Json.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApplication2.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public HttpResponseMessage Get()
        {
            JObject result = new JObject();
            result.Add(new JProperty("UserName", "李先生"));



            JArray jar1 = new JArray();
            JObject jobTemp = new JObject();

            jobTemp.Add(new JProperty("GroupId", "1"));
            jobTemp.Add(new JProperty("GroupName", "群組一"));
            jar1.Add(jobTemp);

            jobTemp = new JObject();
            jobTemp.Add(new JProperty("GroupId", "2"));
            jobTemp.Add(new JProperty("GroupName", "群組二"));
            jar1.Add(jobTemp);

            result.Add(new JProperty("UserGroup", jar1));

            return new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(result), System.Text.Encoding.UTF8, "application/json")
            };
        }

    }
}