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