现在VS2015支持生成Codorva程序了。在Javascript下,JSON格式使用的很多,但是.net framework下,使用起来很不方便,不能像Javascript那么随意。有一个专门的类库Newtonsoft.Json可以使用,但是公司比较正规,不好随便乱用三方的库,而且这个库也比较大,比较重,学习和使用成本都比较高。
后来,我想到了,现在的.net是支持dynamic关键字的,是不是可以利用它来方便的对JSON进行操作。下面是我写的代码,以供参考。
using System; using System.Collections.Generic; using System.Web.Script.Serialization; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { JavaScriptSerializer s = new JavaScriptSerializer(); dynamic o = s.DeserializeObject("{\"name\": \r\n{\"subname\":\"zdeng\"}, \r\n\"age\": 30}"); DynamicDictionaryReader reader = new DynamicDictionaryReader(o); string name2 = reader["name2"]["subname22"]["test"]["sfasfsa"].UnWrap(); string name3 = reader["name"]["subname"].UnWrap(); DynamicDictionaryWriter writer = new DynamicDictionaryWriter(o); writer["name22"]["subname123"] = "zdeng123"; writer["name22"]["zdeng"]["hluo"]["subname123"] = 123; o["name"]["subname"] = "zdeng22"; string newJson = s.Serialize(o); } class DynamicDictionaryReader { public DynamicDictionaryReader(dynamic dyn) { _dyn = dyn; } private dynamic _dyn; public DynamicDictionaryReader this[string key] { get { dynamic result = null; if (_dyn != null) { _dyn.TryGetValue(key, out result); } return new DynamicDictionaryReader(result); } } public dynamic UnWrap() { return _dyn; } } class DynamicDictionaryWriter { public DynamicDictionaryWriter(dynamic dyn) { _dyn = dyn; } private dynamic _dyn; public dynamic this[string key] { get { dynamic result; _dyn.TryGetValue(key, out result); if (result == null) { result = new Dictionary<String, dynamic>(); _dyn[key] = result; } return new DynamicDictionaryWriter(result); } set { _dyn[key] = value; } } } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-19 03:01:33