一、序列化工具
在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);
}
本文介绍了在ASP.NET中如何使用C#进行JSON数据的序列化,推荐使用Newtonsoft.Json库,并展示了将List转换为JSON的方法,以及通过HttpResponseMessage获取响应体内容的方式。
1947

被折叠的 条评论
为什么被折叠?



