• Newtonsoft JsonConvert.DeserializeObject 动态解析json


    十年河东,十年河西,莫欺少年穷

    学无止境,精益求精

    最近在优化项目代码,发现结构基本相同的json在反序列化时需要定义多个类,这大大减少了开发效率

    原来的代码这样写的

            /// <summary>
            /// 仓位状态 心跳包
            /// </summary>
            public string deviceVersionReportResponse(string message)
            {
                try
                {
                    var model = new WA_RequestBase<List<WA_CangweiZtResult>>();
                    model = Newtonsoft.Json.JsonConvert.DeserializeObject<WA_RequestBase<List<WA_CangweiZtResult>>>(message);
                    WA_Base<WA_CangweiZtResponse> result = new WA_Base<WA_CangweiZtResponse>();
                    result.cmd = model.cmd;
                    result.id = model.id;
                    result.rst = 0;
                    if (model.dat != null && model.dat.Count > 0)
                    {
                        WA_CangweiZtResponse dat = new WA_CangweiZtResponse() { tm = CommonMethod.Get13TimeSpan(), dr = 0 };
                        result.dat = dat;
                        return Newtonsoft.Json.JsonConvert.SerializeObject(result);
                    }
                    return "";
                }
                catch (Exception ex)
                {
                    throw ExceptionHelper.GetAggregateException("WA_DeviceResponseService", "deviceVersionReportResponse", message, ex);
                }
            }

    修改后如下:

    实例1、

    json 如下:

    {
        "id": "1111102101280049",
        "cmd": "allst",
        "dat": [{
            "dr": 1,
            "ds": 0,
            "usw": 0,
            "dt": 68,
            "btinfo": ""
        }, {
            "dr": 2,
            "ds": 0,
            "usw": 1,
            "dt": 68,
            "btinfo": "NTQ3MzEyMTEwMDEwMDI3NwJYAKACeAAATmMCAAAAAAEDAQANvgzgRUUTDQwNCg0MDQoNCg0QDQsNvg0LDQsM4QzhDOEM4QzhDOEM4QzhDOECRUVHRwACAFUAJwAAACcAAAAAAAAAAAAAAA=="
        }, {
            "dr": 3,
            "ds": 0,
            "usw": 1,
            "dt": 67,
            "btinfo": "MjIyMzEyMTA0MDEwMDIzNQHgAKAB/wAATmMCHgUjGgEAAQENog0KRUUPDVwNHw0eDVgNTg0KDSYNPA2fDQoNoA2gDaINIQ2gAkVFSEgAAgCbAFEAAwBOAAAAAAAAAAAAAAA="
        }, {
            "dr": 4,
            "ds": 0,
            "usw": 1,
            "dt": 67,
            "btinfo": "MjIyMzEyMTA0MDEwMDUzOAHgAKACBAAATmMCK98xdgEAAQENog0MRUUPDaENog2hDaINoA0MDZ8NoQ1YDQwNcQ1gDU4NjA1dAkVFR0cAAgJwAHcAAwB0AAAAAAAAAAAAAAA="
        }]
    }

    代码:

     /// <summary>
            /// 回复设备消息
            /// </summary>
            /// <param name="method"></param>
            /// <param name="message"></param>
            /// <returns></returns>
            public static string getMessage(string method, string message)
            {
                var result = string.Empty;
                var dict = JsonConvert.DeserializeObject<Dictionary<object, object>>(message);
                var cmd = dict["cmd"];
                var id = dict["id"];
                var rst = 0;
                if (dict.ContainsKey("rst"))
                {
                     rst = Convert.ToInt32(dict["rst"]);
                }
                switch (method)
                {
                    case "allst":var obj = new { cmd =cmd,id=id,rst=rst, dat =new { tm = CommonMethod.Get13TimeSpan(), dr = 0 } }; result = Newtonsoft.Json.JsonConvert.SerializeObject(obj); break;
                }
                return result;
            }

    由于json中不存在rst,因此:需要做key是否存在的判断,否则异常。

    实例2/

    static void Main(string[] args)
    {
    var json = @"{
    'DisplayName': '新一代算法模型',
    'CustomerType': 1,
    'Report': {
    'TotalCustomerCount': 1000,
    'TotalTradeCount': 50
    },
    'CustomerIDHash': [1,2,3,4,5]
    }";
    
    var dict = JsonConvert.DeserializeObject<Dictionary<object, object>>(json);
    
    var report = dict["Report"] as JObject;
    var totalCustomerCount = report["TotalCustomerCount"];
    
    Console.WriteLine($"totalCustomerCount={totalCustomerCount}");
    
    var arr = dict["CustomerIDHash"] as JArray;
    var list = arr.Select(m => m.Value<int>()).ToList();
    
    Console.WriteLine($"list={string.Join(",", list)}");

    @天才卧龙的博客

  • 相关阅读:
    git的使用
    模块化的 require 和 import的区别
    Javascript模块化编程(三):require.js的用法
    Javascript模块化编程(二)commonJS规范和AMD规范
    Javascript模块化编程发展历史
    GULP的使用流程
    jQuery事件对象
    jQuery文档处理 |
    Vue学习笔记【12】——过滤器
    Vue学习笔记【11】——Vue调试工具vue-devtools的安装步骤和使用
  • 原文地址:https://www.cnblogs.com/chenwolong/p/16420473.html
Copyright © 2020-2023  润新知