• json data转匿名对象C#


    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可直接使用更方便,低版本的只能其他方法。

  • 相关阅读:
    Web应用程序使用Hibernate
    Hibernate使用注释
    Hibernate入门程序
    Hibernate体系结构
    Spring MVC文件上传教程
    Spring MVC配置静态资源和资源包教程
    Spring MVC4使用Servlet3 MultiPartConfigElement文件上传实例
    Spring4 MVC文件下载实例
    Spring4 MVC+Hibernate4 Many-to-many连接表+MySQL+Maven实例
    Spring4 MVC+Hibernate4+MySQL+Maven使用注解集成实例
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/12020832.html
Copyright © 2020-2023  润新知