方法一.JavaScriptSerializer
方法二.JsonConvert
示例:
Web API项目
1.新建 Model:
namespace WebApi
{
public class Product
{
public string Name { set; get; }
public string Price { set; get; }
}
public class ShoppingCart
{
public string Name { set; get; }
public List ProductList { set; get; }
}
}
2.序列化与反序列化工具类
(1).新建使用JavaScriptSerializer方法的的工具类JsonHelper:
...
using System.Web.Script.Serialization;
namespace WebApi
{
public static class JsonHelper
{
private static JavaScriptSerializer serializer = new JavaScriptSerializer();
public static string GetJsonStr(T objectList)
{
return serializer.Serialize(objectList);
}
public static List GetObjectList(string jsonStr)
{
List objs = serializer.Deserialize>(jsonStr);
return objs;
}
public static T GetObj(string jsonStr)
{
return serializer.Deserialize(jsonStr);
}
}
}
(1).新建使用JsonConvert方法的的工具类NetJsonHelper:
...
using Newtonsoft.Json;
namespace WebApi.Common
{
public class NetJsonHelper
{
public static string GetJsonStr(T obj)
{
return JsonConvert.SerializeObject(obj);
}
public static T GetObj(string objJsonStr)
{
return (T)JsonConvert.DeserializeObject(objJsonStr);
}
public static List GetObjs(string objsJsonStr)
{
return (List)JsonConvert.DeserializeObject>(objsJsonStr);
}
}
}
3.新建控制器 ShoppingController
public class ShoppingController : ApiController
{
private static ShoppingCart shoppingCart = new ShoppingCart();
private static string productsStr = string.Empty; //保存序列化字符串
public ShoppingController()
{
List products = new List() {
new Product(){Name="Apple",Price="$20/kg"},
new Product(){Name="Banana",Price="$15/kg"},
new Product(){Name="Melon",Price="$20/kg"}
};
shoppingCart.Name = "MyFruitBaskit";
shoppingCart.ProductList = products;
}
public string GetShoppingCart()
{
string JsonStr = JsonHelper.GetJsonStr(shoppingCart);
productsStr=JsonStr; //将序列化后的字符串保存起来用于反序列化接口测试
return JsonStr;
}
public IEnumerable GetFruitList()
{
ShoppingCart shoppingCartObj = JsonHelper.GetObj(productsStr);
return shoppingCartObj.ProductList;
}
public string GetShoppingCartByNetJson()
{
string JsonStr = NetJsonHelper.GetJsonStr(shoppingCart);
productsStr = JsonStr; //将序列化后的字符串保存起来用于反序列化接口测试
return JsonStr;
}
public IEnumerable GetFruitListByNetJson()
{
ShoppingCart shoppingCartObj = NetJsonHelper.GetObj(productsStr);
return shoppingCartObj.ProductList;
}
}
4.启动WEB API进行测试
如:测试JavaScriptSerializer
先: localhost:xxxx/api/Shopping/GetShoppingCart
然后: localhost:xxxx/api/Shopping/GetFruitList
两种方法不论在序列化还是反序列化时,当传入的是null 时均不会出异常