zoukankan      html  css  js  c++  java
  • 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可直接使用更方便,低版本的只能其他方法。

  • 相关阅读:
    线性代数12.图和网络
    【转载】STM32之中断与事件---中断与事件的区别
    头文件重复包含(转)
    C语言位操作
    NOP使用注意事项
    头文件intrins.h的用法
    RAM、SRAM、SDRAM、ROM、EPROM、EEPROM、Flash存储器概念
    const在C语言中的用法
    volatile的作用
    absacc.h keil软件里怎么找不到 ,如何找?
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/12020832.html
Copyright © 2011-2022 走看看