• 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)}");

    @天才卧龙的博客

  • 相关阅读:
    sqli-libs(3)
    python学习之路(18)
    BZOJ3534:[SDOI2014]重建——题解
    洛谷省选斗兽场全通关祭~以及之后的打算!
    BZOJ4596:[SHOI2016]黑暗前的幻想乡——题解
    BZOJ2732:[HNOI2012]射箭——题解
    BZOJ1486:[HNOI2009]最小圈——题解
    BZOJ4552:[HEOI2016/TJOI2016]排序——题解
    BZOJ2830 & 洛谷3830:[SHOI2012]随机树——题解
    BZOJ4889 & 洛谷3759:[TJOI2017]不勤劳的图书管理员——题解
  • 原文地址:https://www.cnblogs.com/chenwolong/p/16420473.html
Copyright © 2020-2023  润新知