using Newtonsoft.Json.Linq;
代码如下:
static void Main(string[] args) { Console.WriteLine("Test 4.8"); var o = new { a = 1, b = "Hello, World!", c = new[] { 1, 2, 3 }, d = new Dictionary<string, int> { { "x", 1 }, { "y", 2 } } }; var json = JsonConvert.SerializeObject(o); /* 1 */ Console.WriteLine("-----------1---------------"); var anonymous = new { a = 0, b = String.Empty, c = new int[0], d = new Dictionary<string, int>() }; var o2 = JsonConvert.DeserializeAnonymousType(json, anonymous); Console.WriteLine(o2.b); Console.WriteLine(o2.c[1]); /* 2 */ Console.WriteLine("-----------2---------------"); var o3 = JsonConvert.DeserializeAnonymousType(json, new { c = new int[0], d = new Dictionary<string, int>() }); Console.WriteLine(o3.d["y"]); /* 3 */ Console.WriteLine("-----------3---------------"); var o4 = JsonConvert.DeserializeObject(json) as JObject; Console.WriteLine((int)o4["a"]); Console.WriteLine((string)o4["b"]); Console.WriteLine(o4["c"].Values().Count()); Console.WriteLine((int)o4["d"]["y"]); /* 4 */ Console.WriteLine("-----------3---------------"); string requestParams = "{"InquiryOrderNo":"1","InquirySolutionNo":"2","PlatPlanNo":"3","State":"4"}"; var entity = JsonConvert.DeserializeObject(requestParams) as JObject; string strInquiryOrderNo = entity != null ? (string)entity["InquiryOrderNo"] : string.Empty; string strInquirySolutionNo = entity != null ? (string)entity["InquirySolutionNo"] : string.Empty; string strPlatPlanNo = entity != null ? (string)entity["PlatPlanNo"] : string.Empty; string strState = entity != null ? (string)entity["State"] : string.Empty; Console.ReadKey(); }
解决创建接收json data的具体对象,缺点不是强类型,无法保证手误导致失败,保证方法是写单元测试。 对于高版本的net framewrok 有动态 类型dynamic可直接使用更方便,低版本的只能其他方法。