ASP.NET(C#)接口返回JSON的方式

本文介绍了在ASP.NET中如何使用C#进行JSON数据的序列化,推荐使用Newtonsoft.Json库,并展示了将List转换为JSON的方法,以及通过HttpResponseMessage获取响应体内容的方式。

一、序列化工具

在asp.net 中有时需要接口返回json格式的数据,可以NuGet安装Newtonsoft.Json程序包,用于序列化JSON的数据。操作如图所示:

 

二、List 转Json

JsonConvert.SerializeObject(List)

三、方式

使用HttpResponseMessage获取请求响应体内容

public HttpResponseMessage Get()
        {
            HttpResponseMessage response = new HttpResponseMessage();
            List<SwiperPic> swiperPics = new List<SwiperPic>() {  
                new SwiperPic {id=1,Url=@"2633.jpg" },
                new SwiperPic { id=2,Url= @"74fe.jpg" },
                new SwiperPic {id =3,Url=@"b888.jpg"}
            };
            response.Content = new StringContent(JsonConvert.SerializeObject(swiperPics),System.Text.Encoding.UTF8,"application/json");
            response.StatusCode = (HttpStatusCode)200;
           return response;
        }

四、不可取的方式

public String Get()
        {
            
            List<SwiperPic> swiperPics = new List<SwiperPic>() {  
                new SwiperPic {id=1,Url=@"2633.jpg" },
                new SwiperPic { id=2,Url= @"74fe.jpg" },
                new SwiperPic {id =3,Url=@"b888.jpg"}
            };

           return JsonConvert.SerializeObject(swiperPics);
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值