Newtonsoft JsonConvert.DeserializeObject 动态解析json


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

学无止境,精益求精

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

原来的代码这样写的

        /// 
        /// 仓位状态 心跳包
        /// 
        public string deviceVersionReportResponse(string message)
        {
            try
            {
                var model = new WA_RequestBase>();
                model = Newtonsoft.Json.JsonConvert.DeserializeObject>>(message);
                WA_Base result = new WA_Base();
                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="
    }]
}

代码:

 /// 
        /// 回复设备消息
        /// 
        /// 
        /// 
        /// 
        public static string getMessage(string method, string message)
        {
            var result = string.Empty;
            var dict = JsonConvert.DeserializeObjectobject, 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.DeserializeObjectobject, 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)}");

@天才卧龙的博客